Bundle: redb / redb.Tests.Integration (redb.Tests.Integration.txt), 331 files Snapshot: 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 Index: https://redbase.app/src/dev-2026-12-06/redb/_index.txt ==== Path: redb/redb.Tests.Integration/Fixtures/CapturingLoggerProvider.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/Fixtures/CapturingLoggerProvider.cs ---- using System.Collections.Concurrent; using Microsoft.Extensions.Logging; namespace redb.Tests.Integration.Fixtures; /// /// Records every log entry of the loggers it creates, so a test can assert that a diagnostic warning was /// written - and written once. /// public sealed class CapturingLoggerProvider : ILoggerProvider { private readonly ConcurrentQueue _entries = new(); public IReadOnlyList Entries => _entries.ToArray(); /// Messages of the Warning entries, in the order they were written. public IReadOnlyList Warnings => _entries.Where(e => e.Level == LogLevel.Warning).Select(e => e.Message).ToList(); public ILogger CreateLogger(string categoryName) => new CapturingLogger(this, categoryName); public void Dispose() { } private sealed class CapturingLogger : ILogger { private readonly CapturingLoggerProvider _owner; private readonly string _category; public CapturingLogger(CapturingLoggerProvider owner, string category) { _owner = owner; _category = category; } public IDisposable? BeginScope(TState state) where TState : notnull => null; public bool IsEnabled(LogLevel logLevel) => true; public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter) => _owner._entries.Enqueue(new CapturedLogEntry(_category, logLevel, formatter(state, exception))); } } public sealed record CapturedLogEntry(string Category, LogLevel Level, string Message); Path: redb/redb.Tests.Integration/Fixtures/CollectionDefinitions.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/Fixtures/CollectionDefinitions.cs ---- namespace redb.Tests.Integration.Fixtures; [CollectionDefinition("Postgres")] public class PostgresCollection : ICollectionFixture; [CollectionDefinition("MsSql")] public class MsSqlCollection : ICollectionFixture; [CollectionDefinition("PostgresPro")] public class PostgresProCollection : ICollectionFixture; [CollectionDefinition("MsSqlPro")] public class MsSqlProCollection : ICollectionFixture; [CollectionDefinition("Sqlite")] public class SqliteCollection : ICollectionFixture; [CollectionDefinition("SqlitePro")] public class SqliteProCollection : ICollectionFixture; // Case folding. Each needs its own collection: the PostgreSQL pair shares one C-ctype database and // must not interleave, and SQLite installs the feature per connection on a file of its own. [CollectionDefinition("PostgresCollation")] public class PostgresCollationCollection : ICollectionFixture; [CollectionDefinition("PostgresNoCollation")] public class PostgresNoCollationCollection : ICollectionFixture; [CollectionDefinition("SqliteCollation")] public class SqliteCollationCollection : ICollectionFixture; [CollectionDefinition("SqliteProCollation")] public class SqliteProCollationCollection : ICollectionFixture; [CollectionDefinition("PostgresProCollation")] public class PostgresProCollationCollection : ICollectionFixture; Path: redb/redb.Tests.Integration/Fixtures/FixtureWipeGuard.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/Fixtures/FixtureWipeGuard.cs ---- using redb.Core.Data; namespace redb.Tests.Integration.Fixtures; /// /// Refuses a fixture wipe of a database that does not look like a test database. The fixtures /// clean their database COMPLETELY on start (DELETE FROM _values / _objects) - lawful on the /// dedicated test database, catastrophic on anything else: on 2026-09-10 a freshly seeded /// 100k-object examples database shared the test connection string and was lost to exactly this /// (and the 8M-row cascade-trigger delete масked itself as an hours-long hang first). /// Examples/seeding live in their own databases (redb_examples) since then; this guard is the /// belt to that suspenders. /// public static class FixtureWipeGuard { /// Way above anything the test suites ever create, way below any real seed. public const long MaxObjectsForWipe = 50_000; public static async Task EnsureLooksLikeATestDatabaseAsync(IRedbContext ctx, string fixtureName) { var count = await ctx.ExecuteScalarAsync("SELECT COUNT(*) FROM _objects"); if (count > MaxObjectsForWipe) throw new InvalidOperationException( $"{fixtureName}: refusing to wipe this database - _objects holds {count:N0} rows " + $"(threshold {MaxObjectsForWipe:N0}). It looks seeded or production-like, and the " + "fixture cleanup deletes EVERYTHING. Point the tests at a dedicated test database; " + "the examples seed belongs in redb_examples."); } } Path: redb/redb.Tests.Integration/Fixtures/MsSqlFixture.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/Fixtures/MsSqlFixture.cs ---- using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Core; using redb.Core.Data; using redb.Core.Extensions; using redb.Core.Models.Configuration; using redb.MSSql.Extensions; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Fixtures; public sealed class MsSqlFixture : IAsyncLifetime { public IRedbService Redb { get; private set; } = null!; public ServiceProvider ServiceProvider { get; private set; } = null!; public async Task InitializeAsync() { var config = new ConfigurationBuilder() .AddJsonFile("appsettings.json") .Build(); var cs = config.GetConnectionString("MSSql")!; var services = new ServiceCollection(); services.AddLogging(b => b.AddConsole().SetMinimumLevel(LogLevel.Warning)); services.AddRedb(options => options .UseMsSql(cs) .Configure(c => { c.PropsSaveStrategy = PropsSaveStrategy.DeleteInsert; c.SkipHashValidationOnCacheCheck = false; c.EnablePropsCache = false; })); ServiceProvider = services.BuildServiceProvider(); Redb = ServiceProvider.GetRequiredService(); try { await Redb.InitializeAsync(ensureCreated: true); } catch { await Redb.InitializeAsync(); } await SyncSchemes(); await Cleanup(); } private async Task SyncSchemes() { await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); // Case-folding suite: MSSQL is asserted to need no setting at all (MsSqlCaseFoldingTests). await Redb.SyncSchemeAsync(); await Redb.InitializeTypeRegistryAsync(); } private async Task Cleanup() { var ctx = ServiceProvider.GetRequiredService(); await FixtureWipeGuard.EnsureLooksLikeATestDatabaseAsync(ctx, nameof(MsSqlFixture)); try { await ctx.ExecuteAsync("DELETE FROM _tree"); } catch { } try { await ctx.ExecuteAsync("DELETE FROM _values"); } catch { } await ctx.ExecuteAsync("DELETE FROM _objects"); try { await ctx.ExecuteAsync("DBCC CHECKIDENT ('_objects', RESEED, 0)"); } catch { } try { await ctx.ExecuteAsync("DBCC CHECKIDENT ('_values', RESEED, 0)"); } catch { } } public async Task DisposeAsync() { if (ServiceProvider is IAsyncDisposable ad) await ad.DisposeAsync(); else ServiceProvider?.Dispose(); // Same as the Postgres fixtures: return the pooled sessions to the server immediately. Microsoft.Data.SqlClient.SqlConnection.ClearAllPools(); } } Path: redb/redb.Tests.Integration/Fixtures/MsSqlProFixture.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/Fixtures/MsSqlProFixture.cs ---- using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Core; using redb.Core.Data; using redb.Core.Models.Configuration; using redb.Core.Pro.Extensions; using redb.MSSql.Pro.Extensions; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Fixtures; public sealed class MsSqlProFixture : IAsyncLifetime { public IRedbService Redb { get; private set; } = null!; public ServiceProvider ServiceProvider { get; private set; } = null!; public async Task InitializeAsync() { var config = new ConfigurationBuilder() .AddJsonFile("appsettings.json") .Build(); var cs = config.GetConnectionString("MSSql")!; var license = config["Redb:License"]; var services = new ServiceCollection(); services.AddLogging(b => b.AddConsole().SetMinimumLevel(LogLevel.Warning)); services.AddRedbPro(options => { options.UseMsSql(cs) .Configure(c => { c.PropsSaveStrategy = PropsSaveStrategy.ChangeTracking; c.SkipHashValidationOnCacheCheck = false; c.EnablePropsCache = false; c.EnablePvtPrefilter = ProTestOptions.PvtPrefilter; }); if (!string.IsNullOrWhiteSpace(license)) options.WithLicense(license); }); ServiceProvider = services.BuildServiceProvider(); Redb = ServiceProvider.GetRequiredService(); try { await Redb.InitializeAsync(ensureCreated: true); } catch { await Redb.InitializeAsync(); } await SyncSchemes(); await Cleanup(); } private async Task SyncSchemes() { await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); } private async Task Cleanup() { var ctx = ServiceProvider.GetRequiredService(); await FixtureWipeGuard.EnsureLooksLikeATestDatabaseAsync(ctx, nameof(MsSqlProFixture)); try { await ctx.ExecuteAsync("DELETE FROM _tree"); } catch { } try { await ctx.ExecuteAsync("DELETE FROM _values"); } catch { } await ctx.ExecuteAsync("DELETE FROM _objects"); try { await ctx.ExecuteAsync("DBCC CHECKIDENT ('_objects', RESEED, 0)"); } catch { } try { await ctx.ExecuteAsync("DBCC CHECKIDENT ('_values', RESEED, 0)"); } catch { } } public async Task DisposeAsync() { if (ServiceProvider is IAsyncDisposable ad) await ad.DisposeAsync(); else ServiceProvider?.Dispose(); // Same as the Postgres fixtures: return the pooled sessions to the server immediately. Microsoft.Data.SqlClient.SqlConnection.ClearAllPools(); } } Path: redb/redb.Tests.Integration/Fixtures/PostgresCollationFixture.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/Fixtures/PostgresCollationFixture.cs ---- using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Npgsql; using redb.Core; using redb.Core.Data; using redb.Core.Extensions; using redb.Core.Models.Configuration; using redb.Postgres.Extensions; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Fixtures; /// /// A PostgreSQL database created with LC_CTYPE=C, which is the only environment where the /// case-folding defect is visible at all. /// /// /// This fixture exists because the ordinary test database is created with en_US.utf8, where /// 'Привет' ILIKE '%привет%' is already true and every assertion below would pass with the /// feature removed. That is precisely how the defect survived: the environment masked it, the same /// way an all-UTC test set masked the DateTime one. A suite that cannot fail on the unfixed code is /// not a regression test. /// /// /// /// The database is created once and reused, so a re-run costs nothing. It is deliberately NOT /// dropped on dispose: recreating a database with a non-default locale is slow, and leaving it /// keeps the next run fast. It carries a name no other suite uses. /// /// public sealed class PostgresCollationFixture : IAsyncLifetime { /// Name of the C-ctype database. Distinct from every other suite's. public const string DatabaseName = "redb_collation_c"; /// Collation used by the tests. Deterministic, which LIKE requires. public const string Collation = "und-x-icu"; public IRedbService Redb { get; private set; } = null!; public ServiceProvider ServiceProvider { get; private set; } = null!; /// Connection string of the C-ctype database, for a second fixture on the same data. public static string ConnectionString { get; private set; } = null!; public async Task InitializeAsync() { var config = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build(); var baseCs = config.GetConnectionString("Postgres")!; ConnectionString = await EnsureCtypeCDatabaseAsync(baseCs); var services = new ServiceCollection(); services.AddLogging(b => b.AddConsole().SetMinimumLevel(LogLevel.Warning)); services.AddRedb(options => options .UsePostgres(ConnectionString) .Configure(c => { c.PropsSaveStrategy = PropsSaveStrategy.DeleteInsert; c.SkipHashValidationOnCacheCheck = false; c.EnablePropsCache = false; c.StringCollation = Collation; // A distinct cache domain: this process also holds services pointed at the ordinary // test database, and the metadata caches are keyed by domain. Sharing one would let // a scheme id from the other database answer a lookup here. c.CacheDomain = "collation-c"; })); ServiceProvider = services.BuildServiceProvider(); Redb = ServiceProvider.GetRequiredService(); try { await Redb.InitializeAsync(ensureCreated: true); } catch { await Redb.InitializeAsync(); } await Redb.SyncSchemeAsync(); await Redb.InitializeTypeRegistryAsync(); var ctx = ServiceProvider.GetRequiredService(); await FixtureWipeGuard.EnsureLooksLikeATestDatabaseAsync(ctx, nameof(PostgresCollationFixture)); await ctx.ExecuteAsync("DELETE FROM _values"); await ctx.ExecuteAsync("DELETE FROM _objects"); } /// /// Creates the database if it is absent. TEMPLATE template0 is required: template1 carries the /// cluster's own locale and CREATE DATABASE refuses a different one from it. /// Every fixture on this database calls it: on a fresh server whichever collection starts first creates the /// database, and a session lock keeps two of them from creating it at once. /// internal static async Task EnsureCtypeCDatabaseAsync(string baseConnectionString) { var builder = new NpgsqlConnectionStringBuilder(baseConnectionString); var target = new NpgsqlConnectionStringBuilder(baseConnectionString) { Database = DatabaseName }; builder.Database = "postgres"; // Unpooled: the session lock below ends with this connection. builder.Pooling = false; await using var admin = new NpgsqlConnection(builder.ConnectionString); await admin.OpenAsync(); await using (var gate = admin.CreateCommand()) { gate.CommandText = "SELECT pg_advisory_lock(hashtext($1))"; gate.Parameters.Add(new NpgsqlParameter { Value = DatabaseName }); await gate.ExecuteNonQueryAsync(); } await using (var check = admin.CreateCommand()) { check.CommandText = "SELECT 1 FROM pg_database WHERE datname = $1"; check.Parameters.Add(new NpgsqlParameter { Value = DatabaseName }); if (await check.ExecuteScalarAsync() is not null) return target.ConnectionString; } await using (var create = admin.CreateCommand()) { // The name is a compile-time constant, not input, so interpolation here is not a hole. create.CommandText = $"CREATE DATABASE \"{DatabaseName}\" TEMPLATE template0 " + "LC_COLLATE 'C' LC_CTYPE 'C' ENCODING 'UTF8'"; await create.ExecuteNonQueryAsync(); } return target.ConnectionString; } public async Task DisposeAsync() { if (ServiceProvider is IAsyncDisposable ad) await ad.DisposeAsync(); else ServiceProvider?.Dispose(); } } /// /// The same C-ctype database, with the feature OFF. Proves the other half of the contract: without /// the setting the behaviour is exactly what it was, so nobody's existing deployment changes under /// them. Creates the database and the schema itself when it starts first. /// public sealed class PostgresNoCollationFixture : IAsyncLifetime { public IRedbService Redb { get; private set; } = null!; public ServiceProvider ServiceProvider { get; private set; } = null!; public async Task InitializeAsync() { var config = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build(); var baseCs = config.GetConnectionString("Postgres")!; // The database may not exist yet: on a fresh server this collection can start before the one that used to // create it. var target = new NpgsqlConnectionStringBuilder(await PostgresCollationFixture.EnsureCtypeCDatabaseAsync(baseCs)); var services = new ServiceCollection(); services.AddLogging(b => b.AddConsole().SetMinimumLevel(LogLevel.Warning)); services.AddRedb(options => options .UsePostgres(target.ConnectionString) .Configure(c => { c.PropsSaveStrategy = PropsSaveStrategy.DeleteInsert; c.SkipHashValidationOnCacheCheck = false; c.EnablePropsCache = false; // StringCollation deliberately left unset — that is the point of this fixture. c.CacheDomain = "collation-c"; })); ServiceProvider = services.BuildServiceProvider(); Redb = ServiceProvider.GetRequiredService(); try { await Redb.InitializeAsync(ensureCreated: true); } catch { await Redb.InitializeAsync(); } await Redb.SyncSchemeAsync(); await Redb.InitializeTypeRegistryAsync(); } public async Task DisposeAsync() { if (ServiceProvider is IAsyncDisposable ad) await ad.DisposeAsync(); else ServiceProvider?.Dispose(); } } Path: redb/redb.Tests.Integration/Fixtures/PostgresFixture.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/Fixtures/PostgresFixture.cs ---- using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Core; using redb.Core.Data; using redb.Core.Extensions; using redb.Core.Models.Configuration; using redb.Postgres.Extensions; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Fixtures; public sealed class PostgresFixture : IAsyncLifetime { public IRedbService Redb { get; private set; } = null!; public ServiceProvider ServiceProvider { get; private set; } = null!; public async Task InitializeAsync() { var config = new ConfigurationBuilder() .AddJsonFile("appsettings.json") .Build(); var cs = config.GetConnectionString("Postgres")!; var services = new ServiceCollection(); services.AddLogging(b => b.AddConsole().SetMinimumLevel(LogLevel.Warning)); services.AddRedb(options => options .UsePostgres(cs) .Configure(c => { c.PropsSaveStrategy = PropsSaveStrategy.DeleteInsert; c.SkipHashValidationOnCacheCheck = false; c.EnablePropsCache = false; })); ServiceProvider = services.BuildServiceProvider(); Redb = ServiceProvider.GetRequiredService(); try { await Redb.InitializeAsync(ensureCreated: true); } catch { await Redb.InitializeAsync(); } await SyncSchemes(); await Cleanup(); } private async Task SyncSchemes() { await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.InitializeTypeRegistryAsync(); } private async Task Cleanup() { var ctx = ServiceProvider.GetRequiredService(); await FixtureWipeGuard.EnsureLooksLikeATestDatabaseAsync(ctx, nameof(PostgresFixture)); try { await ctx.ExecuteAsync("DELETE FROM _tree"); } catch { } await ctx.ExecuteAsync("DELETE FROM _values"); await ctx.ExecuteAsync("DELETE FROM _objects"); } public async Task DisposeAsync() { if (ServiceProvider is IAsyncDisposable ad) await ad.DisposeAsync(); else ServiceProvider?.Dispose(); } } Path: redb/redb.Tests.Integration/Fixtures/PostgresProCollationFixture.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/Fixtures/PostgresProCollationFixture.cs ---- using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Npgsql; using redb.Core; using redb.Core.Data; using redb.Core.Models.Configuration; using redb.Core.Pro.Extensions; using redb.Postgres.Pro.Extensions; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Fixtures; /// /// PostgreSQL Pro on the C-ctype database, feature ON. /// /// /// Free and Pro do not share a code path here. Free builds its SQL inside the database and reads the /// collation from a GUC; Pro builds it in C# and attaches the clause through the dialect. Testing /// only Free would leave every Pro user unprotected, and the two could drift apart without a single /// test going red. This fixture exists because the first version of the suite covered Free alone. /// /// /// /// The PVT prefilter is forced ON regardless of ProTestOptions, because /// PvtPrefilterRenderer is a separate emitter with its own copy of the ILIKE mapping. With /// the prefilter off that file is never executed and its folding is untested. /// /// public sealed class PostgresProCollationFixture : IAsyncLifetime { public IRedbService Redb { get; private set; } = null!; public ServiceProvider ServiceProvider { get; private set; } = null!; public async Task InitializeAsync() { var config = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build(); var baseCs = config.GetConnectionString("Postgres")!; var license = config["Redb:License"]; // The Free collation fixture owns creation of the C-ctype database; reuse it if it has run, // otherwise create it here so this suite can also run alone. var cs = new NpgsqlConnectionStringBuilder(baseCs) { Database = PostgresCollationFixture.DatabaseName }.ConnectionString; await PostgresCollationFixture.EnsureCtypeCDatabaseAsync(baseCs); var services = new ServiceCollection(); services.AddLogging(b => b.AddConsole().SetMinimumLevel(LogLevel.Warning)); services.AddRedbPro(options => { options.UsePostgres(cs) .Configure(c => { c.PropsSaveStrategy = PropsSaveStrategy.ChangeTracking; c.SkipHashValidationOnCacheCheck = false; c.EnablePropsCache = false; c.EnablePvtPrefilter = true; // see the class remark c.StringCollation = PostgresCollationFixture.Collation; c.CacheDomain = "collation-c-pro"; }); if (!string.IsNullOrWhiteSpace(license)) options.WithLicense(license); }); ServiceProvider = services.BuildServiceProvider(); Redb = ServiceProvider.GetRequiredService(); try { await Redb.InitializeAsync(ensureCreated: true); } catch { await Redb.InitializeAsync(); } await Redb.SyncSchemeAsync(); await Redb.InitializeTypeRegistryAsync(); } public async Task DisposeAsync() { if (ServiceProvider is IAsyncDisposable ad) await ad.DisposeAsync(); else ServiceProvider?.Dispose(); } } Path: redb/redb.Tests.Integration/Fixtures/PostgresProFixture.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/Fixtures/PostgresProFixture.cs ---- using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Core; using redb.Core.Data; using redb.Core.Models.Configuration; using redb.Core.Pro.Extensions; using redb.Postgres.Pro.Extensions; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Fixtures; public sealed class PostgresProFixture : IAsyncLifetime { public IRedbService Redb { get; private set; } = null!; public ServiceProvider ServiceProvider { get; private set; } = null!; public async Task InitializeAsync() { var config = new ConfigurationBuilder() .AddJsonFile("appsettings.json") .Build(); var cs = config.GetConnectionString("Postgres")!; var license = config["Redb:License"]; var services = new ServiceCollection(); services.AddLogging(b => b.AddConsole().SetMinimumLevel(LogLevel.Warning)); services.AddRedbPro(options => { options.UsePostgres(cs) .Configure(c => { c.PropsSaveStrategy = PropsSaveStrategy.ChangeTracking; c.SkipHashValidationOnCacheCheck = false; c.EnablePropsCache = false; c.EnablePvtPrefilter = ProTestOptions.PvtPrefilter; }); if (!string.IsNullOrWhiteSpace(license)) options.WithLicense(license); }); ServiceProvider = services.BuildServiceProvider(); Redb = ServiceProvider.GetRequiredService(); try { await Redb.InitializeAsync(ensureCreated: true); } catch { await Redb.InitializeAsync(); } await SyncSchemes(); await Cleanup(); } private async Task SyncSchemes() { await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); } private async Task Cleanup() { var ctx = ServiceProvider.GetRequiredService(); await FixtureWipeGuard.EnsureLooksLikeATestDatabaseAsync(ctx, nameof(PostgresProFixture)); try { await ctx.ExecuteAsync("DELETE FROM _tree"); } catch { } await ctx.ExecuteAsync("DELETE FROM _values"); await ctx.ExecuteAsync("DELETE FROM _objects"); } public async Task DisposeAsync() { if (ServiceProvider is IAsyncDisposable ad) await ad.DisposeAsync(); else ServiceProvider?.Dispose(); } } Path: redb/redb.Tests.Integration/Fixtures/ProTestOptions.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/Fixtures/ProTestOptions.cs ---- namespace redb.Tests.Integration.Fixtures; /// /// Knobs the Pro fixtures read from the environment, so the whole suite can be replayed under a /// different engine configuration without editing code. /// internal static class ProTestOptions { /// /// REDB_PVT_PREFILTER=1|true|on|yes enables the PVT prefilter. Off when the variable is unset, /// although RedbServiceConfiguration.EnablePvtPrefilter defaults to true: the fixtures set /// the flag explicitly, so each pass runs the form it names. /// /// The prefilter is built as a superset and must not change a single result, so BOTH passes are /// expected to be green and identical. A test that passes with it off and fails with it on is a /// bug in the prefilter, never a reason to relax the test. /// public static bool PvtPrefilter => (Environment.GetEnvironmentVariable("REDB_PVT_PREFILTER") ?? string.Empty).Trim().ToLowerInvariant() is "1" or "true" or "on" or "yes"; } Path: redb/redb.Tests.Integration/Fixtures/SchemaUpgradeCleanup.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/Fixtures/SchemaUpgradeCleanup.cs ---- namespace redb.Tests.Integration.Fixtures; /// /// Removes what a schema-upgrade test class created on the test server (its databases, its login or role) when the /// class is done, whether its tests passed or failed. The class registers the removal; the databases live for the whole /// class, because every test of it starts from the deployed one. /// public sealed class SchemaUpgradeCleanup : IAsyncLifetime { private Func? _remove; /// /// A suffix of this run for the names of the databases and the login or role of the class: two runs on one server /// (a host run and a direct one) must not drop each other's database in the middle of a test. /// public string Suffix { get; } = Guid.NewGuid().ToString("N")[..8]; /// The removal of the first test instance is kept: every instance of a class names the same objects. public void Register(Func remove) => _remove ??= remove; public Task InitializeAsync() => Task.CompletedTask; public Task DisposeAsync() => _remove?.Invoke() ?? Task.CompletedTask; } Path: redb/redb.Tests.Integration/Fixtures/SqliteCollationFixture.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/Fixtures/SqliteCollationFixture.cs ---- using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Core; using redb.Core.Data; using redb.Core.Extensions; using redb.Core.Models.Configuration; using redb.SQLite.Data; using redb.SQLite.Extensions; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Fixtures; /// /// SQLite with Unicode case folding enabled. /// /// /// Unlike PostgreSQL, no special database is needed: SQLite's ASCII-only folding is unconditional, /// so an ordinary file reproduces the defect. What the fixture does need is its own file, because /// the feature is installed per connection and the other SQLite fixtures share one database. /// /// public sealed class SqliteCollationFixture : IAsyncLifetime { private const string DbFile = "redb_tests_sqlite_collation.db"; public IRedbService Redb { get; private set; } = null!; public ServiceProvider ServiceProvider { get; private set; } = null!; public async Task InitializeAsync() { var config = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build(); // Reuse the configured shape (pragmas, pooling) but a different file. var baseCs = config.GetConnectionString("Sqlite")!; var cs = System.Text.RegularExpressions.Regex.Replace( baseCs, @"Data Source\s*=\s*[^;]+", "Data Source=" + DbFile, System.Text.RegularExpressions.RegexOptions.IgnoreCase); SqliteDataSource.NativeExtensionPath ??= SqliteTestSupport.ResolveNativeExtension(); SqliteTestSupport.DeleteDbFiles(cs); var services = new ServiceCollection(); services.AddLogging(b => b.AddConsole().SetMinimumLevel(LogLevel.Warning)); services.AddRedb(options => options .UseSqlite(cs) .Configure(c => { c.PropsSaveStrategy = PropsSaveStrategy.DeleteInsert; c.SkipHashValidationOnCacheCheck = false; c.EnablePropsCache = false; // On SQLite the value is not a collation name — there is nothing to attach it to. // It is the switch that installs the Unicode-aware like/lower/upper overrides on // every connection. The name is validated all the same, so a typo fails at startup // rather than turning into silence. c.StringCollation = PostgresCollationFixture.Collation; c.CacheDomain = "collation-sqlite"; })); ServiceProvider = services.BuildServiceProvider(); Redb = ServiceProvider.GetRequiredService(); try { await Redb.InitializeAsync(ensureCreated: true); } catch { await Redb.InitializeAsync(); } await Redb.SyncSchemeAsync(); await Redb.InitializeTypeRegistryAsync(); var ctx = ServiceProvider.GetRequiredService(); await FixtureWipeGuard.EnsureLooksLikeATestDatabaseAsync(ctx, nameof(SqliteCollationFixture)); await ctx.ExecuteAsync("DELETE FROM _values"); await ctx.ExecuteAsync("DELETE FROM _objects"); } public async Task DisposeAsync() { if (ServiceProvider is IAsyncDisposable ad) await ad.DisposeAsync(); else ServiceProvider?.Dispose(); } } Path: redb/redb.Tests.Integration/Fixtures/SqliteFixture.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/Fixtures/SqliteFixture.cs ---- using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Core; using redb.Core.Data; using redb.Core.Extensions; using redb.Core.Models.Configuration; using redb.SQLite.Data; using redb.SQLite.Extensions; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Fixtures; /// /// SQLite Free fixture — hosts the in-DB machinery as the native loadable extension /// (get_object_json / pvt_build_*_sql / ...). The native binary is located by walking up to /// redb.SQLite/native/build/redbsqlite.{dll,so,dylib}. A fresh DB file is used every run (the datetime /// columns are REAL Julian and an old TEXT-schema file is not auto-migrated). /// public sealed class SqliteFixture : IAsyncLifetime { public IRedbService Redb { get; private set; } = null!; public ServiceProvider ServiceProvider { get; private set; } = null!; public async Task InitializeAsync() { var config = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build(); var cs = config.GetConnectionString("Sqlite")!; SqliteDataSource.NativeExtensionPath ??= SqliteTestSupport.ResolveNativeExtension(); SqliteTestSupport.DeleteDbFiles(cs); var services = new ServiceCollection(); services.AddLogging(b => b.AddConsole().SetMinimumLevel(LogLevel.Warning)); services.AddRedb(options => options .UseSqlite(cs) .Configure(c => { c.PropsSaveStrategy = PropsSaveStrategy.DeleteInsert; c.SkipHashValidationOnCacheCheck = false; c.EnablePropsCache = false; })); ServiceProvider = services.BuildServiceProvider(); Redb = ServiceProvider.GetRequiredService(); try { await Redb.InitializeAsync(ensureCreated: true); } catch { await Redb.InitializeAsync(); } await SyncSchemes(); await Cleanup(); } private async Task SyncSchemes() { await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.InitializeTypeRegistryAsync(); } private async Task Cleanup() { var ctx = ServiceProvider.GetRequiredService(); try { await ctx.ExecuteAsync("DELETE FROM _tree"); } catch { } await ctx.ExecuteAsync("DELETE FROM _values"); await ctx.ExecuteAsync("DELETE FROM _objects"); } public async Task DisposeAsync() { if (ServiceProvider is IAsyncDisposable ad) await ad.DisposeAsync(); else ServiceProvider?.Dispose(); } } Path: redb/redb.Tests.Integration/Fixtures/SqliteProCollationFixture.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/Fixtures/SqliteProCollationFixture.cs ---- using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Core; using redb.Core.Data; using redb.Core.Models.Configuration; using redb.Core.Pro.Extensions; using redb.SQLite.Pro.Extensions; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Fixtures; /// /// SQLite Pro with StringCollation set: the Pro registration of SqliteCollationFixture. On SQLite the setting is /// the switch that installs the Unicode-aware like/lower/upper overrides on every connection; its own file, because they /// are installed per connection. /// public sealed class SqliteProCollationFixture : IAsyncLifetime { private const string DbFile = "redb_tests_sqlite_pro_collation.db"; public IRedbService Redb { get; private set; } = null!; public ServiceProvider ServiceProvider { get; private set; } = null!; public async Task InitializeAsync() { var config = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build(); var cs = System.Text.RegularExpressions.Regex.Replace( config.GetConnectionString("Sqlite")!, @"Data Source\s*=\s*[^;]+", "Data Source=" + DbFile, System.Text.RegularExpressions.RegexOptions.IgnoreCase); var license = config["Redb:License"]; // As in SqliteProFixture: the path is process-static and other fixtures set it; set before the first connection. redb.SQLite.Data.SqliteDataSource.NativeExtensionPath ??= SqliteTestSupport.ResolveNativeExtension(); SqliteTestSupport.DeleteDbFiles(cs); var services = new ServiceCollection(); services.AddLogging(b => b.AddConsole().SetMinimumLevel(LogLevel.Warning)); services.AddRedbPro(options => { options.UseSqlite(cs) .Configure(c => { c.PropsSaveStrategy = PropsSaveStrategy.ChangeTracking; c.SkipHashValidationOnCacheCheck = false; c.EnablePropsCache = false; c.EnablePvtPrefilter = ProTestOptions.PvtPrefilter; c.StringCollation = PostgresCollationFixture.Collation; c.CacheDomain = "collation-sqlite-pro"; }); if (!string.IsNullOrWhiteSpace(license)) options.WithLicense(license); }); ServiceProvider = services.BuildServiceProvider(); Redb = ServiceProvider.GetRequiredService(); try { await Redb.InitializeAsync(ensureCreated: true); } catch { await Redb.InitializeAsync(); } await Redb.SyncSchemeAsync(); await Redb.InitializeTypeRegistryAsync(); var ctx = ServiceProvider.GetRequiredService(); await FixtureWipeGuard.EnsureLooksLikeATestDatabaseAsync(ctx, nameof(SqliteProCollationFixture)); await ctx.ExecuteAsync("DELETE FROM _values"); await ctx.ExecuteAsync("DELETE FROM _objects"); } public async Task DisposeAsync() { if (ServiceProvider is IAsyncDisposable ad) await ad.DisposeAsync(); else ServiceProvider?.Dispose(); } } Path: redb/redb.Tests.Integration/Fixtures/SqliteProFixture.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/Fixtures/SqliteProFixture.cs ---- using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Core; using redb.Core.Data; using redb.Core.Models.Configuration; using redb.Core.Pro.Extensions; using redb.SQLite.Pro.Extensions; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Fixtures; /// /// SQLite Pro fixture — pure C# (ProSqlBuilder + C# materialization, no DB-side functions), /// so no native extension is needed. Uses a separate fresh DB file from the Free fixture to avoid /// cross-collection contention on the single-writer SQLite file. /// public sealed class SqliteProFixture : IAsyncLifetime { public IRedbService Redb { get; private set; } = null!; public ServiceProvider ServiceProvider { get; private set; } = null!; /// The fixture's own database file: a test of the collection that builds a host of its own uses this one. public string ConnectionString { get; private set; } = null!; public async Task InitializeAsync() { var config = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build(); // Own DB file: the Free and Pro collections run in PARALLEL (the old comment assumed // sequential and was wrong), and SQLite is a single-writer engine - two collections // hammering one file starve each other on the write lock for minutes (gate hang, // 2026-09-09: NextResult lost the non-FIFO lock race to the other collection's stream // of short transactions over and over). var cs = System.Text.RegularExpressions.Regex.Replace( config.GetConnectionString("Sqlite")!, @"Data Sources*=s*[^;]+", "Data Source=redb_tests_sqlite_pro.db"); var license = config["Redb:License"]; // The native extension path is static for the whole process, and several tests set it (every // Free fixture, and Pro tests built on Free ones). Once it is set, InitializeAsync checks the // extension's version on the connection it is given; a connection this fixture had opened while // the path was still empty carried no extension, and that check failed with "no // pvt_module_version() function" for whichever Pro test happened to run after such a test. Set // here, before the first connection, every connection of the fixture loads the extension - harmless // for Pro, which does not call it - and the order of the tests no longer matters. redb.SQLite.Data.SqliteDataSource.NativeExtensionPath ??= SqliteTestSupport.ResolveNativeExtension(); SqliteTestSupport.DeleteDbFiles(cs); ConnectionString = cs; var services = new ServiceCollection(); services.AddLogging(b => b.AddConsole().SetMinimumLevel(LogLevel.Warning)); services.AddRedbPro(options => { options.UseSqlite(cs) .Configure(c => { c.PropsSaveStrategy = PropsSaveStrategy.ChangeTracking; c.SkipHashValidationOnCacheCheck = false; c.EnablePropsCache = false; c.EnablePvtPrefilter = ProTestOptions.PvtPrefilter; }); if (!string.IsNullOrWhiteSpace(license)) options.WithLicense(license); }); ServiceProvider = services.BuildServiceProvider(); Redb = ServiceProvider.GetRequiredService(); try { await Redb.InitializeAsync(ensureCreated: true); } catch { await Redb.InitializeAsync(); } await SyncSchemes(); await Cleanup(); } private async Task SyncSchemes() { await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); } private async Task Cleanup() { var ctx = ServiceProvider.GetRequiredService(); try { await ctx.ExecuteAsync("DELETE FROM _tree"); } catch { } await ctx.ExecuteAsync("DELETE FROM _values"); await ctx.ExecuteAsync("DELETE FROM _objects"); } public async Task DisposeAsync() { if (ServiceProvider is IAsyncDisposable ad) await ad.DisposeAsync(); else ServiceProvider?.Dispose(); } } Path: redb/redb.Tests.Integration/Fixtures/SqliteTestSupport.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/Fixtures/SqliteTestSupport.cs ---- using System.Text.RegularExpressions; using redb.Core.Data; namespace redb.Tests.Integration.Fixtures; /// Shared helpers for the SQLite fixtures. internal static class SqliteTestSupport { /// /// Locate the Free native loadable extension (redbsqlite.{dll,so,dylib}) by walking up from the test /// output directory to redb.SQLite/native/build/. Returns null to fall back to the packaged locator. /// public static string? ResolveNativeExtension() { var suffix = OperatingSystem.IsWindows() ? ".dll" : OperatingSystem.IsMacOS() ? ".dylib" : ".so"; for (var dir = new DirectoryInfo(AppContext.BaseDirectory); dir != null; dir = dir.Parent) { // Public mirror layout first (redb.SQLite at the top level), then the development repository layout (redb.DB/src). var candidate = Path.Combine(dir.FullName, "redb.SQLite", "native", "build", "redbsqlite" + suffix); if (!File.Exists(candidate)) candidate = Path.Combine(dir.FullName, "redb.DB", "src", "redb.SQLite", "native", "build", "redbsqlite" + suffix); if (File.Exists(candidate)) return candidate; } return null; } /// /// Delete the SQLite DB file (and its -wal/-shm siblings) named in the connection string, so each /// run starts on a freshly created schema (datetimes are REAL Julian; an old TEXT-schema file is /// NOT auto-migrated). /// public static void DeleteDbFiles(string connectionString) { RegisterSweepAtExit(); var m = Regex.Match(connectionString, @"Data Source\s*=\s*([^;]+)", RegexOptions.IgnoreCase); if (!m.Success) return; var file = m.Groups[1].Value.Trim(); foreach (var f in new[] { file, file + "-wal", file + "-shm" }) { try { if (File.Exists(f)) File.Delete(f); } catch { /* locked from a prior run — ignore */ } } // The id cache is a process-wide static in RedbKeyGeneratorBase, holding up to 10000 ids already // reserved against the file we have just deleted. The replacement file starts its sqlite_sequence // at zero, so the surviving cache and the fresh sequence hand out overlapping ids and inserts die // with "UNIQUE constraint failed: _values._id". Both SQLite fixtures share one file inside one // process, so the second one to start is the one that trips over it, which is why this never // reproduces when a single test class is run alone. RedbKeyGeneratorBase.ClearAllCaches(); } private static int _sweepRegistered; /// /// The SQLite files the tests create (relative Data Source=redb_tests_*.db, redb_diag_*.db) are /// deleted before a test uses them but were never deleted after, and the ones named per test by a GUID piled /// up in the output directory, a few hundred per run. They are swept when the process exits, after the /// connection pools are closed (a pooled connection keeps the file open); the sweep goes by name, so it also /// takes what a killed run left. A file still open is skipped. /// /// Registered from , which every SQLite fixture and test calls first, and not from a /// module initializer: a test loads a copy of this assembly into a collectible context, the initializer ran in /// that copy too, and its handler on the process-wide event kept the context alive. Nor at start: the first /// call falls between the starts of collections running in parallel, and a sweep then could take a file a /// neighbour had just created. /// /// private static void RegisterSweepAtExit() { if (Interlocked.Exchange(ref _sweepRegistered, 1) == 1) return; AppDomain.CurrentDomain.ProcessExit += (_, _) => { Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools(); SweepTestDatabases(); }; } private static void SweepTestDatabases() { // A relative Data Source resolves against the current directory, which the runner sets to the output // directory; both are swept in case they differ. var directories = new[] { AppContext.BaseDirectory, Environment.CurrentDirectory } .Select(Path.GetFullPath) .Distinct(StringComparer.OrdinalIgnoreCase); foreach (var directory in directories) { foreach (var pattern in new[] { "redb_tests_*.db*", "redb_diag_*.db*" }) { string[] files; try { files = Directory.GetFiles(directory, pattern); } catch (IOException) { continue; } catch (UnauthorizedAccessException) { continue; } foreach (var file in files) { if (!(file.EndsWith(".db", StringComparison.OrdinalIgnoreCase) || file.EndsWith(".db-wal", StringComparison.OrdinalIgnoreCase) || file.EndsWith(".db-shm", StringComparison.OrdinalIgnoreCase))) continue; try { File.Delete(file); } catch (IOException) { /* open in another process or connection */ } catch (UnauthorizedAccessException) { } } } } } } Path: redb/redb.Tests.Integration/GlobalUsings.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/GlobalUsings.cs ---- global using Xunit; global using AwesomeAssertions; Path: redb/redb.Tests.Integration/Helpers/CommandCounter.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/Helpers/CommandCounter.cs ---- using System.Diagnostics; using redb.Core.Diagnostics; namespace redb.Tests.Integration.Helpers; /// /// Counts the database commands an action runs: the spans of the redb.Core ActivitySource (one per command) under a /// parent span of the caller only, so commands of tests running in parallel are not counted. /// public static class CommandCounter { private const string ProbeName = "redb.Tests.CommandCount"; private static readonly ActivitySource Probe = new(ProbeName); /// The database commands runs. public static Task CountAsync(Func action) => CountAsync(action, excluded: null); /// /// The commands runs other than scalar side commands (db.operation = scalar): its /// data statements, whatever the provider reads them with, and any metadata it reads. The PostgreSQL statistics guard /// is such a side command: until the tables have planner statistics it checks them and sets enable_nestloop around a /// statement with scalar commands, on a recheck interval, so whether a counted call meets it depends on timing. /// public static Task CountWithoutScalarsAsync(Func action) => CountAsync(action, excluded: RedbTelemetry.Scalar); private static async Task CountAsync(Func action, string? excluded) { var spans = new List(); using var listener = new ActivityListener { ShouldListenTo = s => s.Name == RedbActivitySource.SourceName || s.Name == ProbeName, Sample = (ref ActivityCreationOptions _) => ActivitySamplingResult.AllDataAndRecorded, ActivityStopped = a => { lock (spans) spans.Add(a); }, }; ActivitySource.AddActivityListener(listener); ActivityTraceId trace; using (var parent = Probe.StartActivity("count")!) { trace = parent.TraceId; await action(); } lock (spans) return spans.Count(a => a.Source.Name == RedbActivitySource.SourceName && a.TraceId == trace && (excluded == null || (a.GetTagItem("db.operation") as string) != excluded)); } } Path: redb/redb.Tests.Integration/Helpers/TestDataFactory.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/Helpers/TestDataFactory.cs ---- using redb.Core; using redb.Core.Models.Entities; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Helpers; public static class TestDataFactory { private static readonly string[] Positions = ["Developer", "Senior Developer", "Manager", "Analyst", "Tester"]; private static readonly string[] Departments = ["Engineering", "Design", "Sales", "Marketing", "Support"]; private static readonly string[] Cities = ["New York", "London", "Berlin", "Tokyo", "Sydney"]; private static readonly string[] Streets = ["Main St", "Oak Ave", "Pine Rd", "Elm St", "Cedar Blvd"]; private static readonly string[][] SkillSets = [ ["C#", "SQL", "Azure"], ["JavaScript", "React", "Node.js"], ["Python", "Django", "PostgreSQL"], ["Java", "Spring", "Docker"], ["TypeScript", "Angular", "AWS"] ]; public static RedbObject CreateSimple(string title = "Test Item", decimal price = 99.99m) => new() { name = title, Props = new SimpleProps { Title = title, Count = 10, Price = price, CreatedAt = new DateTime(2025, 6, 15, 10, 30, 0, DateTimeKind.Utc), IsActive = true, Code = Guid.NewGuid(), Description = "Test description" } }; public static RedbObject CreateEmployee( int index, string? firstName = null, string? position = null, decimal? salary = null, string? department = null, string? city = null) { var pos = position ?? Positions[index % Positions.Length]; var dept = department ?? Departments[index % Departments.Length]; var c = city ?? Cities[index % Cities.Length]; var sal = salary ?? 50000m + index * 5000m; var fn = firstName ?? $"Employee{index:D3}"; return new RedbObject { name = $"{fn} {pos}", Props = new EmployeeProps { FirstName = fn, LastName = $"Last{index:D3}", Age = 25 + (index % 30), HireDate = new DateTime(2020, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMonths(index), Position = pos, Salary = sal, Department = dept, EmployeeCode = index % 3 == 0 ? null : $"EMP-{index:D4}", IsRemote = index % 2 == 0, Rating = index % 4 == 0 ? null : 3.0 + (index % 5) * 0.5, Skills = SkillSets[index % SkillSets.Length], SkillLevels = [5 - (index % 3), 4, 3 + (index % 2)], HomeAddress = new TestAddress { City = c, Street = Streets[index % Streets.Length], Building = new TestBuildingInfo { Floor = 1 + (index % 20), Name = $"Building {index % 5 + 1}", Amenities = ["Parking", "Gym"] } }, WorkAddress = new TestAddress { City = c, Street = "Office Park 1" }, Contacts = [ new TestContact { Type = "email", Value = $"emp{index}@test.com", IsVerified = true, Metadata = [new TestContactDetail { Label = "work", Value = "primary" }] }, new TestContact { Type = "phone", Value = $"+1-555-{index:D4}", IsVerified = false } ], PhoneDirectory = new Dictionary { ["desk"] = $"555-{1000 + index}", ["mobile"] = $"555-{2000 + index}" }, OfficeLocations = new Dictionary { ["HQ"] = new() { City = "New York", Street = "5th Ave" }, ["Branch"] = new() { City = c, Street = "Local St" } }, BonusByYear = new Dictionary { [2023] = 5000m + index * 100m, [2024] = 6000m + index * 150m }, DepartmentHistory = new Dictionary { [dept] = new() { Name = dept, HeadCount = 10 + index, Projects = [$"Proj-{index}"], Leaders = [new TestTag { Name = "Lead", Priority = 1 }] } }, PerformanceReviews = new Dictionary<(int Year, string Quarter), string> { [(2024, "Q1")] = index % 3 == 0 ? "Excellent" : "Good", [(2024, "Q2")] = "Meets expectations" } } }; } public static async Task> SeedEmployees(IRedbService redb, int count = 20) { var employees = Enumerable.Range(0, count).Select(i => CreateEmployee(i)).ToList(); return await redb.SaveAsync(employees); } public static TreeRedbObject CreateTreeNode( string name, string code, decimal budget = 100000m) => new() { name = name, Props = new TreeNodeProps { Name = name, Description = $"{name} department", IsActive = true, Budget = budget, Code = code } }; } Path: redb/redb.Tests.Integration/Models/AllTextProbeModels.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/Models/AllTextProbeModels.cs ---- using redb.Core.Attributes; namespace redb.Tests.Integration.Models; /// /// A scheme only PostgresProPvtPrefilterEquivalenceTests.AllOfATextField_ProbeThenCounts_SameAnswers saves into: more objects /// than the counterexample probe of AllAsync reads (1 000), so its counts decide. /// [RedbScheme("AllTextProbe")] public class AllTextProbeProps { public string Name { get; set; } = string.Empty; public string? Note { get; set; } } Path: redb/redb.Tests.Integration/Models/ArrayAnyModels.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/Models/ArrayAnyModels.cs ---- using redb.Core.Attributes; namespace redb.Tests.Integration.Models; /// A list of texts next to the arrays of , for Any() over a List<T>. [RedbScheme("TestArrayAny")] public class ArrayAnyProps { public string Marker { get; set; } = string.Empty; public List? Labels { get; set; } public List? Numbers { get; set; } } Path: redb/redb.Tests.Integration/Models/ArrayGroupModels.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/Models/ArrayGroupModels.cs ---- using redb.Core.Attributes; using redb.Core.Models.Entities; namespace redb.Tests.Integration.Models; /// /// GroupByArray over arrays of every simple value column, over an array of classes whose element holds a class /// and over elements with a missing key. Each test writes its own objects under a fresh and /// reads them back by it, so objects other tests leave in the shared database do not count. /// [RedbScheme("TestArrayValues")] public class ArrayValuesProps { public string Marker { get; set; } = string.Empty; public string[]? Words { get; set; } public long[]? Longs { get; set; } public double[]? Doubles { get; set; } public decimal[]? Decimals { get; set; } public bool[]? Flags { get; set; } public DateTime[]? Dates { get; set; } public Guid[]? Ids { get; set; } public ArrayItem[]? Items { get; set; } } public class ArrayItem { /// Null on some elements: the group of the null key. public string? Kind { get; set; } public int Size { get; set; } public bool Active { get; set; } public ArrayItemPlace? Place { get; set; } } public class ArrayItemPlace { public string City { get; set; } = string.Empty; } /// /// Arrays GroupByArray refuses by name: list items and object references. Never saved; the refusal comes first. /// [RedbScheme("TestArrayRefusedElements")] public class ArrayRefusedElementsProps { public List? Roles { get; set; } public RedbObject[]? Links { get; set; } } Path: redb/redb.Tests.Integration/Models/ArrayOfClassesAnyModels.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/Models/ArrayOfClassesAnyModels.cs ---- using redb.Core.Attributes; namespace redb.Tests.Integration.Models; /// An array and a list of classes, for Any() with a condition over the fields of an element. [RedbScheme("TestArrayOfClassesAny")] public class OrderSheetProps { public string Tag { get; set; } = ""; public int Number { get; set; } public OrderLine[]? Lines { get; set; } public List? Extra { get; set; } } public class OrderLine { public string? Kind { get; set; } public bool? Active { get; set; } public int Qty { get; set; } public decimal? Price { get; set; } public DateTime? Due { get; set; } public TimeSpan? Wait { get; set; } } Path: redb/redb.Tests.Integration/Models/ByteArrayLegacyModels.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/Models/ByteArrayLegacyModels.cs ---- using redb.Core.Attributes; namespace redb.Tests.Integration.Models; // ─────────────────────────────────────────────── // Models for the byte[] storage conversion (V4, work Б1): a byte[] at the root and one nested in // a class, both of which the pre-V4 sync classified as Array-of-Byte. Synced by the tests. // ─────────────────────────────────────────────── [RedbScheme(Name = "ByteHolder")] public class ByteHolderProps { public byte[]? Root { get; set; } public ByteAttachment? File { get; set; } } public class ByteAttachment { public string? Name { get; set; } public byte[]? Data { get; set; } } Path: redb/redb.Tests.Integration/Models/CollectionGroupKeyModels.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/Models/CollectionGroupKeyModels.cs ---- using redb.Core.Attributes; namespace redb.Tests.Integration.Models; /// A list field and the number of the group its list belongs to, in a scheme of its own. [RedbScheme("TestCollectionGroupKey")] public class CollectionGroupKeyProps { public string? Label { get; set; } public int Mark { get; set; } public List? Tags { get; set; } } /// A dictionary field and the number of the group its dictionary belongs to, in a scheme of its own. [RedbScheme("TestCollectionGroupKeyDict")] public class CollectionGroupKeyDictProps { public string? Label { get; set; } public int Mark { get; set; } public Dictionary? Codes { get; set; } } Path: redb/redb.Tests.Integration/Models/CollectionKindModels.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/Models/CollectionKindModels.cs ---- using redb.Core.Attributes; namespace redb.Tests.Integration.Models; // A property whose collection kind changes between two builds of one Props class (CollectionKindChangeTestsBase). As in // OlderModelModels, the first build saves under its own scheme name and the test renames that scheme to the second's. [RedbScheme("Kind change: single value, before", Name = "kind_single_before")] public class KindSingleBeforeProps { public string Tag { get; set; } = ""; public int Level { get; set; } } [RedbScheme("Kind change: single value to array", Name = "kind_single", Version = 1)] public class KindSingleToArrayProps { public string Tag { get; set; } = ""; public int[]? Level { get; set; } } [RedbScheme("Kind change: array, before", Name = "kind_array_before")] public class KindArrayBeforeProps { public string Tag { get; set; } = ""; public int[]? Items { get; set; } } [RedbScheme("Kind change: array to single value", Name = "kind_array", Version = 1)] public class KindArrayToSingleProps { public string Tag { get; set; } = ""; public int Items { get; set; } } [RedbScheme("Kind change: array, before (to dictionary)", Name = "kind_array_dict_before")] public class KindArrayDictBeforeProps { public string Tag { get; set; } = ""; public int[]? Items { get; set; } } [RedbScheme("Kind change: array to dictionary", Name = "kind_array_dict", Version = 1)] public class KindArrayToDictionaryProps { public string Tag { get; set; } = ""; public Dictionary? Items { get; set; } } [RedbScheme("Kind change: dictionary, before", Name = "kind_dict_before")] public class KindDictionaryBeforeProps { public string Tag { get; set; } = ""; public Dictionary? Items { get; set; } } [RedbScheme("Kind change: dictionary to array", Name = "kind_dict", Version = 1)] public class KindDictionaryToArrayProps { public string Tag { get; set; } = ""; public int[]? Items { get; set; } } Path: redb/redb.Tests.Integration/Models/ComputedComparisonModels.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/Models/ComputedComparisonModels.cs ---- using redb.Core.Attributes; namespace redb.Tests.Integration.Models; /// Fields to compare with each other and with values computed from them. [RedbScheme("TestComputedComparison")] public class ComputedComparisonProps { public string Tag { get; set; } = string.Empty; public string First { get; set; } = string.Empty; public string Last { get; set; } = string.Empty; public string Full { get; set; } = string.Empty; public int A { get; set; } public int B { get; set; } public decimal Price { get; set; } public decimal Limit { get; set; } } Path: redb/redb.Tests.Integration/Models/ConcurrentWriterModels.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/Models/ConcurrentWriterModels.cs ---- using System; using redb.Core.Attributes; namespace redb.Tests.Integration.Models; /// /// A row written by many concurrent writers at once: one new object with a few root values, the shape of a key ring /// element or a replay reservation. Synced by the tests that use it. /// [RedbScheme(Name = "ConcurrentWriterRow")] public class ConcurrentWriterRowProps { public string? Tag { get; set; } public string? Key { get; set; } public string? Payload { get; set; } public DateTimeOffset? WrittenAt { get; set; } } Path: redb/redb.Tests.Integration/Models/ContainsWalkModels.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/Models/ContainsWalkModels.cs ---- using redb.Core.Attributes; namespace redb.Tests.Integration.Models; /// /// An array of text read by a page in object order (MsSqlProContainsWalkTests): SQL Server Pro walks the array's rows /// before the streams answer. /// [RedbScheme("TestContainsWalk")] public class ContainsWalkProps { public int Age { get; set; } public string? Department { get; set; } public string[]? Skills { get; set; } } Path: redb/redb.Tests.Integration/Models/CtProbeModels.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/Models/CtProbeModels.cs ---- using System; using System.Collections.Generic; using redb.Core.Attributes; using redb.Core.Models.Entities; namespace redb.Tests.Integration.Models; /// /// Probe scheme for the ChangeTracking save-invariants suite (ревью 2026-09-03, волна 1.2 + Ш1/Ш2). /// Synced by the tests that use it, not by the fixtures. /// [RedbScheme(Name = "CtProbe")] public class CtProbeProps { public string? Label { get; set; } public long[]? Longs { get; set; } public decimal[]? Decimals { get; set; } public string?[]? Tags { get; set; } public Dictionary? Dict { get; set; } public Dictionary<(int Year, string Quarter), string>? TupleDict { get; set; } public List? Items { get; set; } public List>? Refs { get; set; } public Dictionary>? RefDict { get; set; } public RedbListItem? Status { get; set; } public List? Roles { get; set; } } public class CtProbeItem { public string? Name { get; set; } public decimal Price { get; set; } /// Ш4: собственный массив внутри класса-элемента массива (коллекция в коллекции). public long[]? Codes { get; set; } /// Ш4: собственный словарь внутри класса-элемента массива. public Dictionary? Meta { get; set; } } /// Отдельная схема-ребёнок для пинов референс-коллекций (Ш2). [RedbScheme(Name = "CtProbeChild")] public class CtProbeChildProps { public string? Tag { get; set; } } Path: redb/redb.Tests.Integration/Models/DeepChainModels.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/Models/DeepChainModels.cs ---- using redb.Core.Attributes; namespace redb.Tests.Integration.Models; /// An element of , for GroupByArray over a deep tree. public class DeepChainMark { public string Kind { get; set; } = string.Empty; } /// A node of a chain deeper than 100 levels (MsSqlProDeepTreeTests), on a scheme of its own. [RedbScheme("TestDeepChain")] public class DeepChainProps { public string Tag { get; set; } = string.Empty; public int Index { get; set; } public string Bucket { get; set; } = string.Empty; public DeepChainMark[]? Marks { get; set; } } Path: redb/redb.Tests.Integration/Models/DictionaryEntryLeadsModels.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/Models/DictionaryEntryLeadsModels.cs ---- using redb.Core.Attributes; namespace redb.Tests.Integration.Models; /// /// Dictionaries whose entries are filtered by their value: a tuple key with a text value, a text key with a number, /// and a text key with a class. Every other key holds the same values, so an answer that lost the key shows at once. /// [RedbScheme("dict_entry_leads")] public class DictionaryEntryLeadsProps { public long Rank { get; set; } public string? Tag { get; set; } public Dictionary<(int Year, string Quarter), string>? Reviews { get; set; } public Dictionary? Scores { get; set; } public Dictionary? Places { get; set; } } public class DictionaryEntryPlace { public string City { get; set; } = ""; public long Floor { get; set; } } Path: redb/redb.Tests.Integration/Models/DictionaryInterfaceModels.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/Models/DictionaryInterfaceModels.cs ---- using redb.Core.Attributes; namespace redb.Tests.Integration.Models; // ─────────────────────────────────────────────── // A dictionary field declared through the interface (DataLoss p.3) // ─────────────────────────────────────────────── [RedbScheme("DictionaryInterfaceProbe")] public class DictionaryInterfaceProbeProps { public string? Label { get; set; } /// /// Declared as the interface on purpose. The scheme builder accepts IDictionary<K,V>, so /// the structure becomes a dictionary, and the RUNTIME value decides whether the save path can /// enumerate it into rows. /// public IDictionary? Tags { get; set; } } Path: redb/redb.Tests.Integration/Models/DictionaryKeyModels.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/Models/DictionaryKeyModels.cs ---- using redb.Core.Attributes; namespace redb.Tests.Integration.Models; /// The value class of the dictionaries of . public class KeyedEntry { public string Name { get; set; } = string.Empty; public int Rank { get; set; } } /// Dictionaries whose value is a class, one per key type, for a filter on a field of an entry. [RedbScheme("TestDictionaryKeys")] public class DictionaryKeyProps { public string Marker { get; set; } = string.Empty; public Dictionary? ByText { get; set; } public Dictionary? ByNumber { get; set; } public Dictionary<(int Year, string Quarter), KeyedEntry>? ByTuple { get; set; } public Dictionary? ByFlag { get; set; } public Dictionary? ByDate { get; set; } public Dictionary? ByRatio { get; set; } } Path: redb/redb.Tests.Integration/Models/DictionaryOrderModels.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/Models/DictionaryOrderModels.cs ---- using redb.Core.Attributes; namespace redb.Tests.Integration.Models; /// Dictionaries at the top level and inside the elements of an array of classes, for the order of their entries. [RedbScheme("TestDictionaryOrder")] public class DictionaryOrderProps { public string Tag { get; set; } = ""; public Dictionary? Top { get; set; } public Dictionary? Numbered { get; set; } public DictionaryOrderRow[]? Rows { get; set; } } public class DictionaryOrderRow { public string Name { get; set; } = ""; public Dictionary? Labels { get; set; } } Path: redb/redb.Tests.Integration/Models/ElementFoldOrderModels.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/Models/ElementFoldOrderModels.cs ---- using redb.Core.Attributes; namespace redb.Tests.Integration.Models; /// A list field and a label, in a scheme of its own. [RedbScheme("TestElementFoldOrder")] public class ElementFoldOrderProps { public string? Label { get; set; } public List? Tags { get; set; } } /// A dictionary field, in a scheme of its own. [RedbScheme("TestElementFoldOrderDict")] public class ElementFoldOrderDictProps { public Dictionary? Codes { get; set; } } Path: redb/redb.Tests.Integration/Models/ElementIndexModels.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/Models/ElementIndexModels.cs ---- using redb.Core.Attributes; using redb.Core.Models.Entities; namespace redb.Tests.Integration.Models; /// /// Arrays and lists read by index in a filter. The object's own Name and Rank share their names with the fields of /// the elements, so a path that lost its element would compare the object's field instead. /// [RedbScheme("TestElementIndex")] public class ElementIndexProps { public string Marker { get; set; } = string.Empty; public string Name { get; set; } = string.Empty; public int Rank { get; set; } public int[]? Levels { get; set; } public List? Tags { get; set; } public ElementIndexItem[]? Items { get; set; } public List? Parts { get; set; } public List? Statuses { get; set; } } public class ElementIndexItem { public string Name { get; set; } = string.Empty; public int Rank { get; set; } public int? Score { get; set; } public ElementIndexInner? Inner { get; set; } public int[]? Marks { get; set; } } public class ElementIndexInner { public string Name { get; set; } = string.Empty; } Path: redb/redb.Tests.Integration/Models/EnumComparisonModels.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/Models/EnumComparisonModels.cs ---- using redb.Core.Attributes; namespace redb.Tests.Integration.Models; public enum ComparisonShade { Red, Green, Blue } /// /// An enum field, nullable and not, each with a text twin holding the name the enum is stored by: a filter on the enum /// must return the ids the same filter on the twin returns. /// [RedbScheme("TestEnumComparison")] public class EnumComparisonProps { public string Tag { get; set; } = string.Empty; public ComparisonShade? Maybe { get; set; } public string? MaybeName { get; set; } public ComparisonShade Always { get; set; } public string AlwaysName { get; set; } = string.Empty; } Path: redb/redb.Tests.Integration/Models/EnumKeyModels.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/Models/EnumKeyModels.cs ---- using redb.Core.Attributes; namespace redb.Tests.Integration.Models; /// An enum key with explicit values out of name order. public enum KeyShade { Red = 3, Green = 1, Blue = 2 } /// A flags enum key: a combination is stored as one key. [Flags] public enum KeyAccess { None = 0, Read = 1, Write = 2, Admin = 4 } /// Dictionaries keyed by an enum, a flags enum and a nullable enum. [RedbScheme("TestEnumKeys")] public class EnumKeyProps { public string Marker { get; set; } = string.Empty; public Dictionary? ByShade { get; set; } public Dictionary? EntryByShade { get; set; } public Dictionary? ByAccess { get; set; } public Dictionary? ByMaybeShade { get; set; } } Path: redb/redb.Tests.Integration/Models/FieldPathModels.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/Models/FieldPathModels.cs ---- using redb.Core.Attributes; namespace redb.Tests.Integration.Models; /// /// A class whose own field and the field of its array elements share a name: a filter path that lost its array part /// would read the field of the object instead of the field of the element. /// [RedbScheme("TestFieldPath")] public class FieldPathProps { public string Name { get; set; } = string.Empty; public int Rank { get; set; } public FieldPathItem[]? Items { get; set; } public List? Parts { get; set; } public Dictionary? ByKey { get; set; } public FieldPathItem? Main { get; set; } public Dictionary? Scores { get; set; } } public class FieldPathItem { public string Name { get; set; } = string.Empty; public int Rank { get; set; } public int? Score { get; set; } } Path: redb/redb.Tests.Integration/Models/GraphModels.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/Models/GraphModels.cs ---- using redb.Core.Attributes; using redb.Core.Models.Entities; namespace redb.Tests.Integration.Models; /// /// A node with two references to nodes of the same scheme: enough to build a graph that is not a tree - two parents /// sharing one target - which is what the save's hashing and collection must handle. /// [RedbScheme] public class GraphNodeProps { public string Title { get; set; } = string.Empty; public RedbObject? Left { get; set; } public RedbObject? Right { get; set; } } Path: redb/redb.Tests.Integration/Models/HashCanonProbeModels.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/Models/HashCanonProbeModels.cs ---- using System; using System.Collections.Generic; using redb.Core.Attributes; namespace redb.Tests.Integration.Models; /// /// Probe scheme for the hash canon collisions: values whose canon strings would coincide if the canon did not escape /// its separators. Synced by the tests that use it, not by the fixtures. /// [RedbScheme(Name = "HashCanonProbe")] public class HashCanonProbeProps { public string? A { get; set; } public string? B { get; set; } public string? Label { get; set; } public List? Tags { get; set; } public Dictionary? Dict { get; set; } public HashCanonPair? Inner { get; set; } public List? Items { get; set; } } /// A class value with two strings: a nested class and an element of a class collection. public class HashCanonPair { public string? A { get; set; } public string? B { get; set; } } /// /// A dictionary key class with value equality and no ToString of its own: its ToString is the type name for every /// key. /// public class HashCanonKey : IEquatable { public string? Code { get; set; } public int Rank { get; set; } public bool Equals(HashCanonKey? other) => other is not null && Code == other.Code && Rank == other.Rank; public override bool Equals(object? obj) => Equals(obj as HashCanonKey); public override int GetHashCode() => HashCode.Combine(Code, Rank); } /// Probe scheme with a dictionary keyed by a class. [RedbScheme(Name = "HashCanonClassKeyProbe")] public class HashCanonClassKeyProps { public string? Label { get; set; } public Dictionary? ByKey { get; set; } } /// Probe scheme with a dictionary keyed by a value tuple of culture-sensitive members. [RedbScheme(Name = "HashCanonTupleKeyProbe")] public class HashCanonTupleKeyProps { public string? Label { get; set; } public Dictionary<(double Rate, DateTime At), string>? ByTuple { get; set; } } Path: redb/redb.Tests.Integration/Models/HeaderProbeModels.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/Models/HeaderProbeModels.cs ---- using redb.Core.Attributes; namespace redb.Tests.Integration.Models; /// /// Props for the props-cache header-freshness pins: a tiny scheme whose objects get their /// HEADER (name, note, value_unique) changed behind the cache's back by "another node". /// [RedbScheme(Name = "HeaderProbe")] public class HeaderProbeProps { public string? Title { get; set; } } Path: redb/redb.Tests.Integration/Models/IgnoredGetterProbeModels.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/Models/IgnoredGetterProbeModels.cs ---- using System.Collections.Concurrent; using redb.Core.Attributes; using redb.Core.Models.Entities; namespace redb.Tests.Integration.Models; /// /// Props with references and two [RedbIgnore] properties whose getters count their reads per object label, so /// suites running in parallel on several hosts never share a count. One property has a setter: the Pro reference /// substitution walks read-write properties only. /// public class IgnoredGetterProbeProps { public static readonly ConcurrentDictionary TechnicalReads = new(); private string? _settable; public string? Label { get; set; } public List>? Refs { get; set; } [RedbIgnore] public string Technical { get { CountRead(); return "technical"; } } [RedbIgnore] public string? TechnicalSettable { get { CountRead(); return _settable; } set => _settable = value; } private void CountRead() => TechnicalReads.AddOrUpdate(Label ?? "", 1, (_, n) => n + 1); } Path: redb/redb.Tests.Integration/Models/IndexDuplicateProbeModels.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/Models/IndexDuplicateProbeModels.cs ---- using redb.Core.Attributes; namespace redb.Tests.Integration.Models; /// /// A scheme only IndexRepairTestsBase.DuplicateRows_KeepTheIndexUnbuilt_AreListed_AndNothingIsDeleted saves into: one text /// field, stored as one root row whose copy the test writes by SQL. /// [RedbScheme("index_duplicate_probe")] public class IndexDuplicateProbeProps { public string Name { get; set; } = string.Empty; } Path: redb/redb.Tests.Integration/Models/InterfaceCollectionModels.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/Models/InterfaceCollectionModels.cs ---- using System.Collections.Generic; namespace redb.Tests.Integration.Models; // A list declared as IEnumerable, ICollection or IList and a dictionary declared as IDictionary, with a // numeric element narrower than the stored one (int, short, byte, float, decimal), a nullable element, and a class // element. One class per shape; no [RedbScheme], the tests sync them. public class IfaceIEnumerableOfIntProps { public IEnumerable? Value { get; set; } } public class IfaceIEnumerableOfShortProps { public IEnumerable? Value { get; set; } } public class IfaceIEnumerableOfByteProps { public IEnumerable? Value { get; set; } } public class IfaceIEnumerableOfFloatProps { public IEnumerable? Value { get; set; } } public class IfaceIEnumerableOfDecimalProps { public IEnumerable? Value { get; set; } } public class IfaceICollectionOfIntProps { public ICollection? Value { get; set; } } public class IfaceICollectionOfShortProps { public ICollection? Value { get; set; } } public class IfaceICollectionOfByteProps { public ICollection? Value { get; set; } } public class IfaceICollectionOfFloatProps { public ICollection? Value { get; set; } } public class IfaceICollectionOfDecimalProps { public ICollection? Value { get; set; } } public class IfaceIListOfIntProps { public IList? Value { get; set; } } public class IfaceIListOfShortProps { public IList? Value { get; set; } } public class IfaceIListOfByteProps { public IList? Value { get; set; } } public class IfaceIListOfFloatProps { public IList? Value { get; set; } } public class IfaceIListOfDecimalProps { public IList? Value { get; set; } } public class IfaceIDictionaryOfIntProps { public IDictionary? Value { get; set; } } public class IfaceIDictionaryOfShortProps { public IDictionary? Value { get; set; } } public class IfaceIDictionaryOfByteProps { public IDictionary? Value { get; set; } } public class IfaceIDictionaryOfFloatProps { public IDictionary? Value { get; set; } } public class IfaceIDictionaryOfDecimalProps { public IDictionary? Value { get; set; } } public class IfaceIListOfNullableIntProps { public IList? Value { get; set; } } public class IfaceItem { public string? Name { get; set; } public int Count { get; set; } } public class IfaceIListOfClassProps { public IList? Value { get; set; } } public class IfaceICollectionOfClassProps { public ICollection? Value { get; set; } } public class IfaceIEnumerableOfClassProps { public IEnumerable? Value { get; set; } } public class IfaceIListOfReferenceProps { public IList>? Value { get; set; } } public class IfaceIEnumerableOfReferenceProps { public IEnumerable>? Value { get; set; } } Path: redb/redb.Tests.Integration/Models/KeyDrawModels.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/Models/KeyDrawModels.cs ---- using redb.Core.Attributes; namespace redb.Tests.Integration.Models; /// An object with scalars, an array of simple values, an array of classes and a nested class. [RedbScheme("Key draw", Name = "test_key_draw")] public class KeyDrawProps { public string Tag { get; set; } = ""; public int Score { get; set; } public int[]? Levels { get; set; } public List? Lines { get; set; } public KeyDrawLine? Main { get; set; } } public class KeyDrawLine { public string Name { get; set; } = ""; public int Rank { get; set; } } Path: redb/redb.Tests.Integration/Models/KeywordNameModels.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/Models/KeywordNameModels.cs ---- using redb.Core.Attributes; namespace redb.Tests.Integration.Models; /// /// Property names that differ from a C# keyword only by case (ref, default, event, string, object). C# keywords are /// case-sensitive, so these are ordinary property names. PostgreSQL refused them at scheme sync ("Field name is a C# /// reserved word"), which compared the name in lower case. Every [RedbScheme] type syncs when a fixture starts, so the /// old refusal stopped the whole PostgreSQL suite. /// [RedbScheme("keyword_names")] public class KeywordNamesProps { public long Ref { get; set; } public string Default { get; set; } = ""; public DateTime Event { get; set; } public string? String { get; set; } public decimal Object { get; set; } } Path: redb/redb.Tests.Integration/Models/LazyOptionModels.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/Models/LazyOptionModels.cs ---- using redb.Core.Attributes; using redb.Core.Models.Entities; namespace redb.Tests.Integration.Models; /// /// V4 Л2 (LAZY_REFERENCES_PLAN §3.2–3.3): the `virtual` marker under test. and /// are virtual references — with the option on the builders emit stubs for /// them regardless of depth; is deliberately NOT virtual and always loads /// eagerly. Self-referencing, so one scheme covers chains and collections. /// [RedbScheme] public class LazyOptionNodeProps { public string? Label { get; set; } /// Virtual reference — lazy when the option is on. public virtual RedbObject? Next { get; set; } /// NOT virtual — always eager, whatever the option says. public RedbObject? Plain { get; set; } /// Virtual collection of references — a list of stubs when the option is on. public virtual List>? Children { get; set; } } Path: redb/redb.Tests.Integration/Models/LazyReferenceModels.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/Models/LazyReferenceModels.cs ---- using redb.Core.Attributes; using redb.Core.Models.Entities; namespace redb.Tests.Integration.Models; /// /// Self-referencing node for the V4 Л1 lazy-reference scenarios (LAZY_REFERENCES_PLAN §6): /// one scheme gives chains of any depth () and collections of references /// (). The [RedbScheme] marker matters: the Pro stub materializer resolves /// the CLR type for a nested reference through the attribute-driven registry. /// [RedbScheme] public class LazyNodeProps { public string? Label { get; set; } /// A single reference — the stub scenario. public RedbObject? Next { get; set; } /// A collection of references — the list-of-stubs scenario. public List>? Children { get; set; } /// /// A nested class: depth counts reference hops, never class nesting, so a class field is loaded /// completely at any depth — by the SQL builders and the Pro materializer alike. /// public LazyNodeMeta? Meta { get; set; } } public class LazyNodeMeta { public string? Tag { get; set; } } Path: redb/redb.Tests.Integration/Models/LikeEscapingModels.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/Models/LikeEscapingModels.cs ---- using redb.Core.Attributes; namespace redb.Tests.Integration.Models; /// /// Probe scheme for the LIKE-metacharacter escaping suite (BR-7, 2026-09-02). /// Synced by the tests that use it, not by the fixtures. /// [RedbScheme(Name = "LikeProbe")] public class LikeProbeProps { public string? S { get; set; } } Path: redb/redb.Tests.Integration/Models/MigrationLiteralProbeModels.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/Models/MigrationLiteralProbeModels.cs ---- using redb.Core.Attributes; using redb.Core.Pro.Migration; namespace redb.Tests.Integration.Models; public enum MigrationLiteralKind { First, Second, } /// /// One field per kind of value a migration writes as a SQL literal: MigrationTestsBase fills each by DefaultValue and /// by a constant in a ComputedFrom lambda, then reads it back and filters on it as a saved value. /// [RedbScheme("Migrations: literal probe", Name = "migration_literal_probe")] public class MigrationLiteralProbeProps { public string? Text { get; set; } public double? Real { get; set; } public decimal? Money { get; set; } public long? Count { get; set; } public Guid? Key { get; set; } public DateTime? At { get; set; } public DateTimeOffset? Seen { get; set; } public DateOnly? Day { get; set; } public TimeOnly? Clock { get; set; } public TimeSpan? Span { get; set; } public MigrationLiteralKind? Kind { get; set; } public byte[]? Blob { get; set; } } /// The values of the literal probe; the negative numbers catch a culture's minus sign. public static class MigrationLiteralValues { public const string Text = "it's C:\\path\\ 'quoted' \\' end Привет"; public const double Real = -1234.5; public const decimal Money = -9876.54m; public const long Count = -42; public static readonly Guid Key = new("8f14e45f-ceea-467a-9a36-dedd4bea2543"); public static readonly DateTime At = new(2026, 5, 17, 10, 30, 15, DateTimeKind.Utc); public static readonly DateTimeOffset Seen = new(2026, 5, 17, 13, 30, 15, TimeSpan.FromHours(3)); public static readonly DateOnly Day = new(2026, 5, 17); public static readonly TimeOnly Clock = new(10, 30, 15); public static readonly TimeSpan Span = new(1, 2, 3, 4); public const MigrationLiteralKind Kind = MigrationLiteralKind.Second; public static readonly byte[] Blob = [0x00, 0xFF, 0x10, 0x27]; /// The kind the two migrations below act on; set by the test before it migrates. public static readonly AsyncLocal Current = new(); } /// DefaultValue of the field named by . public class MigrationLiteralDefaultMigration : IRedbMigration { public void Configure(IMigrationBuilder builder) { switch (MigrationLiteralValues.Current.Value) { case nameof(MigrationLiteralProbeProps.Text): builder.Property(p => p.Text).DefaultValue(MigrationLiteralValues.Text); break; case nameof(MigrationLiteralProbeProps.Real): builder.Property(p => p.Real).DefaultValue(MigrationLiteralValues.Real); break; case nameof(MigrationLiteralProbeProps.Money): builder.Property(p => p.Money).DefaultValue(MigrationLiteralValues.Money); break; case nameof(MigrationLiteralProbeProps.Count): builder.Property(p => p.Count).DefaultValue(MigrationLiteralValues.Count); break; case nameof(MigrationLiteralProbeProps.Key): builder.Property(p => p.Key).DefaultValue(MigrationLiteralValues.Key); break; case nameof(MigrationLiteralProbeProps.At): builder.Property(p => p.At).DefaultValue(MigrationLiteralValues.At); break; case nameof(MigrationLiteralProbeProps.Seen): builder.Property(p => p.Seen).DefaultValue(MigrationLiteralValues.Seen); break; case nameof(MigrationLiteralProbeProps.Day): builder.Property(p => p.Day).DefaultValue(MigrationLiteralValues.Day); break; case nameof(MigrationLiteralProbeProps.Clock): builder.Property(p => p.Clock).DefaultValue(MigrationLiteralValues.Clock); break; case nameof(MigrationLiteralProbeProps.Span): builder.Property(p => p.Span).DefaultValue(MigrationLiteralValues.Span); break; case nameof(MigrationLiteralProbeProps.Kind): builder.Property(p => p.Kind).DefaultValue(MigrationLiteralValues.Kind); break; case nameof(MigrationLiteralProbeProps.Blob): builder.Property(p => p.Blob).DefaultValue(MigrationLiteralValues.Blob); break; case "Null": builder.Property(p => p.Text).DefaultValue(null); break; default: throw new InvalidOperationException($"No literal probe for '{MigrationLiteralValues.Current.Value}'."); } } } /// /// ComputedFrom keeping a stored value and putting a constant where there is none. Numbers, text and the enum are C# /// literals (a constant node); the other kinds can only be a captured or static value. /// public class MigrationLiteralComputedMigration : IRedbMigration { public void Configure(IMigrationBuilder builder) { switch (MigrationLiteralValues.Current.Value) { case nameof(MigrationLiteralProbeProps.Text): builder.Property(p => p.Text).ComputedFrom(p => p.Text ?? "it's C:\\path\\ 'quoted' \\' end Привет"); break; case nameof(MigrationLiteralProbeProps.Real): builder.Property(p => p.Real).ComputedFrom(p => p.Real ?? -1234.5); break; case nameof(MigrationLiteralProbeProps.Money): builder.Property(p => p.Money).ComputedFrom(p => p.Money ?? -9876.54m); break; case nameof(MigrationLiteralProbeProps.Count): builder.Property(p => p.Count).ComputedFrom(p => p.Count ?? -42L); break; case nameof(MigrationLiteralProbeProps.Key): builder.Property(p => p.Key).ComputedFrom(p => p.Key ?? MigrationLiteralValues.Key); break; case nameof(MigrationLiteralProbeProps.At): builder.Property(p => p.At).ComputedFrom(p => p.At ?? MigrationLiteralValues.At); break; case nameof(MigrationLiteralProbeProps.Seen): builder.Property(p => p.Seen).ComputedFrom(p => p.Seen ?? MigrationLiteralValues.Seen); break; case nameof(MigrationLiteralProbeProps.Day): builder.Property(p => p.Day).ComputedFrom(p => p.Day ?? MigrationLiteralValues.Day); break; case nameof(MigrationLiteralProbeProps.Clock): builder.Property(p => p.Clock).ComputedFrom(p => p.Clock ?? MigrationLiteralValues.Clock); break; case nameof(MigrationLiteralProbeProps.Span): builder.Property(p => p.Span).ComputedFrom(p => p.Span ?? MigrationLiteralValues.Span); break; case nameof(MigrationLiteralProbeProps.Kind): builder.Property(p => p.Kind).ComputedFrom(p => p.Kind ?? MigrationLiteralKind.Second); break; case nameof(MigrationLiteralProbeProps.Blob): builder.Property(p => p.Blob).ComputedFrom(p => p.Blob ?? MigrationLiteralValues.Blob); break; default: throw new InvalidOperationException($"No literal probe for '{MigrationLiteralValues.Current.Value}'."); } } } Path: redb/redb.Tests.Integration/Models/MigrationProbeModels.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/Models/MigrationProbeModels.cs ---- using redb.Core.Attributes; using redb.Core.Pro.Migration; namespace redb.Tests.Integration.Models; /// /// Props for the Pro data-migration suite: TotalPrice is recomputed from Quantity * Price. /// [RedbScheme("Миграции: пробный объект", Name = "migration_probe")] public class MigrationProbeProps { public long Quantity { get; set; } public double Price { get; set; } public double TotalPrice { get; set; } } /// /// The migration under test — the canonical ComputedFrom case from the Pro docs. /// public class MigrationProbeMigration : IRedbMigration { public void Configure(IMigrationBuilder builder) { builder.Property(p => p.TotalPrice) .ComputedFrom(p => p.Quantity * p.Price); } } /// /// Props for the DefaultValue and Transform migrations: one string field each, so the two /// migrations of the suite never touch each other's rows. /// [RedbScheme("Migrations: default value and transform probe", Name = "migration_edit_probe")] public class MigrationEditProbeProps { public string? Status { get; set; } public string? Phone { get; set; } public bool Enabled { get; set; } public DateTime? Due { get; set; } public DateTimeOffset? Seen { get; set; } } /// DefaultValue of a DateTime and a DateTimeOffset: the literal must be what the engine stores. public class MigrationDateDefaultValueMigration : IRedbMigration { public static readonly DateTime DueDefault = new(2026, 5, 17, 10, 30, 15, DateTimeKind.Utc); public static readonly DateTimeOffset SeenDefault = new(2026, 5, 17, 13, 30, 15, TimeSpan.FromHours(3)); public void Configure(IMigrationBuilder builder) { builder.Property(p => p.Due).DefaultValue(DueDefault); builder.Property(p => p.Seen).DefaultValue(SeenDefault); } } /// DefaultValue: fills the stored rows of Status that hold no value. public class MigrationDefaultValueMigration : IRedbMigration { public void Configure(IMigrationBuilder builder) { builder.Property(p => p.Status).DefaultValue("Active"); } } /// DefaultValue of a bool: the literal is the engine's own (SQL Server has no TRUE). public class MigrationBoolDefaultValueMigration : IRedbMigration { public void Configure(IMigrationBuilder builder) { builder.Property(p => p.Enabled).DefaultValue(true); } } /// Transform: rewrites Phone in place. public class MigrationTransformMigration : IRedbMigration { public void Configure(IMigrationBuilder builder) { builder.Property(p => p.Phone).Transform(v => v.Replace("-", "")); } } /// /// Props for ComputedFrom on a [RedbUnique] target: the migration rewrites the value, so the stored key /// of the old value must not stay behind. /// [RedbScheme("Migrations: computed unique key probe", Name = "migration_unique_probe")] public class MigrationUniqueProbeProps { public long Quantity { get; set; } public double Price { get; set; } [RedbUnique] public double TotalPrice { get; set; } } /// ComputedFrom onto the key field. public class MigrationUniqueProbeMigration : IRedbMigration { public void Configure(IMigrationBuilder builder) { builder.Property(p => p.TotalPrice) .ComputedFrom(p => p.Quantity * p.Price); } } Path: redb/redb.Tests.Integration/Models/MigrationTargetProbeModels.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/Models/MigrationTargetProbeModels.cs ---- using redb.Core.Attributes; using redb.Core.Pro.Migration; namespace redb.Tests.Integration.Models; /// /// Probes how the migration DSL ADDRESSES a field that is not a root scheme field: a member of a /// nested class and a member of an array element. /// /// Written for review finding PR-32, which states that the compiled migration SQL correlates the /// source subquery by object id and structure id only, carrying neither _array_index nor /// _parent_value_id. That finding only bites if such a target is reachable through the DSL /// at all, so this suite establishes reachability first and records the observed behaviour. /// /// /// Field names are deliberately distinct between levels (GrandTotal at the root, /// LineTotal inside) so a DSL that flattens a dotted path to its leaf name cannot silently /// resolve to the root field of the same shape. /// /// [RedbScheme("Миграции: вложенная цель", Name = "migration_target_probe")] public class MigrationTargetProbeProps { public double Base { get; set; } public double Multiplier { get; set; } public double GrandTotal { get; set; } public LineTargetProps? Details { get; set; } public List Items { get; set; } = new(); } /// Nested (non-array) member and the array element member. public class LineTargetProps { public double Qty { get; set; } public double Price { get; set; } public double LineTotal { get; set; } } /// Control: both target and sources are ROOT fields — the shape every existing migration test uses. public class MigrationTargetRootMigration : IRedbMigration { public void Configure(IMigrationBuilder builder) { builder.Property(p => p.GrandTotal) .ComputedFrom(p => p.Base * p.Multiplier); } } /// Nested-class target and nested sources. public class MigrationTargetNestedMigration : IRedbMigration { public void Configure(IMigrationBuilder builder) { builder.Property(p => p.Details!.LineTotal) .ComputedFrom(p => p.Details!.Qty * p.Details!.Price); } } /// Array-element target and array-element sources. public class MigrationTargetArrayMigration : IRedbMigration { public void Configure(IMigrationBuilder builder) { builder.Property(p => p.Items[0].LineTotal) .ComputedFrom(p => p.Items[0].Qty * p.Items[0].Price); } } Path: redb/redb.Tests.Integration/Models/ModuleUnloadModels.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/Models/ModuleUnloadModels.cs ---- using redb.Core.Attributes; using redb.Core.Interception; namespace redb.Tests.Integration.Models; /// /// The Props type of a "module": the module unload test loads this assembly again into a collectible /// AssemblyLoadContext and works with the copy of this type found there. /// [RedbScheme(Name = "test.module_unload")] public class ModuleUnloadProps { public string Title { get; set; } = ""; } /// The save interceptor of the "module" (see ). public sealed class ModuleUnloadInterceptor : IRedbSaveInterceptor { public int Saved; public int Deleted; public Task SavedAsync(RedbSavedContext context, CancellationToken cancellationToken = default) { Interlocked.Increment(ref Saved); return Task.CompletedTask; } public Task DeletedAsync(RedbDeletedContext context, CancellationToken cancellationToken = default) { Interlocked.Increment(ref Deleted); return Task.CompletedTask; } } Path: redb/redb.Tests.Integration/Models/NestedCollectionModels.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/Models/NestedCollectionModels.cs ---- using System.Collections.Generic; using redb.Core.Attributes; namespace redb.Tests.Integration.Models; // A collection directly inside a collection, and a multi-dimensional array: the scheme sync refuses them. The refused // classes carry no [RedbScheme], so that the start of a test service, which syncs every [RedbScheme] class it finds, // does not meet them; their scheme name is the full class name. public class NestedListOfListsProps { public List>? Value { get; set; } } public class NestedJaggedArrayProps { public int[][]? Value { get; set; } } public class NestedListOfArraysProps { public List? Value { get; set; } } public class NestedListOfDictionariesProps { public List>? Value { get; set; } } public class NestedArrayOfDictionariesProps { public Dictionary[]? Value { get; set; } } public class NestedDictionaryOfListsProps { public Dictionary>? Value { get; set; } } public class NestedDictionaryOfDictionariesProps { public Dictionary>? Value { get; set; } } public class NestedMultidimensionalArrayProps { public int[,]? Value { get; set; } } /// A refused property below a class element of a collection: the sync walks into the element class. public class NestedInsideElementProps { public List? Items { get; set; } } public class NestedGridHolder { public string Name { get; set; } = ""; public List>? Grid { get; set; } } // Allowed and pinned: byte[] as an element or value is one value; a collection inside a class element is stored. [RedbScheme("TestNestedBytesCollections")] public class NestedBytesCollectionsProps { public List? Chunks { get; set; } public Dictionary? Blobs { get; set; } } [RedbScheme("TestNestedCollectionInElement")] public class NestedCollectionInElementProps { public List? Items { get; set; } public Dictionary? ByKey { get; set; } } public class NestedTaggedItem { public string Name { get; set; } = ""; public List? Tags { get; set; } public Dictionary? Scores { get; set; } } // The shapes 4.8.0 synced such properties to: a collection of String (of Long for int[,]) with no children. A scheme // synced from these stands for one synced by 4.8.0; a save of the refused class against it must refuse too. [RedbScheme("TestNestedSaveGuardList")] public class NestedSaveGuardListShape { public List? Value { get; set; } } [RedbScheme("TestNestedSaveGuardDictionary")] public class NestedSaveGuardDictionaryShape { public Dictionary? Value { get; set; } } [RedbScheme("TestNestedSaveGuardGrid")] public class NestedSaveGuardGridShape { public List? Value { get; set; } } Path: redb/redb.Tests.Integration/Models/NullComparisonModels.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/Models/NullComparisonModels.cs ---- using System; using redb.Core.Attributes; using redb.Core.Models.Entities; namespace redb.Tests.Integration.Models; /// /// Pairs of nullable fields of every kind a filter compares: a number, a text, a date, a flag and a list item, each /// left empty on objects of its own period, so a filter meets objects without a value on one side, the other or both. /// [RedbScheme("TestNullComparisons")] public class NullComparisonProps { public string Tag { get; set; } = string.Empty; public int? N { get; set; } public int? N2 { get; set; } public string? S { get; set; } public string? S2 { get; set; } public DateTime? D { get; set; } public DateTime? D2 { get; set; } public bool? B { get; set; } public bool? B2 { get; set; } public RedbListItem? L { get; set; } public RedbListItem? L2 { get; set; } } public enum ContainsColor { Red, Green, Blue } /// A nullable field of every value type a Props field can have, for Contains over a list of that type. [RedbScheme("TestContainsTypes")] public class ContainsTypesProps { public string Tag { get; set; } = string.Empty; public long? I64 { get; set; } public int? I32 { get; set; } public short? I16 { get; set; } public byte? U8 { get; set; } public double? F64 { get; set; } public float? F32 { get; set; } public decimal? Dec { get; set; } public bool? Flag { get; set; } public char? Ch { get; set; } public string? Text { get; set; } public Guid? Id { get; set; } public DateTime? Dt { get; set; } public DateTimeOffset? Dto { get; set; } public DateOnly? Day { get; set; } public TimeOnly? Time { get; set; } public TimeSpan? Span { get; set; } public ContainsColor? Color { get; set; } } Path: redb/redb.Tests.Integration/Models/NullableCollectionModels.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/Models/NullableCollectionModels.cs ---- using System; using System.Collections.Generic; using redb.Core.Attributes; namespace redb.Tests.Integration.Models; /// /// Dictionaries, arrays and lists of nullable value types, each with a null among the values, and a dictionary of a /// class whose nullable field is null in one entry: everything must read back as saved, the nulls in place. /// [RedbScheme("TestNullableCollections")] public class NullableCollectionsProps { public string Tag { get; set; } = string.Empty; public Dictionary? Ints { get; set; } public Dictionary? Longs { get; set; } public Dictionary? Decimals { get; set; } public Dictionary? Dates { get; set; } public Dictionary? Flags { get; set; } public Dictionary? Guids { get; set; } public int?[]? IntArray { get; set; } public List? LongList { get; set; } public List? DecimalList { get; set; } public bool?[]? FlagArray { get; set; } public Dictionary? Entries { get; set; } } public class NullableCollectionsEntry { public string Name { get; set; } = string.Empty; public int? Score { get; set; } public DateTime? At { get; set; } public int?[]? Marks { get; set; } } Path: redb/redb.Tests.Integration/Models/OlderModelModels.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/Models/OlderModelModels.cs ---- using redb.Core.Attributes; namespace redb.Tests.Integration.Models; // A newer and an older build of one Props class, for the older-model suite (OlderModelTestsBase). Two classes cannot // share one scheme name in a process (ClrSchemeTypeIndex), so the newer class syncs and saves under its own name and // the test renames that scheme to the older class's name: the older class then meets exactly the structures and values // the newer build left. /// The newer build: adds Extra. [RedbScheme("Older model: new field, newer build", Name = "older_model_field_newer")] public class OlderModelFieldNewerProps { public string Tag { get; set; } = ""; public string? Extra { get; set; } } /// The older build: no Extra. [RedbScheme("Older model: new field, older build", Name = "older_model_field")] public class OlderModelFieldOlderProps { public string Tag { get; set; } = ""; } /// The newer build: Level is a long. [RedbScheme("Older model: type change, newer build", Name = "older_model_type_newer", Version = 1)] public class OlderModelTypeNewerProps { public string Tag { get; set; } = ""; public long Level { get; set; } } /// The older build: Level was a bool. [RedbScheme("Older model: type change, older build", Name = "older_model_type")] public class OlderModelTypeOlderProps { public string Tag { get; set; } = ""; public bool Level { get; set; } } /// The newer build: adds Country to the nested class and Note to the list element. [RedbScheme("Older model: nested fields, newer build", Name = "older_model_nested_newer")] public class OlderModelNestedNewerProps { public string Tag { get; set; } = ""; public OlderModelPlaceNewer? Place { get; set; } public List? Lines { get; set; } } public class OlderModelPlaceNewer { public string City { get; set; } = ""; public string? Country { get; set; } } public class OlderModelLineNewer { public string Name { get; set; } = ""; public string? Note { get; set; } } /// The older build: no Country, no Note. [RedbScheme("Older model: nested fields, older build", Name = "older_model_nested")] public class OlderModelNestedOlderProps { public string Tag { get; set; } = ""; public OlderModelPlaceOlder? Place { get; set; } public List? Lines { get; set; } } public class OlderModelPlaceOlder { public string City { get; set; } = ""; } public class OlderModelLineOlder { public string Name { get; set; } = ""; } /// A later build that removed Extra and raised the version: the sync may delete it. [RedbScheme("Older model: field removed with a version", Name = "older_model_clean", Version = 1)] public class OlderModelCleanProps { public string Tag { get; set; } = ""; } /// The build before it, which still had Extra. [RedbScheme("Older model: field removed, build before", Name = "older_model_clean_before")] public class OlderModelCleanBeforeProps { public string Tag { get; set; } = ""; public string? Extra { get; set; } } // A type changed without raising the version: the sync holds the change, saves are refused. [RedbScheme("Held type: bool, before", Name = "held_bool_before")] public class HeldBoolBeforeProps { public string Tag { get; set; } = ""; public bool Flag { get; set; } } [RedbScheme("Held type: bool to int", Name = "held_bool")] public class HeldBoolToIntProps { public string Tag { get; set; } = ""; public int Flag { get; set; } } [RedbScheme("Held type: text, before", Name = "held_text_before")] public class HeldTextBeforeProps { public string Tag { get; set; } = ""; public string Flag { get; set; } = ""; } [RedbScheme("Held type: text to int", Name = "held_text")] public class HeldTextToIntProps { public string Tag { get; set; } = ""; public int Flag { get; set; } } [RedbScheme("Held kind: scalar, before", Name = "held_kind_before")] public class HeldKindBeforeProps { public string Tag { get; set; } = ""; public string Flag { get; set; } = ""; } [RedbScheme("Held kind: scalar to list", Name = "held_kind")] public class HeldKindToListProps { public string Tag { get; set; } = ""; public List? Flag { get; set; } } Path: redb/redb.Tests.Integration/Models/OrderAbsentModels.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/Models/OrderAbsentModels.cs ---- using redb.Core.Attributes; namespace redb.Tests.Integration.Models; /// /// Rows of one tag, sorted by a field some of them have no value for, and by a group then a name. /// [RedbScheme("TestOrderAbsent")] public class OrderAbsentProps { public string Tag { get; set; } = string.Empty; public string? Label { get; set; } public int? Rank { get; set; } public int Group { get; set; } public string Name { get; set; } = string.Empty; } Path: redb/redb.Tests.Integration/Models/PageValuesModels.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/Models/PageValuesModels.cs ---- using redb.Core.Attributes; namespace redb.Tests.Integration.Models; /// /// A graph that asks the Pro materializer every kind of lookup over the rows of a page: root fields, a root class, a /// class array whose elements carry a class field, a scalar array and a class array of their own, a dictionary of /// classes, a scalar array of more than ten elements (numeric, not text, order of the array index). /// [RedbScheme("TestPageValuesGraph")] public class PageGraphProps { public string? Title { get; set; } public PageGraphLine? Head { get; set; } public List? Lines { get; set; } public Dictionary? ByCode { get; set; } public List? Numbers { get; set; } public List? Empty { get; set; } public List? Missing { get; set; } } /// An element: its fields hang under the element row. public class PageGraphLine { public string? Code { get; set; } public PageGraphInner? Inner { get; set; } public List? Tags { get; set; } public List? Parts { get; set; } } /// The class inside an element, with an array of its own. public class PageGraphInner { public int Level { get; set; } public string? Note { get; set; } public List? Marks { get; set; } } Path: redb/redb.Tests.Integration/Models/ProjectionModels.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/Models/ProjectionModels.cs ---- using System; using System.Collections.Generic; using redb.Core.Attributes; using redb.Core.Models.Entities; namespace redb.Tests.Integration.Models; /// /// Probe scheme for the Select-projection suite (review 2026-09-03, wave 1.1). /// Synced by the tests that use it, not by the fixtures. /// [RedbScheme(Name = "ProjectionProbe")] public class ProjectionProbeProps { public string? S { get; set; } public int N { get; set; } public decimal? D { get; set; } public bool Flag { get; set; } public ProjectionProbeNested? Nested { get; set; } public List? Items { get; set; } public string[]? Tags { get; set; } public RedbObject? Child { get; set; } } public class ProjectionProbeNested { public string? City { get; set; } public int Zip { get; set; } } public class ProjectionProbeItem { public string? Name { get; set; } public decimal Price { get; set; } } [RedbScheme(Name = "ProjectionProbeChild")] public class ProjectionProbeChildProps { public string? Label { get; set; } } /// DTO target for MemberInit projections (S-5/G-1 shapes). public class ProjectionDto { public string? A { get; set; } public int N { get; set; } public ProjectionSubDto Sub { get; set; } = new(); } public class ProjectionSubDto { public int X { get; set; } } Path: redb/redb.Tests.Integration/Models/RareRangeModels.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/Models/RareRangeModels.cs ---- using redb.Core.Attributes; namespace redb.Tests.Integration.Models; /// /// An open range on one field next to a page sorted by another: Score spread so that Score < x keeps 12, about 900, /// about 1 500 or about 2 900 of 3 000 objects; some objects lack the range value, some the sort value. /// [RedbScheme("rare_range_pages")] public class RareRangeProps { public long? Score { get; set; } public decimal? Salary { get; set; } public DateTime? When { get; set; } } Path: redb/redb.Tests.Integration/Models/ReferenceListProbeModels.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/Models/ReferenceListProbeModels.cs ---- using redb.Core.Attributes; using redb.Core.Models.Entities; namespace redb.Tests.Integration.Models; /// /// A list of references (List<RedbObject<T>>, not an array). The save collected the elements of arrays /// only: references by id in a list got no hash, a new object in a list was never saved, and an edit to a loaded one /// was lost. Synced by the tests that use it. /// [RedbScheme(Name = "ReferenceListProbe")] public class ReferenceListProbeProps { public string? Label { get; set; } public List>? Items { get; set; } } /// /// A reference inside a class that is a dictionary value. The graph collector walks single references, lists, arrays and /// dictionaries of references, classes and arrays of classes, but not the classes of a dictionary: a new object here /// reached the value pass with no id and was saved there on its own. Synced by the tests that use it. /// [RedbScheme(Name = "ReferenceDictProbe")] public class ReferenceDictProbeProps { public string? Label { get; set; } public Dictionary? Holders { get; set; } } public class ReferenceHolder { public string? Note { get; set; } public RedbObject? Target { get; set; } } Path: redb/redb.Tests.Integration/Models/RenameModels.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/Models/RenameModels.cs ---- using redb.Core.Attributes; namespace redb.Tests.Integration.Models; // Props for the [RedbRename] suite. Each scenario is a pair (or a chain) of classes for one scheme: the "V1" class is // the class of an older application version, with no explicit scheme name, so its scheme is named after its FullName; // the later classes pin that FullName as their explicit name. That is how a rename is deployed in the field (the class // changes, the scheme stays), and it keeps the library's guard against two classes claiming one explicit name out of // the way: only one class of each scheme declares the name. /// Older class: a root field and a nested field that the next version renames. public class RenameBasicV1 { public string Title { get; set; } = ""; public long Count { get; set; } public RenameAddressV1 Address { get; set; } = new(); } public class RenameAddressV1 { public string City { get; set; } = ""; public string Street { get; set; } = ""; } /// Next version: Title is Heading, Address.City is Address.Town. [RedbScheme(Name = "redb.Tests.Integration.Models.RenameBasicV1")] public class RenameBasicV2 { [RedbRename("Title")] public string Heading { get; set; } = ""; public long Count { get; set; } public RenameAddressV2 Address { get; set; } = new(); } public class RenameAddressV2 { [RedbRename("City")] public string Town { get; set; } = ""; public string Street { get; set; } = ""; } /// Chain: Title, then Heading (staged by SQL: a second class claiming the explicit name would be a name /// conflict), then Caption. public class RenameChainV1 { public string Title { get; set; } = ""; } [RedbScheme(Name = "redb.Tests.Integration.Models.RenameChainV1")] public class RenameChainV3 { [RedbRename("Title")] [RedbRename("Heading")] public string Caption { get; set; } = ""; } /// Separate scheme for the direct jump V1 to V3 of the chain. public class RenameJumpV1 { public string Title { get; set; } = ""; } [RedbScheme(Name = "redb.Tests.Integration.Models.RenameJumpV1")] public class RenameJumpV3 { [RedbRename("Title")] [RedbRename("Heading")] public string Caption { get; set; } = ""; } /// The database stores both the previous name and the new one. public class RenameBothV1 { public string Title { get; set; } = ""; public string Heading { get; set; } = ""; } [RedbScheme(Name = "redb.Tests.Integration.Models.RenameBothV1")] public class RenameBothV2 { [RedbRename("Title")] public string Heading { get; set; } = ""; } /// A previous name that another property of the same class carries again: read once the rename is applied. public class RenameClashProps { [RedbRename("Title")] public string Heading { get; set; } = ""; public string Title { get; set; } = ""; } /// A name freed by a rename (Title to Heading, staged by SQL) is taken again by a new property. public class RenameReuseV1 { public string Title { get; set; } = ""; } [RedbScheme(Name = "redb.Tests.Integration.Models.RenameReuseV1")] public class RenameReuseV3 { [RedbRename("Title")] public string Heading { get; set; } = ""; public string Title { get; set; } = ""; } /// Rename and type change at once: int Count becomes long Total (both live in _Long). public class RenameTypeV1 { public int Count { get; set; } } [RedbScheme(Name = "redb.Tests.Integration.Models.RenameTypeV1")] public class RenameTypeV2 { [RedbRename("Count")] public long Total { get; set; } } /// A rename that moves the property across another in name order: Title sorts after Alpha, Aaron before. public class RenameHashV1 { public string Alpha { get; set; } = ""; public string Title { get; set; } = ""; public string Zulu { get; set; } = ""; } [RedbScheme(Name = "redb.Tests.Integration.Models.RenameHashV1")] public class RenameHashV2 { [RedbRename("Title")] public string Aaron { get; set; } = ""; public string Alpha { get; set; } = ""; public string Zulu { get; set; } = ""; } /// Two properties that swap names through a temporary name: Left to Tmp, Right to Left, Tmp to Right (the first two /// deployments are staged by SQL). public class RenameSwapV1 { public string Left { get; set; } = ""; public string Right { get; set; } = ""; } [RedbScheme(Name = "redb.Tests.Integration.Models.RenameSwapV1")] public class RenameSwapV3 { [RedbRename("Left")] [RedbRename("Tmp")] public string Right { get; set; } = ""; [RedbRename("Right")] public string Left { get; set; } = ""; } /// A swap in one step: refused from the class alone (no [RedbScheme], so the fixture does not sync it). public class RenameSwapOneStep { [RedbRename("Left")] public string Right { get; set; } = ""; [RedbRename("Right")] public string Left { get; set; } = ""; } Path: redb/redb.Tests.Integration/Models/SchemaLockSyncProbeModels.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/Models/SchemaLockSyncProbeModels.cs ---- using redb.Core.Attributes; namespace redb.Tests.Integration.Models; /// /// A scheme the nodes of the scheme sync race test create and extend together (see SchemeSyncRace). Its name is /// its own: the test deletes the scheme between rounds. /// [RedbScheme(Name = "schema_lock_sync_probe")] public class SchemaLockSyncProbeProps { public string Title { get; set; } = ""; public int Count { get; set; } public string? Note { get; set; } public SchemaLockSyncProbePart? Part { get; set; } } /// A nested class: its structures hang under a parent, as most real schemes have. public class SchemaLockSyncProbePart { public string? City { get; set; } public decimal Weight { get; set; } } Path: redb/redb.Tests.Integration/Models/SchemeNamingModels.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/Models/SchemeNamingModels.cs ---- using redb.Core.Attributes; namespace redb.Tests.Integration.Models; // Props types dedicated to the scheme-naming suite. Every test drives the sync itself and drops the // schemes it touches first, so each scenario starts from a known state regardless of which provider // (or which of Free/Pro) ran before it. // // NOTE: no type here may declare an INVALID explicit name, and no two may declare the SAME one. // InitializeAsync auto-syncs every [RedbScheme] type in every loaded assembly and rethrows // (RedbServiceBase.AutoSyncSchemesAsync), so a single bad name would break fixture start-up for the // whole test project. That is the intended product behaviour — a bad name must not boot. The // negative cases are therefore covered by SchemeNameValidatorTests against the validator directly. /// Baseline: no attribute name — the scheme must keep living by FullName. Scenario A/B. [RedbScheme("Именование: по типу")] public class NamingByTypeProps { public string Title { get; set; } = ""; } /// Explicit name, no alias. Scenarios C, D, E, K, L, N, P. [RedbScheme(Name = "naming.pinned")] public class NamingPinnedProps { public string Title { get; set; } = ""; } /// Explicit name together with a human-readable alias. Scenario M. [RedbScheme("Именование: имя и алиас", Name = "naming.with_alias")] public class NamingWithAliasProps { public string Title { get; set; } = ""; } /// Explicit name used to stage the split-brain scenario F. [RedbScheme(Name = "naming.split")] public class NamingSplitProps { public string Title { get; set; } = ""; } /// Alias-only, mutated across scenarios O/Q/R by editing the alias behind the library's back. [RedbScheme("Именование: алиас исходный")] public class NamingAliasProps { public string Title { get; set; } = ""; } /// Explicit name used by the concurrent-creation scenarios S and T. [RedbScheme(Name = "naming.race")] public class NamingRaceProps { public string Title { get; set; } = ""; } Path: redb/redb.Tests.Integration/Models/SchemeRenameModels.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/Models/SchemeRenameModels.cs ---- using redb.Core.Attributes; namespace redb.Tests.Integration.Models; // Props for the RedbScheme.RenamedFrom suite. The old class of a scenario carries no [RedbScheme], so its scheme is // named after its FullName and the fixture does not sync it at start; the new class names it in RenamedFrom. /// Older class of the plain rename. public class SchemeRenameV1 { public string Title { get; set; } = ""; } /// Next version: another class, another scheme name, the same stored scheme. [RedbScheme(Name = "rename_scheme_v2", RenamedFrom = ["redb.Tests.Integration.Models.SchemeRenameV1"])] public class SchemeRenameV2 { public string Title { get; set; } = ""; } /// Older class of the both-stored case. public class SchemeRenameBothV1 { public string Title { get; set; } = ""; } [RedbScheme(Name = "rename_scheme_both", RenamedFrom = ["redb.Tests.Integration.Models.SchemeRenameBothV1"])] public class SchemeRenameBothV2 { public string Title { get; set; } = ""; } /// A chain of explicit names; the stored names are staged by SQL. [RedbScheme(Name = "rename_scheme_chain", RenamedFrom = ["rename_scheme_chain_a", "rename_scheme_chain_b"])] public class SchemeRenameChainProps { public string Title { get; set; } = ""; } /// A class whose scheme a version this process does not have renamed away (staged by SQL). public class SchemeRenameGuardV1 { public string Title { get; set; } = ""; } /// A class taking a scheme name that a scheme of this application was renamed from (staged by SQL). public class SchemeRenameReuseProps { public string Title { get; set; } = ""; } /// The FullName-to-explicit-name rename that predates RenamedFrom: it records the history too. [RedbScheme(Name = "rename_scheme_legacy")] public class SchemeRenameLegacyProps { public string Title { get; set; } = ""; } Path: redb/redb.Tests.Integration/Models/StaleStructureTreeModels.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/Models/StaleStructureTreeModels.cs ---- using redb.Core.Attributes; namespace redb.Tests.Integration.Models; // Props class of the stale structure tree suite (StaleStructureTreeTestsBase). The tests change the scheme behind the // process's back, as another node would, and then save with this class. /// A field the other node renames, one it drops, one whose type it changes. [RedbScheme("Stale structure tree", Name = "stale_structure_tree")] public class StaleStructureTreeProps { public string Tag { get; set; } = ""; public string? Note { get; set; } public string? Gone { get; set; } public long Level { get; set; } } Path: redb/redb.Tests.Integration/Models/TagsModels.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/Models/TagsModels.cs ---- using redb.Core.Attributes; namespace redb.Tests.Integration.Models; /// /// The free-form _tags marker (V4): [RedbTags] on the class writes the scheme's marker, on a /// property - the structure's; a column WITHOUT the attribute is never touched by sync, so /// direct writes by applications and extensions survive. /// [RedbScheme(Name = "TagsProbe")] [RedbTags("scheme-level,reserved")] public class TagsProbeProps { [RedbTags("prop-level")] public string? Marked { get; set; } public string? Plain { get; set; } } Path: redb/redb.Tests.Integration/Models/TestModels.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/Models/TestModels.cs ---- using redb.Core.Attributes; using redb.Core.Models.Entities; namespace redb.Tests.Integration.Models; // ─────────────────────────────────────────────── // Simple model for basic CRUD tests // ─────────────────────────────────────────────── [RedbScheme("TestSimple")] public class SimpleProps { public string Title { get; set; } = string.Empty; public int Count { get; set; } public decimal Price { get; set; } public DateTime CreatedAt { get; set; } public bool IsActive { get; set; } public Guid Code { get; set; } public string? Description { get; set; } public long? OptionalNumber { get; set; } } // ─────────────────────────────────────────────── // Employee model (main test model, matching Examples) // ─────────────────────────────────────────────── public class TestAddress { public string City { get; set; } = string.Empty; public string Street { get; set; } = string.Empty; public TestBuildingInfo? Building { get; set; } } public class TestBuildingInfo { public int Floor { get; set; } public string Name { get; set; } = string.Empty; public string[]? Amenities { get; set; } } public class TestContact { public string Type { get; set; } = string.Empty; public string Value { get; set; } = string.Empty; public bool IsVerified { get; set; } public TestContactDetail[]? Metadata { get; set; } } public class TestContactDetail { public string Label { get; set; } = string.Empty; public string Value { get; set; } = string.Empty; } public class TestTag { public string Name { get; set; } = string.Empty; public int Priority { get; set; } } public class TestDepartment { public string Name { get; set; } = string.Empty; public int HeadCount { get; set; } public string[] Projects { get; set; } = []; public TestTag[] Leaders { get; set; } = []; public Dictionary? BudgetByYear { get; set; } } [RedbScheme("TestEmployee")] public class EmployeeProps { public string FirstName { get; set; } = string.Empty; public string LastName { get; set; } = string.Empty; public int Age { get; set; } public DateTime HireDate { get; set; } public string Position { get; set; } = string.Empty; public decimal Salary { get; set; } public string Department { get; set; } = string.Empty; public string? EmployeeCode { get; set; } public bool IsRemote { get; set; } public double? Rating { get; set; } // Arrays public string[]? Skills { get; set; } public int[]? SkillLevels { get; set; } // Nested objects public TestAddress? HomeAddress { get; set; } public TestAddress? WorkAddress { get; set; } // Array of business objects public TestContact[]? Contacts { get; set; } // RedbObject reference public RedbObject? CurrentProject { get; set; } // Dictionaries public Dictionary? PhoneDirectory { get; set; } public Dictionary? OfficeLocations { get; set; } public Dictionary? BonusByYear { get; set; } public Dictionary? DepartmentHistory { get; set; } public Dictionary<(int Year, string Quarter), string>? PerformanceReviews { get; set; } } [RedbScheme("TestProjectMetrics")] public class ProjectMetricsProps { public long ProjectId { get; set; } public long? TasksCompleted { get; set; } public long? TasksTotal { get; set; } public long? BugsFixed { get; set; } public double? Budget { get; set; } public long? TeamSize { get; set; } public string[]? Technologies { get; set; } } // ─────────────────────────────────────────────── // Department model (tree hierarchy — mirrors redb.Examples.Models.DepartmentProps) // ─────────────────────────────────────────────── [RedbScheme("TestDepartment")] public class DepartmentProps { public string Name { get; set; } = string.Empty; public string Description { get; set; } = string.Empty; public bool IsActive { get; set; } = true; public decimal Budget { get; set; } public string Code { get; set; } = string.Empty; } // ─────────────────────────────────────────────── // Tree node model // ─────────────────────────────────────────────── [RedbScheme("TestTreeNode")] public class TreeNodeProps { public string Name { get; set; } = string.Empty; public string Description { get; set; } = string.Empty; public bool IsActive { get; set; } = true; public decimal Budget { get; set; } public string Code { get; set; } = string.Empty; } // ─────────────────────────────────────────────── // Polymorphic tree models (3 different scheme types in one tree) // ─────────────────────────────────────────────── [RedbScheme("TestOrgRoot")] public class OrgRootProps { public string OrgName { get; set; } = string.Empty; public string Country { get; set; } = string.Empty; public int FoundedYear { get; set; } } [RedbScheme("TestDivision")] public class DivisionProps { public string DivisionName { get; set; } = string.Empty; public string Head { get; set; } = string.Empty; public decimal AnnualBudget { get; set; } } [RedbScheme("TestTeam")] public class TeamProps { public string TeamName { get; set; } = string.Empty; public int MemberCount { get; set; } public string[] Technologies { get; set; } = []; } // ─────────────────────────────────────────────── // List-related models // ─────────────────────────────────────────────── [RedbScheme("TestPerson")] public class PersonProps { public string Name { get; set; } = string.Empty; public int Age { get; set; } public string Email { get; set; } = string.Empty; public RedbListItem? Status { get; set; } public List? Roles { get; set; } } [RedbScheme("TestCity")] public class CityProps { public string Name { get; set; } = string.Empty; public int Population { get; set; } public string Region { get; set; } = string.Empty; public bool IsCapital { get; set; } public double[]? Coordinates { get; set; } } // ─────────────────────────────────────────────── // Temporal model — exercises every temporal type REDB supports. // The rest of the suite only ever uses DateTime with Kind=Utc, where the // zone-less and the instant reading coincide, so none of the temporal // conversion paths were reachable from a test before this model existed. // ─────────────────────────────────────────────── [RedbScheme("TestTemporal")] public class TemporalProps { /// Zone-less clock reading. 14:00 written is 14:00 read, on any host. public DateTime When { get; set; } /// Native .NET semantics: a real instant with an offset. public DateTimeOffset Moment { get; set; } public DateOnly Day { get; set; } public TimeOnly Clock { get; set; } public TimeSpan Span { get; set; } public string Label { get; set; } = string.Empty; } /// /// Same shape as , own scheme. Round-trip tests insert ad-hoc rows and /// must not pollute the deterministic row set the comparison tests count on. /// [RedbScheme("TestTemporalRoundTrip")] public class TemporalRoundTripProps { public DateTime When { get; set; } public DateTimeOffset Moment { get; set; } public DateOnly Day { get; set; } public TimeOnly Clock { get; set; } public TimeSpan Span { get; set; } public string Label { get; set; } = string.Empty; } // ─────────────────────────────────────────────── // Case-folding model. Text in several scripts, so a search can be checked // against languages whose case mapping behaves differently. // ─────────────────────────────────────────────── [RedbScheme("TestCollation")] public class CollationProps { /// The searched text. public string Text { get; set; } = string.Empty; /// Stable identity of the row, ASCII only so it is never itself affected. public string Label { get; set; } = string.Empty; } Path: redb/redb.Tests.Integration/Models/TimeTicksModels.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/Models/TimeTicksModels.cs ---- using redb.Core.Attributes; namespace redb.Tests.Integration.Models; /// TimeSpan and TimeOnly in every shape a props class holds them: plain, nullable, in an array, a list and a dictionary. [RedbScheme("TestTimeTicks")] public class TimeTicksProps { public string Tag { get; set; } = ""; public TimeSpan Span { get; set; } public TimeSpan? MaybeSpan { get; set; } public TimeOnly Clock { get; set; } public TimeOnly? MaybeClock { get; set; } public TimeSpan[]? Spans { get; set; } public List? Clocks { get; set; } public TimeSpan?[]? MaybeSpans { get; set; } public Dictionary? SpanByName { get; set; } } Path: redb/redb.Tests.Integration/Models/TopLevelCollectionModels.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/Models/TopLevelCollectionModels.cs ---- using System.Collections.Generic; using System.Collections.ObjectModel; using redb.Core.Attributes; namespace redb.Tests.Integration.Models; // Collection types at the top of a property, one class per shape. The refused shapes carry no [RedbScheme]: the start // of a test service syncs every [RedbScheme] class it finds, and a refused shape must not stop it. public class TopHashSetProps { public HashSet? Value { get; set; } } public class TopISetProps { public ISet? Value { get; set; } } public class TopObservableCollectionProps { public ObservableCollection? Value { get; set; } } public class TopQueueProps { public Queue? Value { get; set; } } public class TopStackProps { public Stack? Value { get; set; } } public class TopIReadOnlyListProps { public IReadOnlyList? Value { get; set; } } public class TopSortedDictionaryProps { public SortedDictionary? Value { get; set; } } public class TopIReadOnlyDictionaryProps { public IReadOnlyDictionary? Value { get; set; } } public class TopListOfIntProps { public List? Value { get; set; } } public class TopIEnumerableOfLongProps { public IEnumerable? Value { get; set; } } public class TopIEnumerableOfStringProps { public IEnumerable? Value { get; set; } } public class TopICollectionOfStringProps { public ICollection? Value { get; set; } } public class TopIDictionaryProps { public IDictionary? Value { get; set; } } // A supported shape inside a class element, with a refused one beside it. public class TopHashSetHolder { public string? Label { get; set; } public HashSet? Tags { get; set; } } public class TopHashSetInElementProps { public List? Items { get; set; } } // Save guard: twin shapes that sync to one String structure, as the refused types did before the refusal existed. [RedbScheme("TestTopSaveGuardString")] public class TopSaveGuardStringShape { public string? Value { get; set; } } [RedbScheme("TestTopSaveGuardElement")] public class TopSaveGuardElementShape { public List? Items { get; set; } } public class TopSaveGuardElementHolder { public string? Label { get; set; } public string? Tags { get; set; } } Path: redb/redb.Tests.Integration/Models/TrashModels.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/Models/TrashModels.cs ---- using redb.Core.Attributes; using redb.Core.Models.Entities; namespace redb.Tests.Integration.Models; /// An object that goes to the trash in the trash integrity suites. [RedbScheme(Name = "TrashTarget")] public class TrashTargetProps { public string? Title { get; set; } } /// /// An object that references trash targets - through a single reference and through a collection, /// the two shapes a _values._Object row takes. /// [RedbScheme(Name = "TrashHolder")] public class TrashHolderProps { public string? Title { get; set; } public RedbObject? Target { get; set; } public List>? Targets { get; set; } } Path: redb/redb.Tests.Integration/Models/TypeMigrationModels.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/Models/TypeMigrationModels.cs ---- using redb.Core.Attributes; namespace redb.Tests.Integration.Models; // Props for the scheme-sync type-migration suite. // // Note what these deliberately do NOT do: two classes sharing one [RedbScheme(Name = "...")] would be // the obvious way to stage "the property changed type", but the library refuses it — a duplicate // explicit name is a hard error (ClrSchemeTypeIndex.ThrowIfNameConflict and RedbSchemeNameConflictException), and rightly so. // The suite therefore stages the change the way it actually happens in the field: it writes values // through the current class, then rewrites _structures._id_type and the storage column with raw SQL to // the shape an EARLIER version of the class would have produced, and re-syncs the same class. What the // sync path then sees is indistinguishable from a real deployment where the property's type changed. /// /// Target of the supported case: values are staged as Boolean and the property asks for int, /// which every provider can convert. /// [RedbScheme("Миграция типа: поддержанная", Name = "type_migration_supported", Version = 1)] public class TypeMigrationIntProps { /// The property whose type changes. Staged as Boolean, declared here as int. public int Flag { get; set; } /// Untouched neighbour: proves the migration does not disturb the rest of the structure. public string Tag { get; set; } = ""; } /// /// Target of the unsupported case: Boolean to Guid is in no provider's conversion matrix, so the /// migration must refuse and synchronisation must stop. /// [RedbScheme("Миграция типа: неподдержанная", Name = "type_migration_unsupported", Version = 1)] public class TypeMigrationGuidProps { public Guid Flag { get; set; } public string Tag { get; set; } = ""; } /// /// Same storage column on both sides (Int and Long both live in _Long): the type changes, the /// values do not move, and nothing may be lost. /// [RedbScheme("Миграция типа: та же колонка", Name = "type_migration_samecolumn", Version = 1)] public class TypeMigrationLongProps { public long Flag { get; set; } public string Tag { get; set; } = ""; } /// /// Text to Boolean, the conversion that used to destroy what it could not read: the CASE fell through /// to NULL for an unrecognised token while the same statement cleared the source column, and the row /// was counted as a success. /// [RedbScheme("Миграция типа: булева из текста", Name = "type_migration_bool_from_text", Version = 1)] public class TypeMigrationBoolProps { public bool Flag { get; set; } public string Tag { get; set; } = ""; } /// /// Text source with rows that cannot be read as a number: the convertible ones move, the rest stay, /// and the partial result is a failure — synchronisation stops rather than stranding either group. /// [RedbScheme("Миграция типа: частичная", Name = "type_migration_partial", Version = 1)] public class TypeMigrationPartialProps { public long Flag { get; set; } public string Tag { get; set; } = ""; } Path: redb/redb.Tests.Integration/Models/UnfilteredAggregateModels.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/Models/UnfilteredAggregateModels.cs ---- using redb.Core.Attributes; namespace redb.Tests.Integration.Models; /// /// A scheme no test saves an object into: the aggregates over an empty scheme are compared on it /// (PostgresProPvtPrefilterEquivalenceTests.UnfilteredAggregate_ReadFromTheIndexOfValues_SameAnswers). /// [RedbScheme("UnfilteredAggregateEmpty")] public class UnfilteredAggregateEmptyProps { public long Number { get; set; } public decimal Amount { get; set; } public double Ratio { get; set; } } Path: redb/redb.Tests.Integration/Models/UniqueKeyModels.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/Models/UniqueKeyModels.cs ---- using System; using redb.Core.Attributes; using redb.Core.Models.Entities; namespace redb.Tests.Integration.Models; // ─────────────────────────────────────────────── // Models for the [RedbUnique] key suite (V4, UNIQUE stage 2). // Synced by the tests that use them, not by the fixtures. // ─────────────────────────────────────────────── /// /// One scheme, several independent keys — one per canonical-form rule of /// UniqueKeyEncoder. Each key is nullable: NULL never takes part in uniqueness. /// [RedbScheme(Name = "UniqueOrder")] public class UniqueOrderProps { [RedbUnique] public string? Code { get; set; } [RedbUnique] public long? Number { get; set; } [RedbUnique] public Guid? Token { get; set; } [RedbUnique] public decimal? Amount { get; set; } [RedbUnique] public DateTimeOffset? IssuedAt { get; set; } // Б1 (owner decision 2026-08-31): byte[] is a root scalar in _values._ByteArray, so it can be // a key - dedup by content is the ordinary byte[] scenario (plan decision 4). [RedbUnique] public byte[]? Fingerprint { get; set; } /// Not a key — the control field: duplicates here must stay legal. public string? Note { get; set; } } /// /// A second scheme with the same key property name: uniqueness is per scheme, so the same /// Code in UniqueOrder and UniqueInvoice must coexist. /// [RedbScheme(Name = "UniqueInvoice")] public class UniqueInvoiceProps { [RedbUnique] public string? Code { get; set; } public string? Note { get; set; } } /// A scheme with no keys at all — must stay completely untouched by the machinery. [RedbScheme(Name = "UniqueFree")] public class UniqueFreeProps { public string? Code { get; set; } public string? Note { get; set; } } /// /// S2 (subtree-unique plan): a key on a scalar INSIDE a nested class, reached without crossing /// a collection. The nested field's rows carry their own structure id, so the same index /// enforces them exactly like root keys. /// [RedbScheme(Name = "UniqueNested")] public class UniqueNestedProps { public string? Title { get; set; } public NestedIdentity? Identity { get; set; } } public class NestedIdentity { [RedbUnique] public string? Passport { get; set; } public string? Issuer { get; set; } } /// /// S1 (subtree-unique plan): [RedbUnique] on a root nested class, array and dictionary - the /// key is the CONTENT of the whole subtree (the canonical hash the storage already maintains /// on the base row), unique per scheme. /// [RedbScheme(Name = "UniqueSubtree")] public class UniqueSubtreeProps { [RedbUnique] public SubtreeConfig? Config { get; set; } [RedbUnique] public List? Slots { get; set; } [RedbUnique] public Dictionary? Limits { get; set; } public string? Note { get; set; } } public class SubtreeConfig { public string? Region { get; set; } public long? Tier { get; set; } } /// /// S3 (subtree-unique plan): ELEMENT keys on collections via [RedbUnique(Scope = ...)]. /// Collection scope - no duplicates inside one object's collection; Scheme scope - element /// values unique across every object of the scheme. /// [RedbScheme(Name = "UniqueElems")] public class UniqueElementsProps { [RedbUnique(Scope = UniqueScope.Collection)] public List? Codes { get; set; } [RedbUnique(Scope = UniqueScope.Scheme)] public List? Emails { get; set; } [RedbUnique(Scope = UniqueScope.Collection)] public List>? Links { get; set; } public string? Note { get; set; } } /// /// The forbidden shape for S3: Scope on a SCALAR is meaningless - the bare attribute already /// carries the strongest reading. Not [RedbScheme]-marked: its sync must throw, and the /// fixtures auto-sync every marked type. /// public class ScopedScalarProps { [RedbUnique(Scope = UniqueScope.Collection)] public string? Code { get; set; } } /// Two levels of nesting: the path machinery must be depth-agnostic. [RedbScheme(Name = "UniqueDeep")] public class UniqueDeepProps { public DeepOuter? Outer { get; set; } } public class DeepOuter { public DeepInner? Inner { get; set; } } public class DeepInner { [RedbUnique] public string? Code { get; set; } } /// /// The forbidden shape: a key inside an ELEMENT of a collection of classes. Every element of /// every object shares one structure, so "unique" would degenerate to one value across all /// elements of all objects — the validator must reject it at synchronisation. /// Deliberately NOT [RedbScheme]-marked: the fixtures auto-sync every marked type of the /// assembly at InitializeAsync, and a model whose sync must THROW would kill the fixture. /// The test syncs it explicitly; its scheme name is the CLR FullName. /// public class UniqueInElementProps { public List? Items { get; set; } } public class KeyedElement { [RedbUnique] public string? Code { get; set; } } Path: redb/redb.Tests.Integration/Models/ValueOnlyModels.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/Models/ValueOnlyModels.cs ---- using redb.Core.Attributes; namespace redb.Tests.Integration.Models; /// /// A scheme with no properties at all: the object lives in its base fields (name, value_*, unique key) - flags, /// counters, simple values in the objects table. Loaded, it carries no Props and no _values rows. /// [RedbScheme] public class ValueOnlyProps { } Path: redb/redb.Tests.Integration/Models/WideEqualityLeadsModels.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/Models/WideEqualityLeadsModels.cs ---- using redb.Core.Attributes; namespace redb.Tests.Integration.Models; /// /// An equality that is narrow by its shape on objects where the data makes it wide (Tag == "wide" on 81 % of them) or /// rare ("rare" on 1 %), next to number and date sort fields, the date absent on some objects. /// [RedbScheme("wide_equality_leads")] public class WideEqualityLeadsProps { public string Tag { get; set; } = ""; // The same split as a number: 1 rare, 2 wide, 3 other (SQL Server counts a number on its index of values, not a text). public long Bucket { get; set; } public long Score { get; set; } public DateTime? When { get; set; } } Path: redb/redb.Tests.Integration/README.md 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/README.md ---- # redb.Tests.Integration Integration and unit tests of the redb packages, by provider folder (`Tests/Postgres`, `Tests/PostgresPro`, `Tests/MsSql`, `Tests/MsSqlPro`, `Tests/Sqlite`, `Tests/SqlitePro`, `Tests/Unit`, ...). The Pro folders run in both planner modes (`REDB_PVT_PREFILTER=0` and `=1`). ## Pins a schema change must satisfy Three groups of tests fail on purpose when the schema or the start-up path changes, until the change carries what goes with it: - **Index tables** (`IndexCatalogTests` per provider, and the Pro ones): the expected indexes of each provider are a generated table (`*IndexCatalog.g.cs`), compared both ways with a fresh database. Add, drop or redefine an index and regenerate the table: run the test with `REDB_WRITE_INDEX_CATALOG=1`, or, on a test host that cannot write the source tree, take the file from the failure message (between `===BEGIN` and `===END`). Review the diff. - **Streams index files** (`StreamsIndexesFilePinTests`): `pvt_streams_indexes.sql` of PostgreSQL Pro and SQL Server Pro is built once, at the module step that brings it. A change of a file goes with a new module version and `StreamsIndexes.Since` set to it, then the pinned hash. - **SQLite start-up** (`SqlitePlannerStatisticsTests`): every SQLite start may analyze the file (no statistics and at least 10 000 value rows) or run `PRAGMA optimize`. A test that counts statements or reads `sqlite_stat1` at start-up sees that step. ## Databases the tests leave None, except the shared ones the fixtures reuse on purpose (`redb`, and `redb_collation_c` on PostgreSQL, whose non-default locale is slow to create). A class that creates a database, role or login of its own drops it by exact name when it is done, also when its tests failed. Path: redb/redb.Tests.Integration/Tests/Base/AbsentFieldConsistencyTestsBase.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/AbsentFieldConsistencyTestsBase.cs ---- using redb.Core; using redb.Core.Models.Entities; using redb.Core.Query; using redb.Core.Query.Aggregation; using redb.Core.Query.Window; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// An object that has no value for a field must still be seen by every kind of query: counted, /// selected by "Field == null", grouped under the NULL key, kept in a window. /// /// Aggregates and groupings used to range over rows of _values instead of objects, so an object /// without a row on any field of the statement was not in their input at all. Three symptoms, all /// silent: Agg.Count() depended on which other aggregates shared the batch; a null check /// selected nothing; a nullable grouping key produced no NULL group. Pages, CountAsync and /// AnyAsync, driven by _objects, answered correctly, so the same Where gave different sets /// depending on the terminal operation. /// /// Every expectation here is computed in memory from the loaded objects, and every query runs /// with the planner off and on: both forms have to tell the truth, not merely agree. /// public abstract class AbsentFieldConsistencyTestsBase { protected readonly IRedbService Redb; protected AbsentFieldConsistencyTestsBase(IRedbService redb) => Redb = redb; /// Two persons with a status and four without: the field under test is absent for most. private async Task>> SeedAndLoadAsync(string listName) { var existing = await Redb.ListProvider.GetListByNameAsync(listName); if (existing != null) { var oldItems = await Redb.ListProvider.GetListItemsAsync(existing.Id); if (oldItems.Count > 0) await Redb.Context.Bulk.BulkDeleteValuesByListItemIdsAsync(oldItems.Select(i => i.Id).ToList()); await Redb.ListProvider.DeleteListAsync(existing.Id); } var list = await Redb.ListProvider.SaveListAsync(RedbList.Create(listName, listName)); var items = await Redb.ListProvider.AddItemsAsync(list, ["Active", "Blocked"]); var persons = Enumerable.Range(0, 6).Select(i => new RedbObject { name = $"{listName}_{i}", Props = new PersonProps { Name = $"Person{i}", Age = 30 + i % 2, Email = $"p{i}@absent.test", Status = i < 2 ? items[i] : null } }).ToList(); await Redb.SaveAsync(persons); var all = await Redb.Query().ToListAsync(); all.Count(p => p.Props.Status == null).Should().BeGreaterThan(0, "the seed leaves the status empty"); all.Count(p => p.Props.Status != null).Should().BeGreaterThan(0, "the seed sets the status"); return all; } private async Task EachFormAsync(Func check) { var restore = Redb.Configuration.EnablePvtPrefilter; try { foreach (var on in new[] { false, true }) { Redb.UpdateConfiguration(c => c.EnablePvtPrefilter = on); await check(on ? "planner on" : "planner off"); } } finally { Redb.UpdateConfiguration(c => c.EnablePvtPrefilter = restore); } } [Fact] public async Task NullCheck_SameSetForEveryTerminalOperation() { var all = await SeedAndLoadAsync("AbsentField_Terminal"); var expected = all.Where(p => p.Props.Status == null).ToList(); await EachFormAsync(async form => { IRedbQueryable Query() => Redb.Query().Where(p => p.Status == null); (await Query().CountAsync()).Should().Be(expected.Count, $"CountAsync, {form}"); (await Query().ToListAsync()).Count.Should().Be(expected.Count, $"ToListAsync, {form}"); (await Query().AnyAsync()).Should().BeTrue($"AnyAsync, {form}"); var counted = await Query().AggregateAsync(x => new { Count = Agg.Count() }); counted.Count.Should().Be(expected.Count, $"Agg.Count() alone reads no field but the filtered one, which these objects lack, {form}"); var batch = await Query().AggregateAsync(x => new { Count = Agg.Count(), SumAge = Agg.Sum(x.Props.Age) }); batch.Count.Should().Be(expected.Count, $"Agg.Count() next to Agg.Sum, {form}"); ((long)batch.SumAge).Should().Be(expected.Sum(p => (long)p.Props.Age), $"Agg.Sum(Age), {form}"); var sum = await Query().SumAsync(p => p.Age); ((long)sum).Should().Be(expected.Sum(p => (long)p.Props.Age), $"SumAsync(Age), {form}"); }); } [Fact] public async Task AggregateCount_DoesNotDependOnOtherAggregates() { var all = await SeedAndLoadAsync("AbsentField_Batch"); await EachFormAsync(async form => { var alone = await Redb.Query().AggregateAsync(x => new { Count = Agg.Count() }); alone.Count.Should().Be(all.Count, $"Agg.Count() alone, {form}"); var withNullable = await Redb.Query() .AggregateAsync(x => new { Count = Agg.Count(), MaxStatus = Agg.Max(x.Props.Status!.Id) }); withNullable.Count.Should().Be(all.Count, $"an aggregate over a field most objects lack must not shrink Agg.Count(), {form}"); }); } [Fact] public async Task GroupBy_NullableKey_KeepsObjectsWithoutValue() { var all = await SeedAndLoadAsync("AbsentField_GroupBy"); var withoutStatus = all.Count(p => p.Props.Status == null); var distinctStatuses = all.Where(p => p.Props.Status != null).Select(p => p.Props.Status!.Id).Distinct().Count(); await EachFormAsync(async form => { var groups = await Redb.Query() .GroupBy(p => p.Status!.Id) .SelectAsync(g => new { g.Key, Count = Agg.Count(g) }); groups.Sum(g => g.Count).Should().Be(all.Count, $"every object belongs to a group, {form}"); groups.Count.Should().Be(distinctStatuses + 1, $"objects without a status form the NULL group, {form}"); var filtered = await Redb.Query() .Where(p => p.Status == null) .GroupBy(p => p.Status!.Id) .SelectAsync(g => new { g.Key, Count = Agg.Count(g) }); filtered.Sum(g => g.Count).Should().Be(withoutStatus, $"null check before GroupBy, {form}"); filtered.Count.Should().Be(1, $"only the NULL group is left, {form}"); }); } [Fact] public async Task DistinctBy_NullableKey_KeepsOneObjectWithoutValue() { var all = await SeedAndLoadAsync("AbsentField_DistinctBy"); var distinctStatuses = all.Where(p => p.Props.Status != null).Select(p => p.Props.Status!.Id).Distinct().Count(); await EachFormAsync(async form => { var flat = await Redb.Query().DistinctBy(p => p.Status!.Id).ToListAsync(); flat.Count.Should().Be(distinctStatuses + 1, $"objects without a status share the NULL key, flat query, {form}"); var tree = await Redb.TreeQuery().DistinctBy(p => p.Status!.Id).ToListAsync(); tree.Count.Should().Be(distinctStatuses + 1, $"objects without a status share the NULL key, tree query, {form}"); }); } [Fact] public async Task OrderBy_NullableKey_DoesNotDropObjects() { var all = await SeedAndLoadAsync("AbsentField_OrderBy"); await EachFormAsync(async form => { var flat = await Redb.Query().OrderBy(p => p.Status!.Id).ToListAsync(); flat.Count.Should().Be(all.Count, $"sorting is not filtering, flat query, {form}"); var paged = await Redb.Query().OrderBy(p => p.Status!.Id).Take(all.Count + 10).ToListAsync(); paged.Count.Should().Be(all.Count, $"sorting is not filtering, flat page, {form}"); var tree = await Redb.TreeQuery().OrderBy(p => p.Status!.Id).ToListAsync(); tree.Count.Should().Be(all.Count, $"sorting is not filtering, tree query, {form}"); }); } /// /// Where the objects without a value go: first when ascending, last when descending, as LINQ to /// objects puts null. SQL Server and SQLite do that by default; PostgreSQL did the opposite until /// its sort keys spelled out NULLS FIRST / NULLS LAST. /// [Fact] public async Task OrderBy_NullableKey_PutsObjectsWithoutValueWhereLinqDoes() { var all = await SeedAndLoadAsync("AbsentField_NullOrder"); var withoutStatus = all.Count(p => p.Props.Status == null); withoutStatus.Should().BeGreaterThan(0, "the seed must hold objects without the key"); await EachFormAsync(async form => { var ascending = await Redb.Query().OrderBy(p => p.Status!.Id).ThenByRedb(o => o.Id).ToListAsync(); ascending.Take(withoutStatus).Should().OnlyContain(p => p.Props.Status == null, $"ascending puts null first, as LINQ does, {form}"); var descending = await Redb.Query().OrderByDescending(p => p.Status!.Id).ThenByRedb(o => o.Id).ToListAsync(); descending.Skip(descending.Count - withoutStatus).Should().OnlyContain(p => p.Props.Status == null, $"descending puts null last, as LINQ does, {form}"); var page = await Redb.Query().OrderBy(p => p.Status!.Id).ThenByRedb(o => o.Id).Take(withoutStatus).ToListAsync(); page.Should().OnlyContain(p => p.Props.Status == null, $"the first page of an ascending sort is the objects without a value, {form}"); }); } [Fact] public async Task Window_PartitionByNullableField_KeepsObjectsWithoutValue() { var all = await SeedAndLoadAsync("AbsentField_Window"); var withoutStatus = all.Count(p => p.Props.Status == null); await EachFormAsync(async form => { var rows = await Redb.Query() .WithWindow(w => w.PartitionBy(p => p.Status!.Id).OrderByDesc(p => p.Status!.Id)) .SelectAsync(x => new { x.Id, Row = Win.RowNumber() }); rows.Count.Should().Be(all.Count, $"the window reads no field but the one most objects lack, {form}"); var filtered = await Redb.Query() .Where(p => p.Status == null) .WithWindow(w => w.PartitionBy(p => p.Status!.Id).OrderByDesc(p => p.Status!.Id)) .SelectAsync(x => new { x.Id, Row = Win.RowNumber() }); filtered.Count.Should().Be(withoutStatus, $"null check before the window, {form}"); }); } } Path: redb/redb.Tests.Integration/Tests/Base/AbsentValuesTestsBase.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/AbsentValuesTestsBase.cs ---- using redb.Core; 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; /// /// Analytics over objects that store no value for the fields a statement reads: a null field, an empty or missing array /// and an unset list item have no props row. Every object of the source still counts, groups (the missing value is its /// own group) and takes a window row, as the same LINQ over the objects in memory does. /// /// Also the key of a grouping by a list item: by its Value it is the text of the item, never its id; by the item itself /// it is the item a loaded object carries, with every field of it. /// /// Each test reads only the objects it seeded (by id, or by the root of its tree), so the shared database stays out. /// public abstract class AbsentValuesTestsBase { protected readonly IRedbService Redb; protected AbsentValuesTestsBase(IRedbService redb) => Redb = redb; // SkillLevels: two arrays with elements (average 1.75), an empty one and three with none; Rating: three set, // three null. Ages 30..35 average 32.5. private static readonly int[]?[] Levels = [[1, 2, 2], [2], [], null, null, null]; private static readonly double?[] Ratings = [4.5, 4.5, null, null, 3.0, null]; private sealed record SeededEmployees(long RootId, List Ids, List Props); private async Task SeedEmployeesAsync() { await Redb.SyncSchemeAsync(); var tag = "av-" + Guid.NewGuid().ToString("N")[..8]; var root = new TreeRedbObject { name = $"{tag}-root", Props = TestDataFactory.CreateEmployee(0, department: $"{tag}-root").Props }; root.id = await Redb.SaveAsync(root); var ids = new List(); var props = new List(); for (var i = 0; i < Levels.Length; i++) { var p = TestDataFactory.CreateEmployee(i + 1, firstName: $"{tag}-{i}", department: tag).Props; p.Age = 30 + i; p.SkillLevels = Levels[i]; p.Rating = Ratings[i]; ids.Add(await Redb.CreateChildAsync(new TreeRedbObject { name = $"{tag}-{i}", Props = p }, root)); props.Add(p); } return new SeededEmployees(root.id, ids, props); } private IRedbQueryable Employees(SeededEmployees s, bool tree) { if (tree) return Redb.TreeQuery(s.RootId).WhereRedb(o => o.Id != s.RootId); var idSet = s.Ids.ToHashSet(); return Redb.Query().WhereRedb(o => idSet.Contains(o.Id)); } [Theory] [InlineData(false)] [InlineData(true)] public async Task Aggregate_CountNextToArrayAggregate_CountsEveryObject(bool tree) { var s = await SeedEmployeesAsync(); var elements = s.Props.Where(p => p.SkillLevels != null).SelectMany(p => p.SkillLevels!).ToList(); var r = await Employees(s, tree).AggregateAsync(x => new { Sum = Agg.Sum(x.Props.SkillLevels!.Select(v => v)), Avg = Agg.Average(x.Props.SkillLevels!.Select(v => v)), Count = Agg.Count() }); r.Count.Should().Be(s.Props.Count, "objects without elements are objects of the source too"); r.Sum.Should().Be(elements.Sum()); ((double)r.Avg).Should().BeApproximately(elements.Average(), 1e-9, "the average of integers is not an integer"); (await Employees(s, tree).CountAsync()).Should().Be(s.Props.Count); } [Theory] [InlineData(false)] [InlineData(true)] public async Task Aggregate_CountNextToNullableField_CountsEveryObject(bool tree) { var s = await SeedEmployeesAsync(); var r = await Employees(s, tree).AggregateAsync(x => new { Max = Agg.Max(x.Props.Rating), Count = Agg.Count(), AvgAge = Agg.Average(x.Props.Age) }); r.Count.Should().Be(s.Props.Count); r.Max.Should().Be(s.Props.Max(p => p.Rating)); ((double)r.AvgAge).Should().BeApproximately(s.Props.Average(p => p.Age), 1e-9, "the average of integers is not an integer"); } [Theory] [InlineData(false)] [InlineData(true)] public async Task GroupBy_NullableField_KeepsTheNullGroup(bool tree) { var s = await SeedEmployeesAsync(); var groups = await Employees(s, tree).GroupBy(e => e.Rating) .SelectAsync(g => new { Key = g.Key, Count = Agg.Count(g) }); groups.Select(g => (g.Key, g.Count)).Should().BeEquivalentTo( s.Props.GroupBy(p => p.Rating).Select(g => (g.Key, g.Count()))); } [Theory] [InlineData(false)] [InlineData(true)] public async Task Window_OverNullableField_EveryObjectTakesARow(bool tree) { var s = await SeedEmployeesAsync(); var rows = await Employees(s, tree).WithWindow(w => w.OrderBy(e => e.Rating)) .SelectAsync(e => new { e.Props.FirstName, Row = Win.RowNumber() }); rows.Select(r => r.FirstName).Should().BeEquivalentTo(s.Props.Select(p => p.FirstName)); rows.Select(r => r.Row).Should().BeEquivalentTo(Enumerable.Range(1, s.Props.Count).Select(i => (long)i)); } [Theory] [InlineData(false)] [InlineData(true)] public async Task GroupedWindow_NullableKey_KeepsTheNullGroup(bool tree) { var s = await SeedEmployeesAsync(); var ranked = await Employees(s, tree).GroupBy(e => e.Rating).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( s.Props.GroupBy(p => p.Rating).Select(g => (g.Key, g.Count()))); } [Theory] [InlineData(false)] [InlineData(true)] public async Task List_OrderedByNullableField_ReturnsEveryObject(bool tree) { var s = await SeedEmployeesAsync(); var list = await Employees(s, tree).OrderBy(e => e.Rating).ToListAsync(); list.Select(o => o.Props.FirstName).Should().BeEquivalentTo(s.Props.Select(p => p.FirstName)); } [Theory] [InlineData(false)] [InlineData(true)] public async Task List_OrderedByNullableField_EveryFormThroughTheListPath(bool tree) { var s = await SeedEmployeesAsync(); var unset = s.Ids.Where((_, i) => s.Props[i].Rating == null).ToHashSet(); (await Employees(s, tree).OrderBy(e => e.Rating).Skip(0).Take(s.Props.Count).ToListAsync()) .Should().HaveCount(s.Props.Count, "Take of every object"); (await Employees(s, tree).OrderBy(e => e.Rating).Skip(3).Take(3).ToListAsync()) .Should().HaveCount(3, "the second half of six"); (await Employees(s, tree).OrderBy(e => e.Rating).CountAsync()).Should().Be(s.Props.Count); // Only the objects that leave Rating unset: before the fix nothing came back for them. var onlyUnset = Employees(s, tree).WhereRedb(o => unset.Contains(o.Id)).OrderBy(e => e.Rating); (await onlyUnset.CountAsync()).Should().Be(unset.Count); (await onlyUnset.AnyAsync()).Should().BeTrue(); (await onlyUnset.ToListAsync()).Select(o => o.id).Should().BeEquivalentTo(unset); } // ── List items ────────────────────────────────────────────────────────────── private sealed record SeededPersons(List Ids, List> Loaded); /// Six persons: two Active, one Blocked (both items with an alias), three without a status. private async Task SeedPersonsAsync() { await Redb.SyncSchemeAsync(); var tag = "av-" + Guid.NewGuid().ToString("N")[..8]; var list = await Redb.ListProvider.SaveListAsync(RedbList.Create(tag, tag)); var items = await Redb.ListProvider.AddItemsAsync(list, ["Active", "Blocked"], ["a-alias", "b-alias"]); var active = items.First(i => i.Value == "Active"); var blocked = items.First(i => i.Value == "Blocked"); RedbListItem?[] statuses = [active, active, blocked, null, null, null]; var persons = statuses.Select((st, i) => new RedbObject { name = $"{tag}-{i}", Props = new PersonProps { Name = $"{tag}-{i}", Age = 20 + i, Email = $"{tag}-{i}@test", Status = st } }).ToList(); var ids = await Redb.SaveAsync(persons); var idSet = ids.ToHashSet(); var loaded = await Redb.Query().WhereRedb(o => idSet.Contains(o.Id)).ToListAsync(); return new SeededPersons(ids, loaded.ToList()); } private IRedbQueryable Persons(SeededPersons s) { var idSet = s.Ids.ToHashSet(); return Redb.Query().WhereRedb(o => idSet.Contains(o.Id)); } [Fact] public async Task GroupBy_ListItemId_KeepsTheGroupWithoutAnItem() { var s = await SeedPersonsAsync(); var groups = await Persons(s).GroupBy(p => p.Status!.Id) .SelectAsync(g => new { Key = g.Key, Count = Agg.Count(g) }); // The key is a long: the group of persons without a status reads 0. groups.Select(g => (g.Key, g.Count)).Should().BeEquivalentTo( s.Loaded.GroupBy(o => o.Props.Status?.Id ?? 0).Select(g => (g.Key, g.Count()))); } // Without any filter: a grouping over the whole scheme takes a shorter path on some engines than one with a // condition (PostgreSQL Free: an inline pivot of its own), and that path lost the group without an item too. [Fact] public async Task GroupBy_ListItem_WithoutAnyFilter_KeepsTheGroupWithoutAnItem() { await SeedPersonsAsync(); var all = await Redb.Query().ToListAsync(); var byId = await Redb.Query().GroupBy(p => p.Status!.Id) .SelectAsync(g => new { Key = g.Key, Count = Agg.Count(g) }); var byValue = await Redb.Query().GroupBy(p => p.Status!.Value) .SelectAsync(g => new { Key = g.Key, Count = Agg.Count(g) }); byId.Select(g => (g.Key, g.Count)).Should().BeEquivalentTo( all.GroupBy(o => o.Props.Status?.Id ?? 0).Select(g => (g.Key, g.Count()))); byValue.Select(g => (g.Key, g.Count)).Should().BeEquivalentTo( all.GroupBy(o => o.Props.Status?.Value).Select(g => (g.Key, g.Count()))); } [Fact] public async Task GroupBy_ListItemValue_IsTheTextOfTheItem_AndKeepsTheNullGroup() { var s = await SeedPersonsAsync(); var groups = await Persons(s).GroupBy(p => p.Status!.Value) .SelectAsync(g => new { Key = g.Key, Count = Agg.Count(g) }); groups.Select(g => (g.Key, g.Count)).Should().BeEquivalentTo( s.Loaded.GroupBy(o => o.Props.Status?.Value).Select(g => (g.Key, g.Count()))); } [Fact] public async Task GroupBy_ListItem_KeyIsTheItemALoadedObjectCarries() { var s = await SeedPersonsAsync(); var query = Persons(s).GroupBy(p => p.Status); var groups = await query.SelectAsync(g => new { Key = g.Key, Count = Agg.Count(g) }); static (long?, long?, string?, long?, string?) Shape(RedbListItem? i) => (i?.Id, i?.IdList, i?.Value, i?.IdObject, i?.Alias); groups.Select(g => (Shape(g.Key), g.Count)).Should().BeEquivalentTo( s.Loaded.GroupBy(o => o.Props.Status?.Id).Select(g => (Shape(g.First().Props.Status), g.Count()))); (await query.ToSqlStringAsync(g => new { Key = g.Key, Count = Agg.Count(g) })).Should().NotBeNullOrWhiteSpace(); } } Path: redb/redb.Tests.Integration/Tests/Base/AggregatePathTestsBase.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/AggregatePathTestsBase.cs ---- using redb.Core; using redb.Core.Models.Entities; using redb.Core.Query; using redb.Core.Query.Aggregation; using redb.Core.Query.Window; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// The field path of an aggregate, a group key and a window key follows the filter's rule: a dictionary entry and the /// Value of a nullable read the entry and the value, and a path that cannot be read is refused with /// NotSupportedException. It must never fall back to another field (Items[0].Rank read as the object's own Rank). /// /// Two objects of one tag, both Name "top", Rank 1; Items[0] is { "inner", 7 } and { "other", 7 }; /// Items[1] is { "zz-second", 70 }; ByKey["k"] is { "entry", 5 }, ByKey["z"] is { "zz-other-entry", 50 }; Main.Score /// is 4; Scores is { a: 1, n: null, z: 90 }. The second element and the other entries hold larger values and names /// that sort last, so an answer that reads the wrong element or entry (a MAX over all of them) does not match. /// public abstract class AggregatePathTestsBase { protected readonly IRedbService Redb; protected AggregatePathTestsBase(IRedbService redb) => Redb = redb; private static FieldPathProps Row(string inner) => new() { Name = "top", Rank = 1, Items = [new FieldPathItem { Name = inner, Rank = 7 }, new FieldPathItem { Name = "zz-second", Rank = 70 }], Parts = [new FieldPathItem { Name = inner, Rank = 7 }], ByKey = new Dictionary { ["k"] = new() { Name = "entry", Rank = 5 }, ["z"] = new() { Name = "zz-other-entry", Rank = 50 } }, Main = new FieldPathItem { Name = "main", Rank = 3, Score = 4 }, Scores = new Dictionary { ["a"] = 1, ["n"] = null, ["z"] = 90 } }; /// /// The two objects, as a flat query by their ids, or as the subtree of a root (TreeQuery) whose own values differ, /// so an answer that took the root in would not match either. /// private async Task> SeedAsync(bool tree) { await Redb.SyncSchemeAsync(); var tag = "ap-" + Guid.NewGuid().ToString("N")[..8]; if (tree) { var root = new TreeRedbObject { name = tag + "-root", Props = Row("root") }; root.Props.Rank = 100; root.Props.Items![0].Rank = 100; root.id = await Redb.SaveAsync(root); foreach (var inner in new[] { "inner", "other" }) await Redb.CreateChildAsync(new TreeRedbObject { name = $"{tag}-{inner}", Props = Row(inner) }, root); return Redb.TreeQuery(root.id); } var ids = new List(); foreach (var inner in new[] { "inner", "other" }) ids.Add(await Redb.SaveAsync(new RedbObject { name = $"{tag}-{inner}", Props = Row(inner) })); var a = ids[0]; var b = ids[1]; return Redb.Query().WhereRedb(o => o.Id == a || o.Id == b); } public delegate Task Run(IRedbQueryable q); /// (kind, run, expected, mustWork): mustWork means a refusal is a failure too. private static IEnumerable<(string Kind, Run Run, string Expected, bool MustWork)> Shapes() { // Single aggregates. A plain int? field must work: TField : struct makes the caller write .Value. yield return ("sum-nullable-value", async q => await q.SumAsync(p => p.Main!.Score!.Value), "8", true); yield return ("average-nullable-value", async q => await q.AverageAsync(p => p.Main!.Score!.Value), "4", true); yield return ("min-nullable-value", async q => await q.MinAsync(p => p.Main!.Score!.Value), "4", true); yield return ("max-nullable-value", async q => await q.MaxAsync(p => p.Main!.Score!.Value), "4", true); yield return ("statistics-nullable-value", async q => Stats(await q.GetStatisticsAsync(p => p.Main!.Score!.Value)), "8/4/4/4", true); // Through an element, an entry, an entry's Value: the right answer, or a refusal. yield return ("sum-array-index", async q => await q.SumAsync(p => p.Items![0].Rank), "14", false); yield return ("average-array-index", async q => await q.AverageAsync(p => p.Items![0].Rank), "7", false); yield return ("min-array-index", async q => await q.MinAsync(p => p.Items![0].Rank), "7", false); yield return ("max-array-index", async q => await q.MaxAsync(p => p.Items![0].Rank), "7", false); yield return ("statistics-array-index", async q => Stats(await q.GetStatisticsAsync(p => p.Items![0].Rank)), "14/7/7/7", false); yield return ("sum-dictionary-entry-field", async q => await q.SumAsync(p => p.ByKey!["k"].Rank), "10", false); yield return ("sum-dictionary-nullable-value", async q => await q.SumAsync(p => p.Scores!["a"]!.Value), "2", false); yield return ("aggregate-array-index", async q => (await q.AggregateAsync(x => new { S = Agg.Sum(x.Props.Items![0].Rank) })).S, "14", false); yield return ("aggregate-dictionary-nullable-value", async q => (await q.AggregateAsync(x => new { S = Agg.Sum(x.Props.Scores!["a"]!.Value) })).S, "2", false); yield return ("aggregate-nullable-value", async q => (await q.AggregateAsync(x => new { S = Agg.Sum(x.Props.Main!.Score!.Value) })).S, "8", true); // Group keys. yield return ("group-array-index", async q => Keys((await q.GroupBy(p => p.Items![0].Name).SelectAsync(g => new { g.Key, C = Agg.Count(g) })).Select(r => (object?)r.Key)), "inner,other", false); yield return ("group-dictionary-entry-field", async q => Keys((await q.GroupBy(p => p.ByKey!["k"].Name).SelectAsync(g => new { g.Key, C = Agg.Count(g) })).Select(r => (object?)r.Key)), "entry", false); yield return ("group-dictionary-nullable-value", async q => Keys((await q.GroupBy(p => p.Scores!["a"]!.Value).SelectAsync(g => new { g.Key, C = Agg.Count(g) })).Select(r => (object?)r.Key)), "1", false); // Window keys: partitioned by Items[0].Name both rows are first; by the object's Name they would be 1 and 2. yield return ("window-partition-array-index", async q => Keys((await q.WithWindow(w => w.PartitionBy(p => p.Items![0].Name).OrderBy(p => p.Rank)) .SelectAsync(e => new { N = Win.RowNumber() })).Select(r => (object?)r.N)), "1,1", false); yield return ("window-partition-dictionary-nullable-value", async q => Keys((await q.WithWindow(w => w.PartitionBy(p => p.Scores!["a"]!.Value).OrderBy(p => p.Rank)) .SelectAsync(e => new { N = Win.RowNumber() })).Select(r => (object?)r.N)), "1,2", false); yield return ("window-order-nullable-value", async q => Keys((await q.WithWindow(w => w.OrderBy(p => p.Main!.Score!.Value)) .SelectAsync(e => new { N = Win.RowNumber() })).Select(r => (object?)r.N)), "1,2", true); } public static IEnumerable Cases() { foreach (var tree in new[] { false, true }) foreach (var s in Shapes()) yield return [(tree ? "tree-" : "flat-") + s.Kind, tree, s.Run, s.Expected, s.MustWork]; } private static string Stats(Core.Query.Aggregation.FieldStatistics s) where T : struct => string.Join("/", Fmt(s.Sum), Fmt(s.Average), Convert.ToString(s.Min, System.Globalization.CultureInfo.InvariantCulture), Convert.ToString(s.Max, System.Globalization.CultureInfo.InvariantCulture)); private static string Fmt(object? v) => v is decimal d ? d.ToString("0.##########", System.Globalization.CultureInfo.InvariantCulture) : Convert.ToString(v, System.Globalization.CultureInfo.InvariantCulture) ?? ""; private static string Keys(IEnumerable keys) => string.Join(",", keys.Select(k => Convert.ToString(k, System.Globalization.CultureInfo.InvariantCulture)).OrderBy(k => k, StringComparer.Ordinal)); // The flat Pro answers on PostgreSQL and SQL Server were 0 for these three, with no error: the path came out as // Main.Score.Value or Scores[a].Value, no field of the scheme, and the aggregate dropped it from the statement. [Fact] public async Task AggSumOverANullableValue_ReadsTheField_NotASilentZero() { var q = await SeedAsync(tree: false); (await q.AggregateAsync(x => new { S = Agg.Sum(x.Props.Main!.Score!.Value) })).S.Should().Be(8); } [Fact] public async Task AggSumOverADictionaryEntryValue_ReadsTheEntry_NotASilentZero() { var q = await SeedAsync(tree: false); (await q.AggregateAsync(x => new { S = Agg.Sum(x.Props.Scores!["a"]!.Value) })).S.Should().Be(2); } [Fact] public async Task StatisticsOverANullableValue_ReadTheField_NotSilentZeros() { var q = await SeedAsync(tree: false); Stats(await q.GetStatisticsAsync(p => p.Main!.Score!.Value)).Should().Be("8/4/4/4"); } [Theory] [MemberData(nameof(Cases))] public async Task PathThroughAnEntryAnElementOrANullable_ReadsThatField_OrIsRefused( string kind, bool tree, Run run, string expected, bool mustWork) { var q = await SeedAsync(tree); object? result; try { result = await run(q); } catch (NotSupportedException) when (!mustWork) { return; // refused: never a wrong answer } Fmt(result).Should().Be(expected, $"case {kind}"); } } Path: redb/redb.Tests.Integration/Tests/Base/AggregatePreviewTestsBase.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/AggregatePreviewTestsBase.cs ---- using redb.Core; using redb.Core.Query; using redb.Core.Query.Aggregation; using redb.Tests.Integration.Helpers; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// The aggregate SQL preview shows the query that runs. The Pro previews built it with no filter while /// AggregateAsync passed the query's Where: the preview of a filtered sum showed a sum over the whole scheme. Free asked /// for aggregate_batch_preview, a function of the removed legacy module, and threw NotSupportedException. /// public abstract class AggregatePreviewTestsBase { protected readonly IRedbService Redb; protected AggregatePreviewTestsBase(IRedbService redb) => Redb = redb; [Fact] public async Task AggregatePreview_CarriesTheWhere() { await Redb.SyncSchemeAsync(); var department = $"preview-{Guid.NewGuid():N}"; var sql = await Redb.Query() .Where(e => e.Department == department && e.Salary > 1m) .ToAggregateSqlStringAsync(x => new { Total = Agg.Sum(x.Props.Salary), Headcount = Agg.Count() }); sql.Should().Contain(department, "the preview must carry the Where the aggregate runs with"); } } /// /// On Free the preview is the statement the aggregate runs: pvt_build_aggregate_sql compiles it with every value inline, /// so it runs as it is and gives what AggregateAsync returns. /// public abstract class FreeAggregatePreviewTestsBase : AggregatePreviewTestsBase { protected FreeAggregatePreviewTestsBase(IRedbService redb) : base(redb) { } [Fact] public async Task AggregatePreview_RunAsItIs_GivesWhatTheAggregateReturns() { await Redb.SyncSchemeAsync(); var department = $"preview-{Guid.NewGuid():N}"; await Redb.SaveAsync(Enumerable.Range(1, 3) .Select(i => TestDataFactory.CreateEmployee(i, salary: 100m * i, department: department)).ToList()); IRedbQueryable Tagged() => Redb.Query().Where(e => e.Department == department); var aggregate = await Tagged().AggregateAsync(x => new { Total = Agg.Sum(x.Props.Salary) }); var sql = await Tagged().ToAggregateSqlStringAsync(x => new { Total = Agg.Sum(x.Props.Salary) }); aggregate.Total.Should().Be(600m); (await Redb.Context.ExecuteScalarAsync(sql)).Should().Be(aggregate.Total, "the preview is the statement that runs"); } } /// /// The Pro preview reads the selector with the parser the execution uses. Its own parser took a dictionary's .Values /// and an indexer key for nothing, and the preview showed SELECT 1 AS "_empty" for an aggregate that runs. /// public abstract class ProAggregatePreviewTestsBase : AggregatePreviewTestsBase { protected ProAggregatePreviewTestsBase(IRedbService redb) : base(redb) { } [Fact] public async Task AggregatePreview_DictionaryValues_AggregatesTheValues() { await Redb.SyncSchemeAsync(); var sql = await Redb.Query() .ToAggregateSqlStringAsync(x => new { Total = Agg.Sum(x.Props.BonusByYear!.Values) }); sql.ToUpperInvariant().Should().Contain("SUM("); sql.Should().NotContain("_empty", "the values of the dictionary are aggregated"); } [Fact] public async Task AggregatePreview_DictionaryKey_AggregatesThatKey() { await Redb.SyncSchemeAsync(); var sql = await Redb.Query() .ToAggregateSqlStringAsync(x => new { Bonus = Agg.Sum(x.Props.BonusByYear![2023]) }); sql.Should().ContainEquivalentOf("_array_index", "the key selects one entry of the dictionary"); sql.Should().Contain("2023"); sql.Should().NotContain("_empty"); } } Path: redb/redb.Tests.Integration/Tests/Base/AggregationOverArrayTestsBase.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/AggregationOverArrayTestsBase.cs ---- using redb.Core; using redb.Core.Models.Entities; using redb.Core.Query; using redb.Core.Query.Aggregation; using redb.Tests.Integration.Helpers; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// Deep-coverage integration tests for scalar aggregation over array fields /// (Agg.Sum/Average/Min/Max/Count over arr.Select(...) or arr[i]). /// /// Complements BugRegressionTestsBase.E150_* by exercising: /// * Min/Max over unnested array elements; /// * mixed Sum+Avg+Min+Max+Count in a single AggregateAsync projection; /// * outer Where before AggregateAsync (filter must apply before unnest); /// * indexed access at multiple positions (Skills[0] / Skills[1]); /// * count of unnested elements (Agg.Count over Select). /// /// Targets free PG, Pro PG, Pro MSSql. Free MSSql array-aggregate path is not /// supported. /// public abstract class AggregationOverArrayTestsBase { protected readonly IRedbService Redb; protected AggregationOverArrayTestsBase(IRedbService redb) => Redb = redb; private async Task SeedAsync() => await TestDataFactory.SeedEmployees(Redb, 20); // ────────────────────────────────────────────────────────────────── // Min / Max over all elements (unnest) // ────────────────────────────────────────────────────────────────── [Fact] public async Task AggMinMax_OverArray_AllElements_SkillLevels() { await SeedAsync(); var r = await Redb.Query() .AggregateAsync(x => new { Min = Agg.Min(x.Props.SkillLevels.Select(s => s)), Max = Agg.Max(x.Props.SkillLevels.Select(s => s)) }); // Seed generator: SkillLevels = [5 - (i%3), 4, 3 + (i%2)] for i in 0..19. // Min possible across all elements is 3 (3 + 0), max is 5 (5 - 0). r.Min.Should().BeGreaterThanOrEqualTo(1); r.Max.Should().BeLessThanOrEqualTo(10); r.Min.Should().BeLessThanOrEqualTo(r.Max); } // ────────────────────────────────────────────────────────────────── // Sum + Avg + Min + Max + Count mixed in one projection // ────────────────────────────────────────────────────────────────── [Fact] public async Task AggAll_MixedInOneSelect_SkillLevels_AllPositive() { await SeedAsync(); var r = await Redb.Query() .AggregateAsync(x => new { Sum = Agg.Sum(x.Props.SkillLevels.Select(s => s)), Avg = Agg.Average(x.Props.SkillLevels.Select(s => s)), Min = Agg.Min(x.Props.SkillLevels.Select(s => s)), Max = Agg.Max(x.Props.SkillLevels.Select(s => s)), Rows = Agg.Count() }); r.Sum.Should().BeGreaterThan(0); r.Avg.Should().BeGreaterThan(0); r.Min.Should().BeLessThanOrEqualTo(r.Max); r.Rows.Should().BeGreaterThan(0); // Sum/Rows must be at least Avg (each row contributes ≥1 element). } // ────────────────────────────────────────────────────────────────── // Outer Where applied before array unnest // ────────────────────────────────────────────────────────────────── [Fact] public async Task AggSum_OverArray_AfterOuterWhere_ReducesTotal() { await SeedAsync(); var full = await Redb.Query() .AggregateAsync(x => new { S = Agg.Sum(x.Props.SkillLevels.Select(s => s)) }); var remoteOnly = await Redb.Query() .Where(e => e.IsRemote) .AggregateAsync(x => new { S = Agg.Sum(x.Props.SkillLevels.Select(s => s)) }); full.S.Should().BeGreaterThan(0); remoteOnly.S.Should().BeGreaterThan(0); remoteOnly.S.Should().BeLessThan(full.S, "subset sum must be smaller than total"); } // ────────────────────────────────────────────────────────────────── // Indexed access — two distinct indices // ────────────────────────────────────────────────────────────────── [Fact] public async Task AggSum_OverIndexedElement_FirstVsSecond_BothPositive() { await SeedAsync(); var r = await Redb.Query() .AggregateAsync(x => new { S0 = Agg.Sum(x.Props.SkillLevels[0]), S1 = Agg.Sum(x.Props.SkillLevels[1]) }); r.S0.Should().BeGreaterThan(0); r.S1.Should().BeGreaterThan(0); // Per seed: index 1 is always 4 → S1 == rowCount * 4. } // ────────────────────────────────────────────────────────────────── // Count over unnested elements // ────────────────────────────────────────────────────────────────── [Fact] public virtual async Task AggCount_OverUnnestedElements_EqualsRowsTimesArrayLength() { await SeedAsync(); var r = await Redb.Query() .AggregateAsync(x => new { Rows = Agg.Count(), Elements = Agg.Count(x.Props.SkillLevels.Select(s => s)) }); r.Rows.Should().BeGreaterThan(0); // Each seeded row has SkillLevels of length 3 -> total elements > row count. r.Elements.Should().BeGreaterThan(r.Rows, "Count over unnested array elements must exceed row count"); } // ────────────────────────────────────────────────────────────────── // Min / Max over string array (Skills) // ────────────────────────────────────────────────────────────────── [Fact] public async Task AggMinMax_OverStringArray_Skills_ReturnsString() { await SeedAsync(); var r = await Redb.Query() .AggregateAsync(x => new { MinSkill = Agg.Min(x.Props.Skills.Select(s => s)), MaxSkill = Agg.Max(x.Props.Skills.Select(s => s)) }); r.MinSkill.Should().NotBeNullOrWhiteSpace(); r.MaxSkill.Should().NotBeNullOrWhiteSpace(); string.Compare(r.MinSkill, r.MaxSkill, StringComparison.Ordinal) .Should().BeLessThanOrEqualTo(0, "MIN <= MAX in lexicographic order"); } } Path: redb/redb.Tests.Integration/Tests/Base/AggregationTestsBase.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/AggregationTestsBase.cs ---- using redb.Core; using redb.Core.Exceptions; using redb.Core.Query; using redb.Core.Query.Aggregation; using redb.Tests.Integration.Helpers; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; public abstract class AggregationTestsBase { protected readonly IRedbService Redb; protected readonly bool IsPro; protected AggregationTestsBase(IRedbService redb, bool isPro = false) { Redb = redb; IsPro = isPro; } // Every query reads only the objects its test seeded: other test classes share the database and may leave // employees without salary or department behind. private IRedbQueryable Seeded(List ids) => Redb.Query().WhereRedb(o => ids.Contains(o.Id)); private async Task> SeedAsync() { return await TestDataFactory.SeedEmployees(Redb, 15); } [Fact] public async Task CountAsync_ReturnsTotal() { var ids = await SeedAsync(); var count = await Seeded(ids).CountAsync(); count.Should().Be(15); } [Fact] public async Task CountAsync_WithFilter_Counts() { var ids = await SeedAsync(); var count = await Seeded(ids) .Where(e => e.IsRemote) .CountAsync(); count.Should().BeGreaterThan(0); } [Fact] public async Task AnyAsync_WithData_ReturnsTrue() { var ids = await SeedAsync(); var any = await Seeded(ids).AnyAsync(); any.Should().BeTrue(); } [Fact] public async Task AnyAsync_NoMatch_ReturnsFalse() { var any = await Redb.Query() .Where(e => e.Salary > 99_999_999m) .AnyAsync(); any.Should().BeFalse(); } [Fact] public async Task SumAsync_SumsSalaries() { var ids = await SeedAsync(); var sum = await Seeded(ids) .SumAsync(e => e.Salary); sum.Should().BeGreaterThan(0m); } [Fact] public async Task AverageAsync_AveragesAge() { var ids = await SeedAsync(); var avg = await Seeded(ids) .AverageAsync(e => e.Age); avg.Should().BeGreaterThan(0m); } [Fact] public async Task MinAsync_FindsMinSalary() { var ids = await SeedAsync(); var min = await Seeded(ids) .MinAsync(e => e.Salary); min.Should().NotBeNull(); min.Should().BeGreaterThan(0m); } [Fact] public async Task MaxAsync_FindsMaxSalary() { var ids = await SeedAsync(); var max = await Seeded(ids) .MaxAsync(e => e.Salary); max.Should().NotBeNull(); max!.Value.Should().BeGreaterThan(0m); } [Fact] public async Task AggregateAsync_CustomProjection() { var ids = await SeedAsync(); var result = await Seeded(ids) .AggregateAsync(e => new { TotalSalary = Agg.Sum(e.Props.Salary), AvgAge = Agg.Average(e.Props.Age), MinSalary = Agg.Min(e.Props.Salary), MaxSalary = Agg.Max(e.Props.Salary), Count = Agg.Count() }); result.Should().NotBeNull(); result!.TotalSalary.Should().BeGreaterThan(0m); result.Count.Should().Be(15); result.MinSalary.Should().BeLessThanOrEqualTo(result.MaxSalary); } /// /// A base field in a batch next to Props fields is a property of the object, not of a value row. /// The batch statement ranged over the rows of _values, so an object came once per aggregated /// structure and SUM(Id) came out doubled with two Props fields. Checked against the loaded objects, /// with and without a Props filter. On every provider: the free SQL Server and SQLite providers /// sent the base field without its "0$:" mark, and their modules refused it as a Props path. /// [Fact] public async Task AggregateAsync_BaseFieldNextToPropsFields_CountsEachObjectOnce() { var ids = await SeedAsync(); foreach (var withPropsFilter in new[] { false, true }) { var query = Seeded(ids); if (withPropsFilter) query = query.Where(e => e.Age >= 30); var result = await query.AggregateAsync(x => new { SumId = Agg.Sum(x.Id), Count = Agg.Count(), SumSalary = Agg.Sum(x.Props.Salary), MaxAge = Agg.Max(x.Props.Age), }); var rows = await query.ToListAsync(); result.Should().NotBeNull(); rows.Should().NotBeEmpty(); Convert.ToDecimal(result!.SumId).Should().Be(rows.Sum(o => (decimal)o.Id), $"SUM(Id) is taken once per object (Props filter: {withPropsFilter})"); Convert.ToDecimal(result.Count).Should().Be(rows.Count); Convert.ToDecimal(result.SumSalary).Should().Be(rows.Sum(o => o.Props.Salary)); Convert.ToDecimal(result.MaxAge).Should().Be(rows.Max(o => o.Props.Age)); } } [Fact] public async Task Select_ProjectsFields() { var ids = await SeedAsync(); var results = await Seeded(ids) .OrderBy(e => e.Age) .Take(5) .Select(e => new { e.Props.FirstName, e.Props.Salary }) .ToListAsync(); results.Should().HaveCount(5); results.Should().AllSatisfy(r => { r.FirstName.Should().NotBeEmpty(); r.Salary.Should().BeGreaterThan(0m); }); } [Fact] public async Task Distinct_RemovesDuplicateDepartments() { var ids = await SeedAsync(); var departments = await Seeded(ids) .Select(e => e.Props.Department) .Distinct() .ToListAsync(); departments.Should().OnlyHaveUniqueItems(); } [Fact] public async Task DistinctBy_RemovesDuplicatesByField() { var ids = await SeedAsync(); var results = await Seeded(ids) .DistinctBy(e => e.Department) .ToListAsync(); var depts = results.Select(r => r.Props.Department).ToList(); depts.Should().OnlyHaveUniqueItems(); } [Fact] public async Task WhereIn_FiltersMultipleValues() { var ids = await SeedAsync(); var targets = new[] { "Engineering", "Marketing" }; var results = await Seeded(ids) .WhereIn(e => e.Department, targets) .ToListAsync(); results.Should().NotBeEmpty(); results.Should().AllSatisfy(r => r.Props.Department.Should().BeOneOf(targets)); } [Fact] public async Task SumAsync_WithFilter_SumsFiltered() { var ids = await SeedAsync(); var totalSum = await Seeded(ids) .SumAsync(e => e.Salary); var remoteSum = await Seeded(ids) .Where(e => e.IsRemote) .SumAsync(e => e.Salary); var officeSum = await Seeded(ids) .Where(e => !e.IsRemote) .SumAsync(e => e.Salary); (remoteSum + officeSum).Should().Be(totalSum); } [Fact] public async Task AllAsync_PositiveSalary_ReturnsTrue() { var ids = await SeedAsync(); var all = await Seeded(ids) .AllAsync(e => e.Salary > 0); all.Should().BeTrue(); } // ===== FILTER-AWARE base-field (RedbAsync) aggregations ===== // These cover the gap that let a defect ship: base-field aggregations (SumRedbAsync / AggregateRedbAsync) // routed the filter through the filterJson provider overload, which Pro drops → aggregate over the WHOLE // scheme. Free was fine. Runs on all six fixtures (Free + Pro × 3), so both paths are checked. [Fact] public async Task SumRedbAsync_WithFilter_ScopesToFilteredObjects() { var ids = await SeedAsync(); var oneId = ids[0]; var allSum = await Seeded(ids).SumRedbAsync(o => o.Id); var filteredSum = await Seeded(ids) .WhereRedb(o => o.Id == oneId) .SumRedbAsync(o => o.Id); filteredSum.Should().Be(oneId, "the filter must scope the base-field sum to the one matching object"); filteredSum.Should().NotBe(allSum, "a dropped filter would sum Id over the whole scheme"); } [Fact] public async Task AggregateRedbAsync_WithFilter_ScopesToFilteredObjects() { var ids = await SeedAsync(); var oneId = ids[0]; var stats = await Seeded(ids) .WhereRedb(o => o.Id == oneId) .AggregateRedbAsync(o => new { Count = Agg.Count(), SumId = Agg.Sum(o.Id) }); ((int)stats.Count).Should().Be(1, "the filter must scope the base-field aggregate to one object"); ((long)stats.SumId).Should().Be(oneId); } [Fact] public async Task SumRedbAsync_EmptySelection_ReturnsZero_DoesNotThrow() { // The second defect the filter fix exposed: once WhereRedb actually narrows, a filter matching // nothing yields an EMPTY selection → SUM is NULL in SQL → reading it as a number threw // InvalidOperationException. Before the filter fix the selection was never empty (filter was // dropped), so this path was unreachable. "A ledger with no movements" must sum to 0, not throw. var ids = await SeedAsync(); var sum = await Seeded(ids) .WhereRedb(o => o.Id == -1) // no object has id -1 → empty selection .SumRedbAsync(o => o.Id); sum.Should().Be(0m); } [Fact] public async Task AverageRedbAsync_EmptySelection_ReturnsZero_DoesNotThrow() { var ids = await SeedAsync(); var avg = await Seeded(ids) .WhereRedb(o => o.Id == -1) .AverageRedbAsync(o => o.Id); avg.Should().Be(0m); } [Fact] public async Task GetStatisticsAsync_WithFilter_ScopesToFilteredObjects() { // GetStatisticsAsync is the Props path, but shares the same filterJson-drop defect on Pro. var ids = await SeedAsync(); var allStats = await Seeded(ids).GetStatisticsAsync(e => e.Salary); var remoteStats = await Seeded(ids) .Where(e => e.IsRemote) .GetStatisticsAsync(e => e.Salary); remoteStats.Count.Should().BeLessThan(allStats.Count, "the filter must scope the statistics; a dropped filter would count the whole scheme"); remoteStats.Count.Should().BeGreaterThan(0); } } Path: redb/redb.Tests.Integration/Tests/Base/AmbientTransactionTestsBase.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/AmbientTransactionTestsBase.cs ---- using System.Transactions; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using redb.Core; using redb.Core.Data; using redb.Core.Exceptions; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using redb.Tests.Integration.Helpers; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// redb inside an ambient . /// A redb.Route .Transacted() block is a TransactionScope, and every database write inside it - redb /// objects, raw SQL through redb.Context, a second DI scope of the same database - must commit or roll /// back with that scope. Before the plan none of the three providers did it: /// /// MSSQL - a speculative ROLLBACK right after opening a connection killed the enlistment; raw SQL /// autocommitted and the batch save failed on its savepoint; /// PostgreSQL and MSSQL - the key generator and a second scope opened a second connection inside the /// scope (MSSQL: implicit distributed transaction refused; PostgreSQL: abort at commit); /// SQLite - the driver never takes part in System.Transactions, so everything autocommitted silently. /// /// Verification always goes through a fresh DI scope OUTSIDE any transaction. /// public abstract class AmbientTransactionTestsBase : IAsyncLifetime { private const string NamePrefix = "ambient-tx-"; private readonly IServiceProvider _services; // Free and Pro collections of one provider share a database and may run at the same time: every test // removes only the tags it created, never a whole prefix. private readonly List _tags = new(); protected AmbientTransactionTestsBase(IServiceProvider services) => _services = services; /// Idempotent DDL of the probe table ambient_tx_rows (tag) in the provider's dialect. protected abstract string CreateProbeTableSql { get; } /// A statement that runs for about two seconds in the provider's dialect and returns one number. protected abstract string SlowStatementSql { get; } /// /// A standalone wrapper of this collection's database, outside DI. With /// it carries a session setting the default one does not (lazy references on MSSQL and PostgreSQL, Unicode case /// folding on SQLite). /// protected abstract IRedbConnection CreateStandaloneConnection(IServiceProvider services, bool differentSessionSettings); protected static string ConnString(string name) => new ConfigurationBuilder() .SetBasePath(AppContext.BaseDirectory) .AddJsonFile("appsettings.json") .Build() .GetConnectionString(name)!; public async Task InitializeAsync() { await using var scope = _services.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.Context.ExecuteAsync(CreateProbeTableSql); } public async Task DisposeAsync() { await using var scope = _services.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); foreach (var tag in _tags) { await redb.Context.ExecuteAsync($"DELETE FROM _objects WHERE _name LIKE '{tag}%'"); await redb.Context.ExecuteAsync($"DELETE FROM ambient_tx_rows WHERE tag LIKE '{tag}%'"); } } private static TransactionScope NewScope() => new(TransactionScopeAsyncFlowOption.Enabled); private string NewTag() { var tag = NamePrefix + Guid.NewGuid().ToString("N")[..10]; _tags.Add(tag); return tag; } private static Task InsertRowAsync(IRedbService redb, string tag) => redb.Context.ExecuteAsync("INSERT INTO ambient_tx_rows (tag) VALUES ($1)", tag); private async Task<(long Objects, long Rows)> CountCommittedAsync(string tag) { await using var scope = _services.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); var objects = await redb.Context.ExecuteScalarAsync( $"SELECT COUNT(*) FROM _objects WHERE _name LIKE '{tag}%'"); var rows = await redb.Context.ExecuteScalarAsync( $"SELECT COUNT(*) FROM ambient_tx_rows WHERE tag LIKE '{tag}%'"); return (objects, rows); } [Fact] public async Task SaveAndRawSql_CommitWithScope() { var tag = NewTag(); using (var tx = NewScope()) { await using var scope = _services.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); await redb.SaveAsync(TestDataFactory.CreateSimple(tag, 1m)); await InsertRowAsync(redb, tag); tx.Complete(); } (await CountCommittedAsync(tag)).Should().Be((1L, 1L), "the object and the raw row commit together with the scope"); } [Fact] public async Task SaveAndRawSql_RollbackWithScope() { var tag = NewTag(); using (NewScope()) { await using var scope = _services.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); await redb.SaveAsync(TestDataFactory.CreateSimple(tag, 2m)); await InsertRowAsync(redb, tag); // not completed } (await CountCommittedAsync(tag)).Should().Be((0L, 0L), "an abandoned scope takes back both the object and the raw row"); } [Fact] public async Task ConnectionOpenedBeforeScope_JoinsScope() { var tag = NewTag(); await using var scope = _services.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); // The scope's connection is already open when the transaction starts - the shape of a route that // used redb in an earlier step of the same exchange. await redb.Context.ExecuteScalarAsync("SELECT COUNT(*) FROM ambient_tx_rows"); using (NewScope()) { await redb.SaveAsync(TestDataFactory.CreateSimple(tag, 3m)); await InsertRowAsync(redb, tag); // not completed } (await CountCommittedAsync(tag)).Should().Be((0L, 0L), "work done inside the scope rolls back with it even on a connection opened before it"); } [Fact] public async Task ColdKeyCacheInsideScope_NoSecondConnection() { var committed = NewTag(); var abandoned = NewTag(); RedbKeyGeneratorBase.ClearAllCaches(); using (var tx = NewScope()) { await using var scope = _services.CreateAsyncScope(); await scope.ServiceProvider.GetRequiredService() .SaveAsync(TestDataFactory.CreateSimple(committed, 4m)); tx.Complete(); } RedbKeyGeneratorBase.ClearAllCaches(); using (NewScope()) { await using var scope = _services.CreateAsyncScope(); await scope.ServiceProvider.GetRequiredService() .SaveAsync(TestDataFactory.CreateSimple(abandoned, 5m)); } (await CountCommittedAsync(committed)).Objects.Should().Be(1, "a cold key cache inside the scope still commits"); (await CountCommittedAsync(abandoned)).Objects.Should().Be(0, "and still rolls back"); } [Fact] public async Task TwoScopesSameDatabase_OneTransaction() { var committed = NewTag(); var abandoned = NewTag(); using (var tx = NewScope()) { await using var first = _services.CreateAsyncScope(); await using var second = _services.CreateAsyncScope(); await first.ServiceProvider.GetRequiredService() .SaveAsync(TestDataFactory.CreateSimple(committed + "-a", 6m)); await InsertRowAsync(second.ServiceProvider.GetRequiredService(), committed); tx.Complete(); } using (NewScope()) { await using var first = _services.CreateAsyncScope(); await using var second = _services.CreateAsyncScope(); await first.ServiceProvider.GetRequiredService() .SaveAsync(TestDataFactory.CreateSimple(abandoned + "-a", 7m)); await InsertRowAsync(second.ServiceProvider.GetRequiredService(), abandoned); } (await CountCommittedAsync(committed)).Should().Be((1L, 1L), "two DI scopes of one database write into the same transaction"); (await CountCommittedAsync(abandoned)).Should().Be((0L, 0L), "and roll back together"); } [Fact] public async Task UniqueViolationInsideScope_TransactionStaysAlive() { var tag = NewTag(); await using (var setup = _services.CreateAsyncScope()) { await setup.ServiceProvider.GetRequiredService().SaveAsync(new RedbObject { name = tag + "-winner", ValueUnique = tag + "-KEY", Props = new UniqueOrderProps { Note = "first" } }); } using (var tx = NewScope()) { await using var scope = _services.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); var act = async () => await redb.SaveAsync(new RedbObject { name = tag + "-loser", ValueUnique = tag + "-KEY", Props = new UniqueOrderProps { Note = "second" } }); await act.Should().ThrowAsync(); (await redb.Context.ExecuteScalarAsync("SELECT 1")).Should().Be(1, "the scope's transaction survives a caught unique violation"); await redb.SaveAsync(new RedbObject { name = tag + "-recovered", ValueUnique = tag + "-OTHER", Props = new UniqueOrderProps { Note = "third" } }); tx.Complete(); } (await CountCommittedAsync(tag + "-recovered")).Objects.Should().Be(1, "work done after the recovery commits with the scope"); (await CountCommittedAsync(tag + "-loser")).Objects.Should().Be(0); } [Fact] public async Task ExecuteAtomicWithoutScope_Unchanged() { var committed = NewTag(); var failed = NewTag(); await using var scope = _services.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); await redb.Context.ExecuteAtomicAsync(async () => { await redb.SaveAsync(TestDataFactory.CreateSimple(committed, 8m)); await InsertRowAsync(redb, committed); }); var act = async () => await redb.Context.ExecuteAtomicAsync(async () => { await redb.SaveAsync(TestDataFactory.CreateSimple(failed, 9m)); await InsertRowAsync(redb, failed); throw new InvalidOperationException("ambient-tx-marker"); }); await act.Should().ThrowAsync().WithMessage("*ambient-tx-marker*"); (await CountCommittedAsync(committed)).Should().Be((1L, 1L)); (await CountCommittedAsync(failed)).Should().Be((0L, 0L)); } [Fact] public async Task BeginTransactionInsideScope_StillRefused() { using var tx = NewScope(); await using var scope = _services.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); var act = async () => await redb.Context.BeginTransactionAsync(); await act.Should().ThrowAsync().WithMessage("*Ambient TransactionScope*", "an explicit transaction inside a scope stays refused; a route joins the scope instead"); } [Fact] public async Task BatchSaveInsideScope_RollsBack() { var tag = NewTag(); var batch = Enumerable.Range(0, 25) .Select(i => (IRedbObject)TestDataFactory.CreateSimple($"{tag}-{i:D2}", i)) .ToList(); using (NewScope()) { await using var scope = _services.CreateAsyncScope(); await scope.ServiceProvider.GetRequiredService().SaveAsync(batch); } (await CountCommittedAsync(tag)).Objects.Should().Be(0, "the bulk path of a batch save rolls back with the scope"); } [Fact] public async Task ConcurrentCommandsInOneTransaction_Fail() { // Owner decision P1: parallel branches in ONE transaction are not supported and must fail loudly, // never write silently. Two dependent clones use the transaction's one connection at the same time. // // The collision is forced, not hoped for: the first branch writes a row and then runs a statement of about // two seconds; the second branch starts its command a quarter of a second after the first one announced its // statement, so that statement is in flight on the shared connection. Two branches merely released together // (a barrier before each of 200 inserts) overlapped only by chance: an insert takes microseconds on SQLite, // and under the load of a full run the test failed now and then. // What it guarantees: the second command meets the first one in flight unless the first one needed more than // the quarter second just to start, a margin of the whole slow statement. var tag = NewTag(); Exception? failure = null; try { using var tx = NewScope(); var slowAnnounced = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var branches = Enumerable.Range(0, 2).Select(branch => { var dependent = Transaction.Current!.DependentClone(DependentCloneOption.BlockCommitUntilComplete); return Task.Run(async () => { try { using var branchScope = new TransactionScope(dependent, TransactionScopeAsyncFlowOption.Enabled); await using var scope = _services.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); if (branch == 0) { await InsertRowAsync(redb, $"{tag}-0"); slowAnnounced.SetResult(); await redb.Context.ExecuteScalarAsync(SlowStatementSql); } else { await slowAnnounced.Task; await Task.Delay(250); await InsertRowAsync(redb, $"{tag}-1"); } branchScope.Complete(); } finally { // A branch that fails before announcing must not leave the other waiting. slowAnnounced.TrySetResult(); dependent.Complete(); } }); }).ToArray(); await Task.WhenAll(branches); tx.Complete(); } catch (Exception ex) { failure = ex; } failure.Should().NotBeNull("concurrent writes inside one transaction must fail, not commit silently"); (await CountCommittedAsync(tag)).Rows.Should().Be(0, "nothing of a failed transaction may stay"); } [Fact] public async Task OtherSessionSettings_SameDatabase_OneTransaction_AreRefused() { // The transaction holds one connection per database, set up by the configuration that opened it. A second // redb configuration of the same database with other session settings used to run its commands on it with // settings that are not its own (lazy-reference JSON, collation, case folding), without any error. await using var first = CreateStandaloneConnection(_services, differentSessionSettings: false); await using var other = CreateStandaloneConnection(_services, differentSessionSettings: true); using var tx = NewScope(); (await first.ExecuteScalarAsync("SELECT 1")).Should().Be(1); var act = () => other.ExecuteScalarAsync("SELECT 1"); (await act.Should().ThrowAsync()) .Which.Message.Should().Contain("session settings"); } [Fact] public async Task SameSessionSettings_TwoWrappers_ShareTheTransaction() { // Characterization, green before and after: the refusal above must not touch identical configurations. var tag = NewTag(); await using var first = CreateStandaloneConnection(_services, differentSessionSettings: false); await using var second = CreateStandaloneConnection(_services, differentSessionSettings: false); using (NewScope()) { await first.ExecuteAsync("INSERT INTO ambient_tx_rows (tag) VALUES ($1)", tag); await second.ExecuteAsync("INSERT INTO ambient_tx_rows (tag) VALUES ($1)", tag + "-2"); // not completed } (await CountCommittedAsync(tag)).Rows.Should().Be(0, "both wrappers wrote into the one abandoned transaction"); } } Path: redb/redb.Tests.Integration/Tests/Base/AnalyticsTelemetryTestsBase.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/AnalyticsTelemetryTestsBase.cs ---- using redb.Core; 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 grouping, window and aggregate statements appear in telemetry as commands on every provider: a repeated call (the /// field metadata already cached) opens one redb.Core span per command. SQLite read them on the raw connection and /// opened no span for the statement itself. /// public abstract class AnalyticsTelemetryTestsBase { protected readonly IRedbService Redb; protected AnalyticsTelemetryTestsBase(IRedbService redb) => Redb = redb; /// Commands of one call: Pro runs the statement alone; Free first asks the module for the statement text. protected abstract int CommandsPerCall { get; } private async Task> SeedAsync() { await Redb.SyncSchemeAsync(); var marker = "tl" + Guid.NewGuid().ToString("N")[..10]; for (var i = 0; i < 6; i++) { var p = TestDataFactory.CreateEmployee(i, firstName: $"{marker}-{i:D2}", department: marker, salary: 1000m * (i + 1), position: i % 2 == 0 ? "Even" : "Odd").Props; await Redb.SaveAsync(new RedbObject { name = $"{marker}-{i}", Props = p }); } return Redb.Query().Where(e => e.Department == marker); } /// Runs once to warm the metadata, then counts the commands of a second run. private static async Task SecondRunAsync(Func action) { await action(); return await CommandCounter.CountAsync(action); } [Fact] public async Task GroupBy_AppearsAsItsCommands() { var source = await SeedAsync(); (await SecondRunAsync(() => source.GroupBy(e => e.Position) .SelectAsync(g => new { Key = g.Key, Count = Agg.Count(g) }))).Should().Be(CommandsPerCall); } [Fact] public async Task Window_AppearsAsItsCommands() { var source = await SeedAsync(); (await SecondRunAsync(() => source.WithWindow(w => w.OrderBy(e => e.Salary)) .SelectAsync(e => new { e.Props.Salary, Row = Win.RowNumber() }))).Should().Be(CommandsPerCall); } [Fact] public async Task Aggregate_AppearsAsItsCommands() { var source = await SeedAsync(); (await SecondRunAsync(() => source.AggregateAsync(x => new { Count = Agg.Count(), Sum = Agg.Sum(x.Props.Salary) }))) .Should().Be(CommandsPerCall); } } Path: redb/redb.Tests.Integration/Tests/Base/ArrayAnyTestsBase.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/ArrayAnyTestsBase.cs ---- using System.Linq.Expressions; using redb.Core; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using redb.Core.Query; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// Any() over an array or a list of simple values: true for an object with elements, false for an empty one and for /// one that stores none. It was translated as the length of a text: PostgreSQL refused length(text[]), SQLite counted /// an empty or missing array as non-empty (it measured '[]'), and SQL Server answered !Any() with no object. /// public abstract class ArrayAnyTestsBase { protected readonly IRedbService Redb; protected ArrayAnyTestsBase(IRedbService redb) => Redb = redb; [Fact] public async Task AnyOverArraysOfEveryValueType_TrueOnlyWithElements() { await Redb.SyncSchemeAsync(); var marker = "any-" + Guid.NewGuid().ToString("N")[..8]; var full = new ArrayValuesProps { Marker = marker, Words = ["w"], Longs = [1], Doubles = [1.5], Decimals = [2.5m], Flags = [true], Dates = [new DateTime(2026, 3, 1, 0, 0, 0, DateTimeKind.Utc)], Ids = [Guid.NewGuid()] }; var empty = new ArrayValuesProps { Marker = marker, Words = [], Longs = [], Doubles = [], Decimals = [], Flags = [], Dates = [], Ids = [] }; var none = new ArrayValuesProps { Marker = marker }; await Redb.SaveAsync(new[] { full, empty, none } .Select((p, i) => (IRedbObject)new RedbObject { name = $"{marker}-{i}", Props = p }).ToList()); IRedbQueryable Q() => Redb.Query().Where(p => p.Marker == marker); async Task Check(string name, Expression> any, Expression> notAny) { (await Q().Where(any).CountAsync()).Should().Be(1, $"{name}.Any(): the object with elements"); (await Q().Where(notAny).CountAsync()).Should().Be(2, $"!{name}.Any(): the empty array and the missing one"); } await Check("Words", p => p.Words!.Any(), p => !p.Words!.Any()); await Check("Longs", p => p.Longs!.Any(), p => !p.Longs!.Any()); await Check("Doubles", p => p.Doubles!.Any(), p => !p.Doubles!.Any()); await Check("Decimals", p => p.Decimals!.Any(), p => !p.Decimals!.Any()); await Check("Flags", p => p.Flags!.Any(), p => !p.Flags!.Any()); await Check("Dates", p => p.Dates!.Any(), p => !p.Dates!.Any()); await Check("Ids", p => p.Ids!.Any(), p => !p.Ids!.Any()); } [Fact] public async Task AnyOverListsOfValues_TrueOnlyWithElements() { await Redb.SyncSchemeAsync(); var marker = "anyl-" + Guid.NewGuid().ToString("N")[..8]; var rows = new[] { new ArrayAnyProps { Marker = marker, Labels = ["a", "b"], Numbers = [7] }, new ArrayAnyProps { Marker = marker, Labels = [], Numbers = [] }, new ArrayAnyProps { Marker = marker }, }; await Redb.SaveAsync(rows.Select((p, i) => (IRedbObject)new RedbObject { name = $"{marker}-{i}", Props = p }).ToList()); IRedbQueryable Q() => Redb.Query().Where(p => p.Marker == marker); (await Q().Where(p => p.Labels!.Any()).CountAsync()).Should().Be(1, "List.Any()"); (await Q().Where(p => !p.Labels!.Any()).CountAsync()).Should().Be(2, "!List.Any()"); (await Q().Where(p => p.Numbers!.Any()).CountAsync()).Should().Be(1, "List.Any()"); (await Q().Where(p => p.Numbers!.Any() && p.Labels!.Any()).CountAsync()).Should().Be(1, "two Any() together"); } } Path: redb/redb.Tests.Integration/Tests/Base/ArrayGroupByDeepTestsBase.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/ArrayGroupByDeepTestsBase.cs ---- using redb.Core; using redb.Core.Models.Entities; 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; /// /// Deep-coverage integration tests for GroupByArray. /// /// Complements (HAVING basics) and the /// E142* slice of by exercising: /// * composite array keys (anonymous { Type, IsVerified }); /// * outer Where combined with nested AND/OR; /// * outer Where with string operations (Contains / StartsWith) on parent props; /// * outer WhereIn on base.id; /// * boolean array keys. /// /// Targets the same dialect set as : /// all six classes (PostgreSQL, SQL Server, SQLite; free and Pro). /// public abstract class ArrayGroupByDeepTestsBase { protected readonly IRedbService Redb; protected ArrayGroupByDeepTestsBase(IRedbService redb) => Redb = redb; private async Task SeedAsync() => await TestDataFactory.SeedEmployees(Redb, 20); // What a group of an array unnest counts: one row per contact of that type, over the employees the outer Where // matched. The database is shared by the whole collection, and other tests store employees of the same // departments with no contacts at all, so "one row per matched employee" held only while they ran later. private static int ContactsOfType(IEnumerable> employees, string? type) => employees.Sum(e => e.Props.Contacts?.Count(c => c.Type == type) ?? 0); // ────────────────────────────────────────────────────────────────── // Composite array key (anonymous { Type, IsVerified }) // ────────────────────────────────────────────────────────────────── [Fact] public async Task ArrayGroupBy_CompositeKey_TypeAndVerified_FourGroupsMax() { await SeedAsync(); var results = await Redb.Query() .GroupByArray(e => e.Contacts!, c => new { c.Type, c.IsVerified }) .SelectAsync(g => new { g.Key.Type, g.Key.IsVerified, Count = Agg.Count(g) }); // Seed: every employee has exactly two contacts — // { Type=email, IsVerified=true } and { Type=phone, IsVerified=false }. // So there must be exactly 2 distinct composite groups, each non-empty. results.Should().HaveCount(2); results.Should().Contain(r => r.Type == "email" && r.IsVerified); results.Should().Contain(r => r.Type == "phone" && !r.IsVerified); results.Should().AllSatisfy(r => r.Count.Should().BeGreaterThan(0)); } [Fact] public async Task ArrayGroupBy_CompositeKey_Having_PositiveThreshold_Survives() { await SeedAsync(); var results = await Redb.Query() .GroupByArray(e => e.Contacts!, c => new { c.Type, c.IsVerified }) .Having(g => Agg.Count(g) > 0) .SelectAsync(g => new { g.Key.Type, g.Key.IsVerified, C = Agg.Count(g) }); results.Should().NotBeEmpty(); results.Select(r => r.Type).Distinct().Should().BeEquivalentTo(new[] { "email", "phone" }); } [Fact] public async Task ArrayGroupBy_CompositeKey_Having_ImpossibleThreshold_DropsAll() { await SeedAsync(); var results = await Redb.Query() .GroupByArray(e => e.Contacts!, c => new { c.Type, c.IsVerified }) .Having(g => Agg.Count(g) > 1_000_000) .SelectAsync(g => new { g.Key.Type, C = Agg.Count(g) }); results.Should().BeEmpty(); } // ────────────────────────────────────────────────────────────────── // Outer Where with nested AND/OR over parent props // ────────────────────────────────────────────────────────────────── [Fact] public async Task ArrayGroupBy_OuterWhere_NestedAndOr_Combined() { await SeedAsync(); // Seed has 20 employees, departments cycled through 5 deps, IsRemote = (i%2==0). // (Department == "Engineering" && IsRemote) OR (Department == "Sales" && !IsRemote) // produces a non-empty subset; assert non-empty groups + each group count > 0. var matched = await Redb.Query() .Where(e => (e.Department == "Engineering" && e.IsRemote) || (e.Department == "Sales" && !e.IsRemote)) .ToListAsync(); matched.Should().NotBeEmpty("seed must produce some matches for the compound filter"); var results = await Redb.Query() .Where(e => (e.Department == "Engineering" && e.IsRemote) || (e.Department == "Sales" && !e.IsRemote)) .GroupByArray(e => e.Contacts!, c => c.Type) .SelectAsync(g => new { Type = g.Key, C = Agg.Count(g) }); results.Should().NotBeEmpty(); results.Should().AllSatisfy(r => r.C.Should().Be(ContactsOfType(matched, r.Type), "every contact type must produce exactly one row per such contact of a matched employee after array unnest")); } // ────────────────────────────────────────────────────────────────── // Outer Where with string ops (Contains / StartsWith) on parent props // ────────────────────────────────────────────────────────────────── [Fact] public async Task ArrayGroupBy_OuterWhere_StringContains_OnDepartment() { await SeedAsync(); var matched = await Redb.Query() .Where(e => e.Department.Contains("ing")) // Engineering, Marketing .ToListAsync(); matched.Should().NotBeEmpty(); var results = await Redb.Query() .Where(e => e.Department.Contains("ing")) .GroupByArray(e => e.Contacts!, c => c.Type) .SelectAsync(g => new { Type = g.Key, C = Agg.Count(g) }); results.Should().NotBeEmpty(); results.Select(r => r.Type).Should().BeEquivalentTo(new[] { "email", "phone" }); results.Should().AllSatisfy(r => r.C.Should().Be(ContactsOfType(matched, r.Type))); } [Fact] public async Task ArrayGroupBy_OuterWhere_StringStartsWith_OnFirstName() { await SeedAsync(); var matched = (await Redb.Query() .Where(e => e.FirstName.StartsWith("Employee00")) .ToListAsync()).Count; matched.Should().BeGreaterThan(0); var results = await Redb.Query() .Where(e => e.FirstName.StartsWith("Employee00")) .GroupByArray(e => e.Contacts!, c => c.Type) .SelectAsync(g => new { Type = g.Key, C = Agg.Count(g) }); results.Should().NotBeEmpty(); results.Should().AllSatisfy(r => r.C.Should().Be(matched)); } // ────────────────────────────────────────────────────────────────── // Outer Where narrows to a single employee — exact contact-type cardinality // ────────────────────────────────────────────────────────────────── [Fact] public async Task ArrayGroupBy_OuterWhere_UniqueFirstName_ExactCardinality() { await SeedAsync(); // Seeders are cumulative across tests in the suite, so "Employee001" // may exist N≥1 times. Compute expected cardinality from data. var matched = (await Redb.Query() .Where(e => e.FirstName == "Employee001") .ToListAsync()).Count; matched.Should().BeGreaterThan(0); var results = await Redb.Query() .Where(e => e.FirstName == "Employee001") .GroupByArray(e => e.Contacts!, c => c.Type) .SelectAsync(g => new { Type = g.Key, C = Agg.Count(g) }); results.Should().HaveCount(2, "each matched employee has exactly 2 distinct contact types (email + phone)"); results.Should().AllSatisfy(r => r.C.Should().Be(matched)); } // ────────────────────────────────────────────────────────────────── // Boolean array key (IsVerified on its own) // ────────────────────────────────────────────────────────────────── [Fact] public async Task ArrayGroupBy_BoolKey_IsVerified_TwoGroups() { await SeedAsync(); var results = await Redb.Query() .GroupByArray(e => e.Contacts!, c => c.IsVerified) .SelectAsync(g => new { Verified = g.Key, C = Agg.Count(g) }); // Seed has both verified=true (email) and verified=false (phone) — 2 distinct. results.Should().HaveCount(2); results.Select(r => r.Verified).Should().BeEquivalentTo(new[] { true, false }); results.Should().AllSatisfy(r => r.C.Should().BeGreaterThan(0)); } // ────────────────────────────────────────────────────────────────── // Empty / null arrays — outer filter must exclude employees w/o array // ────────────────────────────────────────────────────────────────── [Fact] public async Task ArrayGroupBy_OuterWhere_ContactsNotNull_StillProducesGroups() { await SeedAsync(); // All seeded employees have Contacts; this is essentially a smoke regression // for the IS NOT NULL outer filter, which used to be rejected by free PG. var results = await Redb.Query() .Where(e => e.Contacts != null) .GroupByArray(e => e.Contacts!, c => c.Type) .SelectAsync(g => new { Type = g.Key, C = Agg.Count(g) }); results.Should().NotBeEmpty(); results.Select(r => r.Type).Should().BeEquivalentTo(new[] { "email", "phone" }); } // ══════════════════════════════════════════════════════════════════ // The forms of GroupByArray. Each test writes its own objects under a fresh marker and compares // the grouping with the same LINQ over those objects in memory. // ══════════════════════════════════════════════════════════════════ private static string NewMarker() => "ag" + Guid.NewGuid().ToString("N")[..10]; /// Employees under with varied inner arrays: Metadata on both contacts or one, /// amenities of two shapes, floors 1..23. private async Task>> SeedVariedAsync(string marker, int count = 12) { var list = new List>(); for (var i = 0; i < count; i++) { var e = TestDataFactory.CreateEmployee(i, firstName: $"{marker}-{i:D2}"); e.Props.Contacts![0].Metadata = i % 3 == 0 ? [new TestContactDetail { Label = "work", Value = "a" }, new TestContactDetail { Label = "home", Value = "b" }] : [new TestContactDetail { Label = "work", Value = "c" }]; e.Props.Contacts[1].Metadata = i % 2 == 0 ? [new TestContactDetail { Label = "night", Value = "d" }] : null; e.Props.HomeAddress!.Building!.Amenities = i % 2 == 0 ? ["Parking", "Gym"] : ["Gym", "Pool", "Cafe"]; e.Props.HomeAddress.Building.Floor = 1 + i * 2; await Redb.SaveAsync(e); list.Add(e); } return list; } private redb.Core.Query.IRedbQueryable Own(string marker) => Redb.Query().Where(e => e.FirstName.StartsWith(marker)); // ---- F1: inner array through SelectMany -------------------------------------------------------------------- [Fact] public async Task Nested_SelectMany_GroupsTheElementsOfTheInnerArray() { var marker = NewMarker(); var seeded = await SeedVariedAsync(marker); var rows = await Own(marker) .GroupByArray(e => e.Contacts!.SelectMany(c => c.Metadata!), m => m.Label) .SelectAsync(g => new { Label = g.Key, Count = Agg.Count(g) }); var expected = seeded.SelectMany(e => e.Props.Contacts!).SelectMany(c => c.Metadata ?? []) .GroupBy(m => m.Label).ToDictionary(g => g.Key, g => g.Count()); rows.ToDictionary(r => r.Label, r => r.Count).Should().BeEquivalentTo(expected); } // Two fields of the element (Label and Value), each joined to its element: the shape of E142, with its condition and // its window. SQL Server joined the second field as a many-to-many merge before it carried a hash-join hint. [Fact] public async Task Nested_SelectMany_TwoElementFields_WithACondition_MatchesTheObjects() { var marker = NewMarker(); var seeded = await SeedVariedAsync(marker); var rows = await Own(marker) .GroupByArray(e => e.Contacts!.SelectMany(c => c.Metadata!), m => m.Label) .WithWindow(w => w.OrderByDesc(g => Agg.Count(g))) .SelectAsync(g => new { Label = g.Key, Entries = Agg.Count(g), OfA = Agg.Count(g, m => m.Value == "a"), Rank = Win.Rank() }); var expected = seeded.SelectMany(e => e.Props.Contacts!).SelectMany(c => c.Metadata ?? []) .GroupBy(m => m.Label) .Select(g => new { Label = g.Key, Entries = g.Count(), OfA = g.Count(m => m.Value == "a") }) .ToList(); rows.Select(r => new { r.Label, r.Entries, r.OfA }).Should().BeEquivalentTo(expected); foreach (var r in rows) r.Rank.Should().Be(1 + expected.Count(x => x.Entries > r.Entries), $"the rank of {r.Label} by its count"); } [Fact] public async Task Nested_SelectMany_TwoElementFields_WithoutACondition_MatchesTheObjects() { await SeedVariedAsync(NewMarker()); var all = await Redb.Query().ToListAsync(); var rows = await Redb.Query() .GroupByArray(e => e.Contacts!.SelectMany(c => c.Metadata!), m => m.Label) .SelectAsync(g => new { Label = g.Key, Entries = Agg.Count(g), OfA = Agg.Count(g, m => m.Value == "a") }); var expected = all.SelectMany(e => e.Props.Contacts ?? []).SelectMany(c => c.Metadata ?? []) .GroupBy(m => m.Label) .Select(g => new { Label = g.Key, Entries = g.Count(), OfA = g.Count(m => m.Value == "a") }) .ToList(); rows.Should().BeEquivalentTo(expected); } [Fact] public void Nested_SelectManyWithAResultSelector_IsRefused() { var build = () => Redb.Query() .GroupByArray(e => e.Contacts!.SelectMany(c => c.Metadata!, (c, m) => m), m => m.Label); build.Should().Throw().WithMessage("*result selector*"); } [Fact] public void ArrayPath_ThroughADictionary_IsRefused() { var build = () => Redb.Query() .GroupByArray(e => e.OfficeLocations!.Values, a => a.City); build.Should().Throw(); } // ---- F2: arrays of simple values --------------------------------------------------------------------------- [Fact] public async Task ScalarArray_GroupsByTheElementItself() { var marker = NewMarker(); var seeded = await SeedVariedAsync(marker); var rows = await Own(marker) .GroupByArray(e => e.Skills!, s => s) .SelectAsync(g => new { Skill = g.Key, Count = Agg.Count(g) }); var expected = seeded.SelectMany(e => e.Props.Skills ?? []).GroupBy(s => s).ToDictionary(g => g.Key, g => g.Count()); rows.ToDictionary(r => r.Skill, r => r.Count).Should().BeEquivalentTo(expected); } [Fact] public async Task ScalarArray_ThroughClasses_GroupsTheInnerArray() { var marker = NewMarker(); var seeded = await SeedVariedAsync(marker); var rows = await Own(marker) .GroupByArray(e => e.HomeAddress!.Building!.Amenities!, a => a) .Having(g => Agg.Count(g) > 3) .SelectAsync(g => new { Amenity = g.Key, Count = Agg.Count(g) }); var expected = seeded.SelectMany(e => e.Props.HomeAddress!.Building!.Amenities!) .GroupBy(a => a).Where(g => g.Count() > 3).ToDictionary(g => g.Key, g => g.Count()); rows.ToDictionary(r => r.Amenity, r => r.Count).Should().BeEquivalentTo(expected); } [Fact] public async Task ScalarArray_AggregatesOverTheElement() { var marker = NewMarker(); var seeded = await SeedVariedAsync(marker); var rows = await Own(marker) .GroupByArray(e => e.SkillLevels!, l => l) .SelectAsync(g => new { Level = g.Key, Count = Agg.Count(g), Sum = Agg.Sum(g, x => x) }); var expected = seeded.SelectMany(e => e.Props.SkillLevels ?? []).GroupBy(l => l) .ToDictionary(g => g.Key, g => (Count: g.Count(), Sum: g.Sum())); rows.Should().HaveCount(expected.Count); foreach (var r in rows) { r.Count.Should().Be(expected[r.Level].Count); r.Sum.Should().Be(expected[r.Level].Sum); } } [Fact] public void ArrayOfListItems_IsRefusedByName() { var build = () => Redb.Query().GroupByArray(e => e.Roles!, r => r.Id); build.Should().Throw().WithMessage("*RedbListItem*"); } [Fact] public void ArrayOfObjectReferences_IsRefusedByName() { var build = () => Redb.Query().GroupByArray(e => e.Links!, r => r.Id); build.Should().Throw().WithMessage("*object references*"); } // ---- A15: one test per value column ----------------------------------------------------------------------- private async Task<(string Marker, List Seeded)> SeedValuesAsync() { await Redb.SyncSchemeAsync(); var marker = NewMarker(); var seeded = new List(); var guids = new[] { Guid.Parse("11111111-1111-1111-1111-111111111111"), Guid.Parse("22222222-2222-2222-2222-222222222222") }; for (var i = 0; i < 6; i++) { var p = new ArrayValuesProps { Marker = marker, Words = i % 2 == 0 ? ["alpha", "beta"] : ["beta", "gamma", "beta"], Longs = [i % 3, 10, 10L * (i % 2)], Doubles = [1.5, i % 2 == 0 ? 2.25 : 1.5], Decimals = [10.10m, i % 3 == 0 ? 20.20m : 10.10m], Flags = [true, i % 2 == 0], Dates = [new DateTime(2026, 1, 1 + i % 2, 0, 0, 0, DateTimeKind.Utc), new DateTime(2026, 3, 1, 0, 0, 0, DateTimeKind.Utc)], Ids = [guids[i % 2], guids[0]], Items = [ new ArrayItem { Kind = i % 3 == 0 ? null : "box", Size = i, Active = i % 2 == 0, Place = i % 2 == 0 ? new ArrayItemPlace { City = "Riga" } : null }, new ArrayItem { Kind = "bag", Size = 10 + i, Active = true, Place = new ArrayItemPlace { City = i % 3 == 0 ? "Oslo" : "Riga" } } ] }; await Redb.SaveAsync(new RedbObject { name = $"{marker}-{i}", Props = p }); seeded.Add(p); } return (marker, seeded); } private redb.Core.Query.IRedbQueryable OwnValues(string marker) => Redb.Query().Where(v => v.Marker == marker); [Fact] public async Task ValueColumn_String() { var (marker, seeded) = await SeedValuesAsync(); var rows = await OwnValues(marker).GroupByArray(v => v.Words!, w => w).SelectAsync(g => new { K = g.Key, C = Agg.Count(g) }); rows.ToDictionary(r => r.K, r => r.C).Should().BeEquivalentTo( seeded.SelectMany(s => s.Words!).GroupBy(x => x).ToDictionary(g => g.Key, g => g.Count())); } [Fact] public async Task ValueColumn_Long() { var (marker, seeded) = await SeedValuesAsync(); var rows = await OwnValues(marker).GroupByArray(v => v.Longs!, w => w) .SelectAsync(g => new { K = g.Key, C = Agg.Count(g), S = Agg.Sum(g, x => x) }); var expected = seeded.SelectMany(s => s.Longs!).GroupBy(x => x).ToDictionary(g => g.Key, g => (g.Count(), g.Sum())); rows.ToDictionary(r => r.K, r => (r.C, r.S)).Should().BeEquivalentTo(expected); } [Fact] public async Task ValueColumn_Double() { var (marker, seeded) = await SeedValuesAsync(); var rows = await OwnValues(marker).GroupByArray(v => v.Doubles!, w => w).SelectAsync(g => new { K = g.Key, C = Agg.Count(g) }); rows.ToDictionary(r => r.K, r => r.C).Should().BeEquivalentTo( seeded.SelectMany(s => s.Doubles!).GroupBy(x => x).ToDictionary(g => g.Key, g => g.Count())); } [Fact] public async Task ValueColumn_Numeric() { var (marker, seeded) = await SeedValuesAsync(); var rows = await OwnValues(marker).GroupByArray(v => v.Decimals!, w => w) .SelectAsync(g => new { K = g.Key, C = Agg.Count(g), S = Agg.Sum(g, x => x) }); var expected = seeded.SelectMany(s => s.Decimals!).GroupBy(x => x).ToDictionary(g => g.Key, g => (g.Count(), g.Sum())); rows.ToDictionary(r => r.K, r => (r.C, r.S)).Should().BeEquivalentTo(expected); } [Fact] public async Task ValueColumn_Boolean() { var (marker, seeded) = await SeedValuesAsync(); var rows = await OwnValues(marker).GroupByArray(v => v.Flags!, w => w).SelectAsync(g => new { K = g.Key, C = Agg.Count(g) }); rows.ToDictionary(r => r.K, r => r.C).Should().BeEquivalentTo( seeded.SelectMany(s => s.Flags!).GroupBy(x => x).ToDictionary(g => g.Key, g => g.Count())); } [Fact] public async Task ValueColumn_DateTime() { var (marker, seeded) = await SeedValuesAsync(); var rows = await OwnValues(marker).GroupByArray(v => v.Dates!, w => w).SelectAsync(g => new { K = g.Key, C = Agg.Count(g) }); rows.ToDictionary(r => r.K, r => r.C).Should().BeEquivalentTo( seeded.SelectMany(s => s.Dates!).GroupBy(x => x).ToDictionary(g => g.Key, g => g.Count())); } [Fact] public async Task ValueColumn_Guid() { var (marker, seeded) = await SeedValuesAsync(); var rows = await OwnValues(marker).GroupByArray(v => v.Ids!, w => w).SelectAsync(g => new { K = g.Key, C = Agg.Count(g) }); rows.ToDictionary(r => r.K, r => r.C).Should().BeEquivalentTo( seeded.SelectMany(s => s.Ids!).GroupBy(x => x).ToDictionary(g => g.Key, g => g.Count())); } // ---- A17: a null key, A9: a field of a class inside the element -------------------------------------------- [Fact] public async Task NullKey_ComesBackAsItsOwnGroup() { var (marker, seeded) = await SeedValuesAsync(); var rows = await OwnValues(marker).GroupByArray(v => v.Items!, i => i.Kind).SelectAsync(g => new { Kind = g.Key, C = Agg.Count(g) }); var expected = seeded.SelectMany(s => s.Items!).GroupBy(i => i.Kind).ToList(); rows.Should().HaveCount(expected.Count); rows.Should().ContainSingle(r => r.Kind == null).Which.C.Should().Be(expected.Single(g => g.Key == null).Count()); foreach (var g in expected.Where(g => g.Key != null)) rows.Single(r => r.Kind == g.Key).C.Should().Be(g.Count()); } [Fact] public async Task KeyOnAFieldOfAClassInsideTheElement() { var (marker, seeded) = await SeedValuesAsync(); var rows = await OwnValues(marker).GroupByArray(v => v.Items!, i => i.Place!.City) .SelectAsync(g => new { City = g.Key, C = Agg.Count(g), Size = Agg.Sum(g, i => i.Size) }); var expected = seeded.SelectMany(s => s.Items!).GroupBy(i => i.Place?.City).ToList(); rows.Should().HaveCount(expected.Count); foreach (var g in expected) { var row = rows.Single(r => r.City == g.Key); row.C.Should().Be(g.Count()); row.Size.Should().Be(g.Sum(i => i.Size)); } } [Fact] public void KeyOnAClass_IsRefused() { var build = () => Redb.Query().GroupByArray(v => v.Items!, i => i.Place); build.Should().Throw().WithMessage("*class*"); } // ---- F4: conditional count ------------------------------------------------------------------------------- [Fact] public async Task ConditionalCount_CountsTheElementsThatSatisfyIt() { var marker = NewMarker(); var seeded = await SeedVariedAsync(marker); var rows = await Own(marker) .GroupByArray(e => e.Contacts!, c => c.Type) .SelectAsync(g => new { Type = g.Key, All = Agg.Count(g), Verified = Agg.Count(g, c => c.IsVerified), VerifiedEmail = Agg.Count(g, c => c.IsVerified && c.Type == "email"), WithValue = Agg.Count(g, c => c.Value != null) }); var contacts = seeded.SelectMany(e => e.Props.Contacts!).ToList(); rows.Should().HaveCount(contacts.Select(c => c.Type).Distinct().Count()); foreach (var r in rows) { var group = contacts.Where(c => c.Type == r.Type).ToList(); r.All.Should().Be(group.Count); r.Verified.Should().Be(group.Count(c => c.IsVerified)); r.VerifiedEmail.Should().Be(group.Count(c => c.IsVerified && c.Type == "email")); r.WithValue.Should().Be(group.Count(c => c.Value != null)); } } [Fact] public async Task ConditionalCount_InHaving() { var marker = NewMarker(); var seeded = await SeedVariedAsync(marker); var rows = await Own(marker) .GroupByArray(e => e.Contacts!, c => c.Type) .Having(g => Agg.Count(g, c => !c.IsVerified) > 0) .SelectAsync(g => new { Type = g.Key, C = Agg.Count(g) }); var expected = seeded.SelectMany(e => e.Props.Contacts!).GroupBy(c => c.Type) .Where(g => g.Count(c => !c.IsVerified) > 0).Select(g => g.Key); rows.Select(r => r.Type).Should().BeEquivalentTo(expected); } [Fact] public async Task ConditionalCount_WithAStringMethod_IsRefused() { var act = async () => await Redb.Query() .GroupByArray(e => e.Contacts!, c => c.Type) .SelectAsync(g => new { Type = g.Key, C = Agg.Count(g, c => c.Value.Contains("x")) }); await act.Should().ThrowAsync().WithMessage("*condition of Agg.Count*"); } [Fact] public async Task ComputedAggregate_IsRefused() { var act = async () => await Redb.Query() .GroupByArray(e => e.Contacts!, c => c.Type) .SelectAsync(g => new { Type = g.Key, L = Agg.Sum(g, c => c.Value.Length) }); await act.Should().ThrowAsync(); } // ---- F5: window over the groups, F3: SQL preview ------------------------------------------------------------ [Fact] public async Task Window_OverTheGroups() { var marker = NewMarker(); var seeded = await SeedVariedAsync(marker); var rows = await Own(marker) .GroupByArray(e => e.Contacts!.SelectMany(c => c.Metadata!), m => m.Label) .WithWindow(w => w.OrderBy(g => g.Key)) .SelectAsync(g => new { Label = g.Key, Count = Agg.Count(g), Row = Win.RowNumber() }); var expected = seeded.SelectMany(e => e.Props.Contacts!).SelectMany(c => c.Metadata ?? []) .GroupBy(m => m.Label).OrderBy(g => g.Key, StringComparer.Ordinal).Select((g, i) => (g.Key, Count: g.Count(), Row: i + 1L)).ToList(); rows.OrderBy(r => r.Row).Select(r => (r.Label, r.Count, r.Row)).Should().Equal(expected); } [Fact] public async Task ToSqlString_ReturnsTheSqlThatRuns() { var sql = await Redb.Query() .Where(e => e.Department == "Sales") .GroupByArray(e => e.Contacts!, c => c.Type) .ToSqlStringAsync(g => new { Type = g.Key, C = Agg.Count(g, c => c.IsVerified) }); sql.Should().Contain("GROUP BY").And.NotContain("not supported"); } // ---- T4: the E142 shape -------------------------------------------------------------------------------------- [Fact] public async Task E142Shape_DeepOuterWhere_CompositeKey_Count() { var marker = NewMarker(); var seeded = await SeedVariedAsync(marker); var rows = await Own(marker) .Where(e => e.HomeAddress!.Building!.Floor > 10) .GroupByArray(e => e.Contacts!, c => new { c.Type, c.IsVerified }) .SelectAsync(g => new { g.Key.Type, g.Key.IsVerified, Count = Agg.Count(g) }); var expected = seeded.Where(e => e.Props.HomeAddress!.Building!.Floor > 10) .SelectMany(e => e.Props.Contacts!) .GroupBy(c => new { c.Type, c.IsVerified }) .ToDictionary(g => (g.Key.Type, g.Key.IsVerified), g => g.Count()); rows.ToDictionary(r => (r.Type, r.IsVerified), r => r.Count).Should().BeEquivalentTo(expected); } } Path: redb/redb.Tests.Integration/Tests/Base/ArrayGroupMetadataCacheTestsBase.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/ArrayGroupMetadataCacheTestsBase.cs ---- using redb.Core; using redb.Core.Models.Entities; using redb.Core.Query; using redb.Core.Query.Aggregation; using redb.Tests.Integration.Helpers; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// Pro GroupByArray reads the metadata of the array path and of the element fields once: a repeated call runs the data /// statement alone, and its SQL preview runs nothing. The commands are counted through the redb.Core ActivitySource, /// one span per database command (CommandCounter). /// public abstract class ArrayGroupMetadataCacheTestsBase { protected readonly IRedbService Redb; protected ArrayGroupMetadataCacheTestsBase(IRedbService redb) => Redb = redb; // The data statement and any metadata read. Not the scalar side commands of the // PostgreSQL statistics guard, which a call meets or not by timing (CommandCounter.CountWithoutScalarsAsync). private static Task CommandsAsync(Func action) => CommandCounter.CountWithoutScalarsAsync(action); private static Task> GroupAsync(IRedbQueryable source) => source.GroupByArray(e => e.Contacts!.SelectMany(c => c.Metadata!), m => m.Label) .SelectAsync(g => new Row { Label = g.Key, Count = Agg.Count(g), Values = Agg.Count(g, m => m.Value == "d") }); private static Task PreviewAsync(IRedbQueryable source) => source.GroupByArray(e => e.Contacts!.SelectMany(c => c.Metadata!), m => m.Label) .ToSqlStringAsync(g => new Row { Label = g.Key, Count = Agg.Count(g), Values = Agg.Count(g, m => m.Value == "d") }); private sealed class Row { public string? Label { get; set; } public int Count { get; set; } public int Values { get; set; } } private static EmployeeProps Employee(int i, string marker) { var p = TestDataFactory.CreateEmployee(i, firstName: $"{marker}-{i:D2}").Props; p.Contacts![0].Metadata = [new TestContactDetail { Label = "work", Value = $"v{i}" }]; p.Contacts[1].Metadata = i % 2 == 0 ? [new TestContactDetail { Label = "night", Value = "d" }] : null; return p; } [Fact] public async Task FlatGrouping_RepeatedCall_RunsTheDataStatementAlone() { await Redb.SyncSchemeAsync(); var marker = "mc" + Guid.NewGuid().ToString("N")[..10]; for (var i = 0; i < 6; i++) await Redb.SaveAsync(new RedbObject { name = $"{marker}-{i}", Props = Employee(i, marker) }); IRedbQueryable Source() => Redb.Query().Where(e => e.FirstName.StartsWith(marker)); var first = await GroupAsync(Source()); first.Should().HaveCount(2, "work and night"); (await CommandsAsync(() => GroupAsync(Source()))).Should().Be(1, "the metadata of the path is cached after the first call"); (await CommandsAsync(() => PreviewAsync(Source()))).Should().Be(0, "the preview builds the statement from cached metadata"); } [Fact] public async Task TreeGrouping_RepeatedCall_RunsTheDataStatementAlone() { await Redb.SyncSchemeAsync(); var marker = "mt" + Guid.NewGuid().ToString("N")[..10]; var root = new TreeRedbObject { name = marker, Props = Employee(0, marker) }; root.id = await Redb.SaveAsync(root); for (var i = 1; i < 6; i++) await Redb.CreateChildAsync(new TreeRedbObject { name = $"{marker}-{i}", Props = Employee(i, marker) }, root); IRedbQueryable Source() => Redb.TreeQuery(root.id); var first = await GroupAsync(Source()); first.Should().HaveCount(2, "work and night under the root"); (await CommandsAsync(() => GroupAsync(Source()))).Should().Be(1, "the metadata of the path is cached after the first call"); (await CommandsAsync(() => PreviewAsync(Source()))).Should().Be(0, "the preview builds the statement from cached metadata"); } } Path: redb/redb.Tests.Integration/Tests/Base/ArrayOfClassesAnyTestsBase.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/ArrayOfClassesAnyTestsBase.cs ---- using System.Linq.Expressions; using redb.Core; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using redb.Core.Query; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// p.Lines.Any(l => ...) over an array or list of classes. redb Pro reads it on every provider, a predicate /// over two fields asks both of one element, and a field an element has no value for matches neither == nor != (SQL's /// rule, as everywhere in redb). The free providers refuse it with a clear message before any SQL; SQL Server Free /// answered 0 without a word, PostgreSQL and SQLite Free failed in their modules, and Pro could not resolve /// "Lines[].Kind". /// public abstract class ArrayOfClassesAnyTestsBase { protected readonly IRedbService Redb; protected ArrayOfClassesAnyTestsBase(IRedbService redb) => Redb = redb; /// True for the Pro suites, which read the form; the free ones refuse it. protected abstract bool ReadsAnyOverClasses { get; } private static readonly DateTime Day = new(2026, 3, 1, 0, 0, 0, DateTimeKind.Utc); private static List Rows(string tag) => [ // a+active and b+inactive: Kind a and Active true are on the same element. new() { Tag = tag, Number = 1, Lines = [new() { Kind = "a", Active = true, Qty = 5, Price = 1.5m, Due = Day, Wait = TimeSpan.FromHours(2) }, new() { Kind = "b", Active = false, Qty = 1 }] }, // a+inactive and b+active: Kind a and Active true are on different elements. new() { Tag = tag, Number = 2, Lines = [new() { Kind = "a", Active = false, Qty = 2, Price = 10m, Due = Day.AddDays(5) }, new() { Kind = "b", Active = true, Qty = 9, Wait = TimeSpan.FromDays(3) }] }, // an element without Kind and Active. new() { Tag = tag, Number = 3, Lines = [new() { Qty = 7, Price = 3m }], Extra = [new() { Kind = "x", Active = true, Qty = 1 }] }, // an empty array and no array. new() { Tag = tag, Number = 4, Lines = [] }, new() { Tag = tag, Number = 5 }, ]; private async Task<(string Tag, List Rows)> SeedAsync() { await Redb.SyncSchemeAsync(); var tag = "aoc-" + Guid.NewGuid().ToString("N")[..8]; var rows = Rows(tag); await Redb.SaveAsync(rows.Select(p => (IRedbObject)new RedbObject { name = $"{tag}-{p.Number}", Props = p }).ToList()); return (tag, rows); } private async Task NumbersAsync(string tag, Expression> filter) => (await Redb.Query().Where(p => p.Tag == tag).Where(filter).ToListAsync()) .Select(o => o.Props.Number).OrderBy(n => n).ToArray(); // SQL's rule over one element: a comparison with a field the element has no value for is not true. private static bool Eq(T? a, T b) where T : struct => a.HasValue && a.Value.Equals(b); private static int[] Expect(List rows, Func rule) => rows.Where(rule).Select(r => r.Number).OrderBy(n => n).ToArray(); [Fact] public async Task AnyWithACondition_OverAnArrayOfClasses() { var (tag, rows) = await SeedAsync(); if (!ReadsAnyOverClasses) { var refused = async () => await NumbersAsync(tag, p => p.Lines!.Any(l => l.Kind == "a")); (await refused.Should().ThrowAsync()).Which.Message .Should().Contain("not supported by the free providers"); return; } (await NumbersAsync(tag, p => p.Lines!.Any(l => l.Kind == "a"))).Should().Equal(1, 2); (await NumbersAsync(tag, p => p.Lines!.Any(l => l.Active == true))).Should().Equal(1, 2); // Both conditions of one element: object 2 has Kind a and Active true on different elements. (await NumbersAsync(tag, p => p.Lines!.Any(l => l.Kind == "a" && l.Active == true))).Should().Equal(1); (await NumbersAsync(tag, p => p.Lines!.Any(l => l.Kind == "b" && l.Qty > 5))).Should().Equal(2); (await NumbersAsync(tag, p => p.Lines!.Any(l => l.Kind == "b" || l.Qty == 7))).Should().Equal(1, 2, 3); // SQL's rule inside the element: the element without Kind matches neither == nor !=, nor its negation. (await NumbersAsync(tag, p => p.Lines!.Any(l => l.Kind != "a"))) .Should().Equal(Expect(rows, r => r.Lines?.Any(l => l.Kind != null && l.Kind != "a") == true)); (await NumbersAsync(tag, p => p.Lines!.Any(l => !(l.Kind == "a")))) .Should().Equal(Expect(rows, r => r.Lines?.Any(l => l.Kind != null && l.Kind != "a") == true)); (await NumbersAsync(tag, p => p.Lines!.Any(l => l.Kind == null))).Should().Equal(3); (await NumbersAsync(tag, p => p.Lines!.Any(l => l.Kind != null && l.Active == false))).Should().Equal(1, 2); // Ranges and other value types of the element. (await NumbersAsync(tag, p => p.Lines!.Any(l => l.Qty >= 7))).Should().Equal(2, 3); (await NumbersAsync(tag, p => p.Lines!.Any(l => l.Price > 2m))).Should().Equal(2, 3); var due = Day.AddDays(1); (await NumbersAsync(tag, p => p.Lines!.Any(l => l.Due > due))).Should().Equal(2); (await NumbersAsync(tag, p => p.Lines!.Any(l => l.Wait > TimeSpan.FromDays(1)))).Should().Equal(2); var kinds = new List { "b", "z" }; (await NumbersAsync(tag, p => p.Lines!.Any(l => kinds.Contains(l.Kind)))).Should().Equal(1, 2); // The negation of the whole Any: objects with no such element, an empty or a missing array included. (await NumbersAsync(tag, p => !p.Lines!.Any(l => l.Kind == "a"))).Should().Equal(3, 4, 5); // With other filters, and over a List. (await NumbersAsync(tag, p => p.Number > 1 && p.Lines!.Any(l => l.Kind == "a"))).Should().Equal(2); (await NumbersAsync(tag, p => p.Extra!.Any(l => l.Kind == "x" && l.Active == true))).Should().Equal(3); (await Redb.Query().Where(p => p.Tag == tag).Where(p => p.Lines!.Any(l => l.Kind == "a")).CountAsync()) .Should().Be(2); } [Fact] public async Task AnyOverAnArrayOfClasses_RefusesWhatItDoesNotRead() { var (tag, _) = await SeedAsync(); if (!ReadsAnyOverClasses) return; var outer = async () => await NumbersAsync(tag, p => p.Lines!.Any(l => l.Qty == p.Number)); (await outer.Should().ThrowAsync()).Which.Message.Should().Contain("reads only the fields of the element"); var text = async () => await NumbersAsync(tag, p => p.Lines!.Any(l => l.Kind!.StartsWith("a"))); (await text.Should().ThrowAsync()).Which.Message.Should().Contain("cannot read"); } } Path: redb/redb.Tests.Integration/Tests/Base/ArrayTestsBase.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/ArrayTestsBase.cs ---- using redb.Core; using redb.Tests.Integration.Helpers; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// Array querying tests — e.Skills.Contains("C#"), etc. /// public abstract class ArrayTestsBase { protected readonly IRedbService Redb; protected ArrayTestsBase(IRedbService redb) => Redb = redb; private async Task> SeedAsync() { return await TestDataFactory.SeedEmployees(Redb, 20); } [Fact] public async Task ArrayContains_SingleValue_Filters() { var ids = await SeedAsync(); var results = await Redb.Query() .Where(e => e.Skills != null && e.Skills.Contains("C#")) .ToListAsync(); results.Should().NotBeEmpty(); results.Should().AllSatisfy(r => r.Props.Skills.Should().Contain("C#")); } [Fact] public async Task ArrayContains_Or_MatchesEither() { var ids = await SeedAsync(); var results = await Redb.Query() .Where(e => e.Skills != null && (e.Skills.Contains("C#") || e.Skills.Contains("Python"))) .ToListAsync(); results.Should().NotBeEmpty(); results.Should().AllSatisfy(r => { var skills = r.Props.Skills!; (skills.Contains("C#") || skills.Contains("Python")).Should().BeTrue(); }); } [Fact] public async Task ArrayContains_Not_ExcludesValue() { var ids = await SeedAsync(); var results = await Redb.Query() .Where(e => e.Skills != null && e.Skills.Contains("C#") && !e.Skills.Contains("Python")) .ToListAsync(); results.Should().NotBeEmpty(); results.Should().AllSatisfy(r => { r.Props.Skills.Should().Contain("C#"); r.Props.Skills.Should().NotContain("Python"); }); } [Fact] public async Task ArrayContains_And_MustHaveAll() { var ids = await SeedAsync(); var results = await Redb.Query() .Where(e => e.Skills != null && e.Skills.Contains("C#") && e.Skills.Contains("SQL")) .ToListAsync(); results.Should().AllSatisfy(r => { r.Props.Skills.Should().Contain("C#"); r.Props.Skills.Should().Contain("SQL"); }); } [Fact] public async Task ArrayContains_WithScalarFilter_Combined() { var ids = await SeedAsync(); var results = await Redb.Query() .Where(e => e.Age > 30 && e.Skills != null && e.Skills.Contains("C#")) .ToListAsync(); results.Should().AllSatisfy(r => { r.Props.Age.Should().BeGreaterThan(30); r.Props.Skills.Should().Contain("C#"); }); } } Path: redb/redb.Tests.Integration/Tests/Base/BareRedbObjectFieldTestsBase.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/BareRedbObjectFieldTestsBase.cs ---- using redb.Core; using redb.Core.Models.Entities; namespace redb.Tests.Integration.Tests.Base; /// /// A bare (non-generic) RedbObject declared as a Props field (discussion #12, п.6). The /// scheme sync used to classify it as a business CLASS and reflect over its own properties - the /// framework's service fields in two casings (id/Id, name/Name...), so /// MSSQL's CI collation hit UNIQUE IX__structures, PostgreSQL hit the reserved-name trigger /// (23514), and the user got a driver error naming neither the field nor the cure. A reference /// field is declared as RedbObject<TProps> - the sync must say exactly that. /// public abstract class BareRedbObjectFieldTestsBase : IAsyncLifetime { protected readonly IRedbService Redb; protected BareRedbObjectFieldTestsBase(IRedbService redb) => Redb = redb; public Task InitializeAsync() => CleanupAsync(); public Task DisposeAsync() => CleanupAsync(); private async Task CleanupAsync() { // Order matters: a refused sync may leave the scheme with a few structures already // inserted (the refusal fires mid-walk), and _structures holds an FK to _schemes. const string schemes = "SELECT _id FROM _schemes WHERE _name IN ('redb.Tests.Integration.Tests.Base.BareRefProbeProps', 'redb.Tests.Integration.Tests.Base.BareRefListProbeProps')"; await Redb.Context.ExecuteAsync($"DELETE FROM _objects WHERE _id_scheme IN ({schemes})"); await Redb.Context.ExecuteAsync($"DELETE FROM _structures WHERE _id_scheme IN ({schemes})"); await Redb.Context.ExecuteAsync($"DELETE FROM _schemes WHERE _id IN ({schemes})"); } [Fact] public async Task BareRedbObjectField_SyncRefusesLoudly() { var act = async () => await Redb.SyncSchemeAsync(); await act.Should().ThrowAsync() .WithMessage("*RedbObject*", "a bare RedbObject field must be refused with the cure in the message, " + "not crash on a unique index or a reserved-name trigger"); } [Fact] public async Task BareRedbObjectCollection_SyncRefusesLoudly() { var act = async () => await Redb.SyncSchemeAsync(); await act.Should().ThrowAsync() .WithMessage("*RedbObject*"); } } // No [RedbScheme]: the fixtures auto-sync every attributed model in the assembly at start-up, // and these two must fail only inside the pin, not kill the whole collection. public class BareRefProbeProps { public string? Label { get; set; } public RedbObject? Target { get; set; } } public class BareRefListProbeProps { public string? Label { get; set; } public List? Targets { get; set; } } Path: redb/redb.Tests.Integration/Tests/Base/BaseFieldNameCollisionTestsBase.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/BaseFieldNameCollisionTestsBase.cs ---- using redb.Core; using redb.Core.Models.Entities; using redb.Core.Query; using redb.Core.Query.Aggregation; using redb.Core.Query.Window; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// A Props field may be called like a base field of the object: Name, Key, Note, DateBegin. /// OrderBy(p => p.Name) and GroupBy(p => p.Name) mean the Props field; /// OrderByRedb(o => o.Name) and GroupByRedb(o => o.Name) mean the object's own. /// /// Sorting and grouping used to decide by the name as well as by the flag the parser sets, so both /// pairs read the object's column: a sort by Props.Name came back sorted by the object name, and /// a grouping by Props.Name returned object names as keys. Filters decided by the flag alone and /// were right, which is why the same field filtered correctly and sorted wrongly. /// /// The seed makes the two orders opposite, so a query that reads the wrong column cannot pass. /// public abstract class BaseFieldNameCollisionTestsBase { protected readonly IRedbService Redb; protected BaseFieldNameCollisionTestsBase(IRedbService redb) => Redb = redb; /// Three persons: object names a, b, c; Props.Name z, y, x. private async Task SeedAsync() { var tag = Guid.NewGuid().ToString("N")[..8]; foreach (var (objectName, propsName) in new[] { ("a", "z"), ("b", "y"), ("c", "x") }) { await Redb.SaveAsync(new RedbObject { name = $"{objectName}-{tag}", Props = new PersonProps { Name = $"{propsName}-{tag}", Age = 30, Email = $"{objectName}@collision-{tag}" } }); } return tag; } private IRedbQueryable Flat(string tag) => Redb.Query().Where(p => p.Email.EndsWith($"@collision-{tag}")); private IRedbQueryable Tree(string tag) => Redb.TreeQuery().Where(p => p.Email.EndsWith($"@collision-{tag}")); private async Task EachFormAsync(Func check) { var restore = Redb.Configuration.EnablePvtPrefilter; try { foreach (var on in new[] { false, true }) { Redb.UpdateConfiguration(c => c.EnablePvtPrefilter = on); await check(on ? "planner on" : "planner off"); } } finally { Redb.UpdateConfiguration(c => c.EnablePvtPrefilter = restore); } } private static string[] PropsNames(IEnumerable rows) where T : RedbObject => rows.Select(r => r.Props.Name[..1]).ToArray(); [Fact] public async Task OrderBy_PropsFieldNamedLikeBaseField_SortsByProps() { var tag = await SeedAsync(); await EachFormAsync(async form => { PropsNames(await Flat(tag).OrderBy(p => p.Name).ToListAsync()) .Should().Equal(["x", "y", "z"], $"OrderBy, {form}"); PropsNames(await Flat(tag).OrderBy(p => p.Name).Take(10).ToListAsync()) .Should().Equal(["x", "y", "z"], $"OrderBy with Take, {form}"); PropsNames(await Flat(tag).OrderByDescending(p => p.Name).ToListAsync()) .Should().Equal(["z", "y", "x"], $"OrderByDescending, {form}"); PropsNames(await Flat(tag).OrderBy(p => p.Age).ThenBy(p => p.Name).ToListAsync()) .Should().Equal(["x", "y", "z"], $"ThenBy, {form}"); PropsNames(await Flat(tag).OrderBy(p => p.Name.ToLower()).ToListAsync()) .Should().Equal(["x", "y", "z"], $"OrderBy over an expression, {form}"); var tree = await Tree(tag).OrderBy(p => p.Name).ToListAsync(); tree.Select(r => r.Props.Name[..1]).Should().Equal(["x", "y", "z"], $"tree OrderBy, {form}"); }); } [Fact] public async Task OrderByRedb_SortsByTheObjectsOwnField() { var tag = await SeedAsync(); await EachFormAsync(async form => { PropsNames(await Flat(tag).OrderByRedb(o => o.Name).ToListAsync()) .Should().Equal(["z", "y", "x"], $"object names run a, b, c, {form}"); var tree = await Tree(tag).OrderByRedb(o => o.Name).ToListAsync(); tree.Select(r => r.Props.Name[..1]).Should().Equal(["z", "y", "x"], $"tree OrderByRedb, {form}"); }); } [Fact] public async Task GroupBy_PropsFieldNamedLikeBaseField_GroupsByProps() { var tag = await SeedAsync(); await EachFormAsync(async form => { var flat = await Flat(tag).GroupBy(p => p.Name).SelectAsync(g => new { g.Key, Count = Agg.Count(g) }); flat.Select(g => g.Key[..1]).OrderBy(k => k).Should().Equal(["x", "y", "z"], $"GroupBy keys, {form}"); var tree = await Tree(tag).GroupBy(p => p.Name).SelectAsync(g => new { g.Key, Count = Agg.Count(g) }); tree.Select(g => g.Key[..1]).OrderBy(k => k).Should().Equal(["x", "y", "z"], $"tree GroupBy keys, {form}"); }); } [Fact] public async Task GroupByRedb_GroupsByTheObjectsOwnField() { var tag = await SeedAsync(); await EachFormAsync(async form => { var flat = await Flat(tag).GroupByRedb(o => o.Name).SelectAsync(g => new { g.Key, Count = Agg.Count(g) }); flat.Select(g => g.Key[..1]).OrderBy(k => k).Should().Equal(["a", "b", "c"], $"GroupByRedb keys, {form}"); }); } [Fact] public async Task Where_PropsFieldNamedLikeBaseField_FiltersByProps() { var tag = await SeedAsync(); var rows = await Flat(tag).Where(p => p.Name.StartsWith("x")).ToListAsync(); rows.Should().ContainSingle().Which.name.Should().StartWith("c", "Props.Name x belongs to object c"); } [Fact] public async Task Aggregates_TellPropsFieldFromTheObjectsOwn() { var tag = await SeedAsync(); await EachFormAsync(async form => { foreach (var (kind, query) in new[] { ("flat", Flat(tag)), ("tree", Tree(tag)) }) { var props = await query.AggregateAsync(x => new { Max = Agg.Max(x.Props.Name), Min = Agg.Min(x.Props.Name), Count = Agg.Count() }); props.Max[..1].Should().Be("z", $"Agg.Max(x.Props.Name), {kind}, {form}"); props.Min[..1].Should().Be("x", $"Agg.Min(x.Props.Name), {kind}, {form}"); props.Count.Should().Be(3, $"{kind}, {form}"); var own = await query.AggregateAsync(x => new { Max = Agg.Max(x.Name), Min = Agg.Min(x.Name) }); own.Max[..1].Should().Be("c", $"Agg.Max(x.Name) is the object's name, {kind}, {form}"); own.Min[..1].Should().Be("a", $"Agg.Min(x.Name) is the object's name, {kind}, {form}"); var mixed = await query.AggregateAsync(x => new { Props = Agg.Max(x.Props.Name), Own = Agg.Max(x.Name), Ages = Agg.Sum(x.Props.Age) }); mixed.Props[..1].Should().Be("z", $"both in one batch, {kind}, {form}"); mixed.Own[..1].Should().Be("c", $"both in one batch, {kind}, {form}"); mixed.Ages.Should().Be(90, $"three persons aged 30, {kind}, {form}"); } }); } [Fact] public async Task AggregateInsideGroupBy_ReadsProps() { var tag = await SeedAsync(); await EachFormAsync(async form => { var flat = await Flat(tag).GroupBy(p => p.Age).SelectAsync(g => new { g.Key, Max = Agg.Max(g, e => e.Name) }); flat.Should().ContainSingle().Which.Max[..1].Should().Be("z", $"flat, {form}"); var tree = await Tree(tag).GroupBy(p => p.Age).SelectAsync(g => new { g.Key, Max = Agg.Max(g, e => e.Name) }); tree.Should().ContainSingle().Which.Max[..1].Should().Be("z", $"tree, {form}"); }); } [Fact] public async Task GroupedWindow_KeyFollowsGroupByOrGroupByRedb() { var tag = await SeedAsync(); await EachFormAsync(async form => { foreach (var (kind, query) in new[] { ("flat", Flat(tag)), ("tree", Tree(tag)) }) { var byProps = await query.GroupBy(p => p.Name) .WithWindow(w => w.OrderByDesc(g => Agg.Sum(g, e => e.Age))) .SelectAsync(g => new { g.Key, Ages = Agg.Sum(g, e => e.Age), Row = Win.RowNumber() }); byProps.Select(g => g.Key[..1]).OrderBy(k => k).Should().Equal(["x", "y", "z"], $"GroupBy key, {kind}, {form}"); var byObject = await query.GroupByRedb(o => o.Name) .WithWindow(w => w.OrderByDesc(g => Agg.Sum(g, e => e.Age))) .SelectAsync(g => new { g.Key, Ages = Agg.Sum(g, e => e.Age), Row = Win.RowNumber() }); byObject.Select(g => g.Key[..1]).OrderBy(k => k).Should().Equal(["a", "b", "c"], $"GroupByRedb key, {kind}, {form}"); } }); } [Fact] public async Task GroupedWindow_OrdersByKeyAndByCount() { // Ages are equal in the seed, so the grouping here is by the Props name: three groups of one. var tag = await SeedAsync(); await EachFormAsync(async form => { foreach (var (kind, query) in new[] { ("flat", Flat(tag)), ("tree", Tree(tag)) }) { var byKey = await query.GroupBy(p => p.Name) .WithWindow(w => w.OrderBy(g => g.Key)) .SelectAsync(g => new { g.Key, Count = Agg.Count(g), Row = Win.RowNumber() }); byKey.OrderBy(g => g.Row).Select(g => g.Key[..1]) .Should().Equal(["x", "y", "z"], $"window ordered by g.Key, {kind}, {form}"); var byKeyDescending = await query.GroupBy(p => p.Name) .WithWindow(w => w.OrderByDesc(g => g.Key)) .SelectAsync(g => new { g.Key, Count = Agg.Count(g), Row = Win.RowNumber() }); byKeyDescending.OrderBy(g => g.Row).Select(g => g.Key[..1]) .Should().Equal(["z", "y", "x"], $"window ordered by g.Key descending, {kind}, {form}"); var byCount = await query.GroupBy(p => p.Age) .WithWindow(w => w.OrderByDesc(g => Agg.Count(g))) .SelectAsync(g => new { g.Key, Count = Agg.Count(g), Row = Win.RowNumber() }); byCount.Should().ContainSingle($"all three persons share an age, {kind}, {form}") .Which.Count.Should().Be(3); } }); } [Fact] public async Task GroupedWindow_OrderedByAnAggregateTheSelectorLacks_Works() { // Two persons aged 30 and one aged 40: sums 60 and 40, averages 30 and 40, counts 2 and 1. var tag = Guid.NewGuid().ToString("N")[..8]; foreach (var (name, age) in new[] { ("a", 30), ("b", 30), ("c", 40) }) { await Redb.SaveAsync(new RedbObject { name = $"{name}-{tag}", Props = new PersonProps { Name = $"{name}-{tag}", Age = age, Email = $"{name}@collision-{tag}" } }); } await EachFormAsync(async form => { foreach (var (kind, query) in new[] { ("flat", Flat(tag)), ("tree", Tree(tag)) }) { var bySum = await query.GroupBy(p => p.Age) .WithWindow(w => w.OrderByDesc(g => Agg.Sum(g, e => e.Age))) .SelectAsync(g => new { g.Key, Row = Win.RowNumber() }); bySum.OrderBy(g => g.Row).Select(g => g.Key).Should().Equal([30, 40], $"Sum is not in the selector, {kind}, {form}"); var byAverage = await query.GroupBy(p => p.Age) .WithWindow(w => w.OrderByDesc(g => Agg.Average(g, e => e.Age))) .SelectAsync(g => new { g.Key, Count = Agg.Count(g), Row = Win.RowNumber() }); byAverage.OrderBy(g => g.Row).Select(g => g.Key).Should().Equal([40, 30], $"Average is not in the selector, {kind}, {form}"); var byCount = await query.GroupBy(p => p.Age) .WithWindow(w => w.OrderByDesc(g => Agg.Count(g))) .SelectAsync(g => new { g.Key, Sum = Agg.Sum(g, e => e.Age), Row = Win.RowNumber() }); byCount.OrderBy(g => g.Row).Select(g => g.Key).Should().Equal([30, 40], $"Count is not in the selector, {kind}, {form}"); var averageShown = await query.GroupBy(p => p.Age) .WithWindow(w => w.OrderBy(g => Agg.Average(g, e => e.Age))) .SelectAsync(g => new { g.Key, Average = Agg.Average(g, e => e.Age), Row = Win.RowNumber() }); averageShown.OrderBy(g => g.Row).Select(g => g.Key).Should().Equal([30, 40], $"Average in the selector, {kind}, {form}"); } }); } } Path: redb/redb.Tests.Integration/Tests/Base/BugRegressionTestsBase.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/BugRegressionTestsBase.cs ---- using redb.Core; using redb.Core.Models.Users; using redb.Core.Query.Aggregation; using redb.Tests.Integration.Helpers; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// Regression suite for bugs surfaced by redb.Examples cases /// E110, E111, E142, E150 and E200. /// /// All tests are written so that fixing the corresponding bug makes the /// test pass; a failing test is a real regression that has to be fixed /// either in core (parser / projection extractor) or in the provider /// (PVT SQL / Pro inline SQL). /// /// Targets: /// * E110 — WhereHasAncestor over a single scheme tree; /// * E111 — WhereHasDescendant over a single scheme tree; /// * E142 — GroupByArray with an outer Where filter /// (free PG used to RAISE EXCEPTION, now compiled /// via pvt_build_query_sql → IN-list); /// * E150 — array aggregation via Agg.Sum(arr.Select(s => s)) /// and the indexed variant Agg.Sum(arr[0]); /// * E200 — string concatenation inside ToLower().Contains(...), /// currently broken in . /// public abstract class BugRegressionTestsBase { protected readonly IRedbService Redb; protected BugRegressionTestsBase(IRedbService redb) => Redb = redb; private async Task SeedEmployeesAsync() => await TestDataFactory.SeedEmployees(Redb, 20); /// /// Tree: Company(1_000_000) -> Engineering(500_000) -> Backend(200_000) /// -> Frontend(150_000) /// -> Marketing(300_000) /// private async Task<(long root, long eng, long backend, long frontend, long marketing)> SeedTreeAsync() { var root = TestDataFactory.CreateTreeNode("Company", "BUG-ROOT", 1_000_000m); root.id = await Redb.SaveAsync(root); var eng = TestDataFactory.CreateTreeNode("Engineering", "BUG-ENG", 500_000m); eng.id = await Redb.CreateChildAsync(eng, root); var backend = TestDataFactory.CreateTreeNode("Backend", "BUG-BE", 200_000m); backend.id = await Redb.CreateChildAsync(backend, eng); var frontend = TestDataFactory.CreateTreeNode("Frontend", "BUG-FE", 150_000m); frontend.id = await Redb.CreateChildAsync(frontend, eng); var marketing = TestDataFactory.CreateTreeNode("Marketing", "BUG-MKT", 300_000m); marketing.id = await Redb.CreateChildAsync(marketing, root); return (root.id, eng.id, backend.id, frontend.id, marketing.id); } // ────────────────────────────────────────────────────────────────── // E110 — WhereHasAncestor // ────────────────────────────────────────────────────────────────── [Fact] public async Task E110_WhereHasAncestor_ReturnsDescendantsOfMatchingAncestor() { var (root, eng, be, fe, mkt) = await SeedTreeAsync(); // Only the root (1_000_000) has Budget > 500_000. // Its descendants are: eng, be, fe, mkt — 4 nodes (root itself excluded). var ids = await Redb.TreeQuery() .WhereHasAncestor(anc => anc.Budget > 500_000m) .ToListAsync(); var seeded = new[] { root, eng, be, fe, mkt }; var hits = ids.Where(o => seeded.Contains(o.id)).Select(o => o.id).ToHashSet(); hits.Should().NotContain(root, "root has no ancestor with Budget > 500k"); hits.Should().Contain(new[] { eng, be, fe, mkt }, "all nodes under root must inherit it"); } // ────────────────────────────────────────────────────────────────── // E111 — WhereHasDescendant // ────────────────────────────────────────────────────────────────── [Fact] public async Task E111_WhereHasDescendant_ReturnsAncestorsOfMatchingDescendant() { var (root, eng, be, fe, mkt) = await SeedTreeAsync(); // All non-root nodes (eng, be, fe, mkt) have Budget > 100_000. // Ancestors of any of them are: root and eng (root is ancestor of all four; // eng is ancestor of be & fe). var ids = await Redb.TreeQuery() .WhereHasDescendant(desc => desc.Budget > 100_000m) .ToListAsync(); var seeded = new[] { root, eng, be, fe, mkt }; var hits = ids.Where(o => seeded.Contains(o.id)).Select(o => o.id).ToHashSet(); hits.Should().Contain(new[] { root, eng }, "root and eng have qualifying descendants"); hits.Should().NotContain(new[] { be, fe, mkt }, "leaves have no descendants"); } // ────────────────────────────────────────────────────────────────── // E142 — GroupByArray with outer Where (filter on parent object) // ────────────────────────────────────────────────────────────────── [Fact] public async Task E142_GroupByArray_WithOuterWhere_ReturnsFilteredGroups() { await SeedEmployeesAsync(); // Outer filter: only employees that actually have a Contacts array // populated. Pre-fix this raised // P0001: pvt_build_array_groupby_sql: outer p_filter is not yet supported // After fix the filter compiles via pvt_build_query_sql and is applied // before unnest. var results = await Redb.Query() .Where(e => e.Contacts != null) .GroupByArray(e => e.Contacts!, c => c.Type) .SelectAsync(g => new { Type = g.Key, Count = Agg.Count(g) }); results.Should().NotBeEmpty("outer filter is satisfied by every seeded employee"); results.Select(r => r.Type).Should().Contain("email"); results.Select(r => r.Type).Should().Contain("phone"); results.Should().AllSatisfy(r => { r.Type.Should().NotBeNullOrEmpty(); r.Count.Should().BeGreaterThan(0); }); } [Fact] public async Task E142_GroupByArray_WithOuterWhere_FilterDropsAll() { await SeedEmployeesAsync(); // Outer filter that matches nothing — the SQL must still compile and // return an empty set rather than raising or returning all rows. var results = await Redb.Query() .Where(e => e.FirstName == "__NoSuchEmployee__") .GroupByArray(e => e.Contacts!, c => c.Type) .SelectAsync(g => new { Type = g.Key, Count = Agg.Count(g) }); results.Should().BeEmpty("outer filter matches no parent objects"); } // ────────────────────────────────────────────────────────────────── // E142.b — GroupByArray with HAVING on aggregated element column. // Each seeded employee has exactly 2 contacts (email + phone), so the // total count per Type group is 20 (one per employee). A HAVING // > 0 keeps both, HAVING > 10 keeps both, HAVING > 25 keeps none. // ────────────────────────────────────────────────────────────────── [Fact] public async Task E142b_GroupByArray_HavingCount_KeepsAllGroups() { await SeedEmployeesAsync(); var results = await Redb.Query() .GroupByArray(e => e.Contacts!, c => c.Type) .Having(g => Agg.Count(g) > 10) .SelectAsync(g => new { Type = g.Key, Count = Agg.Count(g) }); results.Select(r => r.Type).Should().Contain(new[] { "email", "phone" }); results.Should().AllSatisfy(r => r.Count.Should().BeGreaterThanOrEqualTo(20)); } [Fact] public async Task E142b_GroupByArray_HavingCount_DropsAllGroups() { await SeedEmployeesAsync(); var results = await Redb.Query() .GroupByArray(e => e.Contacts!, c => c.Type) .Having(g => Agg.Count(g) > 1_000_000) .SelectAsync(g => new { Type = g.Key, Count = Agg.Count(g) }); results.Should().BeEmpty(); } // ────────────────────────────────────────────────────────────────── // E142.c — GroupByArray with outer Where on a Props field // (FirstName == seeded value). Expected: 2 groups (email + phone), // each with Count == 1 because only one employee matched the filter. // ────────────────────────────────────────────────────────────────── [Fact] public async Task E142c_GroupByArray_WithOuterPropsWhere_GroupsMatchEmployees() { await SeedEmployeesAsync(); // Tests share the same DB; account for accumulated rows by computing // the matched-employee count dynamically. var matched = (await Redb.Query() .Where(e => e.FirstName == "Employee005") .ToListAsync()).Count; matched.Should().BeGreaterThan(0); var results = await Redb.Query() .Where(e => e.FirstName == "Employee005") .GroupByArray(e => e.Contacts!, c => c.Type) .SelectAsync(g => new { Type = g.Key, Count = Agg.Count(g) }); results.Should().HaveCount(2); results.Select(r => r.Type).Should().BeEquivalentTo(new[] { "email", "phone" }); results.Should().AllSatisfy(r => r.Count.Should().Be(matched), "each contact-type group must contain exactly one row per matched employee"); } // ────────────────────────────────────────────────────────────────── // E142.d — GroupByArray with multi-aggregation selector // (Count + Sum/Avg over a numeric element field is not possible // on Contacts; we use Skills array which contains strings only, // so we stick to Count + key, and additionally validate that an // outer Where on base "id" combined with HAVING compiles & runs.) // ────────────────────────────────────────────────────────────────── [Fact] public async Task E142d_GroupByArray_OuterWhereAndHaving_Combined() { await SeedEmployeesAsync(); var matched = await Redb.Query() .Where(e => e.IsRemote == true) .ToListAsync(); matched.Should().NotBeEmpty(); var results = await Redb.Query() .Where(e => e.IsRemote == true) .GroupByArray(e => e.Contacts!, c => c.Type) .Having(g => Agg.Count(g) > 0) .SelectAsync(g => new { Type = g.Key, Count = Agg.Count(g) }); // One row per contact of that type over the matched employees: the database is shared, and other tests store // remote employees with no contacts, so "one row per matched employee" held only while they ran later. results.Should().NotBeEmpty(); results.Select(r => r.Type).Should().Contain(new[] { "email", "phone" }); results.Should().AllSatisfy(r => r.Count.Should().Be( matched.Sum(e => e.Props.Contacts?.Count(c => c.Type == r.Type) ?? 0)), "outer Where filter must be applied before array aggregation"); } // ────────────────────────────────────────────────────────────────── // E150 — Array aggregation (regression lock: already works) // ────────────────────────────────────────────────────────────────── [Fact] public async Task E150_ArrayAggregation_SumAverage_AllElements() { await SeedEmployeesAsync(); // Aggregate ALL elements of SkillLevels[] (unnested). var all = await Redb.Query() .AggregateAsync(x => new { Total = Agg.Sum(x.Props.SkillLevels.Select(s => s)), Avg = Agg.Average(x.Props.SkillLevels.Select(s => s)), Count = Agg.Count() }); all.Count.Should().BeGreaterThan(0); all.Total.Should().BeGreaterThan(0); all.Avg.Should().BeGreaterThan(0); } [Fact] public async Task E150_ArrayAggregation_SumAverage_SpecificIndex() { await SeedEmployeesAsync(); // Aggregate only the first element of SkillLevels[] (indexed access). var first = await Redb.Query() .AggregateAsync(x => new { SumFirst = Agg.Sum(x.Props.SkillLevels[0]), AvgFirst = Agg.Average(x.Props.SkillLevels[0]) }); first.SumFirst.Should().BeGreaterThan(0); first.AvgFirst.Should().BeGreaterThan(0); } // ────────────────────────────────────────────────────────────────── // E200 — string concatenation inside ToLower().Contains(...) // Currently broken in BaseFilterExpressionParser.ExtractProperty: // "Expression must be a property access, got MethodBinaryExpression" // The test asserts the expression builds AND returns at least one match // against the seeded data. // ────────────────────────────────────────────────────────────────── [Fact] public async Task E200_StringConcat_ToLowerContains_ParsesAndExecutes() { await SeedEmployeesAsync(); // Seeded names look like "Employee000 Last000"..; lower-case contains "employee" always matches. var hits = await Redb.Query() .Where(e => (e.FirstName + " " + e.LastName).ToLower().Contains("employee")) .ToListAsync(); hits.Should().NotBeEmpty( "string concatenation inside ToLower().Contains(...) must compile to SQL `||` + ILIKE"); } // ────────────────────────────────────────────────────────────────── // GitHub #4 — ChangePasswordAsync is Task ("true if changed"), // so a WRONG current password must return false, not throw // UnauthorizedAccessException. A plain change-password form built // against the documented contract otherwise 500s on the most common // user error. // ────────────────────────────────────────────────────────────────── [Fact] public async Task ChangePassword_WrongCurrent_ReturnsFalse_NotThrows() { var login = "pw_" + Guid.NewGuid().ToString("N").Substring(0, 12); var user = await Redb.UserProvider.CreateUserAsync( new CreateUserRequest { Login = login, Name = login, Password = "correct-horse" }); var wrong = await Redb.UserProvider.ChangePasswordAsync(user, "definitely-wrong", "new-password-123"); wrong.Should().BeFalse("a wrong current password is a user error, not an exception"); var ok = await Redb.UserProvider.ChangePasswordAsync(user, "correct-horse", "new-password-123"); ok.Should().BeTrue("the correct current password changes it"); } } Path: redb/redb.Tests.Integration/Tests/Base/BulkCreateAtomicityTestsBase.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/BulkCreateAtomicityTestsBase.cs ---- using redb.Core; using redb.Core.Models.Entities; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// AddNewObjectsAsync outside a caller transaction writes the object rows and then the value rows. When the value insert /// fails, the create as a whole has failed: none of its objects may stay behind without their values. The failure here is /// a duplicate key of a [RedbUnique] field, which the value rows carry; it does not depend on the scheme. /// public abstract class BulkCreateAtomicityTestsBase : IAsyncLifetime { private const string Marker = "bulk-create-atomicity"; protected readonly IRedbService Redb; protected BulkCreateAtomicityTestsBase(IRedbService redb) => Redb = redb; public async Task InitializeAsync() { await Redb.SyncSchemeAsync(); await CleanAsync(); } public Task DisposeAsync() => CleanAsync(); private Task CleanAsync() => Redb.Context.ExecuteAsync($"DELETE FROM _objects WHERE _name LIKE '{Marker}%'"); private Task CountAsync(string name) => Redb.Context.ExecuteScalarAsync($"SELECT COUNT(*) FROM _objects WHERE _name = '{name}'"); [Fact] public async Task AddNewObjects_WhenTheValueInsertFails_LeavesNoObjectBehind() { var code = $"{Marker}-{Guid.NewGuid():N}"; await Redb.SaveAsync(new RedbObject { name = $"{Marker}-seed", Props = new UniqueOrderProps { Code = code } }); var duplicate = new RedbObject { name = $"{Marker}-duplicate", Props = new UniqueOrderProps { Code = code, Note = "the key is taken" } }; var create = () => Redb.AddNewObjectsAsync(new[] { duplicate }); await create.Should().ThrowAsync("the value rows break the unique key of Code"); Redb.Context.IsInTransaction.Should().BeFalse("the create ran on its own, outside a caller transaction"); (await CountAsync($"{Marker}-duplicate")).Should().Be(0, "a failed create leaves no object row without its values"); (await CountAsync($"{Marker}-seed")).Should().Be(1); } } Path: redb/redb.Tests.Integration/Tests/Base/BytesRoundTripTestsBase.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/BytesRoundTripTestsBase.cs ---- using redb.Core; using redb.Core.Attributes; using redb.Core.Models.Entities; namespace redb.Tests.Integration.Tests.Base; /// /// A byte matrix of the Props and projection read paths as a permanent suite: the /// report's repro was a manual run against published 3.7.2 packages, and five of six Free /// cells were broken (a byte[] property classified as a Byte collection; PG emitting hex /// instead of base64; MSSQL silently dropping value_bytes on write). Running on all six /// fixtures turns each cell into a pin against the current tree. /// public abstract class BytesRoundTripTestsBase : IAsyncLifetime { protected readonly IRedbService Redb; protected BytesRoundTripTestsBase(IRedbService redb) => Redb = redb; public async Task InitializeAsync() => await ResetAsync(); public async Task DisposeAsync() => await ResetAsync(); private async Task ResetAsync() => await Redb.Context.ExecuteAsync( "DELETE FROM _objects WHERE _id_scheme IN (SELECT _id FROM _schemes WHERE _name = 'BytesProbe')"); [Fact] public async Task PropsByteArray_RoundTrips() { // §3.1 of the report: byte[] in Props was synced as a Byte COLLECTION (a row per byte) // and the Free JSON projection emitted an array where System.Text.Json expects a // base64 string - loading threw. A megabyte also meant a million _values rows. await Redb.SyncSchemeAsync(); var payload = new byte[8192]; new Random(42).NextBytes(payload); var id = await Redb.SaveAsync(new RedbObject { name = "bytes-props", Props = new BytesProbeProps { Label = "p", Blob = payload }, }); var loaded = await Redb.LoadAsync(id, depth: 1); loaded!.Props.Blob.Should().NotBeNull(); loaded.Props.Blob!.SequenceEqual(payload).Should().BeTrue("byte[] Props must round-trip byte-for-byte"); // The scalar-BLOB layout: one _values row for the property, not a row per byte. var rowCount = await Redb.Context.ExecuteScalarAsync( "SELECT COUNT(*) FROM _values v JOIN _structures s ON s._id = v._id_structure " + $"WHERE v._id_object = {id} AND s._name = 'Blob'"); rowCount.Should().Be(1, "a byte[] property is a scalar BLOB, not a collection of Byte rows"); } public static TheoryData EdgeLengths => new() { 0, 1, 2, 3, 4, 5, 255, 256, 1023 }; [Theory] [MemberData(nameof(EdgeLengths))] public async Task PropsByteArray_EdgeLengths_RoundTrip(int length) { // Base64 emission has three padding classes (len % 3) and an empty-input case where a // wrong spelling yields NULL instead of "" and poisons the whole JSON string. Every // provider walks its own emitter here, so the boundary belongs in the shared suite. await Redb.SyncSchemeAsync(); var payload = new byte[length]; for (var i = 0; i < length; i++) payload[i] = (byte)(i % 256); var id = await Redb.SaveAsync(new RedbObject { name = $"bytes-len-{length}", Props = new BytesProbeProps { Label = "e", Blob = payload }, }); var loaded = await Redb.LoadAsync(id, depth: 1); loaded!.Props.Blob.Should().NotBeNull($"a {length}-byte array must survive the round trip"); loaded.Props.Blob!.SequenceEqual(payload).Should().BeTrue("bytes must come back identical"); } [Fact] public async Task PropsByteArray_AllByteValues_RoundTrip() { // All 256 values in order: catches any encoder that mangles high bytes or treats the // payload as text. await Redb.SyncSchemeAsync(); var payload = new byte[256]; for (var i = 0; i < 256; i++) payload[i] = (byte)i; var id = await Redb.SaveAsync(new RedbObject { name = "bytes-all-values", Props = new BytesProbeProps { Label = "a", Blob = payload }, }); var loaded = await Redb.LoadAsync(id, depth: 1); loaded!.Props.Blob!.SequenceEqual(payload).Should().BeTrue("every byte value must round-trip"); } [Fact] public async Task RootValueBytes_EmptyArray_RoundTrips() { // The empty root blob: distinct from NULL, and the spelling that returns NULL for it // would break the base-field JSON rather than the properties object. await Redb.SyncSchemeAsync(); var id = await Redb.SaveAsync(new RedbObject { name = "bytes-root-empty", value_bytes = [], Props = new BytesProbeProps { Label = "re" }, }); var loaded = await Redb.LoadAsync(id, depth: 1); loaded!.value_bytes.Should().NotBeNull("an empty blob is not a missing blob"); loaded.value_bytes!.Length.Should().Be(0); } [Fact] public async Task RootValueBytes_PersistsToDbAndRoundTrips() { // §3.2/§3.3 of the report: PG emitted bytea hex instead of base64 on load; MSSQL // dropped value_bytes on write with no exception. The DB-side NULL check is the pin // against the silent-loss variant - a cache could mask it on reload. await Redb.SyncSchemeAsync(); var payload = new byte[] { 1, 2, 3, 4, 5 }; var id = await Redb.SaveAsync(new RedbObject { name = "bytes-root", value_bytes = payload, Props = new BytesProbeProps { Label = "r" }, }); var storedCount = await Redb.Context.ExecuteScalarAsync( $"SELECT COUNT(*) FROM _objects WHERE _id = {id} AND _value_bytes IS NOT NULL"); storedCount.Should().Be(1, "value_bytes must reach the _objects column - silent NULL was the §3.3 defect"); var loaded = await Redb.LoadAsync(id, depth: 1); loaded!.value_bytes.Should().NotBeNull(); loaded.value_bytes!.SequenceEqual(payload).Should().BeTrue("root value_bytes must round-trip byte-for-byte"); } } [RedbScheme(Name = "BytesProbe")] public class BytesProbeProps { public string? Label { get; set; } public byte[]? Blob { get; set; } } Path: redb/redb.Tests.Integration/Tests/Base/CacheBehaviorTestsBase.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/CacheBehaviorTestsBase.cs ---- using redb.Core; using redb.Core.Caching; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// Cross-cache E2E over the live service: the domain metadata cache (schemes), the process-global /// ClrSchemeTypeIndex, and the list cache. Verifies caching, invalidation and the per-domain isolation /// invariant. (PropsCache is covered separately by unit /// tests since the fixtures run with EnablePropsCache=false.) /// public abstract class CacheBehaviorTestsBase { protected readonly IRedbService Redb; protected CacheBehaviorTestsBase(IRedbService redb) => Redb = redb; // ===== GlobalMetadataCache ===== [Fact] public async Task MetadataCache_AfterSync_SchemeIsCached() { await Redb.SyncSchemeAsync(); // GetSchemeFromCache is a pure in-memory lookup (no DB) — non-null means it is cached. Redb.GetSchemeFromCache().Should().NotBeNull(); } [Fact] public async Task MetadataCache_Invalidate_RemovesScheme() { var scheme = await Redb.SyncSchemeAsync(); Redb.GetSchemeFromCache().Should().NotBeNull(); Redb.Cache.InvalidateScheme(scheme.Name); Redb.GetSchemeFromCache().Should().BeNull("invalidation must drop the cached scheme"); } [Fact] public async Task MetadataCache_ByName_CountsAHit() { var scheme = await Redb.SyncSchemeAsync(); var name = scheme.Name; // Prime the SchemeByName projection, then a second lookup must register a hit. await Redb.GetSchemeByNameAsync(name); var before = Redb.Cache.GetStatistics().SchemeHits; var again = await Redb.GetSchemeByNameAsync(name); again.Should().NotBeNull(); Redb.Cache.GetStatistics().SchemeHits.Should().BeGreaterThan(before); } [Fact] public void MetadataCache_IsEnabledInFixtures() { Redb.Cache.IsEnabled.Should().BeTrue(); } // ===== ClrSchemeTypeIndex (process-global name → Type) ===== [Fact] public async Task ClrSchemeTypeIndex_ResolvesSyncedNameToType() { var scheme = await Redb.SyncSchemeAsync(); // The name → Type index is a code fact shared across all cache domains. ClrSchemeTypeIndex.Resolve(scheme.Name).Should().Be(typeof(NamingByTypeProps)); } [Fact] public async Task ClrSchemeTypeIndex_ResolvesAliasToo() { await Redb.SyncSchemeAsync(); // NamingByTypeProps carries an alias — it must resolve to the same type as the scheme name. ClrSchemeTypeIndex.Resolve("Именование: по типу").Should().Be(typeof(NamingByTypeProps)); } // ===== GlobalListCache ===== [Fact] public void ListCache_EnabledByDefault_AndTogglesReported() { Redb.ListCache.IsEnabled.Should().BeTrue("fixtures leave EnableListCache at its default (true)"); Redb.ListCache.SetTtl(TimeSpan.FromMinutes(3)); // must not throw Redb.ListCache.SetEnabled(false); Redb.ListCache.IsEnabled.Should().BeFalse(); Redb.ListCache.SetEnabled(true); Redb.ListCache.IsEnabled.Should().BeTrue(); } [Fact] public void ListCache_Clear_DoesNotThrow_AndStaysEnabled() { Redb.ListCache.Clear(); Redb.ListCache.IsEnabled.Should().BeTrue(); } } Path: redb/redb.Tests.Integration/Tests/Base/CancellationTestsBase.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/CancellationTestsBase.cs ---- using redb.Core; using redb.Core.Models.Entities; using redb.Tests.Integration.Helpers; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// The cancellation contract (CANCELLATION_PLAN, wave B5): cancellation surfaces as /// and nothing else; a cancelled save leaves the /// database untouched (the rollback always completes, s3.2/s3.4); after a successful commit /// the token is never consulted again (s3.3). A pre-cancelled token is the deterministic /// probe - it must stop every verb before the first write. The in-flight tests are /// provider-specific (PG pg_sleep / MSSQL WAITFOR) and hang off . /// public abstract class CancellationTestsBase : IAsyncLifetime { protected readonly IRedbService Redb; protected CancellationTestsBase(IRedbService redb) => Redb = redb; /// A statement that sleeps ~30s server-side, or null when the engine cannot sleep (SQLite). protected virtual string? SleepSql => null; public async Task InitializeAsync() => await ResetAsync(); public async Task DisposeAsync() => await ResetAsync(); private async Task ResetAsync() => await Redb.Context.ExecuteAsync("DELETE FROM _objects WHERE _name LIKE 'ct-probe-%'"); private static CancellationToken Cancelled() { var cts = new CancellationTokenSource(); cts.Cancel(); return cts.Token; } private Task CountByNameAsync(string name) => Redb.Context.ExecuteScalarAsync( $"SELECT COUNT(*) FROM _objects WHERE _name = '{name}'"); [Fact] public async Task PreCancelledSave_ThrowsOce_AndWritesNothing() { await Redb.SyncSchemeAsync(); var obj = TestDataFactory.CreateSimple("ct-probe-save", 5m); var act = async () => await Redb.SaveAsync(obj, Cancelled()); await act.Should().ThrowAsync( "cancellation has exactly one shape - OperationCanceledException"); (await CountByNameAsync("ct-probe-save")).Should().Be(0, "a cancelled save must leave no trace in the database"); } [Fact] public async Task PreCancelledBatchSave_ThrowsOce_AndWritesNothing() { await Redb.SyncSchemeAsync(); var batch = Enumerable.Range(0, 20) .Select(i => (Core.Models.Contracts.IRedbObject)TestDataFactory.CreateSimple($"ct-probe-batch-{i}", i)) .ToList(); var act = async () => await Redb.SaveAsync(batch, Cancelled()); await act.Should().ThrowAsync(); var count = await Redb.Context.ExecuteScalarAsync( "SELECT COUNT(*) FROM _objects WHERE _name LIKE 'ct-probe-batch-%'"); count.Should().Be(0, "the batch is atomic: cancelled means nothing landed"); } [Fact] public async Task PreCancelledLoad_ThrowsOce() { await Redb.SyncSchemeAsync(); var id = await Redb.SaveAsync(TestDataFactory.CreateSimple("ct-probe-load", 1m)); var act = async () => await Redb.LoadAsync(id, depth: 1, cancellationToken: Cancelled()); await act.Should().ThrowAsync(); } [Fact] public async Task PreCancelledToList_ThrowsOce() { await Redb.SyncSchemeAsync(); await Redb.SaveAsync(TestDataFactory.CreateSimple("ct-probe-query", 2m)); var act = async () => await Redb.Query().ToListAsync(Cancelled()); await act.Should().ThrowAsync(); } [Fact] public async Task PreCancelledDelete_ThrowsOce_AndTheRowSurvives() { await Redb.SyncSchemeAsync(); var id = await Redb.SaveAsync(TestDataFactory.CreateSimple("ct-probe-delete", 3m)); var act = async () => await Redb.DeleteAsync(id, Cancelled()); await act.Should().ThrowAsync(); (await CountByNameAsync("ct-probe-delete")).Should().Be(1, "the DELETE never reached the database - the row must survive"); } [Fact] public async Task PreCancelledPurgeTrash_ThrowsOce() { // Unified cancellation semantics (owner decision, 2026-09-08): PurgeTrashAsync gave up // its historical graceful return (a Cancelled progress report and a soft exit) - like // every other verb it now surfaces OCE. The farewell progress report survives. var act = async () => await Redb.PurgeTrashAsync(trashId: -1, totalCount: 0, cancellationToken: Cancelled()); await act.Should().ThrowAsync( "a pre-cancelled purge must throw like every other cancelled verb, not return quietly"); } [Fact] public async Task PreCancelledDeleteWithPurge_ThrowsOce_AndNothingIsMarked() { await Redb.SyncSchemeAsync(); var id = await Redb.SaveAsync(TestDataFactory.CreateSimple("ct-probe-purge", 4m)); var act = async () => await Redb.DeleteWithPurgeAsync(new[] { id }, cancellationToken: Cancelled()); await act.Should().ThrowAsync(); (await CountByNameAsync("ct-probe-purge")).Should().Be(1, "the cancelled call must not even mark the object for deletion"); } [Fact] public async Task InFlightCancel_BreaksALongStatement_Quickly() { if (SleepSql is null) return; // the engine has no server-side sleep (SQLite) - covered by the pre-cancelled probes using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(300)); var sw = System.Diagnostics.Stopwatch.StartNew(); var act = async () => await Redb.Context.ExecuteAsync(SleepSql, System.Array.Empty(), cts.Token); await act.Should().ThrowAsync( "an in-flight command must be torn down by the token, not awaited to completion"); sw.Stop(); sw.Elapsed.Should().BeLessThan(TimeSpan.FromSeconds(15), "cancellation must interrupt the ~30s sleep long before it finishes"); } [Fact] public async Task InFlightCancelledBatch_LeavesNoTrace_OrCommitsWhole() { // A racing cancel: either the save finished first (every object is in), or the OCE // won and the transaction rolled back (nothing is in). Any in-between state is the // failure this test exists to catch (s3.2: atomicity survives cancellation). await Redb.SyncSchemeAsync(); const int n = 60; var batch = Enumerable.Range(0, n) .Select(i => (Core.Models.Contracts.IRedbObject)TestDataFactory.CreateSimple($"ct-probe-race-{i}", i)) .ToList(); using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(20)); var cancelled = false; try { await Redb.SaveAsync(batch, cts.Token); } catch (OperationCanceledException) { cancelled = true; } var count = await Redb.Context.ExecuteScalarAsync( "SELECT COUNT(*) FROM _objects WHERE _name LIKE 'ct-probe-race-%'"); if (cancelled) count.Should().Be(0, "a cancelled batch save must roll back completely"); else count.Should().Be(n, "an uncancelled save must have committed every object"); } /// /// The token given to reaches the load. It was accepted and dropped /// on the way to the query, so a cancelled reader still ran the scheme lookup and the load. /// [Fact] public async Task PreCancelledListItemObject_ThrowsOce() { var linkedId = await Redb.SaveAsync(TestDataFactory.CreateSimple("ct-probe-item-target", 4m)); var list = await Redb.ListProvider.SaveListAsync(RedbList.Create($"ct-probe-list-{Guid.NewGuid():N}", "ct-probe")); var item = await Redb.ListProvider.SaveListItemAsync( new RedbListItem { IdList = list.Id, Value = "linked", IdObject = linkedId }); using (Redb.BeginAccess()) { var act = async () => await item.GetObjectAsync(Cancelled()); await act.Should().ThrowAsync(); } } } Path: redb/redb.Tests.Integration/Tests/Base/CaseFoldingTestsBase.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/CaseFoldingTestsBase.cs ---- using redb.Core; using redb.Core.Models.Entities; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// Case-insensitive text search across scripts, with the feature ON. /// /// /// Case folding is driven by the database's own rules and those cover only ASCII in two of the three /// providers. The point of this suite is not Cyrillic: it is that a single setting fixes every script /// whose case mapping is one character to one character, and that three specific classes are NOT /// fixed by it and never will be. Both halves are asserted, because a suite that only proves the /// happy path lets an over-promise ship in the documentation. /// /// /// /// On PostgreSQL these tests are meaningful only against a database created with /// LC_CTYPE=C (see PostgresCollationFixture). On the ordinary test database every one /// of them passes with the feature removed, which is exactly how the defect went unnoticed. /// /// public abstract class CaseFoldingTestsBase { protected readonly IRedbService Redb; private bool _seeded; protected CaseFoldingTestsBase(IRedbService redb) => Redb = redb; /// /// One row per script, upper-cased at the source so a lower-case needle has to fold to find it. /// private static readonly (string Label, string Text)[] Rows = { ("cyrillic", "ПРИВЕТ МИР"), ("greek", "ΑΘΗΝΑ ΠΟΛΗ"), ("hungarian", "ŐSZ ÚTON JÁRTAM"), ("polish", "ŻÓŁW ŁÓDŹ"), ("czech", "ŘEKA ČESKÁ"), ("french", "ÉTÉ À PARIS"), ("german", "STRAßE GROß"), ("turkish", "İSTANBUL"), ("umlaut", "MÜLLER"), ("ascii", "HELLO WORLD"), }; protected async Task EnsureSeededAsync() { if (_seeded) return; // Scheme name is the CLR FullName: the positional [RedbScheme("...")] argument is the alias. await Redb.Context.ExecuteAsync( "DELETE FROM _objects WHERE _id_scheme IN (SELECT _id FROM _schemes WHERE _name = " + $"'{typeof(CollationProps).FullName}')"); var objects = Rows.Select(r => new RedbObject { name = r.Label, Props = new CollationProps { Text = r.Text, Label = r.Label } }).ToList(); await Redb.SaveAsync(objects); _seeded = true; } private async Task> FindAsync(string needle) { var results = await Redb.Query() .Where(c => c.Text.Contains(needle, StringComparison.OrdinalIgnoreCase)) .Take(50).ToListAsync(); return results.Select(r => r.Props.Label).OrderBy(x => x).ToList(); } // ===================================================================== // Fixed by the setting: every one-to-one case mapping // ===================================================================== /// /// The whole point in one test: this is not about Cyrillic. Each of these scripts maps case one /// character to one character, and one setting covers all of them with no per-language work. /// [Theory] [InlineData("привет", "cyrillic")] [InlineData("αθηνα", "greek")] [InlineData("ősz úton", "hungarian")] [InlineData("żółw", "polish")] [InlineData("řeka česká", "czech")] [InlineData("été à paris", "french")] [InlineData("hello", "ascii")] public async Task ContainsIgnoreCase_FoldsEveryOneToOneScript(string needle, string expectedLabel) { await EnsureSeededAsync(); (await FindAsync(needle)).Should().Contain(expectedLabel); } /// The reverse direction: an upper-case needle against the same rows. [Theory] [InlineData("ПРИВЕТ", "cyrillic")] [InlineData("ŻÓŁW", "polish")] [InlineData("ÉTÉ", "french")] public async Task ContainsIgnoreCase_FoldsInBothDirections(string needle, string expectedLabel) { await EnsureSeededAsync(); (await FindAsync(needle)).Should().Contain(expectedLabel); } [Fact] public async Task StartsWithIgnoreCase_Folds() { await EnsureSeededAsync(); var results = await Redb.Query() .Where(c => c.Text.StartsWith("привет", StringComparison.OrdinalIgnoreCase)) .Take(50).ToListAsync(); results.Select(r => r.Props.Label).Should().Contain("cyrillic"); } [Fact] public async Task EndsWithIgnoreCase_Folds() { await EnsureSeededAsync(); var results = await Redb.Query() .Where(c => c.Text.EndsWith("мир", StringComparison.OrdinalIgnoreCase)) .Take(50).ToListAsync(); results.Select(r => r.Props.Label).Should().Contain("cyrillic"); } /// /// ToLower is the other half of "one solution covers everything". Fixing the search while /// leaving ToLower ASCII-only would let a query find a row that a later comparison rejects. /// [Fact] public async Task ToLower_Folds() { await EnsureSeededAsync(); var results = await Redb.Query() .Where(c => c.Text.ToLower().Contains("привет")) .Take(50).ToListAsync(); results.Select(r => r.Props.Label).Should().Contain("cyrillic"); } [Fact] public async Task ToUpper_Folds() { await EnsureSeededAsync(); var results = await Redb.Query() .Where(c => c.Text.ToUpper().Contains("ПРИВЕТ")) .Take(50).ToListAsync(); results.Select(r => r.Props.Label).Should().Contain("cyrillic"); } /// A needle matching nothing must still match nothing. Folding is not widening. [Fact] public async Task ContainsIgnoreCase_DoesNotMatchUnrelatedRows() { await EnsureSeededAsync(); (await FindAsync("привет")).Should().NotContain("greek").And.NotContain("ascii"); } /// The same word with ß on both sides matches everywhere: that mapping is one to one. [Fact] public async Task GermanSharpS_MatchesItself() { await EnsureSeededAsync(); (await FindAsync("straße")).Should().Contain("german"); } /// With the diacritic present it matches, which is the case-folding half working. [Fact] public async Task Diacritics_MatchWhenPresent() { await EnsureSeededAsync(); (await FindAsync("müller")).Should().Contain("umlaut"); } // ===================================================================== // Boundaries. Provider-specific on purpose — see the remark below. // ===================================================================== /// /// German ß against SS, Turkish İ against i, and diacritics are the three things a collation /// cannot fold uniformly. What each provider actually does with them differs, and that surprised /// this suite: SQL Server's CI_AS folds ß to SS and İ to i, while the ICU root collation used on /// PostgreSQL folds neither. Asserting one answer for all three providers would have been wrong, /// so each states its own and the differences are the documentation. /// /// /// Diacritics are the one boundary that holds everywhere: "muller" never finds "Müller". That is /// not case folding at all, and on PostgreSQL it is refused outright — a nondeterministic /// collation, which is what accent-insensitivity needs, cannot be used with ILIKE. /// /// [Fact] public async Task KnownBoundary_Diacritics_AreNotFolded() { await EnsureSeededAsync(); (await FindAsync("muller")).Should().NotContain("umlaut"); } /// /// Does this provider fold ß to SS? Overridden per provider rather than assumed; see /// for why the boundaries are not shared. /// protected abstract bool FoldsSharpSToDoubleS { get; } /// Does this provider fold the Turkish dotted capital İ to a plain i? protected abstract bool FoldsTurkishDottedI { get; } /// /// BR-6 (owner decision 2026-09-02): the PLAIN string predicates (StartsWith/Contains/EndsWith /// without a comparison) translate to LIKE and keep each database's own case rules - redb does /// not decide for the programmer. PostgreSQL: case-sensitive; SQLite: ASCII case-insensitive; /// MSSQL: whatever the collation says (CI on the default). Explicit control is the *IgnoreCase /// forms plus StringCollation. This flag states the provider's documented default. /// protected abstract bool PlainStartsWithIsCaseSensitive { get; } [Fact] public async Task PlainStartsWith_IsTheDatabasesOwnSemantics_ByContract() { await EnsureSeededAsync(); // Exact case matches everywhere - the sanity half of the contract. var exact = await Redb.Query() .Where(c => c.Text.StartsWith("HELLO")).Take(50).ToListAsync(); exact.Select(r => r.Props.Label).Should().Contain("ascii"); // A lower-case needle against the upper-cased row: the database's own rule decides. var folded = await Redb.Query() .Where(c => c.Text.StartsWith("hello")).Take(50).ToListAsync(); if (PlainStartsWithIsCaseSensitive) folded.Select(r => r.Props.Label).Should().NotContain("ascii", "this database's LIKE is case-sensitive and redb passes its rule through"); else folded.Select(r => r.Props.Label).Should().Contain("ascii", "this database's LIKE folds ASCII case and redb passes its rule through"); } [Fact] public async Task Boundary_GermanSharpS_AgainstDoubleS() { await EnsureSeededAsync(); var found = await FindAsync("strasse"); if (FoldsSharpSToDoubleS) found.Should().Contain("german", "this provider's collation expands ß to SS"); else found.Should().NotContain("german", "pattern matching folds character by character and cannot change a string's length, " + "even though UPPER on the same database does expand ß to SS"); } [Fact] public async Task Boundary_TurkishDottedI() { await EnsureSeededAsync(); var found = await FindAsync("istanbul"); if (FoldsTurkishDottedI) found.Should().Contain("turkish", "this provider's collation folds İ to i"); else found.Should().NotContain("turkish", "İ (U+0130) folds to i with a combining dot, not to plain i. Unfixable by one " + "setting anyway: Turkish wants I→ı where every other locale wants I→i"); } } Path: redb/redb.Tests.Integration/Tests/Base/ColdSchemeLinkedObjectTestsBase.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/ColdSchemeLinkedObjectTestsBase.cs ---- using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Core; using redb.Core.Extensions; using redb.Core.Models.Configuration; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// The object behind a list item loads typed on a node whose metadata cache has never seen its scheme - a fresh /// process, another cluster node. The single linked-object loaders took the CLR type from that cache only; on a miss /// they fell back to get_object_json with an untyped result, which a Pro SQLite database does not even have. The /// batch preload path already resolved cold schemes by id, so the preload is off here. /// public abstract class ColdSchemeLinkedObjectTestsBase { protected abstract void UseProvider(RedbOptionsBuilder options); protected virtual void Register(IServiceCollection services, Action configure) => services.AddRedb(configure); 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.PreloadListItemLinkedObjects = false; c.CacheDomain = cacheDomain; }); }); return services.BuildServiceProvider(); } private sealed record Seed(long ItemId, long LinkedObjectId, long SchemeId); private static async Task SeedAsync(ServiceProvider writer) { var tag = Guid.NewGuid().ToString("N")[..8]; var redb = writer.GetRequiredService(); await redb.InitializeAsync(ensureCreated: true); await redb.SyncSchemeAsync(); await redb.InitializeTypeRegistryAsync(); var linkedObjectId = await redb.SaveAsync(new RedbObject { name = $"coldscheme-linked-{tag}", Props = new SimpleProps { Title = "linked" } }); var list = await redb.ListProvider.SaveListAsync(RedbList.Create($"coldscheme-{tag}", "coldscheme")); var item = await redb.ListProvider.SaveListItemAsync(new RedbListItem { IdList = list.Id, Value = "linked", IdObject = linkedObjectId }); var schemeId = (await redb.LoadAsync(linkedObjectId))!.scheme_id; return new Seed(item.Id, linkedObjectId, schemeId); } /// A reader with a cache domain of its own takes the item through its list provider. private async Task RunOnColdReaderAsync(Func touch) { var run = Guid.NewGuid().ToString("N")[..8]; await using var writer = Build($"cold-scheme-writer-{run}"); var seed = await SeedAsync(writer); await using var reader = Build($"cold-scheme-reader-{run}"); await using var scope = reader.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); redb.Cache.GetClrType(seed.SchemeId).Should().BeNull("precondition: the reader's metadata cache has never seen the scheme"); var item = await redb.ListProvider.GetListItemAsync(seed.ItemId); item.Should().NotBeNull(); item!.IdObject.Should().Be(seed.LinkedObjectId); item.IsObjectLoaded.Should().BeFalse("precondition: no preload, the single loader resolves the object"); await touch(item, seed); } private static void AssertTyped(IRedbObject? loaded, Seed seed) { loaded.Should().BeOfType>("a cold scheme is resolved by its id, not loaded untyped"); var typed = (RedbObject)loaded!; typed.id.Should().Be(seed.LinkedObjectId); typed.Props.Title.Should().Be("linked"); } [Fact] public Task SyncGetter_ColdSchemeCache_LoadsTheLinkedObjectTyped() => RunOnColdReaderAsync((item, seed) => { AssertTyped(item.Object, seed); return Task.CompletedTask; }); [Fact] public Task AsyncLoad_ColdSchemeCache_LoadsTheLinkedObjectTyped() => RunOnColdReaderAsync(async (item, seed) => AssertTyped(await item.GetObjectAsync(), seed)); } Path: redb/redb.Tests.Integration/Tests/Base/ColdSchemeTreeFilterTestsBase.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/ColdSchemeTreeFilterTestsBase.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; /// /// WhereHasAncestor / WhereHasDescendant on a node whose metadata cache has never seen the target's scheme - a fresh /// process, a Tsak worker that does not sync it. The target scheme is found as Query<T>() finds it, in the cache and /// then in the database; the filters read the cache alone and threw "scheme for type ... not found" for a scheme the /// database has. /// public abstract class ColdSchemeTreeFilterTestsBase { protected abstract void UseProvider(RedbOptionsBuilder options); protected virtual void Register(IServiceCollection services, Action configure) => services.AddRedb(configure); 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.CacheDomain = cacheDomain; }); }); return services.BuildServiceProvider(); } private sealed record Seed(string Tag, long Department, long Child); /// A department with a child below it, and a second object of the child's scheme outside it. private static async Task SeedAsync(ServiceProvider writer) { var tag = "cst-" + Guid.NewGuid().ToString("N")[..8]; var redb = writer.GetRequiredService(); await redb.InitializeAsync(ensureCreated: true); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.InitializeTypeRegistryAsync(); var department = new TreeRedbObject { name = tag + "-d", Props = new DepartmentProps { Name = tag, Code = tag + "-A" } }; department.id = await redb.SaveAsync(department); var child = new TreeRedbObject { name = tag + "-c", Props = new SimpleProps { Title = tag } }; child.id = await redb.CreateChildAsync(child, department); await redb.SaveAsync(new TreeRedbObject { name = tag + "-o", Props = new SimpleProps { Title = tag } }); return new Seed(tag, department.id, child.id); } /// A reader with a cache domain of its own, which has never seen the scheme of . private async Task RunOnColdReaderAsync(Func run) where TTarget : class, new() { var id = Guid.NewGuid().ToString("N")[..8]; await using var writer = Build($"cold-tree-writer-{id}"); var seed = await SeedAsync(writer); await using var reader = Build($"cold-tree-reader-{id}"); await using var scope = reader.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); redb.Cache.GetSchemeIdByClrType(typeof(TTarget)).Should().BeNull("precondition: the reader's metadata cache has never seen the target scheme"); await run(redb, seed); } [Fact] public Task WhereHasAncestor_TargetSchemeOnlyInTheDatabase_Filters() => RunOnColdReaderAsync(async (redb, seed) => { var nodes = await redb.TreeQuery().Where(p => p.Title == seed.Tag) .WhereHasAncestor(d => d.Code == seed.Tag + "-A").ToListAsync(); nodes.Select(n => n.Id).Should().Equal(new[] { seed.Child }, "only the child lies below the department"); }); [Fact] public Task WhereHasDescendant_TargetSchemeOnlyInTheDatabase_Filters() => RunOnColdReaderAsync(async (redb, seed) => { var nodes = await redb.TreeQuery().Where(d => d.Name == seed.Tag) .WhereHasDescendant(s => s.Title == seed.Tag).ToListAsync(); nodes.Select(n => n.Id).Should().Equal(new[] { seed.Department }, "the department has the child below it"); }); } Path: redb/redb.Tests.Integration/Tests/Base/CollectionFilterAnalyticsTestsBase.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/CollectionFilterAnalyticsTestsBase.cs ---- using System.Linq.Expressions; using redb.Core; 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; /// /// Every analytic form over a filter that reads an array, a dictionary entry or a field of a nested class, flat and /// over a tree, compared with the same LINQ over the seeded objects in memory: SumAsync, AggregateAsync, GroupBy, /// WithWindow, GroupBy.WithWindow, GroupByArray, and for the tree also ToListAsync and CountAsync. /// /// Pro answers such a filter with the list statement of the same filter inside the analytic statement (a subquery on /// PostgreSQL and SQLite, a temporary table of the same batch on SQL Server); it used to run that statement first and /// inline the ids it returned. A filter that matches nothing and a filter that matches one object are part of the set: /// the first must not turn into "every object", the second must give exactly one. /// public abstract class CollectionFilterAnalyticsTestsBase { protected readonly IRedbService Redb; protected CollectionFilterAnalyticsTestsBase(IRedbService redb) => Redb = redb; private sealed record Seeded(long RootId, string Tag, List Children); /// A root and eight children of one department, varied in skills, phone keys, floors and contacts. private async Task SeedAsync() { await Redb.SyncSchemeAsync(); var tag = "cf-" + Guid.NewGuid().ToString("N")[..8]; var root = new TreeRedbObject { name = $"{tag}-root", Props = TestDataFactory.CreateEmployee(0, department: $"{tag}-root", salary: 90_000m).Props }; root.id = await Redb.SaveAsync(root); var children = new List(); for (var i = 1; i <= 8; i++) { var p = TestDataFactory.CreateEmployee(i, firstName: $"{tag}-n{i}", department: tag, salary: 1000m * i, position: i % 2 == 0 ? "Even" : "Odd").Props; p.Skills = i % 3 == 0 ? ["sql", "x"] : ["x"]; p.PhoneDirectory = i % 2 == 0 ? new Dictionary { ["desk"] = $"{i}" } : new Dictionary { ["home"] = $"{i}" }; p.HomeAddress!.Building!.Floor = i; // Email verified, phone not: the shape every seeded employee has, which ArrayGroupByDeepTestsBase counts on // over the shared database. p.Contacts = [ new TestContact { Type = i % 2 == 0 ? "email" : "phone", IsVerified = i % 2 == 0, Value = $"{tag}-{i}-a" }, new TestContact { Type = "email", IsVerified = true, Value = $"{tag}-{i}-b" } ]; await Redb.CreateChildAsync(new TreeRedbObject { name = $"{tag}-c{i}", Props = p }, root); children.Add(p); } return new Seeded(root.id, tag, children); } /// The filter of each case, always within the seeded department so other tests' data stays out. private static Expression> Filter(string kind, string tag) { var narrowName = tag + "-n4"; return kind switch { "nested" => e => e.Department == tag && e.HomeAddress!.Building!.Floor > 4, "array" => e => e.Department == tag && e.Skills!.Contains("sql"), "dict" => e => e.Department == tag && e.PhoneDirectory!.ContainsKey("desk"), "none" => e => e.Department == tag && e.Skills!.Contains("absent"), "narrow" => e => e.Department == tag && e.FirstName == narrowName && e.Skills!.Contains("x"), _ => throw new ArgumentOutOfRangeException(nameof(kind)) }; } public static IEnumerable Kinds() => new[] { "nested", "array", "dict", "none", "narrow" }.Select(k => new object[] { k }); private IRedbQueryable Source(Seeded s, bool tree, string kind) => (tree ? Redb.TreeQuery(s.RootId) : Redb.Query()).Where(Filter(kind, s.Tag)); private static List Expected(Seeded s, string kind) => s.Children.Where(Filter(kind, s.Tag).Compile()).ToList(); [Theory] [MemberData(nameof(Kinds))] public Task Flat_EveryForm_MatchesLinq(string kind) => EveryFormAsync(kind, tree: false); [Theory] [MemberData(nameof(Kinds))] public Task Tree_EveryForm_MatchesLinq(string kind) => EveryFormAsync(kind, tree: true); private async Task EveryFormAsync(string kind, bool tree) { var s = await SeedAsync(); var expected = Expected(s, kind); var because = $"{(tree ? "tree" : "flat")} {kind}"; if (kind == "none") expected.Should().BeEmpty("precondition"); if (kind == "narrow") expected.Should().HaveCount(1, "precondition"); // Single aggregate and AggregateAsync. (await Source(s, tree, kind).SumAsync(e => e.Salary)).Should().Be(expected.Sum(e => e.Salary), because); var batch = await Source(s, tree, kind).AggregateAsync(x => new { Count = Agg.Count(), Sum = Agg.Sum(x.Props.Salary) }); batch.Count.Should().Be(expected.Count, because); batch.Sum.Should().Be(expected.Sum(e => e.Salary), because); // GroupBy. var groups = await Source(s, tree, kind).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( expected.GroupBy(e => e.Position).Select(g => (g.Key, g.Count(), g.Sum(e => e.Salary))), because); // Window over the objects. var rows = await Source(s, tree, kind).WithWindow(w => w.OrderBy(e => e.Salary)) .SelectAsync(e => new { e.Props.Salary, Row = Win.RowNumber() }); rows.Select(r => r.Salary).Should().BeEquivalentTo(expected.Select(e => e.Salary), because); rows.Select(r => r.Row).Should().BeEquivalentTo(Enumerable.Range(1, expected.Count).Select(i => (long)i), because); // Window over the groups. var ranked = await Source(s, tree, kind).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( expected.GroupBy(e => e.Position).Select(g => (g.Key, g.Count())), because); // GroupByArray over the contacts. var types = await Source(s, tree, kind).GroupByArray(e => e.Contacts!, c => c.Type) .SelectAsync(g => new { Key = g.Key, Count = Agg.Count(g) }); types.Select(g => (g.Key, g.Count)).Should().BeEquivalentTo( expected.SelectMany(e => e.Contacts!).GroupBy(c => c.Type).Select(g => (g.Key, g.Count())), because); // The list and the count of the same filter. (await Source(s, tree, kind).CountAsync()).Should().Be(expected.Count, because); (await Source(s, tree, kind).ToListAsync()).Select(o => o.Props.FirstName) .Should().BeEquivalentTo(expected.Select(e => e.FirstName), because); } [Fact] public async Task GroupByArray_NotNullOfAMemberOnThePath_IsImplied() { // "Contacts != null" asks nothing of a grouping over Contacts.Metadata: an element there means Contacts is set. var s = await SeedAsync(); var rows = await Redb.Query() .Where(e => e.Department == s.Tag && e.Contacts != null && e.HomeAddress!.Building!.Floor > 4) .GroupByArray(e => e.Contacts!, c => c.Type) .SelectAsync(g => new { Key = g.Key, Count = Agg.Count(g) }); rows.Select(g => (g.Key, g.Count)).Should().BeEquivalentTo( s.Children.Where(e => e.HomeAddress!.Building!.Floor > 4).SelectMany(e => e.Contacts!) .GroupBy(c => c.Type).Select(g => (g.Key, g.Count()))); } } Path: redb/redb.Tests.Integration/Tests/Base/CollectionGroupKeyTestsBase.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/CollectionGroupKeyTestsBase.cs ---- using Microsoft.Extensions.DependencyInjection; using redb.Core; using redb.Core.Models.Entities; using redb.Core.Query.Aggregation; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// GroupBy over a whole collection field groups by the same folded key that OrderBy and DistinctBy read: the elements /// in index order, a dictionary's values in key order. Equal lists are one group; the same elements in another order /// are another group. A dictionary entry, Codes["k"], is not an ordering or DistinctBy key: it is refused with a /// message that names what can be one. /// public abstract class CollectionGroupKeyTestsBase : IAsyncLifetime { private readonly IServiceProvider _services; private string _clearSql = ""; protected CollectionGroupKeyTestsBase(IServiceProvider services) => _services = services; // The two schemes are this class's own: every object in them is removed before and after each test. public async Task InitializeAsync() { await using var scope = _services.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); var lists = await redb.SyncSchemeAsync(); var dictionaries = await redb.SyncSchemeAsync(); _clearSql = $"DELETE FROM _objects WHERE _id_scheme IN ({lists.Id}, {dictionaries.Id})"; await redb.Context.ExecuteAsync(_clearSql); } public async Task DisposeAsync() { await using var scope = _services.CreateAsyncScope(); await scope.ServiceProvider.GetRequiredService().Context.ExecuteAsync(_clearSql); } private static CollectionGroupKeyProps List(int mark, params string[] tags) => new() { Label = "x", Mark = mark, Tags = tags.ToList() }; private static CollectionGroupKeyDictProps Dict(int mark, params (string Key, string Value)[] entries) => new() { Label = "x", Mark = mark, Codes = entries.ToDictionary(e => e.Key, e => e.Value) }; // Every group must hold objects of one mark only, and the marks must have the expected counts. private static void ShouldBeGroups(IEnumerable<(int Min, int Max, int Count)> rows, params (int Mark, int Count)[] expected) { var list = rows.ToList(); list.Should().OnlyContain(r => r.Min == r.Max, "one group holds the objects of one key only"); list.Select(r => (r.Min, r.Count)).Should().BeEquivalentTo(expected); } // Marks: 1 - t3,t1,t2 twice (the second one written by the bulk path); 2 - the same elements as t1,t2,t3; // 3 - t3,t9 twice; 4 - t9,t3. private static readonly (int Mark, string[] Tags)[] Lists = { (1, new[] { "t3", "t1", "t2" }), (1, new[] { "t3", "t1", "t2" }), (2, new[] { "t1", "t2", "t3" }), (3, new[] { "t3", "t9" }), (3, new[] { "t3", "t9" }), (4, new[] { "t9", "t3" }), }; private static readonly (int, int)[] ListGroups = { (1, 2), (2, 1), (3, 2), (4, 1) }; [Fact] public async Task GroupBy_OverAWholeList_EqualListsAreOneGroup_AnotherOrderIsAnother() { await using var scope = _services.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); await redb.SaveAsync(new RedbObject { Name = "a", Props = List(Lists[0].Mark, Lists[0].Tags) }); await redb.AddNewObjectsAsync(Lists.Skip(1).Select((l, i) => new RedbObject { Name = $"n{i}", Props = List(l.Mark, l.Tags) }).ToArray()); var rows = await redb.Query().GroupBy(x => x.Tags) .SelectAsync(g => new { Min = Agg.Min(g, x => x.Mark), Max = Agg.Max(g, x => x.Mark), N = Agg.Count(g) }); ShouldBeGroups(rows.Select(r => (r.Min, r.Max, r.N)), ListGroups); var filtered = await redb.Query().Where(x => x.Label == "x").GroupBy(x => x.Tags) .SelectAsync(g => new { Min = Agg.Min(g, x => x.Mark), Max = Agg.Max(g, x => x.Mark), N = Agg.Count(g) }); ShouldBeGroups(filtered.Select(r => (r.Min, r.Max, r.N)), ListGroups); } [Fact] public async Task GroupBy_OverAWholeList_InATree_EqualListsAreOneGroup_AnotherOrderIsAnother() { await using var scope = _services.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); var root = new TreeRedbObject { name = "root", Props = List(0, "r") }; root.id = await redb.SaveAsync(root); for (var i = 0; i < Lists.Length; i++) await redb.CreateChildAsync(new TreeRedbObject { name = $"n{i}", Props = List(Lists[i].Mark, Lists[i].Tags) }, root); var rows = await redb.TreeQuery(root.id).GroupBy(x => x.Tags) .SelectAsync(g => new { Min = Agg.Min(g, x => x.Mark), Max = Agg.Max(g, x => x.Mark), N = Agg.Count(g) }); ShouldBeGroups(rows.Where(r => r.Min != 0).Select(r => (r.Min, r.Max, r.N)), ListGroups); } [Fact] public async Task GroupBy_OverAWholeDictionary_GroupsByItsValuesInKeyOrder() { await using var scope = _services.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); // Values in key order: mark 1 -> 2,1 (keys written in either order); mark 2 -> 1,2. await redb.SaveAsync(new RedbObject { Name = "h", Props = Dict(1, ("b", "1"), ("a", "2")) }); await redb.SaveAsync(new RedbObject { Name = "k", Props = Dict(1, ("a", "2"), ("b", "1")) }); await redb.SaveAsync(new RedbObject { Name = "i", Props = Dict(2, ("a", "1"), ("b", "2")) }); var rows = await redb.Query().GroupBy(x => x.Codes) .SelectAsync(g => new { Min = Agg.Min(g, x => x.Mark), Max = Agg.Max(g, x => x.Mark), N = Agg.Count(g) }); ShouldBeGroups(rows.Select(r => (r.Min, r.Max, r.N)), (1, 2), (2, 1)); } [Fact] public async Task GroupBy_OverAWholeList_WithAWindowOverTheGroups_KeysTheSameWay() { await using var scope = _services.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); await redb.AddNewObjectsAsync(Lists.Select((l, i) => new RedbObject { Name = $"n{i}", Props = List(l.Mark, l.Tags) }).ToArray()); var root = new TreeRedbObject { name = "root", Props = List(0, "r") }; root.id = await redb.SaveAsync(root); for (var i = 0; i < Lists.Length; i++) await redb.CreateChildAsync(new TreeRedbObject { name = $"t{i}", Props = List(Lists[i].Mark, Lists[i].Tags) }, root); var flat = await redb.Query().Where(x => x.Mark > 0).GroupBy(x => x.Tags) .WithWindow(w => w.OrderBy(g => g.Key)) .SelectAsync(g => new { Min = Agg.Min(g, x => x.Mark), Max = Agg.Max(g, x => x.Mark), N = Agg.Count(g), Row = Win.RowNumber() }); // Every list is in the scheme twice over: once flat, once under the root. ShouldBeGroups(flat.Select(r => (r.Min, r.Max, r.N)), ListGroups.Select(g => (g.Item1, g.Item2 * 2)).ToArray()); var tree = await redb.TreeQuery(root.id).GroupBy(x => x.Tags) .WithWindow(w => w.OrderBy(g => g.Key)) .SelectAsync(g => new { Min = Agg.Min(g, x => x.Mark), Max = Agg.Max(g, x => x.Mark), N = Agg.Count(g), Row = Win.RowNumber() }); ShouldBeGroups(tree.Where(r => r.Min != 0).Select(r => (r.Min, r.Max, r.N)), ListGroups); } // A dictionary entry cannot be an ordering or DistinctBy key: the expression is refused before any SQL, and the // message says so in words. [Fact] public async Task OrderByAndDistinctBy_OverADictionaryEntry_AreRefused_SayingWhatCanBeAKey() { await using var scope = _services.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); await redb.SaveAsync(new RedbObject { Name = "p", Props = Dict(0, ("a", "3"), ("b", "1")) }); var attempts = new Func[] { () => redb.Query().OrderBy(x => x.Codes!["a"]).ToListAsync(), () => redb.Query().OrderByDescending(x => x.Codes!["b"]).ToListAsync(), () => redb.Query().Where(x => x.Label == "x").OrderBy(x => x.Codes!["a"]).ToListAsync(), () => redb.Query().DistinctBy(x => x.Codes!["a"]).ToListAsync(), () => redb.Query().Where(x => x.Label == "x").DistinctBy(x => x.Codes!["a"]).ToListAsync(), }; foreach (var attempt in attempts) (await attempt.Should().ThrowAsync()) .Which.Message.Should().Contain("dictionary entry").And.Contain("cannot be").And.Contain("x.Address.City"); } } Path: redb/redb.Tests.Integration/Tests/Base/CollectionKindChangeTestsBase.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/CollectionKindChangeTestsBase.cs ---- using redb.Core; using redb.Core.Exceptions; using redb.Core.Models.Entities; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// A class of a higher version changes the collection kind of a property (single value, array, dictionary). Values are /// never converted between kinds: with values stored the sync is refused naming the scheme, the property and both kinds, /// and the structure, its rows and the scheme's version stay as they were; with no values stored the kind just changes. /// Before 4.8.0 the kind flipped over the stored rows, which the new class then read wrong until a save dropped them. /// public abstract class CollectionKindChangeTestsBase : IAsyncLifetime { protected readonly IRedbService Redb; protected CollectionKindChangeTestsBase(IRedbService redb) => Redb = redb; private static readonly string[] Schemes = ["kind_single_before", "kind_single", "kind_array_before", "kind_array", "kind_array_dict_before", "kind_array_dict", "kind_dict_before", "kind_dict"]; 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(); } private async Task HandOverAsync(string before, string after) { await Redb.Context.ExecuteAsync($"UPDATE _schemes SET _name = '{after}' WHERE _name = '{before}'"); Redb.Cache.Clear(); } private async Task<(long Id, long? Kind, long Rows, long Version)> StructureStateAsync(string scheme, string name) { var id = (await Redb.Context.ExecuteScalarAsync( $"SELECT _id FROM _structures WHERE _name = '{name}' AND _id_parent IS NULL AND _id_scheme IN (SELECT _id FROM _schemes WHERE _name = '{scheme}')"))!.Value; var kind = await Redb.Context.ExecuteScalarAsync($"SELECT _collection_type FROM _structures WHERE _id = {id}"); var rows = await Redb.Context.ExecuteScalarAsync($"SELECT CAST(COUNT(*) AS BIGINT) FROM _values WHERE _id_structure = {id}") ?? 0; var version = await Redb.Context.ExecuteScalarAsync( $"SELECT CAST(COALESCE(_version, 0) AS BIGINT) FROM _schemes WHERE _name = '{scheme}'") ?? 0; return (id, kind, rows, version); } private async Task RefusedAsync(string before, string after, string property, Func props, string storedKind, string declaredKind) where TBefore : class, new() where TAfter : class, new() { await Redb.SyncSchemeAsync(); for (var i = 0; i < 3; i++) await Redb.SaveAsync(new RedbObject { name = $"kind-{i}", Props = props(i) }); await HandOverAsync(before, after); var state = await StructureStateAsync(after, property); state.Rows.Should().BeGreaterThan(0, "precondition: values are stored"); var sync = () => Redb.SyncSchemeAsync(); var e = (await sync.Should().ThrowAsync()).Which; e.SchemeName.Should().Be(after); e.PropertyName.Should().Be(property); e.StructureId.Should().Be(state.Id); e.StoredKind.Should().Be(storedKind); e.DeclaredKind.Should().Be(declaredKind); e.Message.Should().Contain("new property name"); Redb.Cache.Clear(); (await StructureStateAsync(after, property)).Should().Be(state, "the structure, its rows and the scheme's version stay as they were"); } [Fact] public Task SingleValueToArray_WithValues_IsRefused() => RefusedAsync("kind_single_before", "kind_single", "Level", i => new() { Tag = $"t{i}", Level = i + 1 }, "single value", "array"); [Fact] public Task ArrayToSingleValue_WithValues_IsRefused() => RefusedAsync("kind_array_before", "kind_array", "Items", i => new() { Tag = $"t{i}", Items = [i, i + 1] }, "array", "single value"); [Fact] public Task ArrayToDictionary_WithValues_IsRefused() => RefusedAsync("kind_array_dict_before", "kind_array_dict", "Items", i => new() { Tag = $"t{i}", Items = [i, i + 1] }, "array", "dictionary"); [Fact] public Task DictionaryToArray_WithValues_IsRefused() => RefusedAsync("kind_dict_before", "kind_dict", "Items", i => new() { Tag = $"t{i}", Items = new() { ["a"] = i, ["b"] = i + 1 } }, "dictionary", "array"); [Fact] public async Task KindChange_WithoutValues_Applies() { // The array is never set: its structure holds no row, so nothing can be read wrong. await Redb.SyncSchemeAsync(); for (var i = 0; i < 3; i++) await Redb.SaveAsync(new RedbObject { name = $"kind-{i}", Props = new() { Tag = $"t{i}" } }); await HandOverAsync("kind_array_dict_before", "kind_array_dict"); (await StructureStateAsync("kind_array_dict", "Items")).Rows.Should().Be(0, "precondition"); await Redb.SyncSchemeAsync(); var after = await StructureStateAsync("kind_array_dict", "Items"); after.Kind.Should().Be(redb.Core.Utils.RedbTypeIds.Dictionary); after.Version.Should().Be(1); var id = await Redb.SaveAsync(new RedbObject { name = "kind-new", Props = new() { Tag = "n", Items = new() { ["x"] = 7 } } }); (await Redb.LoadAsync(id))!.Props.Items.Should().BeEquivalentTo(new Dictionary { ["x"] = 7 }); } } Path: redb/redb.Tests.Integration/Tests/Base/ComputedComparisonTestsBase.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/ComputedComparisonTestsBase.cs ---- using System.Linq.Expressions; using redb.Core; using redb.Core.Models.Entities; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// A comparison of a field with a computed value answers as LINQ over the same objects does: a value of the caller built /// from several parts (tag + "-x", a + 1, x ?? "d", a ternary), a field against an expression over fields (A == B + 1), /// a field against a field (A > B), on either side of the operator. Each of these failed before with "variable 'p' ... /// is not defined": the side without arithmetic was evaluated as a constant, the field side included. /// /// Each case runs on four objects of its own and is checked against the same predicate compiled and run in memory. /// public abstract class ComputedComparisonTestsBase { protected readonly IRedbService Redb; protected ComputedComparisonTestsBase(IRedbService redb) => Redb = redb; private static List Seeds(string tag) => [ new() { Tag = tag, First = "Ann", Last = "Lee", Full = "Ann Lee", A = 3, B = 2, Price = 10.5m, Limit = 21m }, new() { Tag = tag, First = "Bob", Last = "Ray", Full = "Bob X", A = 5, B = 5, Price = 7m, Limit = 7m }, new() { Tag = tag, First = "Cid", Last = "Moe", Full = tag + "-x", A = 1, B = 4, Price = 2.25m, Limit = 3m }, new() { Tag = tag, First = "Dee", Last = "Ito", Full = "Dee-y", A = 9, B = 4, Price = 40m, Limit = 80m }, ]; public static IEnumerable Cases() => [ // A value of the caller built from parts, the field alone on the other side. ["closure-concat"], ["closure-concat-reversed"], ["closure-arithmetic"], ["closure-coalesce"], ["closure-ternary"], // A field against an expression over fields, either side, and a field against a field. ["field-eq-field-plus-1"], ["field-plus-1-eq-field"], ["field-eq-field"], ["field-gt-field"], ["field-eq-field-times-2"], ["decimal-field-eq-field-times-2"], ["field-eq-concat-of-fields"], ["field-eq-field-concat-caller"], ["field-eq-field-minus-caller"], ["not-field-eq-field-plus-1"], ]; private static Expression> Predicate(string kind, string tag) { var one = 1; string? none = null; var flag = true; var suffix = "-y"; var k = 3; return kind switch { "closure-concat" => p => p.Full == tag + "-x", "closure-concat-reversed" => p => tag + "-x" == p.Full, "closure-arithmetic" => p => p.A == one + 2, "closure-coalesce" => p => p.Full == (none ?? tag + "-x"), "closure-ternary" => p => p.Full == (flag ? tag + "-x" : "other"), "field-eq-field-plus-1" => p => p.A == p.B + 1, "field-plus-1-eq-field" => p => p.B + 1 == p.A, "field-eq-field" => p => p.A == p.B, "field-gt-field" => p => p.A > p.B, "field-eq-field-times-2" => p => p.A * 2 > p.B + 4, "decimal-field-eq-field-times-2" => p => p.Limit == p.Price * 2, "field-eq-concat-of-fields" => p => p.Full == p.First + " " + p.Last, "field-eq-field-concat-caller" => p => p.Full == p.First + suffix, "field-eq-field-minus-caller" => p => p.A == p.B - k + 2, "not-field-eq-field-plus-1" => p => !(p.A == p.B + 1), _ => throw new ArgumentOutOfRangeException(nameof(kind), kind, null) }; } [Theory] [MemberData(nameof(Cases))] public async Task ComputedComparison_AnswersAsLinq(string kind) { await Redb.SyncSchemeAsync(); var tag = "cc-" + Guid.NewGuid().ToString("N")[..8]; var seeds = Seeds(tag); await Redb.SaveAsync(seeds.Select((p, i) => new RedbObject { name = $"{tag}-{i}", Props = p }).ToList()); var predicate = Predicate(kind, tag); var expected = seeds.Where(predicate.Compile()).Select(p => p.First).OrderBy(x => x).ToList(); var query = Redb.Query().Where(p => p.Tag == tag).Where(predicate); var rows = await query.ToListAsync(); rows.Select(r => r.Props.First).OrderBy(x => x).Should().Equal(expected, $"case {kind}"); (await query.CountAsync()).Should().Be(expected.Count, $"case {kind}, count"); } } Path: redb/redb.Tests.Integration/Tests/Base/ConcurrencyStressTestsBase.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/ConcurrencyStressTestsBase.cs ---- using Microsoft.Extensions.DependencyInjection; using redb.Core; using redb.Core.Query.Aggregation; using redb.Tests.Integration.Helpers; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// Concurrency stress integration tests — drives the query pipeline with /// 50 parallel tasks against shared seed data. /// Catches parameter-list leaks between concurrent queries (a classical bug /// in inline-parameterised SQL builders that re-use a global counter), and /// asserts that no exception leaks out. /// /// IMPORTANT: a single instance shares one /// (= one Npgsql connection in PG, one /// EF DbContext in MSSql). Neither can multiplex concurrent commands, so /// each parallel worker must resolve its OWN from /// a fresh DI scope. /// /// Hosted on PostgreSQL and SQL Server, Free and Pro. Free SQL Server was left out while /// array aggregation and HAVING were unsupported there; both hold now. /// public abstract class ConcurrencyStressTestsBase { private const int Parallelism = 50; protected readonly IRedbService Redb; protected readonly IServiceProvider Services; protected ConcurrencyStressTestsBase(IRedbService redb, IServiceProvider services) { Redb = redb; Services = services; } private async Task SeedAsync() => await TestDataFactory.SeedEmployees(Redb, 20); /// /// Runs in parallel with each task using its own /// freshly-scoped instance (= own connection). /// private Task RunParallel(int count, Func> work) { var tasks = Enumerable.Range(0, count).Select(async _ => { using var scope = Services.CreateScope(); var redb = scope.ServiceProvider.GetRequiredService(); return await work(redb); }).ToArray(); return Task.WhenAll(tasks); } [Fact] public async Task Stress_50Parallel_GroupByArray_NoExceptionsAndStableShape() { await SeedAsync(); var shapes = await RunParallel(Parallelism, async redb => { var res = await redb.Query() .GroupByArray(e => e.Contacts!, c => c.Type) .SelectAsync(g => new { Type = g.Key, C = Agg.Count(g) }); return res.OrderBy(r => r.Type).Select(r => (r.Type, r.C)).ToArray(); }); shapes.Should().HaveCount(Parallelism); var reference = shapes[0]; reference.Should().NotBeEmpty(); shapes.Should().AllSatisfy(s => s.Should().Equal(reference, "every parallel GroupByArray must yield identical aggregation shape")); } [Fact] public async Task Stress_50Parallel_AggregateOverArray_NoParamLeak() { await SeedAsync(); var results = await RunParallel(Parallelism, redb => redb.Query() .AggregateAsync(x => new { S = Agg.Sum(x.Props.SkillLevels.Select(s => s)), A = Agg.Average(x.Props.SkillLevels.Select(s => s)) })); results.Should().HaveCount(Parallelism); var first = results[0]; results.Should().AllSatisfy(r => { r.S.Should().Be(first.S, "Sum must be deterministic under concurrency"); r.A.Should().Be(first.A, "Average must be deterministic under concurrency"); }); } [Fact] public async Task Stress_50Parallel_HavingQueries_DistinctThresholds_DoNotInterfere() { await SeedAsync(); var tasks = Enumerable.Range(0, Parallelism).Select(async i => { var threshold = i % 5; using var scope = Services.CreateScope(); var redb = scope.ServiceProvider.GetRequiredService(); var res = await redb.Query() .GroupByArray(e => e.Contacts!, c => c.Type) .Having(g => Agg.Count(g) > threshold) .SelectAsync(g => new { Type = g.Key, C = Agg.Count(g) }); return (threshold, count: res.Count); }).ToArray(); var results = await Task.WhenAll(tasks); results.Should().HaveCount(Parallelism); // Group results by threshold; results sharing the same threshold MUST have identical count. foreach (var grp in results.GroupBy(r => r.threshold)) { grp.Select(r => r.count).Distinct().Should().HaveCount(1, $"all queries with threshold={grp.Key} must produce the same row count"); } } } Path: redb/redb.Tests.Integration/Tests/Base/ConcurrentDeleteCountTestsBase.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/ConcurrentDeleteCountTestsBase.cs ---- using Microsoft.Extensions.DependencyInjection; using redb.Core; using redb.Core.Models.Entities; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// A delete answers with what it deleted, also when another session deletes the same object meanwhile. The race is /// made deterministic: another session holds a lock on the object's row, the delete of redb runs until it waits on that /// lock, then the holder deletes the object (or moves it to the trash) and commits. SQL Server's cascade procedures /// returned the number of ids they had collected, so DeleteAsync answered true and the batch counted the object; a soft /// delete moved an object already in the trash into its own trash and counted it (SQL Server and PostgreSQL). /// public abstract class ConcurrentDeleteCountTestsBase { protected readonly IRedbService Redb; private readonly IServiceProvider _services; protected ConcurrentDeleteCountTestsBase(IRedbService redb, IServiceProvider services) { Redb = redb; _services = services; } /// A session of its own holding an update lock on one object's row, inside an open transaction. public interface IRowHolder : IAsyncDisposable { /// Returns once another session waits on the held lock; fails after the timeout. Task WaitUntilSomeoneWaitsAsync(TimeSpan timeout); /// Runs the statement in the holder's transaction and commits it. Task ExecuteAndCommitAsync(string sql); } protected abstract Task HoldRowAsync(long objectId); private async Task NewObjectAsync(string tag) { await Redb.SyncSchemeAsync(); return await Redb.SaveAsync(new RedbObject { name = tag, Props = new SimpleProps { Title = tag } }); } private static string NewTag() => "cdc-" + Guid.NewGuid().ToString("N")[..8]; /// The values go with the object: an FK cascade on PostgreSQL and SQLite, the INSTEAD OF trigger on SQL Server. private static string DeleteStatement(long id) => $"DELETE FROM _objects WHERE _id = {id}"; /// The holder deletes the object while waits on its lock; returns what the delete answered. private async Task RaceAsync(long heldId, string holderStatement, Func> delete) { var holder = await HoldRowAsync(heldId); var pending = Task.Run(delete); try { await holder.WaitUntilSomeoneWaitsAsync(TimeSpan.FromSeconds(20)); await holder.ExecuteAndCommitAsync(holderStatement); } catch { // The delete must not outlive the test on the shared service: release the lock and let it finish. await holder.DisposeAsync(); try { await pending; } catch { /* the holder's failure is the one reported */ } throw; } await holder.DisposeAsync(); return await pending; } [Fact] public async Task DeleteById_OfAnObjectAnotherSessionDeletedMeanwhile_AnswersFalse() { var id = await NewObjectAsync(NewTag()); var answer = await RaceAsync(id, DeleteStatement(id), () => Redb.DeleteAsync(id)); answer.Should().BeFalse("the other session deleted the object; this call deleted nothing"); } [Fact] public async Task DeleteObject_OfAnObjectAnotherSessionDeletedMeanwhile_AnswersFalse() { var id = await NewObjectAsync(NewTag()); var obj = new RedbObject { id = id }; var answer = await RaceAsync(id, DeleteStatement(id), () => Redb.DeleteAsync(obj)); answer.Should().BeFalse("the other session deleted the object; this call deleted nothing"); } [Fact] public async Task DeleteBatch_CountsOnlyTheObjectsThisCallDeleted() { var tag = NewTag(); var raced = await NewObjectAsync(tag); var mine = await NewObjectAsync(tag); var count = await RaceAsync(raced, DeleteStatement(raced), () => Redb.DeleteAsync(new[] { raced, mine })); count.Should().Be(1, "of the two requested objects this call deleted one; the other session deleted the other"); (await Redb.LoadAsync(mine)).Should().BeNull(); } [Fact] public async Task DeleteBatch_DoesNotCountDescendants() { var tag = NewTag(); var parent = new TreeRedbObject { name = tag, Props = new SimpleProps { Title = tag } }; parent.id = await Redb.SaveAsync(parent); await Redb.CreateChildAsync(new TreeRedbObject { name = tag + "-c1", Props = new SimpleProps { Title = tag } }, parent); await Redb.CreateChildAsync(new TreeRedbObject { name = tag + "-c2", Props = new SimpleProps { Title = tag } }, parent); (await Redb.DeleteAsync(new[] { parent.id })).Should().Be(1, "one object was requested; its children go with it uncounted, on every provider"); } [Fact] public async Task SoftDelete_OfAnObjectAnotherSessionMovedToTheTrashMeanwhile_MarksNothing() { var id = await NewObjectAsync(NewTag()); var mark = await RaceAsync(id, $"UPDATE _objects SET _id_scheme = -10 WHERE _id = {id}", () => Redb.SoftDeleteAsync(new[] { id })); try { mark.MarkedCount.Should().Be(0, "the other session had moved the object to the trash; this call moved nothing"); (await Redb.Context.ExecuteScalarAsync($"SELECT _id_parent FROM _objects WHERE _id = {id}")) .Should().NotBe(mark.TrashId, "the object stays where the other session put it, not in a second trash"); } finally { await Redb.Context.ExecuteAsync(DeleteStatement(id)); await Redb.Context.ExecuteAsync(DeleteStatement(mark.TrashId)); } } /// /// The same race without choreography: several sessions delete one object at once, each through a scope (a connection) /// of its own. Exactly one of them deleted it, so the answers add up to one, round after round. /// [Fact] public async Task ConcurrentDeletesOfOneObject_ExactlyOneAnswersTrue() { const int rounds = 30, sessions = 8; var tag = NewTag(); var wrong = new List(); for (var round = 0; round < rounds; round++) { var id = await NewObjectAsync($"{tag}-{round}"); using var start = new Barrier(sessions); var answers = await Task.WhenAll(Enumerable.Range(0, sessions).Select(_ => Task.Run(async () => { using var scope = _services.CreateScope(); var redb = scope.ServiceProvider.GetRequiredService(); start.SignalAndWait(); return await redb.DeleteAsync(id); }))); var yes = answers.Count(a => a); if (yes != 1) wrong.Add($"round {round}: {yes} of {sessions} answered true"); } wrong.Should().BeEmpty("one object was deleted once in every round"); } } Path: redb/redb.Tests.Integration/Tests/Base/ConcurrentDeleteListTestsBase.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/ConcurrentDeleteListTestsBase.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 query reads the objects first and their values after, each statement on its own snapshot. An object deleted in /// between used to come back with null Props. It now leaves the list: the page is shorter by it, and every object handed /// out has its Props. The delete is put exactly between the two statements through the test context, no code of the /// library takes part in it. /// public abstract class ConcurrentDeleteListTestsBase { private readonly SqlRecorder _recorder = new(); protected abstract void UseProvider(RedbOptionsBuilder options); protected virtual void Register(IServiceCollection services, Action configure) => services.AddRedb(configure); private ServiceProvider Build(bool decorate) { var services = new ServiceCollection(); services.AddLogging(b => b.SetMinimumLevel(LogLevel.Warning)); Register(services, options => { UseProvider(options); options.Configure(c => { c.EnablePropsCache = false; c.CacheDomain = $"concurrent-delete-{GetType().Name}-{Guid.NewGuid():N}"; }); }); if (decorate) RecordingRedbContext.Decorate(services, _recorder); return services.BuildServiceProvider(); } /// The statement that reads the values of the objects found: Pro's bulk read of _values, Free's get_object_json. private static bool ReadsValues(string sql) => sql.Contains("get_object_json", StringComparison.OrdinalIgnoreCase) || (sql.Contains("_array_parent_id, _array_index", StringComparison.Ordinal) && sql.Contains("FROM _values", StringComparison.Ordinal)); [Fact] public async Task ObjectDeletedBetweenTheQueryAndItsValues_LeavesThePage_NoObjectWithoutProps() { await using var writerHost = Build(decorate: false); var writer = writerHost.GetRequiredService(); await writer.InitializeAsync(ensureCreated: true); await writer.SyncSchemeAsync(); var tag = "cdel-" + Guid.NewGuid().ToString("N")[..8]; var ids = new List(); for (var i = 0; i < 3; i++) ids.Add(await writer.SaveAsync(new RedbObject { name = $"{tag}-{i}", Props = new SimpleProps { Title = $"{tag}-{i}", Price = i } })); await using var readerHost = Build(decorate: true); var reader = readerHost.GetRequiredService(); await reader.InitializeAsync(ensureCreated: true); var deleted = 0; _recorder.BeforeQuery = async sql => { if (!ReadsValues(sql) || Interlocked.Exchange(ref deleted, 1) == 1) return; await writer.DeleteAsync(ids[1]); }; List> page; try { page = await reader.Query().Where(p => p.Title.StartsWith(tag)).OrderBy(p => p.Price).ToListAsync(); } finally { _recorder.BeforeQuery = null; } deleted.Should().Be(1, "precondition: the delete ran between the read of the objects and of their values"); page.Select(o => o.id).Should().Equal(ids[0], ids[2]); page.Should().OnlyContain(o => o.Props != null); page.Select(o => o.Props.Title).Should().Equal($"{tag}-0", $"{tag}-2"); await writer.DeleteAsync(new[] { ids[0], ids[2] }); } } Path: redb/redb.Tests.Integration/Tests/Base/ConcurrentWritersTestsBase.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/ConcurrentWritersTestsBase.cs ---- using Microsoft.Extensions.DependencyInjection; using redb.Core; using redb.Core.Exceptions; using redb.Core.Models.Entities; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// Many writers saving at the same instant through the public API, each on its own service scope (its own /// connection), the way an application's concurrent requests do. Two shapes: /// /// top-level saves of new objects (a key ring element per writer); /// a lookup and an insert of the same unique key inside ExecuteAtomicAsync (a replay reservation: /// exactly one writer may win, the others see the row or the unique violation). /// /// No writer may fail with anything else: a deadlock between writers is a failure of the save, not of the writer. /// public abstract class ConcurrentWritersTestsBase : IAsyncLifetime { private const int Writers = 16; private const int Rounds = 5; private readonly IServiceProvider _services; protected ConcurrentWritersTestsBase(IServiceProvider services) => _services = services; public async Task InitializeAsync() { using var scope = _services.CreateScope(); await scope.ServiceProvider.GetRequiredService().SyncSchemeAsync(); } public Task DisposeAsync() => Task.CompletedTask; /// /// Starts writers together: each gets its scope and service first, then all are released at /// once, so the saves overlap instead of running one after another as the tasks start. /// private async Task RunTogetherAsync(Func> write) { var start = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var tasks = Enumerable.Range(0, Writers).Select(i => Task.Run(async () => { await using var scope = _services.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); await start.Task; return await write(redb, i); })).ToArray(); start.SetResult(); return await Task.WhenAll(tasks); } [Fact] public async Task NewObjects_SavedConcurrently_AllSaved() { for (var round = 0; round < Rounds; round++) { var tag = $"new-{Guid.NewGuid():N}"; var ids = await RunTogetherAsync((redb, i) => redb.SaveAsync(new RedbObject { name = $"{tag}-{i}", Props = new ConcurrentWriterRowProps { Tag = tag, Key = $"{tag}-{i}", Payload = new string('x', 200), WrittenAt = DateTimeOffset.UtcNow } })); ids.Should().OnlyHaveUniqueItems().And.NotContain(0); var stored = await Query(tag); stored.Should().Be(Writers, $"round {round}: every writer's object is saved"); } } [Fact] public async Task SameUniqueKey_ReservedConcurrentlyInsideExecuteAtomic_ExactlyOneWins() { for (var round = 0; round < Rounds; round++) { var tag = $"res-{Guid.NewGuid():N}"; var key = $"{tag}-key"; var won = await RunTogetherAsync((redb, _) => redb.Context.ExecuteAtomicAsync(async () => { var existing = await redb.Query() .Where(o => o.Key == key) .FirstOrDefaultAsync(); if (existing is not null) return false; try { await redb.SaveAsync(new RedbObject { name = key, ValueUnique = key, Props = new ConcurrentWriterRowProps { Tag = tag, Key = key, WrittenAt = DateTimeOffset.UtcNow } }); return true; } catch (RedbUniqueViolationException) { return false; } })); won.Count(w => w).Should().Be(1, $"round {round}: one reservation per key"); (await Query(tag)).Should().Be(1); } } private async Task Query(string tag) { using var scope = _services.CreateScope(); var redb = scope.ServiceProvider.GetRequiredService(); return (await redb.Query().Where(o => o.Tag == tag).ToListAsync()).Count; } } Path: redb/redb.Tests.Integration/Tests/Base/ConnectionLeaseTestsBase.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/ConnectionLeaseTestsBase.cs ---- using System.Data.Common; using System.Transactions; using Microsoft.Extensions.DependencyInjection; using redb.Core; using redb.Core.Data; using redb.Tests.Integration.Helpers; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// : the caller's own command on the connection redb works on, in the /// transaction redb's commands run in. A Route .Transacted() block with a SQL step and a redb save into the same /// database must hold ONE connection: a second one makes the transaction distributed (SQL Server refuses or promotes, /// PostgreSQL needs prepared transactions) or, on SQLite, waits for the write lock the scope's connection holds. /// Verification always goes through a fresh DI scope outside any transaction. /// public abstract class ConnectionLeaseTestsBase : IAsyncLifetime { private const string NamePrefix = "conn-lease-"; private readonly IServiceProvider _services; // Free and Pro collections of one provider share a database and may run at the same time: every test // removes only the tags it created, never a whole prefix. private readonly List _tags = new(); protected ConnectionLeaseTestsBase(IServiceProvider services) => _services = services; /// Idempotent DDL of the probe table connection_lease_rows (tag) in the provider's dialect. protected abstract string CreateProbeTableSql { get; } /// /// Whether a lease inside a carries a transaction object: true where the driver /// cannot enlist and redb runs its own transaction on the scope's connection (SQLite). /// protected abstract bool AmbientLeaseCarriesTransaction { get; } public async Task InitializeAsync() { await using var scope = _services.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); await redb.SyncSchemeAsync(); await redb.Context.ExecuteAsync(CreateProbeTableSql); } public async Task DisposeAsync() { await using var scope = _services.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); foreach (var tag in _tags) { await redb.Context.ExecuteAsync($"DELETE FROM _objects WHERE _name LIKE '{tag}%'"); await redb.Context.ExecuteAsync($"DELETE FROM connection_lease_rows WHERE tag LIKE '{tag}%'"); } } private static TransactionScope NewScope() => new(TransactionScopeAsyncFlowOption.Enabled); private string NewTag() { var tag = NamePrefix + Guid.NewGuid().ToString("N")[..10]; _tags.Add(tag); return tag; } // The tag is generated here (prefix and hex digits), so the literal is safe and the statement needs no // parameter syntax of a particular driver. private static async Task InsertThroughLeaseAsync(RedbConnectionLease lease, string tag) { await using DbCommand command = lease.CreateCommand(); command.CommandText = $"INSERT INTO connection_lease_rows (tag) VALUES ('{tag}')"; (await command.ExecuteNonQueryAsync()).Should().Be(1); } private async Task<(long Objects, long Rows)> CountCommittedAsync(string tag) { await using var scope = _services.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); var objects = await redb.Context.ExecuteScalarAsync( $"SELECT COUNT(*) FROM _objects WHERE _name LIKE '{tag}%'"); var rows = await redb.Context.ExecuteScalarAsync( $"SELECT COUNT(*) FROM connection_lease_rows WHERE tag LIKE '{tag}%'"); return (objects, rows); } [Fact] public async Task TransactionScope_LeaseAndSave_CommitTogether_OnOneConnection() { var tag = NewTag(); using (var tx = NewScope()) { await using var scope = _services.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); await using (var lease = await redb.Context.Db.LeaseAsync()) { (lease.Transaction != null).Should().Be(AmbientLeaseCarriesTransaction); await InsertThroughLeaseAsync(lease, tag); } await redb.SaveAsync(TestDataFactory.CreateSimple(tag, 1m)); Transaction.Current!.TransactionInformation.DistributedIdentifier.Should().Be(Guid.Empty, "the lease and the save share the scope's one connection, so the transaction never becomes distributed"); tx.Complete(); } (await CountCommittedAsync(tag)).Should().Be((1L, 1L), "the leased command and the redb save commit together with the scope"); } [Fact] public async Task TransactionScope_LeaseAndSave_RollBackTogether() { var tag = NewTag(); using (NewScope()) { await using var scope = _services.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); await using (var lease = await redb.Context.Db.LeaseAsync()) await InsertThroughLeaseAsync(lease, tag); await redb.SaveAsync(TestDataFactory.CreateSimple(tag, 2m)); // not completed } (await CountCommittedAsync(tag)).Should().Be((0L, 0L), "an abandoned scope takes back the leased command's row and the redb object alike"); } [Fact] public async Task ExplicitTransaction_LeaseCarriesIt_CommitAndRollback() { var committed = NewTag(); var rolledBack = NewTag(); await using var scope = _services.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); await using (var tx = await redb.Context.BeginTransactionAsync()) { await using (var lease = await redb.Context.Db.LeaseAsync()) { lease.Transaction.Should().NotBeNull("commands on a connection with an explicit transaction are bound to it"); await InsertThroughLeaseAsync(lease, committed); } await redb.SaveAsync(TestDataFactory.CreateSimple(committed, 3m)); await tx.CommitAsync(); } await using (var tx = await redb.Context.BeginTransactionAsync()) { await using (var lease = await redb.Context.Db.LeaseAsync()) await InsertThroughLeaseAsync(lease, rolledBack); await redb.SaveAsync(TestDataFactory.CreateSimple(rolledBack, 4m)); await tx.RollbackAsync(); } (await CountCommittedAsync(committed)).Should().Be((1L, 1L), "the commit takes both"); (await CountCommittedAsync(rolledBack)).Should().Be((0L, 0L), "the rollback takes back both"); } [Fact] public async Task NoTransaction_LeasedCommandAutocommits() { var tag = NewTag(); await using var scope = _services.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); await using (var lease = await redb.Context.Db.LeaseAsync()) { lease.Transaction.Should().BeNull("no transaction is active"); await InsertThroughLeaseAsync(lease, tag); } (await CountCommittedAsync(tag)).Rows.Should().Be(1L, "without a transaction the command commits on its own"); } [Fact] public async Task WhileLeaseIsHeld_RedbOnTheConnectionAndInTheScope_IsRefused_ThenWorksAfterRelease() { var tag = NewTag(); await using var scope = _services.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); await using (await redb.Context.Db.LeaseAsync()) { var sameConnection = async () => await redb.Context.ExecuteScalarAsync("SELECT 1"); await sameConnection.Should().ThrowAsync( "the lease holds the connection's command gate, as a redb command does"); } (await redb.Context.ExecuteScalarAsync("SELECT 1")).Should().Be(1L, "the release gives the gate back"); using (var tx = NewScope()) { await using var other = _services.CreateAsyncScope(); var otherRedb = other.ServiceProvider.GetRequiredService(); await using (var lease = await redb.Context.Db.LeaseAsync()) { var otherScope = async () => await otherRedb.Context.ExecuteScalarAsync("SELECT 1"); await otherScope.Should().ThrowAsync( "inside a TransactionScope every DI scope of the database shares the scope's connection and its gate"); await InsertThroughLeaseAsync(lease, tag); } await otherRedb.SaveAsync(TestDataFactory.CreateSimple(tag, 5m)); tx.Complete(); } (await CountCommittedAsync(tag)).Should().Be((1L, 1L)); } [Fact] public async Task HolderThrowsInsideAwaitUsing_GatesAreReleased_AndTheScopeRollsBackWhole() { var tag = NewTag(); using (NewScope()) { await using var scope = _services.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); var holder = async () => { await using var lease = await redb.Context.Db.LeaseAsync(); await InsertThroughLeaseAsync(lease, tag); throw new ApplicationException("the holder failed"); }; await holder.Should().ThrowAsync(); await redb.SaveAsync(TestDataFactory.CreateSimple(tag, 6m)); // not completed: the step failed } (await CountCommittedAsync(tag)).Should().Be((0L, 0L)); } [Fact] public async Task HolderClosedTheConnection_ReleaseThrows_AndTheNextCommandStillRuns() { await using var scope = _services.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); var lease = await redb.Context.Db.LeaseAsync(); await lease.Connection.CloseAsync(); var release = async () => await lease.DisposeAsync(); await release.Should().ThrowAsync().WithMessage("*not open*"); (await redb.Context.ExecuteScalarAsync("SELECT 1")).Should().Be(1L, "the release left the gate although it reported the closed connection"); } [Fact] public async Task LeaseAfterTheAmbientTransactionEnded_IsRefused_AndLeavesNoGateBehind() { await using var scope = _services.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); using (NewScope()) { Transaction.Current!.Rollback(); var lease = async () => await redb.Context.Db.LeaseAsync(); await lease.Should().ThrowAsync( "a connection taken for a transaction that already ended would run outside it"); } (await redb.Context.ExecuteScalarAsync("SELECT 1")).Should().Be(1L, "the refused lease did not keep the connection's gate"); } } Path: redb/redb.Tests.Integration/Tests/Base/ConnectionTeardownTestsBase.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/ConnectionTeardownTestsBase.cs ---- using Microsoft.Extensions.Configuration; using redb.Core.Data; namespace redb.Tests.Integration.Tests.Base; /// /// Scope-teardown contract of (a production report, 2026-09-11): /// disposing a connection must not race an in-flight command. The reported shape: an HTTP /// exchange's ReleaseScopes() hit NpgsqlOperationInProgressException because a /// SEDA-side lazy loader was still reading through the dying scope's connection - the /// command guard existed, but DisposeAsync was exempt from it. /// /// Pinned contract: (1) DisposeAsync WAITS for the running command, both complete cleanly; /// (2) a command entered after teardown is refused with - /// the lazy loader's cue to fall back to a detached scope. /// public abstract class ConnectionTeardownTestsBase { /// A fresh, self-owned connection - never the fixture's shared one. protected abstract IRedbConnection CreateConnection(); /// A scalar query that runs for roughly the given time on this provider. protected abstract string SleepSql(double seconds); protected virtual string ProbeSql => "SELECT 1"; protected static string ConnString(string name) => new ConfigurationBuilder() .SetBasePath(AppContext.BaseDirectory) .AddJsonFile("appsettings.json") .Build() .GetConnectionString(name)!; [Fact] public async Task Dispose_WaitsForTheInFlightCommand() { var conn = CreateConnection(); var clock = System.Diagnostics.Stopwatch.StartNew(); long commandDoneAt = 0; var command = Task.Run(async () => { await conn.ExecuteScalarAsync(SleepSql(1.5)); Interlocked.Exchange(ref commandDoneAt, clock.ElapsedMilliseconds); }); await Task.Delay(300); // the command is reliably in flight by now // Capped awaits: the un-fixed teardown can HANG under a running command (worse than // the reported exception) - a hang must fail the pin, not the whole run. var dispose = conn.DisposeAsync().AsTask(); (await Task.WhenAny(dispose, Task.Delay(TimeSpan.FromSeconds(20)))).Should().Be(dispose, "teardown must complete once the in-flight command finishes, never hang"); await dispose; // propagate a teardown fault (the reported OperationInProgress shape) var disposeDoneAt = clock.ElapsedMilliseconds; // The command must complete cleanly - not die under a concurrent Reset/Close. (await Task.WhenAny(command, Task.Delay(TimeSpan.FromSeconds(20)))).Should().Be(command); await command; var cmdAt = Interlocked.Read(ref commandDoneAt); cmdAt.Should().BeGreaterThan(0); disposeDoneAt.Should().BeGreaterThanOrEqualTo(cmdAt, "teardown must wait for the in-flight command instead of racing it"); } [Fact] public async Task Command_AfterDispose_IsRefusedWithObjectDisposed() { var conn = CreateConnection(); await conn.ExecuteScalarAsync(ProbeSql); // open the physical connection for real await conn.DisposeAsync(); var act = async () => await conn.ExecuteScalarAsync(ProbeSql); await act.Should().ThrowAsync( "a command entered after teardown must be refused cleanly - the lazy loader " + "falls back to a detached scope on this signal"); } } Path: redb/redb.Tests.Integration/Tests/Base/ConstantPredicateTestsBase.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/ConstantPredicateTestsBase.cs ---- using redb.Core; using redb.Core.Models.Entities; using redb.Core.Query; using redb.Tests.Integration.Helpers; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// A predicate that is a constant, alone or inside a condition: Where(x => true) keeps every object, Where(x => false) /// keeps none, and inside AND / OR / NOT the constant folds as in LINQ over the same objects in memory. The same for /// WhereRedb and AllAsync, on a flat query and on a tree query, for the list, the count and Any. /// /// Each test reads only the objects it seeded (by id, or by the root of its tree), so the shared database stays out. /// public abstract class ConstantPredicateTestsBase { protected readonly IRedbService Redb; protected ConstantPredicateTestsBase(IRedbService redb) => Redb = redb; private const int Total = 4; // ages 30, 31, 32, 33 private sealed record Seeded(long RootId, List Ids); private async Task SeedAsync() { await Redb.SyncSchemeAsync(); var tag = "cp-" + Guid.NewGuid().ToString("N")[..8]; var root = new TreeRedbObject { name = $"{tag}-root", Props = TestDataFactory.CreateEmployee(0, department: $"{tag}-root").Props }; root.id = await Redb.SaveAsync(root); var ids = new List(); for (var i = 0; i < Total; i++) { var p = TestDataFactory.CreateEmployee(i + 1, firstName: $"{tag}-{i}", department: tag).Props; p.Age = 30 + i; ids.Add(await Redb.CreateChildAsync(new TreeRedbObject { name = $"{tag}-{i}", Props = p }, root)); } return new Seeded(root.id, ids); } private IRedbQueryable Employees(Seeded s, bool tree) { if (tree) return Redb.TreeQuery(s.RootId).WhereRedb(o => o.Id != s.RootId); var idSet = s.Ids.ToHashSet(); return Redb.Query().WhereRedb(o => idSet.Contains(o.Id)); } /// The query of a case and the number of seeded objects it keeps. private static (IRedbQueryable Query, int Expected) Case(IRedbQueryable q, string kind) { // A bool value of the caller is the constant it holds. var yes = true; var no = false; return kind switch { "true" => (q.Where(e => true), Total), "false" => (q.Where(e => false), 0), "captured-true" => (q.Where(e => yes), Total), "captured-false" => (q.Where(e => no), 0), "field-and-captured-true" => (q.Where(e => e.Age >= 32 && yes), 2), "field-and-captured-false" => (q.Where(e => e.Age >= 32 && no), 0), "field-or-captured-true" => (q.Where(e => e.Age >= 32 || yes), Total), "field-or-captured-false" => (q.Where(e => e.Age >= 32 || no), 2), "not-captured-true" => (q.Where(e => !yes), 0), "not-captured-false" => (q.Where(e => !no), Total), "nested-captured" => (q.Where(e => (e.Age == 30 || no) && (yes || e.Age == 99)), 1), // NOT over a condition that folds to a constant. "not-or-literal-true" => (q.Where(e => !(e.Age >= 32 || true)), 0), "not-and-literal-false" => (q.Where(e => !(e.Age >= 32 && false)), Total), "not-or-literal-false" => (q.Where(e => !(e.Age >= 32 || false)), 2), "true-then-field" => (q.Where(e => true).Where(e => e.Age >= 32), 2), "field-then-true" => (q.Where(e => e.Age >= 32).Where(e => true), 2), "field-then-false" => (q.Where(e => e.Age >= 32).Where(e => false), 0), "nested-literal" => (q.Where(e => (e.Age == 30 || false) && (true || e.Age == 99)), 1), "field-or-literal-true" => (q.Where(e => e.Age >= 32 || true), Total), "field-or-literal-false" => (q.Where(e => e.Age >= 32 || false), 2), "field-and-literal-true" => (q.Where(e => e.Age >= 32 && true), 2), "field-and-literal-false" => (q.Where(e => e.Age >= 32 && false), 0), "redb-true" => (q.WhereRedb(o => true), Total), "redb-false" => (q.WhereRedb(o => false), 0), "redb-true-then-field" => (q.WhereRedb(o => true).Where(e => e.Age >= 32), 2), _ => throw new ArgumentOutOfRangeException(nameof(kind), kind, null) }; } public static IEnumerable Cases() { string[] kinds = [ "true", "false", "true-then-field", "field-then-true", "field-then-false", "nested-literal", "field-or-literal-true", "field-or-literal-false", "field-and-literal-true", "field-and-literal-false", "redb-true", "redb-false", "redb-true-then-field", "captured-true", "captured-false", "field-and-captured-true", "field-and-captured-false", "field-or-captured-true", "field-or-captured-false", "not-captured-true", "not-captured-false", "nested-captured", "not-or-literal-true", "not-and-literal-false", "not-or-literal-false" ]; foreach (var tree in new[] { false, true }) foreach (var kind in kinds) yield return [tree, kind]; } [Theory] [MemberData(nameof(Cases))] public async Task ConstantInWhere_ListCountAndAnyAgree(bool tree, string kind) { var s = await SeedAsync(); var (query, expected) = Case(Employees(s, tree), kind); var list = await query.ToListAsync(); var count = await query.CountAsync(); var any = await query.AnyAsync(); list.Should().HaveCount(expected); count.Should().Be(expected); any.Should().Be(expected > 0); } [Theory] [InlineData(false)] [InlineData(true)] public async Task All_WithConstant_AnswersAsLinq(bool tree) { var s = await SeedAsync(); var q = Employees(s, tree); var none = q.Where(e => e.Age > 1000); (await q.AllAsync(e => true)).Should().BeTrue(); (await q.AllAsync(e => false)).Should().BeFalse(); (await none.AllAsync(e => true)).Should().BeTrue(); (await none.AllAsync(e => false)).Should().BeTrue("All over an empty set is true for any predicate"); } } Path: redb/redb.Tests.Integration/Tests/Base/CrudTestsBase.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/CrudTestsBase.cs ---- using redb.Core; using redb.Core.Models.Entities; using redb.Tests.Integration.Helpers; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; public abstract class CrudTestsBase { protected readonly IRedbService Redb; protected CrudTestsBase(IRedbService redb) => Redb = redb; [Fact] public async Task Save_NewObject_ReturnsPositiveId() { var obj = TestDataFactory.CreateSimple("CRUD-Save", 42.50m); obj.id = await Redb.SaveAsync(obj); obj.id.Should().BeGreaterThan(0); } [Fact] public async Task Load_AfterSave_ReturnsSameData() { var obj = TestDataFactory.CreateSimple("CRUD-Load", 123.45m); obj.id = await Redb.SaveAsync(obj); var loaded = await Redb.LoadAsync(obj.id); loaded.Should().NotBeNull(); loaded!.Props.Title.Should().Be("CRUD-Load"); loaded.Props.Price.Should().Be(123.45m); loaded.Props.Count.Should().Be(10); loaded.Props.IsActive.Should().BeTrue(); loaded.Props.CreatedAt.Should().Be(new DateTime(2025, 6, 15, 10, 30, 0, DateTimeKind.Utc)); loaded.Props.Code.Should().Be(obj.Props.Code); loaded.Props.Description.Should().Be("Test description"); } [Fact] public async Task Update_ExistingObject_PersistsChanges() { var obj = TestDataFactory.CreateSimple("CRUD-Update", 100m); obj.id = await Redb.SaveAsync(obj); var loaded = await Redb.LoadAsync(obj.id); loaded!.Props.Title = "CRUD-Updated"; loaded.Props.Price = 200m; loaded.Props.IsActive = false; await Redb.SaveAsync(loaded); var updated = await Redb.LoadAsync(obj.id); updated!.Props.Title.Should().Be("CRUD-Updated"); updated.Props.Price.Should().Be(200m); updated.Props.IsActive.Should().BeFalse(); } [Fact] public async Task Delete_SingleObject_Removes() { var obj = TestDataFactory.CreateSimple("CRUD-Delete"); obj.id = await Redb.SaveAsync(obj); var result = await Redb.DeleteAsync(obj.id); result.Should().BeTrue(); var loaded = await Redb.LoadAsync(obj.id); loaded.Should().BeNull(); } [Fact] public async Task Delete_NonExistent_ReturnsFalse() { var result = await Redb.DeleteAsync(999_999_999L); result.Should().BeFalse(); } [Fact] public async Task Save_WithNullableFields_HandlesNulls() { var obj = new RedbObject { name = "CRUD-Nulls", Props = new SimpleProps { Title = "Nulls", Count = 0, Price = 0m, CreatedAt = DateTime.UtcNow, IsActive = false, Code = Guid.Empty, Description = null, OptionalNumber = null } }; obj.id = await Redb.SaveAsync(obj); var loaded = await Redb.LoadAsync(obj.id); loaded!.Props.Description.Should().BeNull(); loaded.Props.OptionalNumber.Should().BeNull(); } [Fact] public async Task Save_WithNestedObject_RoundTrips() { var emp = TestDataFactory.CreateEmployee(0, city: "Berlin"); emp.id = await Redb.SaveAsync(emp); var loaded = await Redb.LoadAsync(emp.id); loaded!.Props.HomeAddress.Should().NotBeNull(); loaded.Props.HomeAddress!.City.Should().Be("Berlin"); loaded.Props.HomeAddress.Street.Should().NotBeEmpty(); loaded.Props.HomeAddress.Building.Should().NotBeNull(); loaded.Props.HomeAddress.Building!.Floor.Should().BeGreaterThan(0); } [Fact] public async Task Save_WithDeepNested_RoundTrips() { var emp = TestDataFactory.CreateEmployee(0); emp.id = await Redb.SaveAsync(emp); var loaded = await Redb.LoadAsync(emp.id); loaded!.Props.HomeAddress!.Building!.Name.Should().NotBeEmpty(); loaded.Props.HomeAddress.Building.Amenities.Should().Contain("Parking"); } [Fact] public async Task Save_WithContacts_ArrayOfObjectsRoundTrips() { var emp = TestDataFactory.CreateEmployee(0); emp.id = await Redb.SaveAsync(emp); var loaded = await Redb.LoadAsync(emp.id); loaded!.Props.Contacts.Should().HaveCount(2); loaded.Props.Contacts![0].Type.Should().Be("email"); loaded.Props.Contacts[0].IsVerified.Should().BeTrue(); loaded.Props.Contacts[1].Type.Should().Be("phone"); } [Fact] public async Task BulkSave_MultipleObjects_AllPersisted() { var objects = Enumerable.Range(0, 10) .Select(i => TestDataFactory.CreateSimple($"Bulk-{i}", i * 10m)) .Cast>() .ToList(); var ids = await Redb.SaveAsync(objects); for (int i = 0; i < objects.Count; i++) objects[i].id = ids[i]; var count = await Redb.Query() .Where(s => s.Title.Contains("Bulk-")) .CountAsync(); count.Should().BeGreaterThanOrEqualTo(10); } [Fact] public async Task Delete_Batch_RemovesAll() { var objects = Enumerable.Range(0, 5) .Select(i => TestDataFactory.CreateSimple($"BatchDel-{i}")) .Cast>() .ToList(); var ids = await Redb.SaveAsync(objects); var deleted = await Redb.DeleteAsync(ids); deleted.Should().Be(5); foreach (var id in ids) { var loaded = await Redb.LoadAsync(id); loaded.Should().BeNull(); } } [Fact] public async Task Save_NonGenericRedbObject_BaseFieldsOnly() { var obj = new RedbObject { name = "NonGeneric-Test", value_string = "hello", value_long = 42, value_bool = true }; obj.id = await Redb.SaveAsync(obj); obj.id.Should().BeGreaterThan(0); } } Path: redb/redb.Tests.Integration/Tests/Base/CtPerfBenchmarkTestsBase.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/CtPerfBenchmarkTestsBase.cs ---- using System.Diagnostics; using redb.Core; using redb.Core.Models.Entities; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// CT performance benchmark harness. /// No-op unless REDB_BENCH=1: results are wall-clock numbers, not assertions, so they must /// never run (or fail) in regular suites. Results are appended to the file named by /// REDB_BENCH_OUT (semicolon-separated: provider;scenario;ops;total_ms;ms_per_op). /// public abstract class CtPerfBenchmarkTestsBase { protected readonly IRedbService Redb; protected abstract string ProviderName { get; } protected CtPerfBenchmarkTestsBase(IRedbService redb) => Redb = redb; private static bool Enabled => Environment.GetEnvironmentVariable("REDB_BENCH") == "1"; private static void Report(string provider, string scenario, int ops, double totalMs) { var outPath = Environment.GetEnvironmentVariable("REDB_BENCH_OUT"); if (string.IsNullOrEmpty(outPath)) return; var line = FormattableString.Invariant( $"{provider};{scenario};{ops};{totalMs:F1};{totalMs / ops:F2}"); lock (typeof(CtPerfBenchmarkTestsBase)) File.AppendAllText(outPath, line + Environment.NewLine); } private async Task CleanupAsync() { await Redb.Context.ExecuteAsync( "DELETE FROM _objects WHERE _id_scheme IN (SELECT _id FROM _schemes WHERE _name = 'CtProbe') AND _name LIKE 'bench-%'"); } private async Task SeedAsync(string name, CtProbeProps props) { await Redb.SyncSchemeAsync(); return await Redb.SaveAsync(new RedbObject { name = name, Props = props }); } private static CtProbeProps ArrayProps(int arrayLen, string label) => new() { Label = label, Longs = [.. Enumerable.Range(1, arrayLen).Select(i => (long)i)], }; [Fact] public async Task B1_BatchMostlyUnchanged_Resave() { if (!Enabled) return; await CleanupAsync(); // 60 objects x (scalar + 50-element array), 3 of them edited, resave the whole batch. // The F1 target: unchanged objects must not pay for the value pipeline. var objects = new List>(); await Redb.SyncSchemeAsync(); for (var i = 0; i < 60; i++) objects.Add(new RedbObject { name = $"bench-b1-{i}", Props = ArrayProps(50, $"o{i}") }); var ids = await Redb.SaveAsync(objects); for (var i = 0; i < objects.Count; i++) objects[i].id = ids[i]; var reloaded = new List>(); foreach (var id in ids) reloaded.Add((await Redb.LoadAsync(id, depth: 2))!); reloaded[5].Props.Longs![7] = 9999; reloaded[25].Props.Label = "edited"; reloaded[45].Props.Longs![49] = 8888; const int rounds = 5; var sw = Stopwatch.StartNew(); for (var r = 0; r < rounds; r++) await Redb.SaveAsync(reloaded.Cast().ToList()); sw.Stop(); Report(ProviderName, "B1_batch60_3edited", rounds, sw.Elapsed.TotalMilliseconds); await CleanupAsync(); } [Fact] public async Task B2_ResaveUnchangedLargeArray() { if (!Enabled) return; await CleanupAsync(); // Single object with a 500-element array, resaved untouched. F1/F2 target. var id = await SeedAsync("bench-b2", ArrayProps(500, "big")); var loaded = await Redb.LoadAsync(id, depth: 2); const int rounds = 20; var sw = Stopwatch.StartNew(); for (var r = 0; r < rounds; r++) await Redb.SaveAsync(loaded!); sw.Stop(); Report(ProviderName, "B2_resave_array500", rounds, sw.Elapsed.TotalMilliseconds); await CleanupAsync(); } [Fact] public async Task B3_SingleElementEdit_LargeArray() { if (!Enabled) return; await CleanupAsync(); // Single object with a 500-element array, one element changed per save. F2/F5 target. var id = await SeedAsync("bench-b3", ArrayProps(500, "big")); var loaded = await Redb.LoadAsync(id, depth: 2); const int rounds = 20; var sw = Stopwatch.StartNew(); for (var r = 0; r < rounds; r++) { loaded!.Props.Longs![r % 500] = 100000 + r; await Redb.SaveAsync(loaded); } sw.Stop(); Report(ProviderName, "B3_edit1_array500", rounds, sw.Elapsed.TotalMilliseconds); await CleanupAsync(); } [Fact] public async Task B5_ScalarEdit_UntouchedLargeArray() { if (!Enabled) return; await CleanupAsync(); // Object changes (so F1 cannot skip it) but the 500-element array is untouched: // the F2 target - the array's base hash matches and elements need no walk. var id = await SeedAsync("bench-b5", ArrayProps(500, "big")); var loaded = await Redb.LoadAsync(id, depth: 2); const int rounds = 20; var sw = Stopwatch.StartNew(); for (var r = 0; r < rounds; r++) { loaded!.Props.Label = "big-" + r; await Redb.SaveAsync(loaded); } sw.Stop(); Report(ProviderName, "B5_scalar_edit_array500", rounds, sw.Elapsed.TotalMilliseconds); await CleanupAsync(); } [Fact] public async Task B4_SmallObjectResave() { if (!Enabled) return; await CleanupAsync(); // The most frequent real-world case: one small object saved repeatedly. F7 target. var id = await SeedAsync("bench-b4", new CtProbeProps { Label = "small", Longs = [1, 2, 3], Dict = new() { ["a"] = "1" }, }); var loaded = await Redb.LoadAsync(id, depth: 2); const int rounds = 100; var sw = Stopwatch.StartNew(); for (var r = 0; r < rounds; r++) { loaded!.Props.Label = "small-" + r; await Redb.SaveAsync(loaded); } sw.Stop(); Report(ProviderName, "B4_small_edit_x100", rounds, sw.Elapsed.TotalMilliseconds); await CleanupAsync(); } } Path: redb/redb.Tests.Integration/Tests/Base/CtSaveInvariantsTestsBase.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/CtSaveInvariantsTestsBase.cs ---- using redb.Core; using redb.Core.Models.Entities; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// Инварианты сохранения (ревью 2026-09-03, волна 1.2). Главный: повторный save без правок - /// ноль диффа; точечная правка меняет только своё. На фикстурах с ChangeTracking /// ( = true) дополнительно проверяется, что строки _values /// нетронутых полей сохраняют свои _id - Delete/Insert их пересоздаёт, CT обязан не трогать. /// Тест канона хеша массива - пин под снос расходящегося пересчёта (CT-2): хеш базовой записи /// массива после CT-правки элемента обязан совпадать с хешем свежесозданного объекта с тем же /// содержимым. /// public abstract class CtSaveInvariantsTestsBase : IAsyncLifetime { protected readonly IRedbService Redb; protected CtSaveInvariantsTestsBase(IRedbService redb) => Redb = redb; /// true на фикстурах со стратегией ChangeTracking: строки нетронутых значений обязаны сохранять _id. protected virtual bool ExpectStableValueRowIds => false; public async Task InitializeAsync() => await ResetAsync(); public async Task DisposeAsync() => await ResetAsync(); private async Task ResetAsync() { // Порядок обязателен: FK fk__values__objects_ref запрещает удалять объект, на который // жива ссылка _values._Object. Сначала родители (их строки-ссылки уходят каскадом // вместе с values), потом дети. await Redb.Context.ExecuteAsync( "DELETE FROM _objects WHERE _id_scheme IN (SELECT _id FROM _schemes WHERE _name = 'CtProbe')"); await Redb.Context.ExecuteAsync( "DELETE FROM _objects WHERE _id_scheme IN (SELECT _id FROM _schemes WHERE _name = 'CtProbeChild')"); } private async Task SeedAsync(CtProbeProps props) { await Redb.SyncSchemeAsync(); return await Redb.SaveAsync(new RedbObject { name = "ct-probe", Props = props }); } private sealed class ValueRow { public long Id { get; set; } public long IdStructure { get; set; } public string? ArrayIndex { get; set; } } private async Task> SnapshotRowsAsync(long objectId) => await Redb.Context.QueryAsync( $"SELECT _id AS Id, _id_structure AS IdStructure, _array_index AS ArrayIndex FROM _values WHERE _id_object = {objectId} ORDER BY _id"); private async Task ArrayBaseHashAsync(long objectId, string fieldName) => await Redb.Context.ExecuteScalarAsync( "SELECT v._Guid FROM _values v JOIN _structures s ON s._id = v._id_structure " + $"WHERE v._id_object = {objectId} AND s._name = '{fieldName}' AND v._array_index IS NULL AND v._array_parent_id IS NULL"); /// Ш4: после любой операции ресейв без правок обязан быть ноль-диффом /// (хеш стабилен; на CT-фикстурах - и _id строк значений). private async Task AssertResaveIsZeroDiffAsync(long id) { var loaded = await Redb.LoadAsync(id, depth: 2); var hash = loaded!.hash; var rows = await SnapshotRowsAsync(id); await Redb.SaveAsync(loaded); var after = await Redb.LoadAsync(id, depth: 2); after!.hash.Should().Be(hash, "ресейв без правок обязан быть ноль-диффом"); if (ExpectStableValueRowIds) (await SnapshotRowsAsync(id)).Select(r => r.Id).Should().Equal(rows.Select(r => r.Id), "ресейв без правок не имеет права пересоздавать строки значений"); } private static CtProbeProps FullProps() => new() { Label = "base", Longs = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], Decimals = [1.5m, 2.5m, 3.5m], Dict = new() { ["a"] = "1", ["b"] = "2" }, Items = [ new CtProbeItem { Name = "i0", Price = 10m }, new CtProbeItem { Name = "i1", Price = 20m }, new CtProbeItem { Name = "i2", Price = 30m }, ], }; [Fact] public async Task ResaveWithoutChanges_IsAZeroDiff() { var id = await SeedAsync(FullProps()); var loaded = await Redb.LoadAsync(id, depth: 2); var hashBefore = loaded!.hash; var rowsBefore = await SnapshotRowsAsync(id); await Redb.SaveAsync(loaded); var reloaded = await Redb.LoadAsync(id, depth: 2); reloaded!.hash.Should().Be(hashBefore, "содержимое не менялось - хеш обязан быть стабилен"); reloaded.Props.Longs.Should().Equal(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12); reloaded.Props.Dict.Should().Equal(new Dictionary { ["a"] = "1", ["b"] = "2" }); if (ExpectStableValueRowIds) { var rowsAfter = await SnapshotRowsAsync(id); rowsAfter.Select(r => r.Id).Should().Equal(rowsBefore.Select(r => r.Id), "ChangeTracking при нулевом диффе не имеет права пересоздавать строки значений"); } } [Fact] public async Task SingleElementEdit_InALongArray_TouchesOnlyItsRow() { // Массив из 12 элементов - индексы с двузначными номерами: строковая сортировка // индексов ("10" < "2") ломала бы порядок; численная - нет. var id = await SeedAsync(FullProps()); var rowsBefore = await SnapshotRowsAsync(id); var loaded = await Redb.LoadAsync(id, depth: 2); loaded!.Props.Longs![10] = 999; await Redb.SaveAsync(loaded); var reloaded = await Redb.LoadAsync(id, depth: 2); reloaded!.Props.Longs.Should().Equal(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 999, 12); if (ExpectStableValueRowIds) { var rowsAfter = await SnapshotRowsAsync(id); var untouchedBefore = rowsBefore.Where(r => r.ArrayIndex != "10").Select(r => r.Id); var untouchedAfter = rowsAfter.Where(r => r.ArrayIndex != "10").Select(r => r.Id); untouchedAfter.Should().BeEquivalentTo(untouchedBefore, "правка одного элемента не имеет права пересоздавать строки остальных"); } } [Fact] public async Task ArrayBaseHash_AfterEdit_MatchesTheCanonicalHash() { // Пин под снос CT-2: после правки элемента хеш базовой записи массива обязан совпадать // с хешем свежесозданного объекта с тем же содержимым (канон - RedbHash.ComputeForProps // от CLR-массива, не пересчёт по строкам _values). var id = await SeedAsync(FullProps()); var loaded = await Redb.LoadAsync(id, depth: 2); loaded!.Props.Longs![10] = 999; loaded.Props.Decimals![1] = 9.75m; await Redb.SaveAsync(loaded); var canonId = await SeedAsync(new CtProbeProps { Label = "canon", Longs = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 999, 12], Decimals = [1.5m, 9.75m, 3.5m], }); (await ArrayBaseHashAsync(id, "Longs")).Should().Be(await ArrayBaseHashAsync(canonId, "Longs"), "хеш массива после правки обязан быть каноническим"); (await ArrayBaseHashAsync(id, "Decimals")).Should().Be(await ArrayBaseHashAsync(canonId, "Decimals"), "хеш decimal-массива после правки обязан быть каноническим"); } [Fact] public async Task TupleKeyedDictionary_AddEditRemove_RoundTrips() { // Ш1 (стратегия владельца 2026-09-03): ключ словаря - ValueTuple, в _array_index он // лежит сериализованным (Base64(JSON), Item1..ItemN вручную). Пин детерминизма // сериализации ключа через полный цикл: правка значения по ключу, удаление ключа, // добавление нового, перечитка, ресейв без правок = ноль диффа. var id = await SeedAsync(new CtProbeProps { Label = "tuple", TupleDict = new Dictionary<(int Year, string Quarter), string> { [(2026, "Q1")] = "start", [(2026, "Q2")] = "mid", }, }); var loaded = await Redb.LoadAsync(id, depth: 2); loaded!.Props.TupleDict.Should().NotBeNull("словарь с tuple-ключом обязан перечитываться"); loaded.Props.TupleDict![(2026, "Q1")] = "changed"; loaded.Props.TupleDict.Remove((2026, "Q2")); loaded.Props.TupleDict[(2027, "Q1")] = "new-year"; await Redb.SaveAsync(loaded); var reloaded = await Redb.LoadAsync(id, depth: 2); reloaded!.Props.TupleDict.Should().Equal(new Dictionary<(int Year, string Quarter), string> { [(2026, "Q1")] = "changed", [(2027, "Q1")] = "new-year", }); // Ресейв без правок: хеш стабилен, на CT-фикстурах строки не пересозданы. var hashBefore = reloaded.hash; var rowsBefore = await SnapshotRowsAsync(id); await Redb.SaveAsync(reloaded); var after = await Redb.LoadAsync(id, depth: 2); after!.hash.Should().Be(hashBefore, "ресейв без правок не имеет права двигать хеш"); if (ExpectStableValueRowIds) { var rowsAfter = await SnapshotRowsAsync(id); rowsAfter.Select(r => r.Id).Should().Equal(rowsBefore.Select(r => r.Id), "нулевой дифф tuple-словаря не имеет права пересоздавать строки"); } } [Fact] public async Task Dictionary_EditRemoveAdd_RoundTrips() { var id = await SeedAsync(FullProps()); var loaded = await Redb.LoadAsync(id, depth: 2); loaded!.Props.Dict!["a"] = "changed"; loaded.Props.Dict.Remove("b"); loaded.Props.Dict["c"] = "new"; await Redb.SaveAsync(loaded); var reloaded = await Redb.LoadAsync(id, depth: 2); reloaded!.Props.Dict.Should().Equal(new Dictionary { ["a"] = "changed", ["c"] = "new", }); } private async Task> SeedChildAsync(string tag) { await Redb.SyncSchemeAsync(); var child = new RedbObject { name = $"child-{tag}", Props = new CtProbeChildProps { Tag = tag } }; await Redb.SaveAsync(child); return child; } private async Task ElementGuidAsync(long objectId, string fieldName, string arrayIndex) => await Redb.Context.ExecuteScalarAsync( "SELECT v._Guid FROM _values v JOIN _structures s ON s._id = v._id_structure " + $"WHERE v._id_object = {objectId} AND s._name = '{fieldName}' AND v._array_index = '{arrayIndex}'"); [Fact] public async Task ReferenceArray_ReplaceOneElement_TouchesOnlyItsRow() { // Ш2: массив РЕФЕРЕНСОВ - в строках только _Object=id + _Guid=персистентный хеш ребёнка. // Замена одного элемента-ссылки не имеет права трогать строки соседей, а _Guid заменённой // строки обязан стать хешем НОВОГО ребёнка. var c1 = await SeedChildAsync("c1"); var c2 = await SeedChildAsync("c2"); var c3 = await SeedChildAsync("c3"); var id = await SeedAsync(new CtProbeProps { Label = "refs", Refs = [c1, c2] }); var rowsBefore = await SnapshotRowsAsync(id); var loaded = await Redb.LoadAsync(id, depth: 2); loaded!.Props.Refs.Should().HaveCount(2); loaded.Props.Refs![1] = c3; await Redb.SaveAsync(loaded); var reloaded = await Redb.LoadAsync(id, depth: 2); reloaded!.Props.Refs!.Select(r => r.id).Should().Equal(c1.id, c3.id); (await ElementGuidAsync(id, "Refs", "1")).Should().Be(c3.hash, "строка-ссылка несёт персистентный хеш нового ребёнка"); if (ExpectStableValueRowIds) { var rowsAfter = await SnapshotRowsAsync(id); var untouchedBefore = rowsBefore.Where(r => r.ArrayIndex != "1").Select(r => r.Id); var untouchedAfter = rowsAfter.Where(r => r.ArrayIndex != "1").Select(r => r.Id); untouchedAfter.Should().BeEquivalentTo(untouchedBefore, "замена одной ссылки не имеет права пересоздавать строки соседей"); } } [Fact] public async Task ReferenceDictionary_ReplaceByKey_RoundTrips() { // Ш2: словарь референсов - ключ в _array_index, значение _Object=id + _Guid=хеш. var c1 = await SeedChildAsync("d1"); var c2 = await SeedChildAsync("d2"); var c3 = await SeedChildAsync("d3"); var id = await SeedAsync(new CtProbeProps { Label = "refdict", RefDict = new Dictionary> { ["a"] = c1, ["b"] = c2 }, }); var rowsBefore = await SnapshotRowsAsync(id); var loaded = await Redb.LoadAsync(id, depth: 2); loaded!.Props.RefDict.Should().NotBeNull(); loaded.Props.RefDict!["b"] = c3; await Redb.SaveAsync(loaded); var reloaded = await Redb.LoadAsync(id, depth: 2); reloaded!.Props.RefDict!.Keys.Should().BeEquivalentTo(new[] { "a", "b" }); reloaded.Props.RefDict["a"].id.Should().Be(c1.id); reloaded.Props.RefDict["b"].id.Should().Be(c3.id); (await ElementGuidAsync(id, "RefDict", "b")).Should().Be(c3.hash, "строка-ссылка словаря несёт персистентный хеш нового ребёнка"); if (ExpectStableValueRowIds) { var rowsAfter = await SnapshotRowsAsync(id); var untouchedBefore = rowsBefore.Where(r => r.ArrayIndex != "b").Select(r => r.Id); var untouchedAfter = rowsAfter.Where(r => r.ArrayIndex != "b").Select(r => r.Id); untouchedAfter.Should().BeEquivalentTo(untouchedBefore, "замена значения по одному ключу не имеет права пересоздавать строки соседей"); } } [Fact] public async Task NullElements_InPrimitiveArray_RoundTrip() { // Ш2б («null должен быть null»): null-элементы строкового массива переживают цикл, // правка соседа их не трогает, ресейв - ноль диффа. Red-before: Pro-читатель выкидывал // строки без значений (В-3). var id = await SeedAsync(new CtProbeProps { Label = "nulls", Tags = ["a", null, "b"] }); var loaded = await Redb.LoadAsync(id, depth: 2); loaded!.Props.Tags.Should().Equal("a", null, "b"); loaded.Props.Tags![0] = "a2"; await Redb.SaveAsync(loaded); var reloaded = await Redb.LoadAsync(id, depth: 2); reloaded!.Props.Tags.Should().Equal("a2", null, "b"); var hashBefore = reloaded.hash; await Redb.SaveAsync(reloaded); (await Redb.LoadAsync(id, depth: 2))!.hash.Should().Be(hashBefore, "null-элементы не имеют права дрожать между ресейвами"); } [Fact] public async Task NullValue_InDictionary_RoundTrips() { // В-2 («null должен быть null»): ключ с null-значением обязан сохраниться при чтении. var id = await SeedAsync(new CtProbeProps { Label = "dict-null", Dict = new() { ["a"] = "1", ["b"] = null! }, }); var loaded = await Redb.LoadAsync(id, depth: 2); loaded!.Props.Dict.Should().ContainKey("b"); loaded.Props.Dict!["b"].Should().BeNull("ключ с null-значением обязан вернуться ключом с null"); loaded.Props.Dict["a"] = "2"; await Redb.SaveAsync(loaded); var reloaded = await Redb.LoadAsync(id, depth: 2); reloaded!.Props.Dict.Should().HaveCount(2); reloaded.Props.Dict!["a"].Should().Be("2"); reloaded.Props.Dict["b"].Should().BeNull(); } [Fact] public async Task NullElement_InClassList_RoundTrips() { // В-1 («null должен быть null»): null-элемент списка КЛАССОВ обязан вернуться null-ом. // Дифференциатор в базе: null-элемент - строка без _Guid; у класса хеш есть всегда. var id = await SeedAsync(new CtProbeProps { Label = "class-nulls", Items = [ new CtProbeItem { Name = "i0", Price = 10m }, null!, new CtProbeItem { Name = "i2", Price = 30m }, ], }); var loaded = await Redb.LoadAsync(id, depth: 2); loaded!.Props.Items.Should().HaveCount(3); loaded.Props.Items![1].Should().BeNull("null-элемент списка классов обязан вернуться null-ом"); loaded.Props.Items[2] = new CtProbeItem { Name = "i2", Price = 31m }; await Redb.SaveAsync(loaded); var reloaded = await Redb.LoadAsync(id, depth: 2); reloaded!.Props.Items.Should().HaveCount(3); reloaded.Props.Items![1].Should().BeNull(); reloaded.Props.Items[2]!.Price.Should().Be(31m); } [Fact] public async Task LegacyClassElement_WithoutGuid_StillReadsAsObject() { // Р-1 (ревью null-фиксов): дифференциатор «null-элемент = строка без _Guid» усилен // legacy-толерантностью «...И без детей». Если исторический писатель не ставил хеш // класс-элементу, но дети есть - это КЛАСС, и его данные обязаны читаться, а не // превращаться в null. У настоящего null-элемента детей не бывает никогда. var id = await SeedAsync(new CtProbeProps { Label = "legacy", Items = [new CtProbeItem { Name = "keep-me", Price = 7m }], }); // Имитация legacy-строки: снести хеш у класс-элемента (дети остаются). await Redb.Context.ExecuteAsync( "UPDATE _values SET _Guid = NULL WHERE _id_object = " + id + " AND _array_index IS NOT NULL AND _id_structure IN (SELECT _id FROM _structures WHERE _name = 'Items')"); var loaded = await Redb.LoadAsync(id, depth: 2); loaded!.Props.Items.Should().HaveCount(1); loaded.Props.Items![0].Should().NotBeNull("класс-элемент с детьми обязан читаться объектом даже без legacy-хеша"); loaded.Props.Items[0]!.Name.Should().Be("keep-me"); } [Fact] public async Task NestedClassInObjectArray_Edit_RoundTrips() { var id = await SeedAsync(FullProps()); var loaded = await Redb.LoadAsync(id, depth: 2); loaded!.Props.Items![1].Price = 21.5m; await Redb.SaveAsync(loaded); var reloaded = await Redb.LoadAsync(id, depth: 2); reloaded!.Props.Items!.Select(i => i.Price).Should().Equal(10m, 21.5m, 30m); reloaded.Props.Items.Select(i => i.Name).Should().Equal("i0", "i1", "i2"); } [Fact] public async Task ValuelessObject_Load_TerminatesAndReturnsObject() { // Объект без единой value-строки (properties:null в json) - легальное состояние: // чужой процесс успел стереть values (гонка), или объект создан голым. Free-путь // одиночной ленивой загрузки на таком объекте уходил в вечную рекурсию // get_Props -> LoadProps -> LoadPropsAsync -> return obj.Props (петля съедала по // треду пула на виток). Загрузка обязана завершиться, а не жевать пул. var id = await SeedAsync(new CtProbeProps { Label = "soon-valueless" }); await Redb.Context.ExecuteAsync("DELETE FROM _values WHERE _id_object = " + id); var loaded = await Redb.LoadAsync(id, depth: 2); loaded.Should().NotBeNull(); loaded!.id.Should().Be(id); // Петля живёт не в LoadAsync, а в СИНХРОННОМ геттере Props стаба (Install повесил // лоадер на корень) - гвардим само обращение, иначе красный прогон висит вечно. var propsTask = Task.Run(() => loaded.GetPropsDirectly() ?? loaded.Props); var winner = await Task.WhenAny(propsTask, Task.Delay(TimeSpan.FromSeconds(30))); winner.Should().BeSameAs(propsTask, "доступ к Props объекта без values обязан завершаться, а не зацикливаться"); } [Fact] public async Task ListItemRename_DoesNotMoveOwnerHash_AndResaveIsAZeroDiff() { // О-1/Б-3 (вердикт владельца): в _values живёт ИДЕНТИФИКАТОР элемента справочника, // хеш владельца - от идентификаторов; за содержимое ListItem values-слой не отвечает. // Переименование значения в _list_items не имеет права двигать хеш владельца и // порождать дифф при ресейве без правок. var listName = "CtProbeRoles"; var existing = await Redb.ListProvider.GetListByNameAsync(listName); if (existing != null) { var stale = await Redb.ListProvider.GetListItemsAsync(existing.Id); if (stale.Count > 0) await Redb.Context.Bulk.BulkDeleteValuesByListItemIdsAsync(stale.Select(i => i.Id).ToList()); await Redb.ListProvider.DeleteListAsync(existing.Id); } var list = await Redb.ListProvider.SaveListAsync(RedbList.Create(listName, "ct-probe roles")); var items = await Redb.ListProvider.AddItemsAsync(list, ["Admin", "User", "Viewer"]); var id = await SeedAsync(new CtProbeProps { Label = "listitem", Status = items[0], Roles = [items[1], items[2]], }); var hashBefore = (await Redb.LoadAsync(id, depth: 2))!.hash; var rowsBefore = await SnapshotRowsAsync(id); // Переименование значения справочника - контент ListItem живёт своей жизнью. items[1].Value = "User-Renamed"; await Redb.ListProvider.SaveListItemAsync(items[1]); var reloaded = await Redb.LoadAsync(id, depth: 2); await Redb.SaveAsync(reloaded!); var after = await Redb.LoadAsync(id, depth: 2); after!.hash.Should().Be(hashBefore, "хеш владельца считается от идентификаторов ListItem - переименование значения не двигает его"); after.Props.Status!.Id.Should().Be(items[0].Id); after.Props.Roles!.Select(r => r.Id).Should().Equal(items[1].Id, items[2].Id); if (ExpectStableValueRowIds) { var rowsAfter = await SnapshotRowsAsync(id); rowsAfter.Select(r => r.Id).Should().Equal(rowsBefore.Select(r => r.Id), "ресейв без правок владельца обязан быть ноль-диффом и после переименования в справочнике"); } } // ===== Ш4: жёсткая матрица вложенности (только тесты, Б-4) ===== private static CtProbeProps NestedMatrixProps() => new() { Label = "matrix", Items = [ new CtProbeItem { Name = "i0", Price = 10m, Codes = [100, 101, 102], Meta = new() { ["k0"] = "v0", ["k1"] = "v1" }, }, new CtProbeItem { Name = "i1", Price = 20m, Codes = [200, 201], Meta = new() { ["m0"] = "w0" }, }, ], }; [Fact] public async Task NestedCollectionsInsideArrayElement_EditAtEachLevel_RoundTrips() { // Класс-элемент массива с СОБСТВЕННЫМИ массивом и словарём: правка на каждом // уровне вложенности, после каждой операции - перечитка и ноль-дифф ресейва. var id = await SeedAsync(NestedMatrixProps()); await AssertResaveIsZeroDiffAsync(id); // Уровень 3: элемент вложенного массива класса-элемента. var loaded = await Redb.LoadAsync(id, depth: 3); loaded!.Props.Items![0].Codes![1] = 999; await Redb.SaveAsync(loaded); var r1 = await Redb.LoadAsync(id, depth: 3); r1!.Props.Items![0].Codes.Should().Equal(100, 999, 102); r1.Props.Items[1].Codes.Should().Equal(200, 201); await AssertResaveIsZeroDiffAsync(id); // Уровень 3: значение ключа вложенного словаря + правка поля самого класса. loaded = await Redb.LoadAsync(id, depth: 3); loaded!.Props.Items![1].Meta!["m0"] = "w0-changed"; loaded.Props.Items[1].Price = 21.5m; await Redb.SaveAsync(loaded); var r2 = await Redb.LoadAsync(id, depth: 3); r2!.Props.Items![1].Meta.Should().Equal(new Dictionary { ["m0"] = "w0-changed" }); r2.Props.Items[1].Price.Should().Be(21.5m); r2.Props.Items[0].Meta.Should().Equal(new Dictionary { ["k0"] = "v0", ["k1"] = "v1" }); await AssertResaveIsZeroDiffAsync(id); // Add/delete на вложенных коллекциях: рост массива i1, усушка массива i0, // добавление и удаление ключей словаря i0 вперемешку. loaded = await Redb.LoadAsync(id, depth: 3); loaded!.Props.Items![1].Codes = [200, 201, 202, 203]; loaded.Props.Items[0].Codes = [100, 999]; loaded.Props.Items[0].Meta!.Remove("k0"); loaded.Props.Items[0].Meta["k2"] = "v2"; await Redb.SaveAsync(loaded); var r3 = await Redb.LoadAsync(id, depth: 3); r3!.Props.Items![1].Codes.Should().Equal(200, 201, 202, 203); r3.Props.Items[0].Codes.Should().Equal(100, 999); r3.Props.Items[0].Meta.Should().Equal(new Dictionary { ["k1"] = "v1", ["k2"] = "v2" }); await AssertResaveIsZeroDiffAsync(id); } [Fact] public async Task ArrayElementAddDelete_WithNestedCollections_RoundTrips() { // Add/delete самих класс-элементов (у каждого - собственные коллекции): // удаление элемента с детьми, добавление нового с детьми. var id = await SeedAsync(NestedMatrixProps()); var loaded = await Redb.LoadAsync(id, depth: 3); loaded!.Props.Items!.RemoveAt(0); // i0 уходит вместе со своими Codes/Meta loaded.Props.Items.Add(new CtProbeItem { Name = "i2", Price = 30m, Codes = [300], Meta = new() { ["z"] = "zz" }, }); await Redb.SaveAsync(loaded); var r = await Redb.LoadAsync(id, depth: 3); r!.Props.Items!.Select(i => i.Name).Should().Equal("i1", "i2"); r.Props.Items[0].Codes.Should().Equal(200, 201); r.Props.Items[1].Codes.Should().Equal(300); r.Props.Items[1].Meta.Should().Equal(new Dictionary { ["z"] = "zz" }); await AssertResaveIsZeroDiffAsync(id); } [Fact] public async Task LargeArrayReorder_RoundTrips() { // Reorder большого массива примитивов и reorder класс-элементов: порядок - часть // содержимого, перечитка обязана вернуть новый порядок, ресейв после - ноль-дифф. var id = await SeedAsync(FullProps()); var loaded = await Redb.LoadAsync(id, depth: 2); loaded!.Props.Longs = [.. loaded.Props.Longs!.Reverse()]; await Redb.SaveAsync(loaded); var r1 = await Redb.LoadAsync(id, depth: 2); r1!.Props.Longs.Should().Equal(12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1); await AssertResaveIsZeroDiffAsync(id); // Reorder класс-элементов: [i0,i1,i2] -> [i2,i0,i1]. loaded = await Redb.LoadAsync(id, depth: 2); var items = loaded!.Props.Items!; loaded.Props.Items = [items[2], items[0], items[1]]; await Redb.SaveAsync(loaded); var r2 = await Redb.LoadAsync(id, depth: 2); r2!.Props.Items!.Select(i => i.Name).Should().Equal("i2", "i0", "i1"); r2.Props.Items.Select(i => i.Price).Should().Equal(30m, 10m, 20m); await AssertResaveIsZeroDiffAsync(id); } [Fact] public async Task DictionaryKeysAddDeleteMixed_RoundTrips() { // Перемешанные add+delete ключей корневого словаря за один save: удаление, // добавление двух, правка выжившего. var id = await SeedAsync(FullProps()); var loaded = await Redb.LoadAsync(id, depth: 2); loaded!.Props.Dict!.Remove("a"); loaded.Props.Dict["c"] = "3"; loaded.Props.Dict["d"] = "4"; loaded.Props.Dict["b"] = "2-changed"; await Redb.SaveAsync(loaded); var r = await Redb.LoadAsync(id, depth: 2); r!.Props.Dict.Should().Equal(new Dictionary { ["b"] = "2-changed", ["c"] = "3", ["d"] = "4", }); await AssertResaveIsZeroDiffAsync(id); } [Fact] public async Task ArrayBaseHash_DependsOnElementContent_NotJustSize() { // Canon defect found while preparing F2: ComputeForProps(collection) reflected over the // collection type's OWN properties (List: Capacity|Count; long[]: Length|...), so two // same-sized collections with different content produced the SAME base-row hash. Any // consumer trusting the base hash (the F2 short-circuit above all) would then treat // different arrays as equal. The base hash must depend on element content. var idA = await SeedAsync(new CtProbeProps { Label = "canonA", Longs = [1, 2, 3, 4, 5], Items = [new CtProbeItem { Name = "x", Price = 1m }], }); var idB = await SeedAsync(new CtProbeProps { Label = "canonB", Longs = [9, 9, 9, 9, 9], Items = [new CtProbeItem { Name = "y", Price = 2m }], }); var longsA = await ArrayBaseHashAsync(idA, "Longs"); var longsB = await ArrayBaseHashAsync(idB, "Longs"); longsA.Should().NotBeNull(); longsA.Should().NotBe(longsB!.Value, "same-length arrays with different content must not share a base hash"); var itemsA = await ArrayBaseHashAsync(idA, "Items"); var itemsB = await ArrayBaseHashAsync(idB, "Items"); itemsA.Should().NotBeNull(); itemsA.Should().NotBe(itemsB!.Value, "class arrays with different element content must not share a base hash"); } [Fact] public async Task BatchResave_UntouchedNeighborKeepsItsValues() { // F1 guard (hash shortcut): an unchanged object in a batch is excluded from the value // pipeline entirely. A filtering bug that let it reach the diff with an empty new tree // would read as "delete all its values" - this pin makes that loud on every provider. var idA = await SeedAsync(FullProps()); var idB = await SeedAsync(new CtProbeProps { Label = "neighbor", Longs = [7, 8, 9] }); var a = await Redb.LoadAsync(idA, depth: 2); var b = await Redb.LoadAsync(idB, depth: 2); var bRowsBefore = await SnapshotRowsAsync(idB); a!.Props.Longs![0] = 111; await Redb.SaveAsync(new List { a, b! }); var rA = await Redb.LoadAsync(idA, depth: 2); rA!.Props.Longs![0].Should().Be(111); var rB = await Redb.LoadAsync(idB, depth: 2); rB!.Props.Label.Should().Be("neighbor"); rB.Props.Longs.Should().Equal(7, 8, 9); rB.Props.Dict.Should().BeNull(); if (ExpectStableValueRowIds) (await SnapshotRowsAsync(idB)).Select(v => v.Id).Should().Equal(bRowsBefore.Select(v => v.Id), "untouched batch neighbor's value rows must survive byte-for-byte"); } } Path: redb/redb.Tests.Integration/Tests/Base/DbInfoTestsBase.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/DbInfoTestsBase.cs ---- using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Core; using redb.Core.Extensions; namespace redb.Tests.Integration.Tests.Base; /// /// Server facts through : the version and the database size. The SQLite service sent the /// PostgreSQL text - version() and pg_database_size(current_database()) - and failed on its own provider; /// MSSQL reported the size in kilobytes while the others reported bytes. /// public abstract class DbInfoTestsBase { /// 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); /// Text every version string of this provider contains. protected abstract string VersionMarker { get; } /// The database size in bytes, straight from the server's own catalog, to pin the unit. protected abstract string SizeInBytesSql { get; } private ServiceProvider Build() { var services = new ServiceCollection(); services.AddLogging(b => b.SetMinimumLevel(LogLevel.Warning)); Register(services, options => { UseProvider(options); options.Configure(c => c.CacheDomain = "db-info"); }); return services.BuildServiceProvider(); } [Fact] public async Task Version_ComesFromTheServer() { await using var sp = Build(); var service = sp.GetRequiredService(); await service.InitializeAsync(ensureCreated: true); (await service.GetDbVersionAsync()).Should().Contain(VersionMarker); service.dbVersion.Should().Contain(VersionMarker); } [Fact] public async Task Size_IsInBytes() { await using var sp = Build(); var service = sp.GetRequiredService(); await service.InitializeAsync(ensureCreated: true); var reported = service.dbSize; var expected = await service.Context.ExecuteScalarAsync(SizeInBytesSql); expected.Should().BeGreaterThan(0); reported.Should().NotBeNull(); // Other suites write to the shared database meanwhile: the unit is pinned, not the exact byte count. reported!.Value.Should().BeInRange(expected / 2, expected * 2, "dbSize reports bytes on every provider"); } } Path: redb/redb.Tests.Integration/Tests/Base/DecimalRoundTripTestsBase.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/DecimalRoundTripTestsBase.cs ---- using redb.Core; using redb.Core.Models.Entities; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// A decimal saved and read back is the decimal that was saved: by a load, by a query, by Min and Max. SQLite keeps a /// decimal in a REAL column by default, so its reader turns a double into a decimal; that conversion must give the /// number that was stored on every runtime (the explicit conversion rounded to 15 digits up to .NET 10 and gives the /// exact binary value from .NET 11 on: 123.45 came back as 123.45000000000000284217094304). /// /// Each test reads only the objects it seeded (by a title of its own), so the shared database stays out. /// public abstract class DecimalRoundTripTestsBase { protected readonly IRedbService Redb; protected DecimalRoundTripTestsBase(IRedbService redb) => Redb = redb; /// The provider keeps a decimal in a binary floating-point column (SQLite's default REAL mode). protected virtual bool StoresDecimalAsDouble => false; // The kinds a user has: an integer, a price, a long fraction (15 significant digits), a negative value, a small one. public static IEnumerable Values() => [ [42m], [123.45m], [0.1m], [0.333333333333333m], [-98765.4321m], [0.000001234m], [999999999.99m] ]; [Theory] [MemberData(nameof(Values))] public async Task Decimal_LoadedQueriedAndAggregated_IsTheSavedValue(decimal value) { var tag = "dec-" + Guid.NewGuid().ToString("N")[..8]; var id = await Redb.SaveAsync(new RedbObject { name = tag, Props = new SimpleProps { Title = tag, Price = value } }); (await Redb.LoadAsync(id))!.Props.Price.Should().Be(value, "a load gives the saved decimal"); var queried = await Redb.Query().Where(p => p.Title == tag).ToListAsync(); queried.Should().ContainSingle().Which.Props.Price.Should().Be(value, "a query gives the saved decimal"); (await Redb.Query().Where(p => p.Title == tag).MaxAsync(p => p.Price)).Should().Be(value, "Max of one value is that value"); (await Redb.Query().Where(p => p.Title == tag).MinAsync(p => p.Price)).Should().Be(value, "Min of one value is that value"); } [Fact] public async Task Decimal_WithMoreDigitsThanADoubleHolds_KeepsWhatTheColumnHolds() { // 17 significant digits: a numeric column keeps them; a REAL column holds the double the save converted the // decimal to, and the read gives the shortest decimal of that double. The conversion is the runtime's: .NET 10 // gives 12345678901234.568, .NET 11 the nearest double, 12345678901234.566. Not a const: the compiler would // fold (double)value with the conversion of the runtime it runs on (SDK 11 on .NET 11), not of the tests. var value = decimal.Parse("12345678901234.567", System.Globalization.CultureInfo.InvariantCulture); var tag = "dec-" + Guid.NewGuid().ToString("N")[..8]; var id = await Redb.SaveAsync(new RedbObject { name = tag, Props = new SimpleProps { Title = tag, Price = value } }); var expected = StoresDecimalAsDouble ? decimal.Parse(((double)value).ToString("R", System.Globalization.CultureInfo.InvariantCulture), System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture) : value; (await Redb.LoadAsync(id))!.Props.Price.Should().Be(expected); (await Redb.Query().Where(p => p.Title == tag).MaxAsync(p => p.Price)).Should().Be(expected); } } Path: redb/redb.Tests.Integration/Tests/Base/DeleteBatchCountTestsBase.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/DeleteBatchCountTestsBase.cs ---- using redb.Core; using redb.Core.Models.Entities; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// DeleteAsync over a batch counts every requested object it deleted, a parent and its child both. On SQLite the /// _id_parent cascade removed the child with its parent before the statement reached it, and the child was not counted. /// A descendant that was not requested is deleted with its parent and not counted, as on every provider. /// public abstract class DeleteBatchCountTestsBase { protected readonly IRedbService Redb; protected DeleteBatchCountTestsBase(IRedbService redb) => Redb = redb; private async Task<(long Parent, long Child, long Grandchild)> SeedAsync() { await Redb.SyncSchemeAsync(); var tag = "dbc-" + Guid.NewGuid().ToString("N")[..8]; var parent = new TreeRedbObject { name = $"{tag}-p", Props = new SimpleProps { Title = tag } }; parent.id = await Redb.SaveAsync(parent); var child = new TreeRedbObject { name = $"{tag}-c", Props = new SimpleProps { Title = tag, Count = 1 } }; child.id = await Redb.CreateChildAsync(child, parent); var grandchild = new TreeRedbObject { name = $"{tag}-g", Props = new SimpleProps { Title = tag, Count = 2 } }; grandchild.id = await Redb.CreateChildAsync(grandchild, child); return (parent.id, child.id, grandchild.id); } [Fact] public async Task DeleteBatch_HoldingAParentAndItsChild_CountsBoth() { var (parent, child, grandchild) = await SeedAsync(); var deleted = await Redb.DeleteAsync(new[] { parent, child }); deleted.Should().Be(2, "both requested objects were deleted by this call"); (await Redb.LoadAsync(grandchild)).Should().BeNull("the descendant goes with its parent"); } [Fact] public async Task DeleteBatch_ChildListedBeforeItsParent_CountsBoth() { var (parent, child, _) = await SeedAsync(); (await Redb.DeleteAsync(new[] { child, parent })).Should().Be(2); } private async Task<(long Parent, long Child, long Grandchild, string Tag)> SeedTaggedAsync() { var (parent, child, grandchild) = await SeedAsync(); var tag = (await Redb.LoadAsync(parent))!.Props.Title; return (parent, child, grandchild, tag); } // A query delete whose filter matches a parent and its child counts both. Pro on SQLite builds its own DELETE, and // changes() missed the child the cascade had removed with the parent; a filter on base fields only failed there // ("no such column: o._id"). Free threw NotSupportedException: it asked the removed search_objects_simple for the ids. [Fact] public async Task QueryDelete_MatchingAParentAndItsChild_CountsBoth() { var (_, child, grandchild, tag) = await SeedTaggedAsync(); // Count 0 is the parent, 1 the child: a Props filter, so Pro reads it through the pivot. var deleted = await Redb.Query().Where(p => p.Title == tag && p.Count < 2).DeleteAsync(); deleted.Should().Be(2, "the filter matched the parent and the child"); (await Redb.LoadAsync(child)).Should().BeNull(); (await Redb.LoadAsync(grandchild)).Should().BeNull("the descendant goes with its parent"); } [Fact] public async Task QueryDelete_OnBaseFieldsOnly_MatchingAParentAndItsChild_CountsBoth() { var (parent, child, _, _) = await SeedTaggedAsync(); var deleted = await Redb.Query().WhereRedb(o => o.Id == parent || o.Id == child).DeleteAsync(); deleted.Should().Be(2); } [Fact] public async Task QueryDelete_MatchingNothing_CountsZero() { var (_, _, _, tag) = await SeedTaggedAsync(); (await Redb.Query().Where(p => p.Title == tag && p.Count > 100).DeleteAsync()).Should().Be(0); (await Redb.Query().Where(p => p.Title == tag).CountAsync()).Should().Be(3, "nothing was deleted"); } /// A tree query delete removes the nodes the tree query reads: here the child and the grandchild. [Fact] public async Task TreeQueryDelete_BelowTheParent_CountsTheNodesItReads() { var (parent, child, grandchild, tag) = await SeedTaggedAsync(); var deleted = await Redb.TreeQuery(parent).Where(p => p.Title == tag && p.Count > 0).DeleteAsync(); deleted.Should().Be(2); (await Redb.LoadAsync(parent)).Should().NotBeNull("the filter leaves the parent out (Count 0)"); (await Redb.LoadAsync(child)).Should().BeNull(); (await Redb.LoadAsync(grandchild)).Should().BeNull(); } } Path: redb/redb.Tests.Integration/Tests/Base/DeleteSubtreeCountTestsBase.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/DeleteSubtreeCountTestsBase.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; /// /// DeleteSubtreeAsync answers how many objects of the subtree it deleted, the start object included. It collects the /// subtree first and deletes it after; it used to answer the size of what it collected, so an object another session /// deleted in between was counted too. The delete is put exactly after the collection through the test context. /// public abstract class DeleteSubtreeCountTestsBase { private readonly SqlRecorder _recorder = new(); protected abstract void UseProvider(RedbOptionsBuilder options); protected virtual void Register(IServiceCollection services, Action configure) => services.AddRedb(configure); private ServiceProvider Build(bool decorate) { var services = new ServiceCollection(); services.AddLogging(b => b.SetMinimumLevel(LogLevel.Warning)); Register(services, options => { UseProvider(options); options.Configure(c => c.CacheDomain = $"subtree-count-{GetType().Name}-{Guid.NewGuid():N}"); }); if (decorate) RecordingRedbContext.Decorate(services, _recorder); return services.BuildServiceProvider(); } /// The statement that collects the subtree (Tree_SelectSubtreeRows). private static bool CollectsSubtree(string sql) => sql.Contains("AS IdParent, _id_scheme AS IdScheme, depth AS Depth", StringComparison.Ordinal); /// A root, three children, a grandchild under the first child: five objects. private static async Task<(long Root, long Grandchild)> SeedAsync(IRedbService redb) { await redb.SyncSchemeAsync(); var tag = "subc-" + Guid.NewGuid().ToString("N")[..8]; var root = new TreeRedbObject { name = $"{tag}-root", Props = new SimpleProps { Title = tag } }; root.id = await redb.SaveAsync(root); long firstChild = 0; for (var i = 0; i < 3; i++) { var child = new TreeRedbObject { name = $"{tag}-c{i}", Props = new SimpleProps { Title = tag, Count = i } }; child.id = await redb.CreateChildAsync(child, root); if (i == 0) firstChild = child.id; } var grandchild = new TreeRedbObject { name = $"{tag}-g", Props = new SimpleProps { Title = tag, Count = 9 } }; var parent = new TreeRedbObject { id = firstChild }; grandchild.id = await redb.CreateChildAsync(grandchild, parent); return (root.id, grandchild.id); } [Fact] public async Task DeleteSubtree_CountsEveryObjectOfTheSubtree() { await using var host = Build(decorate: false); var redb = host.GetRequiredService(); await redb.InitializeAsync(ensureCreated: true); var (root, _) = await SeedAsync(redb); var deleted = await redb.DeleteSubtreeAsync(new RedbObject { id = root }); deleted.Should().Be(5); (await redb.LoadAsync(root)).Should().BeNull(); } [Fact] public async Task ObjectDeletedAfterTheSubtreeWasCollected_IsNotCounted() { await using var writerHost = Build(decorate: false); var writer = writerHost.GetRequiredService(); await writer.InitializeAsync(ensureCreated: true); var (root, grandchild) = await SeedAsync(writer); await using var deleterHost = Build(decorate: true); var deleter = deleterHost.GetRequiredService(); await deleter.InitializeAsync(ensureCreated: true); var interleaved = 0; _recorder.AfterQuery = async sql => { if (!CollectsSubtree(sql) || Interlocked.Exchange(ref interleaved, 1) == 1) return; (await writer.DeleteAsync(grandchild)).Should().BeTrue("precondition: the other session deletes the grandchild"); }; int deleted; try { deleted = await deleter.DeleteSubtreeAsync(new RedbObject { id = root }); } finally { _recorder.AfterQuery = null; } interleaved.Should().Be(1, "precondition: the delete ran between the collection and the delete of the subtree"); deleted.Should().Be(4, "the grandchild was deleted by the other session, not by this call"); (await writer.LoadAsync(root)).Should().BeNull(); } } Path: redb/redb.Tests.Integration/Tests/Base/DictionaryEntryKeyFilterTestsBase.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/DictionaryEntryKeyFilterTestsBase.cs ---- using System.Linq.Expressions; using redb.Core; using redb.Core.Models.Entities; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// A filter on a field of a dictionary entry whose value is a class (ByTuple[(2024, "Q1")].Name == v) finds the /// entry by its key as it is stored, for every key type: text, number, tuple, bool, DateTime and double. Each object /// has two entries per dictionary, so a key written in another form than the stored one finds nothing, and a key that /// matched every entry would find the other one too. Compared with the same LINQ over the seeded objects in memory. /// public abstract class DictionaryEntryKeyFilterTestsBase { protected readonly IRedbService Redb; protected DictionaryEntryKeyFilterTestsBase(IRedbService redb) => Redb = redb; private static readonly DateTime DayOne = new(2024, 3, 1, 8, 30, 0, DateTimeKind.Utc); private static readonly DateTime DayTwo = new(2024, 3, 2, 8, 30, 0, DateTimeKind.Utc); private async Task<(string Tag, List Props)> SeedAsync() { await Redb.SyncSchemeAsync(); var tag = "dk-" + Guid.NewGuid().ToString("N")[..8]; var props = new List(); for (var i = 0; i < 4; i++) { var hit = i % 2 == 0 ? $"{tag}-hit" : $"{tag}-miss"; KeyedEntry First() => new() { Name = hit, Rank = i }; KeyedEntry Second() => new() { Name = $"{tag}-second", Rank = 10 + i }; var p = new DictionaryKeyProps { Marker = tag, ByText = new() { ["a"] = First(), ["b"] = Second() }, ByNumber = new() { [1] = First(), [2] = Second() }, ByTuple = new() { [(2024, "Q1")] = First(), [(2024, "Q2")] = Second() }, ByFlag = new() { [true] = First(), [false] = Second() }, ByDate = new() { [DayOne] = First(), [DayTwo] = Second() }, ByRatio = new() { [0.1] = First(), [2.25] = Second() } }; await Redb.SaveAsync(new RedbObject { name = $"{tag}-{i}", Props = p }); props.Add(p); } return (tag, props); } private async Task MatchesLinqAsync(Func>> filterOf) { var (tag, seeded) = await SeedAsync(); var filter = filterOf(tag + "-hit"); var expected = seeded.Where(filter.Compile()).Select(p => p.ByNumber![1].Rank).ToList(); expected.Should().HaveCount(2, "precondition"); var query = Redb.Query().Where(p => p.Marker == tag).Where(filter); (await query.ToListAsync()).Select(o => o.Props.ByNumber![1].Rank).Should().BeEquivalentTo(expected); (await query.CountAsync()).Should().Be(2); } [Fact] public Task TextKey() => MatchesLinqAsync(v => p => p.ByText!["a"].Name == v); [Fact] public Task NumberKey() => MatchesLinqAsync(v => p => p.ByNumber![1].Name == v); [Fact] public Task TupleKey() { // An expression tree takes no tuple literal: the key is a captured value, as in a query of an application. var quarter = (2024, "Q1"); return MatchesLinqAsync(v => p => p.ByTuple![quarter].Name == v); } [Fact] public Task BoolKey() => MatchesLinqAsync(v => p => p.ByFlag![true].Name == v); [Fact] public Task DateTimeKey() => MatchesLinqAsync(v => p => p.ByDate![DayOne].Name == v); [Fact] // 0.1 is stored in its round-trip form (0.10000000000000001), which ToString() does not give. public Task DoubleKey() => MatchesLinqAsync(v => p => p.ByRatio![0.1].Name == v); } Path: redb/redb.Tests.Integration/Tests/Base/DictionaryEntryLeadsTestsBase.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/DictionaryEntryLeadsTestsBase.cs ---- using redb.Core; using redb.Core.Models.Entities; using redb.Core.Query; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// A condition on the value of a dictionary entry, Dict[key] == x, is a leaf the index of values can lead, like a scalar /// equality: the entry is one row per object, its key on the row. Before, the general form read every entry of the key /// and sorted them. The answers must not change: every query here runs with the planner off and on and is compared with /// the answer computed from the loaded objects, at a value on 1 % and on a third of the objects, sorted by id and by /// another field. Every other key holds the same values, so a lost key cannot pass. /// public abstract class DictionaryEntryLeadsTestsBase { private const int Objects = 300; private static readonly SemaphoreSlim SeedLock = new(1, 1); protected readonly IRedbService Redb; protected DictionaryEntryLeadsTestsBase(IRedbService redb) => Redb = redb; private static readonly (int Year, string Quarter) Q1 = (2024, "Q1"); // 1 % rare, a third wide, the rest other; the same three values under the second key, shifted. private static string Grade(int i) => i % 100 == 0 ? "rare" : i % 3 == 0 ? "wide" : "other"; private async Task>> SeedAsync() { await SeedLock.WaitAsync(); try { var all = await Redb.Query().ToListAsync(); if (all.Count == Objects) return all; if (all.Count > 0) await Redb.DeleteAsync(all.Select(o => o.Id).ToList()); var objects = Enumerable.Range(0, Objects).Select(i => new RedbObject { name = $"dict-entry-{i:000}", Props = new DictionaryEntryLeadsProps { Rank = (i * 7) % Objects, // No Tag and no 2024-Q1 entry on every tenth object: the leaf's row is missing there. Tag = i % 10 == 5 ? null : Grade(i), Reviews = i % 10 == 5 ? new() { [(2024, "Q2")] = Grade(i + 1) } : new() { [Q1] = Grade(i), [(2024, "Q2")] = Grade(i + 1) }, Scores = new() { ["math"] = i, ["art"] = Objects - 1 - i }, Places = new() { ["home"] = new DictionaryEntryPlace { City = Grade(i), Floor = i % 5 }, ["work"] = new DictionaryEntryPlace { City = Grade(i + 1), Floor = i % 7 } } } }).ToList(); await Redb.SaveAsync(objects); all = await Redb.Query().ToListAsync(); all.Should().HaveCount(Objects); return all; } finally { SeedLock.Release(); } } private async Task EachFormAsync(Func check) { var restore = Redb.Configuration.EnablePvtPrefilter; try { foreach (var on in new[] { false, true }) { Redb.UpdateConfiguration(c => c.EnablePvtPrefilter = on); await check(on ? "planner on" : "planner off"); } } finally { Redb.UpdateConfiguration(c => c.EnablePvtPrefilter = restore); } } private static List ById(IEnumerable> all, Func keep, int take) => all.Where(o => keep(o.Props)).Select(o => o.Id).OrderBy(id => id).Take(take).ToList(); private static List ByRank(IEnumerable> all, Func keep, int take) => all.Where(o => keep(o.Props)).OrderBy(o => o.Props.Rank).ThenBy(o => o.Id).Select(o => o.Id).Take(take).ToList(); private static string? Review(DictionaryEntryLeadsProps p, (int Year, string Quarter) key) => p.Reviews != null && p.Reviews.TryGetValue(key, out var v) ? v : null; /// /// A page ordered by the id alone and led by an equality, on a scalar and on a dictionary entry, with Skip and both /// directions: SQLite reads the ids off the row of the equality's field (its index of values is in object order within /// the value). Every tenth object has no such row at all, which the equality must keep out as before. /// [Theory] [InlineData("rare", 0)] [InlineData("wide", 0)] [InlineData("wide", 25)] public async Task PageById_LedByEquality_SkipAndMissingRows(string grade, int skip) { var all = await SeedAsync(); var key = Q1; List Expected(Func keep, bool descending) { var ids = all.Where(o => keep(o.Props)).Select(o => o.Id); return (descending ? ids.OrderByDescending(id => id) : ids.OrderBy(id => id)).Skip(skip).Take(10).ToList(); } await EachFormAsync(async form => { foreach (var descending in new[] { false, true }) { var scalar = Redb.Query().Where(p => p.Tag == grade); var scalarPage = await (descending ? scalar.OrderByDescendingRedb(o => o.Id) : scalar.OrderByRedb(o => o.Id)) .Skip(skip).Take(10).ToListAsync(); scalarPage.Select(o => o.Id).Should().Equal(Expected(p => p.Tag == grade, descending), $"scalar {grade}, skip {skip}, {(descending ? "desc" : "asc")}, {form}"); var entry = Redb.Query().Where(p => p.Reviews![key] == grade); var entryPage = await (descending ? entry.OrderByDescendingRedb(o => o.Id) : entry.OrderByRedb(o => o.Id)) .Skip(skip).Take(10).ToListAsync(); entryPage.Select(o => o.Id).Should().Equal(Expected(p => Review(p, key) == grade, descending), $"entry {grade}, skip {skip}, {(descending ? "desc" : "asc")}, {form}"); } }); } [Theory] [InlineData("rare")] [InlineData("wide")] public async Task TupleKey_Equality_ById_AndByAnotherField(string grade) { var all = await SeedAsync(); var key = Q1; bool Keep(DictionaryEntryLeadsProps p) => p.Reviews != null && p.Reviews.TryGetValue(key, out var v) && v == grade; await EachFormAsync(async form => { var byId = await Redb.Query().Where(p => p.Reviews![key] == grade) .OrderByRedb(o => o.Id).Take(10).ToListAsync(); byId.Select(o => o.Id).Should().Equal(ById(all, Keep, 10), $"by id, {grade}, {form}"); var byRank = await Redb.Query().Where(p => p.Reviews![key] == grade) .OrderBy(p => p.Rank).ThenByRedb(o => o.Id).Take(10).ToListAsync(); byRank.Select(o => o.Id).Should().Equal(ByRank(all, Keep, 10), $"by rank, {grade}, {form}"); (await Redb.Query().Where(p => p.Reviews![key] == grade).CountAsync()) .Should().Be(all.Count(o => Keep(o.Props)), $"count, {grade}, {form}"); (await Redb.Query().Where(p => p.Reviews![key] == grade).AnyAsync()) .Should().BeTrue($"any, {grade}, {form}"); }); } [Theory] [InlineData(297, 1000)] // 1 % [InlineData(0, 99)] // a third public async Task TextKey_NumberRange_ById_AndByAnotherField(int from, int to) { var all = await SeedAsync(); decimal lo = from, hi = to; bool Keep(DictionaryEntryLeadsProps p) => p.Scores != null && p.Scores.TryGetValue("math", out var v) && v >= lo && v <= hi; await EachFormAsync(async form => { var byId = await Redb.Query().Where(p => p.Scores!["math"] >= lo && p.Scores!["math"] <= hi) .OrderByRedb(o => o.Id).Take(10).ToListAsync(); byId.Select(o => o.Id).Should().Equal(ById(all, Keep, 10), $"by id, {from}-{to}, {form}"); var byRank = await Redb.Query().Where(p => p.Scores!["math"] >= lo && p.Scores!["math"] <= hi) .OrderBy(p => p.Rank).ThenByRedb(o => o.Id).Take(10).ToListAsync(); byRank.Select(o => o.Id).Should().Equal(ByRank(all, Keep, 10), $"by rank, {from}-{to}, {form}"); var open = await Redb.Query().Where(p => p.Scores!["math"] >= lo) .OrderByRedb(o => o.Id).Take(10).ToListAsync(); open.Select(o => o.Id).Should().Equal( ById(all, p => p.Scores != null && p.Scores.TryGetValue("math", out var v) && v >= lo, 10), $"open range, {from}, {form}"); }); } [Theory] [InlineData("rare")] [InlineData("wide")] public async Task ClassValueField_Equality_SameAnswer(string grade) { var all = await SeedAsync(); bool Keep(DictionaryEntryLeadsProps p) => p.Places != null && p.Places.TryGetValue("home", out var v) && v.City == grade; await EachFormAsync(async form => { var byId = await Redb.Query().Where(p => p.Places!["home"].City == grade) .OrderByRedb(o => o.Id).Take(10).ToListAsync(); byId.Select(o => o.Id).Should().Equal(ById(all, Keep, 10), $"by id, {grade}, {form}"); var byRank = await Redb.Query().Where(p => p.Places!["home"].City == grade) .OrderBy(p => p.Rank).ThenByRedb(o => o.Id).Take(10).ToListAsync(); byRank.Select(o => o.Id).Should().Equal(ByRank(all, Keep, 10), $"by rank, {grade}, {form}"); }); } [Fact] public async Task EntryNextToAnotherCondition_AndAll_SameAnswer() { var all = await SeedAsync(); var key = Q1; await EachFormAsync(async form => { var both = await Redb.Query().Where(p => p.Reviews![key] == "wide" && p.Scores!["art"] < 150m) .OrderByRedb(o => o.Id).Take(10).ToListAsync(); both.Select(o => o.Id).Should().Equal(ById(all, p => Review(p, key) == "wide" && p.Scores!["art"] < 150m, 10), $"entry and entry, {form}"); var withRank = await Redb.Query().Where(p => p.Reviews![key] == "wide" && p.Rank < 30) .OrderBy(p => p.Rank).ThenByRedb(o => o.Id).Take(10).ToListAsync(); withRank.Select(o => o.Id).Should().Equal(ByRank(all, p => Review(p, key) == "wide" && p.Rank < 30, 10), $"entry and scalar, {form}"); var either = await Redb.Query().Where(p => p.Reviews![key] == "rare" || p.Scores!["math"] == 5m) .OrderByRedb(o => o.Id).Take(10).ToListAsync(); either.Select(o => o.Id).Should().Equal(ById(all, p => Review(p, key) == "rare" || p.Scores!["math"] == 5m, 10), $"entry or entry, {form}"); // On the key every object holds: an absent entry makes no comparison true, so All over 2024-Q1 would be false. var everyone = (Year: 2024, Quarter: "Q2"); (await Redb.Query().AllAsync(p => p.Reviews![everyone] != "missing")) .Should().BeTrue($"all, {form}"); (await Redb.Query().AllAsync(p => p.Reviews![everyone] == "wide")) .Should().BeFalse($"all, {form}"); }); } } Path: redb/redb.Tests.Integration/Tests/Base/DictionaryOrderTestsBase.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/DictionaryOrderTestsBase.cs ---- using redb.Core; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// A dictionary reads back with its entries in the order of their keys, at the top level and inside an element of an /// array of classes, by a load and by a query, the same on every provider. The entries came in the order of the rows /// of the read in Pro (which moved between reads and between its planner modes) and of the JSON the free modules built: /// by key length on PostgreSQL, by the collation of the key text on SQL Server (Zulu after zeta). SQLite Free already /// listed them by key. /// public abstract class DictionaryOrderTestsBase { protected readonly IRedbService Redb; protected DictionaryOrderTestsBase(IRedbService redb) => Redb = redb; private static readonly string[] TopKeys = ["zeta", "alpha", "mu", "beta", "omega", "kappa", "Zulu"]; private static readonly int[] NumberKeys = [10, 2, -3, 100, 0, 21]; private static readonly string[] LabelKeys = ["z", "a", "m", "b", "y", "c"]; private static DictionaryOrderProps Sample(string tag, int n) => new() { Tag = tag, Top = TopKeys.Select((k, i) => (k, i)).ToDictionary(e => e.k, e => e.i + n), Numbered = NumberKeys.ToDictionary(k => k, k => $"{k}-{n}"), Rows = [ new() { Name = "r0", Labels = LabelKeys.ToDictionary(k => k, k => k + n) }, new() { Name = "r1", Labels = LabelKeys.Reverse().ToDictionary(k => k, k => k + n) }, ] }; private static void AssertKeyOrder(DictionaryOrderProps props, int n) { props.Top!.Keys.Should().Equal(TopKeys.Order(StringComparer.Ordinal)); props.Top.Should().BeEquivalentTo(Sample(props.Tag, n).Top); props.Numbered!.Keys.Should().Equal(NumberKeys.Order()); props.Rows![0].Labels!.Keys.Should().Equal(LabelKeys.Order(StringComparer.Ordinal)); props.Rows![1].Labels!.Keys.Should().Equal(LabelKeys.Order(StringComparer.Ordinal)); } [Fact] public async Task Dictionary_ReadsBackInTheOrderOfItsKeys() { await Redb.SyncSchemeAsync(); var tag = "dor-" + Guid.NewGuid().ToString("N")[..8]; var objects = Enumerable.Range(0, 5) .Select(n => (IRedbObject)new RedbObject { name = $"{tag}-{n}", Props = Sample(tag, n) }) .ToList(); await Redb.SaveAsync(objects); for (var n = 0; n < objects.Count; n++) AssertKeyOrder((await Redb.LoadAsync(objects[n].Id))!.Props, n); var queried = await Redb.Query().Where(p => p.Tag == tag).ToListAsync(); queried.Should().HaveCount(objects.Count); foreach (var o in queried) AssertKeyOrder(o.Props, int.Parse(o.name[(tag.Length + 1)..])); } } Path: redb/redb.Tests.Integration/Tests/Base/DictionaryTestsBase.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/DictionaryTestsBase.cs ---- using redb.Core; using redb.Core.Exceptions; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using redb.Tests.Integration.Helpers; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// Dictionary querying tests — ContainsKey, indexer, nested. /// public abstract class DictionaryTestsBase { protected readonly IRedbService Redb; protected DictionaryTestsBase(IRedbService redb) => Redb = redb; private async Task> SeedAsync() { return await TestDataFactory.SeedEmployees(Redb, 20); } [Fact] public async Task DictContainsKey_Filters() { var ids = await SeedAsync(); var results = await Redb.Query() .Where(e => e.PhoneDirectory!.ContainsKey("desk")) .Take(20) .ToListAsync(); results.Should().NotBeEmpty(); results.Should().AllSatisfy(r => r.Props.PhoneDirectory.Should().ContainKey("desk")); } [Fact] public async Task DictIndexer_ValueComparison() { var ids = await SeedAsync(); var results = await Redb.Query() .Where(e => e.BonusByYear![2023] > 5000m) .Take(20) .ToListAsync(); results.Should().NotBeEmpty(); results.Should().AllSatisfy(r => r.Props.BonusByYear![2023].Should().BeGreaterThan(5000m)); } [Fact] public async Task DictNestedClassProperty_Filters() { var ids = await SeedAsync(); var results = await Redb.Query() .Where(e => e.OfficeLocations!["HQ"].City == "New York") .Take(20) .ToListAsync(); results.Should().NotBeEmpty(); results.Should().AllSatisfy(r => r.Props.OfficeLocations!["HQ"].City.Should().Be("New York")); } [Fact] public async Task DictTupleKey_Filters() { var ids = await SeedAsync(); var reviewKey = (Year: 2024, Quarter: "Q1"); var results = await Redb.Query() .Where(e => e.PerformanceReviews![reviewKey] == "Excellent") .Take(20) .ToListAsync(); results.Should().NotBeEmpty(); results.Should().AllSatisfy(r => r.Props.PerformanceReviews![(2024, "Q1")].Should().Be("Excellent")); } /// /// The provider's bound on a dictionary key (_array_index), or null when it has none. SQL Server: 430 /// (NVARCHAR(430)); PostgreSQL and SQLite: unbounded text. /// protected virtual int? DictionaryKeyBound => null; private static RedbObject EmployeeWithKey(int index, string key) { var employee = TestDataFactory.CreateEmployee(index); employee.Props.PhoneDirectory = new Dictionary { ["desk"] = "100", [key] = "200" }; return employee; } [Fact] public async Task DictKeyOverTheProviderBound_IsRefusedBeforeTheWrite_OnEverySavePath() { var bound = DictionaryKeyBound ?? 430; var tooLong = new string('k', bound + 1); var fits = new string('f', bound); // An object already stored: a refused re-save must leave its dictionary as it was. var stored = EmployeeWithKey(9100, "home"); var storedId = await Redb.SaveAsync(stored); stored.Props.PhoneDirectory![tooLong] = "300"; Func resave = () => Redb.SaveAsync(stored); Func single = () => Redb.SaveAsync(EmployeeWithKey(9101, tooLong)); Func batch = () => Redb.SaveAsync(new List> { EmployeeWithKey(9102, "a"), EmployeeWithKey(9103, tooLong) }); Func addNew = () => Redb.AddNewObjectsAsync(new List> { EmployeeWithKey(9104, tooLong) }); if (DictionaryKeyBound is { } limit) { foreach (var act in new[] { resave, single, batch, addNew }) { var refused = (await act.Should().ThrowAsync()).Which; refused.Length.Should().Be(limit + 1); refused.Limit.Should().Be(limit); refused.Property.Should().Be(nameof(EmployeeProps.PhoneDirectory)); } var reloaded = await Redb.LoadAsync(storedId); reloaded!.Props.PhoneDirectory.Should().BeEquivalentTo( new Dictionary { ["desk"] = "100", ["home"] = "200" }, "the refusal comes before any row of the save is written"); } else { foreach (var act in new[] { resave, single, batch, addNew }) await act.Should().NotThrowAsync("this provider stores keys of any length"); var reloaded = await Redb.LoadAsync(storedId); reloaded!.Props.PhoneDirectory.Should().ContainKey(tooLong); } var fitId = await Redb.SaveAsync(EmployeeWithKey(9105, fits)); (await Redb.LoadAsync(fitId))!.Props.PhoneDirectory.Should().ContainKey(fits, "a key exactly at the bound fits"); } } Path: redb/redb.Tests.Integration/Tests/Base/DisposedScopeGuardTestsBase.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/DisposedScopeGuardTestsBase.cs ---- using Microsoft.Extensions.DependencyInjection; using redb.Core.Data; namespace redb.Tests.Integration.Tests.Base; /// /// A context whose DI scope has ended must refuse to work, not quietly open a fresh physical /// connection on behalf of a dead scope. Before the fix, GetOpenConnectionAsync saw the /// null left behind by Dispose and re-opened: the new connection belonged to nobody, the /// second Dispose was a no-op, and the pool slot was gone for the life of the process (a consumer's production database, /// 2026-09: ~30 idle PostgreSQL sessions a day until restart). /// public abstract class DisposedScopeGuardTestsBase { private readonly IServiceProvider _root; protected DisposedScopeGuardTestsBase(IServiceProvider root) => _root = root; [Fact] public async Task Context_AfterItsScopeIsDisposed_ThrowsInsteadOfReopening() { var scope = _root.CreateAsyncScope(); var ctx = scope.ServiceProvider.GetRequiredService(); // The context has a live connection now; the scope then ends. (await ctx.ExecuteScalarAsync("SELECT 1")).Should().Be(1); await scope.DisposeAsync(); ctx.IsDisposed.Should().BeTrue(); var act = () => ctx.ExecuteScalarAsync("SELECT 1"); await act.Should().ThrowAsync( "a disposed context must fail loudly; re-opening a connection here leaks it for the life of the process"); } } Path: redb/redb.Tests.Integration/Tests/Base/ElementFoldOrderTestsBase.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/ElementFoldOrderTestsBase.cs ---- using Microsoft.Extensions.DependencyInjection; using redb.Core; using redb.Core.Models.Entities; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// DistinctBy and OrderBy over a whole collection field read the collection folded into one key, its elements in index /// order (a dictionary: its values in key order). Every path that reads the key - the pivot, the streams form, the plain /// sort with no pivot at all - must read the same key, so equal lists are one key and the sort follows the folded list. /// public abstract class ElementFoldOrderTestsBase : IAsyncLifetime { private readonly IServiceProvider _services; private string _clearSql = ""; protected ElementFoldOrderTestsBase(IServiceProvider services) => _services = services; // The two schemes are this class's own: every object in them is removed before and after each test. public async Task InitializeAsync() { await using var scope = _services.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); var lists = await redb.SyncSchemeAsync(); var dictionaries = await redb.SyncSchemeAsync(); _clearSql = $"DELETE FROM _objects WHERE _id_scheme IN ({lists.Id}, {dictionaries.Id})"; await redb.Context.ExecuteAsync(_clearSql); } public async Task DisposeAsync() { await using var scope = _services.CreateAsyncScope(); await scope.ServiceProvider.GetRequiredService().Context.ExecuteAsync(_clearSql); } private static RedbObject Item(string name, params string[] tags) => new() { Name = name, Props = new ElementFoldOrderProps { Label = "x", Tags = tags.ToList() } }; // a and b hold one list (b written by the bulk path); c has the same elements in another order; d shares the first // element. The keys sort a,b < a,z < b,a < t1,t2,t3 < t3,t1,t2 (a, b) < t3,t9 as joined text, as an array and as a // JSON array alike. private static async Task SeedListsAsync(IRedbService redb) { await redb.SaveAsync(Item("a", "t3", "t1", "t2")); await redb.AddNewObjectsAsync(new[] { Item("b", "t3", "t1", "t2") }); await redb.SaveAsync(Item("c", "t1", "t2", "t3")); await redb.SaveAsync(Item("d", "t3", "t9")); await redb.SaveAsync(Item("e", "b", "a")); await redb.SaveAsync(Item("f", "a", "z")); await redb.SaveAsync(Item("g", "a", "b")); } private static void ShouldBeSixKeys(IEnumerable names) { var list = names.ToList(); list.Should().HaveCount(6, "a and b hold one list; every other list is a key of its own"); list.Count(n => n is "a" or "b").Should().Be(1); list.Should().Contain(new[] { "c", "d", "e", "f", "g" }); } [Fact] public async Task DistinctBy_OverAWholeList_EqualListsAreOneKey_AndASortByItFollowsTheList() { await using var scope = _services.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); await SeedListsAsync(redb); ShouldBeSixKeys((await redb.Query().DistinctBy(x => x.Tags).ToListAsync()).Select(o => o.Name)); var ordered = await redb.Query().DistinctBy(x => x.Tags).OrderBy(x => x.Tags).ToListAsync(); ordered.Select(o => o.Name is "b" ? "a" : o.Name).Should().Equal("g", "f", "e", "c", "a", "d"); } [Fact] public async Task DistinctBy_OverAWholeList_UnderAPropsFilterAndAPage_ReadsTheSameKey() { await using var scope = _services.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); await SeedListsAsync(redb); var page = await redb.Query() .Where(x => x.Label == "x").DistinctBy(x => x.Tags).Take(100).ToListAsync(); ShouldBeSixKeys(page.Select(o => o.Name)); } [Fact] public async Task OrderBy_OverAWholeList_WithNoFilter_SortsByTheListInIndexOrder() { await using var scope = _services.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); await SeedListsAsync(redb); for (var run = 0; run < 2; run++) { var ordered = await redb.Query().OrderBy(x => x.Tags).ThenByRedb(o => o.Id).ToListAsync(); ordered.Select(o => o.Name).Should().Equal(new[] { "g", "f", "e", "c", "a", "b", "d" }, "the keys are a,b < a,z < b,a < t1,t2,t3 < t3,t1,t2 (twice, by id) < t3,t9"); } var page = await redb.Query().OrderBy(x => x.Tags).ThenByRedb(o => o.Id).Take(3).ToListAsync(); page.Select(o => o.Name).Should().Equal("g", "f", "e"); } [Fact] public async Task OrderBy_OverAWholeDictionary_SortsByItsValuesInKeyOrder() { await using var scope = _services.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); // Values in key order: h -> 2,1; i -> 1,9; j -> 1,2. Keys inserted out of order on purpose. await redb.SaveAsync(new RedbObject { Name = "h", Props = new() { Codes = new() { ["b"] = "1", ["a"] = "2" } } }); await redb.SaveAsync(new RedbObject { Name = "i", Props = new() { Codes = new() { ["b"] = "9", ["a"] = "1" } } }); await redb.SaveAsync(new RedbObject { Name = "j", Props = new() { Codes = new() { ["a"] = "1", ["b"] = "2" } } }); var ordered = await redb.Query().OrderBy(x => x.Codes).ThenByRedb(o => o.Id).ToListAsync(); ordered.Select(o => o.Name).Should().Equal(new[] { "j", "i", "h" }, "the keys are 1,2 < 1,9 < 2,1"); } } Path: redb/redb.Tests.Integration/Tests/Base/ElementIndexFilterTestsBase.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/ElementIndexFilterTestsBase.cs ---- using System.Linq.Expressions; using redb.Core; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// A filter of redb Pro reads an element of an array or a list by its index: the element itself (Levels[0] == 5) /// or one field of an element of a class (Items[0].Name == v). An element past the end is no value, as a missing /// dictionary key or a missing field is: == and != leave the object out, == null takes it. The /// expected answers are written out per case (LINQ to objects would throw on an index past the end). /// /// Four objects, Marker o0..o3; the object's own Name and Rank differ from every element's: /// o0: Levels [5, 1], Tags [a, b], Items/Parts [(x0, 1, null), (y0, 2, 3)], Statuses [Admin, User]; /// o1: Levels [1, 5], Tags [b, a], Items/Parts [(y1, 2, 4), (x1, 1, null)], Statuses [User]; /// o2: Levels [5], Tags [a], Items/Parts [(x2, 3, 7)], Statuses []; /// o3: no arrays. /// public abstract class ElementIndexFilterTestsBase { protected readonly IRedbService Redb; protected ElementIndexFilterTestsBase(IRedbService redb) => Redb = redb; private async Task<(string Tag, RedbList List)> SeedAsync() { await Redb.SyncSchemeAsync(); var tag = "ei-" + Guid.NewGuid().ToString("N")[..8]; var list = await Redb.ListProvider.SaveListAsync(RedbList.Create(tag, tag)); var items = await Redb.ListProvider.AddItemsAsync(list, ["Admin", "User"]); var admin = items.First(i => i.Value == "Admin"); var user = items.First(i => i.Value == "User"); static ElementIndexItem[] Elements(params (string Name, int Rank, int? Score)[] e) => e.Select(x => new ElementIndexItem { Name = x.Name, Rank = x.Rank, Score = x.Score }).ToArray(); var props = new[] { new ElementIndexProps { Levels = [5, 1], Tags = ["a", "b"], Items = Elements(("x0", 1, null), ("y0", 2, 3)), Statuses = [admin, user] }, new ElementIndexProps { Levels = [1, 5], Tags = ["b", "a"], Items = Elements(("y1", 2, 4), ("x1", 1, null)), Statuses = [user] }, new ElementIndexProps { Levels = [5], Tags = ["a"], Items = Elements(("x2", 3, 7)), Statuses = [] }, new ElementIndexProps() }; for (var i = 0; i < props.Length; i++) { props[i].Marker = tag; props[i].Name = "own"; props[i].Rank = 9; props[i].Parts = props[i].Items?.Select(e => new ElementIndexItem { Name = e.Name, Rank = e.Rank, Score = e.Score }).ToList(); await Redb.SaveAsync(new RedbObject { name = $"o{i}", Props = props[i] }); } return (tag, list); } private async Task NamesAsync(string tag, Expression> filter) => (await Redb.Query().Where(p => p.Marker == tag).Where(filter).ToListAsync()) .Select(o => o.name!).OrderBy(n => n).ToArray(); private async Task CleanupAsync(RedbList list) { var items = await Redb.ListProvider.GetListItemsAsync(list.Id); await Redb.Context.Bulk.BulkDeleteValuesByListItemIdsAsync(items.Select(i => i.Id).ToList()); await Redb.ListProvider.DeleteListAsync(list.Id); } public static IEnumerable ReadCases() { static object[] Case(string kind, Expression> filter, params string[] names) => [kind, filter, names]; // The element itself: an array and a list of simple values. yield return Case("array-first", p => p.Levels![0] == 5, "o0", "o2"); yield return Case("array-second", p => p.Levels![1] == 5, "o1"); yield return Case("array-range", p => p.Levels![0] > 1, "o0", "o2"); yield return Case("list-first", p => p.Tags![0] == "a", "o0", "o2"); yield return Case("list-second-not-equal", p => p.Tags![1] != "a", "o0"); // A field of an element of a class: an array and a list. yield return Case("array-field", p => p.Items![0].Name == "x0", "o0"); yield return Case("array-field-second", p => p.Items![1].Rank == 1, "o1"); yield return Case("array-field-range", p => p.Items![0].Rank > 1, "o1", "o2"); yield return Case("list-field", p => p.Parts![0].Name == "y1", "o1"); yield return Case("list-field-second", p => p.Parts![1].Name == "y0", "o0"); yield return Case("field-string-function", p => p.Items![0].Name.StartsWith("x"), "o0", "o2"); yield return Case("field-nullable-value", p => p.Items![0].Score!.Value == 7, "o2"); yield return Case("field-and-own-field", p => p.Items![0].Rank == 1 && p.Rank == 9, "o0"); yield return Case("two-elements", p => p.Items![0].Rank == 2 && p.Items![1].Rank == 1, "o1"); // A missing value: a null field of an element, an element past the end. One rule for both, as for a missing // dictionary key: no value matches neither == nor !=, and == null takes it. yield return Case("field-null", p => p.Items![0].Score == null, "o0", "o3"); yield return Case("field-not-null", p => p.Items![0].Score != null, "o1", "o2"); yield return Case("past-end-equal", p => p.Items![5].Name == "x0"); yield return Case("past-end-not-equal", p => p.Items![5].Name != "x0"); yield return Case("past-end-null", p => p.Items![5].Name == null, "o0", "o1", "o2", "o3"); yield return Case("second-missing-not-equal", p => p.Items![1].Name != "x1", "o0"); yield return Case("second-missing-null", p => p.Items![1].Name == null, "o2", "o3"); yield return Case("element-past-end-null", p => p.Tags![2] == null, "o0", "o1", "o2", "o3"); yield return Case("element-missing-null", p => p.Tags![1] == null, "o2", "o3"); yield return Case("class-element-present", p => p.Items![1] != null, "o0", "o1"); yield return Case("class-element-missing", p => p.Items![1] == null, "o2", "o3"); yield return Case("element-missing-not-equal", p => p.Levels![1] != 5, "o0"); } [Theory] [MemberData(nameof(ReadCases))] public async Task ElementByIndex_IsRead(string kind, Expression> filter, string[] expected) { var (tag, list) = await SeedAsync(); try { (await NamesAsync(tag, filter)).Should().Equal(expected.OrderBy(n => n), $"case {kind}"); } finally { await CleanupAsync(list); } } /// /// The same null rule when the element field is the only Props condition (the objects picked by id): SQL Server Pro /// without the planner read such a filter from the entries that have a value under them and answered no object. /// [Fact] public async Task NullCheck_OnTheOnlyPropsCondition_TakesTheObjectsWithoutAValue() { var (tag, list) = await SeedAsync(); try { var ids = (await Redb.Query().Where(p => p.Marker == tag).ToListAsync()).Select(o => o.id).ToList(); async Task Names(Expression> filter) => (await Redb.Query().WhereInRedb(o => o.Id, ids).Where(filter).ToListAsync()) .Select(o => o.name!).OrderBy(n => n).ToArray(); (await Names(p => p.Items![1].Name == null)).Should().Equal("o2", "o3"); (await Names(p => p.Items![0].Score == null)).Should().Equal("o0", "o3"); (await Names(p => p.Items![1].Name != "x1")).Should().Equal("o0"); (await Names(p => p.Items![1].Name == "x1")).Should().Equal("o1"); } finally { await CleanupAsync(list); } } [Fact] public async Task Index_FromAVariable_IsRead() { var (tag, list) = await SeedAsync(); try { var second = 1; (await NamesAsync(tag, p => p.Items![second].Rank == 1)).Should().Equal("o1"); (await NamesAsync(tag, p => p.Levels![second] == 5)).Should().Equal("o1"); } finally { await CleanupAsync(list); } } public static IEnumerable RefusedCases() { static object[] Case(string kind, Expression> filter) => [kind, filter]; // An element that is a list item is not read by index: Any(s => s.Value == v) asks for it in any position. yield return Case("list-item-element", p => p.Statuses![0].Value == "Admin"); yield return Case("negative-index", p => p.Items![-1].Name == "x0"); yield return Case("index-from-the-object", p => p.Items![p.Rank].Name == "x0"); yield return Case("nested-class-in-element", p => p.Items![0].Inner!.Name == "x"); yield return Case("array-in-element", p => p.Items![0].Marks![0] == 1); yield return Case("first", p => p.Items!.First().Name == "x0"); yield return Case("element-at", p => p.Items!.ElementAt(0).Name == "x0"); } [Theory] [MemberData(nameof(RefusedCases))] public async Task ElementPathItCannotRead_IsRefused(string kind, Expression> filter) { await Redb.SyncSchemeAsync(); var act = () => Redb.Query().Where(filter).ToListAsync(); var ex = (await act.Should().ThrowAsync($"case {kind}")).Which; ex.Message.Should().StartWith("A query cannot read", $"case {kind}"); } [Fact] public async Task SortByAnElement_IsRefused() { await Redb.SyncSchemeAsync(); var act = () => Redb.Query().OrderBy(p => p.Items![0].Rank).ToListAsync(); await act.Should().ThrowAsync(); } } Path: redb/redb.Tests.Integration/Tests/Base/EnumComparisonTestsBase.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/EnumComparisonTestsBase.cs ---- using System.Linq.Expressions; using redb.Core; using redb.Core.Models.Entities; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// A filter on an enum field, nullable or not, with a constant or a captured value, by == and !=, against null, and in a /// Contains: each returns the ids the same filter returns on the text twin that holds the stored name. /// public abstract class EnumComparisonTestsBase { protected readonly IRedbService Redb; protected EnumComparisonTestsBase(IRedbService redb) => Redb = redb; [Fact] public async Task EnumFilters_ReturnTheIdsOfTheSameFilterOnTheStoredName() { await Redb.SyncSchemeAsync(); var tag = $"enum-cmp-{Guid.NewGuid():N}"; var shades = new ComparisonShade?[] { ComparisonShade.Red, ComparisonShade.Green, ComparisonShade.Blue, null }; var objects = Enumerable.Range(0, 8).Select(i => { var maybe = shades[i % 4]; var always = (ComparisonShade)(i % 3); return new RedbObject { name = $"{tag}-{i}", Props = new EnumComparisonProps { Tag = tag, Maybe = maybe, MaybeName = maybe?.ToString(), Always = always, AlwaysName = always.ToString(), } }; }).ToList(); await Redb.SaveAsync(objects); ComparisonShade? maybeGreen = ComparisonShade.Green; var green = ComparisonShade.Green; ComparisonShade? noShade = null; var nullable = new List { ComparisonShade.Red, ComparisonShade.Blue }; var plain = new List { ComparisonShade.Red, ComparisonShade.Blue }; var names = new List { "Red", "Blue" }; var cases = new (string Name, Expression> Enum, Expression> Text)[] { ("nullable == constant", p => p.Maybe == ComparisonShade.Green, p => p.MaybeName == "Green"), ("nullable != constant", p => p.Maybe != ComparisonShade.Green, p => p.MaybeName != "Green"), ("constant == nullable", p => ComparisonShade.Green == p.Maybe, p => p.MaybeName == "Green"), ("nullable == captured nullable", p => p.Maybe == maybeGreen, p => p.MaybeName == "Green"), ("nullable != captured nullable", p => p.Maybe != maybeGreen, p => p.MaybeName != "Green"), ("nullable == captured plain", p => p.Maybe == green, p => p.MaybeName == "Green"), ("nullable == null", p => p.Maybe == null, p => p.MaybeName == null), ("nullable != null", p => p.Maybe != null, p => p.MaybeName != null), ("nullable == captured null", p => p.Maybe == noShade, p => p.MaybeName == null), ("nullable in Contains", p => nullable.Contains(p.Maybe), p => names.Contains(p.MaybeName)), ("plain == constant", p => p.Always == ComparisonShade.Green, p => p.AlwaysName == "Green"), ("plain != constant", p => p.Always != ComparisonShade.Green, p => p.AlwaysName != "Green"), ("plain == captured", p => p.Always == green, p => p.AlwaysName == "Green"), ("plain != captured", p => p.Always != green, p => p.AlwaysName != "Green"), ("plain in Contains", p => plain.Contains(p.Always), p => names.Contains(p.AlwaysName)), }; var failures = new List(); foreach (var (name, byEnum, byText) in cases) { var expected = await IdsAsync(tag, byText); try { var got = await IdsAsync(tag, byEnum); if (!got.SequenceEqual(expected)) failures.Add($"{name}: [{string.Join(",", got)}], the name gives [{string.Join(",", expected)}]"); } catch (Exception ex) { failures.Add($"{name}: {ex.GetType().Name}: {ex.Message.Split('\n')[0]}"); } } failures.Should().BeEmpty(string.Join("; ", failures)); } private async Task> IdsAsync(string tag, Expression> filter) => (await Redb.Query().Where(p => p.Tag == tag).Where(filter).ToListAsync()) .Select(o => o.Id).OrderBy(id => id).ToList(); } Path: redb/redb.Tests.Integration/Tests/Base/EnumDictionaryKeyTestsBase.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/EnumDictionaryKeyTestsBase.cs ---- using System.Linq.Expressions; using redb.Core; using redb.Core.Data; using redb.Core.Exceptions; using redb.Core.Models.Entities; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// A dictionary keyed by an enum, by a flags enum and by a nullable enum: saved, loaded, filtered by ContainsKey, by /// D[key] == value and by a field of the entry, and read back in a stable key order. Filters are compared with the same /// LINQ over the seeded objects in memory. A stored key that no longer names a member of the enum stops the load. /// public abstract class EnumDictionaryKeyTestsBase { protected readonly IRedbService Redb; protected EnumDictionaryKeyTestsBase(IRedbService redb) => Redb = redb; private static EnumKeyProps Sample(string tag, int i) => new() { Marker = tag, ByShade = i % 2 == 0 ? new() { [KeyShade.Red] = 10 + i, [KeyShade.Green] = 20 + i, [KeyShade.Blue] = 30 + i } : new() { [KeyShade.Green] = 20 + i }, EntryByShade = new() { [KeyShade.Blue] = new() { Name = i % 2 == 0 ? $"{tag}-hit" : $"{tag}-miss", Rank = i }, [KeyShade.Red] = new() { Name = $"{tag}-other", Rank = 100 + i }, }, ByAccess = new() { [KeyAccess.Read] = "r", [KeyAccess.Read | KeyAccess.Write] = i % 2 == 0 ? "rw" : "rw-odd", [KeyAccess.None] = "none", }, ByMaybeShade = i % 2 == 0 ? new() { [KeyShade.Green] = 5, [KeyShade.Red] = 6 } : new() { [KeyShade.Blue] = 7 }, }; private async Task<(string Tag, List<(long Id, EnumKeyProps Props)> Seeded)> SeedAsync() { await Redb.SyncSchemeAsync(); var tag = "ek-" + Guid.NewGuid().ToString("N")[..8]; var seeded = new List<(long, EnumKeyProps)>(); for (var i = 0; i < 4; i++) { var props = Sample(tag, i); var id = await Redb.SaveAsync(new RedbObject { name = $"{tag}-{i}", Props = props }); seeded.Add((id, props)); } return (tag, seeded); } private async Task MatchesLinqAsync(Func>> filterOf, int expectedCount) { var (tag, seeded) = await SeedAsync(); var filter = filterOf(tag); var expected = seeded.Where(s => filter.Compile()(s.Props)).Select(s => s.Id).ToList(); expected.Should().HaveCount(expectedCount, "precondition"); var query = Redb.Query().Where(p => p.Marker == tag).Where(filter); (await query.ToListAsync()).Select(o => o.Id).Should().BeEquivalentTo(expected); (await query.CountAsync()).Should().Be(expectedCount); } [Fact] public async Task Load_ReturnsEveryEntry_OfEveryKeyKind() { var (_, seeded) = await SeedAsync(); foreach (var (id, props) in seeded) { var loaded = (await Redb.LoadAsync(id))!.Props; loaded.ByShade.Should().BeEquivalentTo(props.ByShade); loaded.EntryByShade.Should().BeEquivalentTo(props.EntryByShade); loaded.ByAccess.Should().BeEquivalentTo(props.ByAccess, "a flags combination is one key"); loaded.ByMaybeShade.Should().BeEquivalentTo(props.ByMaybeShade); } } [Fact] public async Task Query_ReturnsEveryEntry_OfEveryKeyKind() { var (tag, seeded) = await SeedAsync(); var loaded = await Redb.Query().Where(p => p.Marker == tag).ToListAsync(); foreach (var o in loaded) { var props = seeded.Single(s => s.Id == o.Id).Props; o.Props.ByShade.Should().BeEquivalentTo(props.ByShade); o.Props.ByAccess.Should().BeEquivalentTo(props.ByAccess); o.Props.ByMaybeShade.Should().BeEquivalentTo(props.ByMaybeShade); } } [Fact] public Task ContainsKey() => MatchesLinqAsync(_ => p => p.ByShade!.ContainsKey(KeyShade.Red), 2); [Fact] public Task IndexerEquals() => MatchesLinqAsync(_ => p => p.ByShade![KeyShade.Green] == 21, 1); [Fact] public Task EntryField() => MatchesLinqAsync(tag => p => p.EntryByShade![KeyShade.Blue].Name == tag + "-hit", 2); [Fact] public Task FlagsCombination() { var both = KeyAccess.Read | KeyAccess.Write; return MatchesLinqAsync(_ => p => p.ByAccess![both] == "rw", 2); } [Fact] public Task FlagsSingleMember_IsNotTheCombination() => MatchesLinqAsync(_ => p => p.ByAccess!.ContainsKey(KeyAccess.Write), 0); [Fact] public Task NullableKey_ContainsKey() { KeyShade? green = KeyShade.Green; return MatchesLinqAsync(_ => p => p.ByMaybeShade!.ContainsKey(green), 2); } [Fact] public Task NullableKey_IndexerEquals() { // ContainsKey first only for the LINQ in memory, where a missing key throws; redb finds no row for it. KeyShade? blue = KeyShade.Blue; return MatchesLinqAsync(_ => p => p.ByMaybeShade!.ContainsKey(blue) && p.ByMaybeShade[blue] == 7, 2); } [Fact] public async Task Keys_ComeBackInOneStableOrder_ByLoadAndByQuery() { var (tag, seeded) = await SeedAsync(); var (id, _) = seeded[0]; var byLoad = (await Redb.LoadAsync(id))!.Props; var byQuery = (await Redb.Query().Where(p => p.Marker == tag).ToListAsync()).Single(o => o.Id == id).Props; // The order of the keys as the enum compares them: by value (Green = 1, Blue = 2, Red = 3), not by name. var shadeOrder = new[] { KeyShade.Green, KeyShade.Blue, KeyShade.Red }; byLoad.ByShade!.Keys.Should().Equal(shadeOrder); byQuery.ByShade!.Keys.Should().Equal(shadeOrder); var accessOrder = new[] { KeyAccess.None, KeyAccess.Read, KeyAccess.Read | KeyAccess.Write }; byLoad.ByAccess!.Keys.Should().Equal(accessOrder); byQuery.ByAccess!.Keys.Should().Equal(accessOrder); } /// Changes a stored key of one object to text no member of the enum has (a member renamed since). protected virtual string RenameStoredKeySql(long objectId) => $"UPDATE _values SET _array_index = 'Crimson' WHERE _id_object = {objectId} AND _array_index = 'Red'"; [Fact] public async Task StoredKey_ThatNoLongerParses_StopsTheLoad_NamingFieldAndKey() { var (_, seeded) = await SeedAsync(); var (id, _) = seeded[1]; // ByShade holds Green only; EntryByShade holds Red await Redb.Context.ExecuteAsync(RenameStoredKeySql(id)); var load = () => Redb.LoadAsync(id); AssertUnreadableKey((await load.Should().ThrowAsync()).Which); } /// /// What a load reports for a stored key that does not read as the key type. Pro: /// naming the field, the stored key and the key type; no entry is skipped. /// protected virtual void AssertUnreadableKey(Exception thrown) { var e = thrown.Should().BeOfType().Subject; e.Field.Should().Be("EntryByShade"); e.StoredKey.Should().Be("Crimson"); e.KeyType.Should().Be(typeof(KeyShade)); e.Message.Should().Contain("EntryByShade").And.Contain("Crimson").And.Contain(nameof(KeyShade)); } } Path: redb/redb.Tests.Integration/Tests/Base/ExportRenameHistoryTestsBase.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/ExportRenameHistoryTestsBase.cs ---- using System.Text.RegularExpressions; using Microsoft.Extensions.DependencyInjection; using redb.Core; using redb.Core.Data; using redb.Core.Exceptions; using redb.Core.Models.Entities; using redb.Export.Providers; using redb.Export.Services; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// redb.Export carries _schemes._renamed_from and _structures._renamed_from: the rename history the sync /// reads to stop a class older than a rename. Without it a database that went through an export and an import let the /// old class add its old names again. A file written before the columns existed imports as before, with no history. /// Every test runs on scratch databases of its own; the subclass creates and drops them. /// public abstract class ExportRenameHistoryTestsBase { private const string PropertyScheme = "redb.Tests.Integration.Models.RenameBasicV1"; private const string RenamedScheme = "rename_scheme_v2"; private const string GhostScheme = "rename_scheme_ghost"; /// The provider name of : postgres, mssql or sqlite. protected abstract string ProviderName { get; } /// A new empty database of this run; the subclass drops it afterwards. protected abstract Task NewDatabaseAsync(string suffix); /// A redb service over with a cache domain of its own. protected abstract ServiceProvider Build(string cs); /// The first column of the first row as text (a blob as hex), null for SQL NULL or no row. protected abstract Task ScalarAsync(string cs, string sql); /// Runs a statement on . protected abstract Task ExecuteSqlAsync(string cs, string sql); /// The first two columns of every row as text. protected abstract Task> PairsAsync(string cs, string sql); /// A value of a reader as the text the assertions compare: a blob as hex. protected static string? AsText(object? value) => value switch { null or DBNull => null, byte[] bytes => Convert.ToHexString(bytes), _ => value.ToString(), }; /// A file the subclass deletes afterwards. protected abstract string NewFile(); [Fact] public async Task ARoundTrip_KeepsTheRenameHistory_TheNewClassesSyncAsANoOp_AndTheOldClassesStop() { var source = await RenamedSourceAsync(); var before = await HistoryAsync(source); var target = await NewEmptyAsync("dst"); await ImportAsync(target, await ExportAsync(source, null)); (await HistoryAsync(target)).Should().Equal(before, "the history travels as the stored JSON text"); await NewClassesAreANoOpAsync(target); await OldClassesStopAsync(target); } [Fact] public async Task ASchemeFilteredExport_CarriesTheHistoryOfTheSchemesItExports() { var source = await RenamedSourceAsync(); var before = await HistoryAsync(source); var schemeIds = new[] { long.Parse((await ScalarAsync(source, $"SELECT _id FROM _schemes WHERE _name = '{PropertyScheme}'"))!), long.Parse((await ScalarAsync(source, $"SELECT _id FROM _schemes WHERE _name = '{RenamedScheme}'"))!), long.Parse((await ScalarAsync(source, $"SELECT _id FROM _schemes WHERE _name = '{GhostScheme}'"))!), }; var target = await NewEmptyAsync("dst"); await ImportAsync(target, await ExportAsync(source, schemeIds)); (await HistoryAsync(target)).Should().Equal(before); await OldClassesStopAsync(target); } [Fact] public async Task AFileWrittenBeforeTheColumns_ImportsAsBefore_WithNoHistory() { var source = await RenamedSourceAsync(); var file = await ExportAsync(source, null); // A file of an older redb.Export: the same records without the property. var lines = await File.ReadAllLinesAsync(file); lines.Count(l => l.Contains("\"renamed_from\":", StringComparison.Ordinal)).Should().Be(4, "precondition: the export writes the history of the two renamed schemes and of the two renamed properties"); await File.WriteAllLinesAsync(file, lines.Select(l => Regex.Replace(l, @",""renamed_from"":""(?:[^""\\]|\\.)*""", ""))); var target = await NewEmptyAsync("dst"); await ImportAsync(target, file); (await ScalarAsync(target, "SELECT COUNT(*) FROM _schemes WHERE _renamed_from IS NOT NULL")).Should().Be("0"); (await ScalarAsync(target, "SELECT COUNT(*) FROM _structures WHERE _renamed_from IS NOT NULL")).Should().Be("0"); (await ScalarAsync(target, $"SELECT COUNT(*) FROM _schemes WHERE _name = '{RenamedScheme}'")).Should().Be("1", "everything else of the file is imported"); } /// /// A database where a property of (and one of its nested class) and the scheme of /// were renamed by the sync, each with an object stored before the rename. The scheme of /// is renamed as a version this process does not have would leave it: this process /// declares , so to it the name of is free again, and only a /// scheme renamed by a class it does not have shows the guard. /// private async Task RenamedSourceAsync() { var source = await NewEmptyAsync("src"); await using var provider = Build(source); var redb = provider.GetRequiredService(); await InitializeAsync(redb); await redb.SyncSchemeAsync(); await redb.SaveAsync(new RedbObject { name = "renamed-props", Props = new RenameBasicV1 { Title = "t", Count = 1, Address = new RenameAddressV1 { City = "Paris", Street = "Rue" } }, }); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.SaveAsync(new RedbObject { name = "renamed-scheme", Props = new SchemeRenameV1 { Title = "s" } }); await redb.SyncSchemeAsync(); var guard = await redb.SyncSchemeAsync(); await redb.SaveAsync(new RedbObject { name = "renamed-away", Props = new SchemeRenameGuardV1 { Title = "g" } }); await ExecuteSqlAsync(source, $"UPDATE _schemes SET _name = '{GhostScheme}', _renamed_from = '[\"{typeof(SchemeRenameGuardV1).FullName}\"]' WHERE _id = {guard.Id}"); (await ScalarAsync(source, $"SELECT _renamed_from FROM _schemes WHERE _name = '{RenamedScheme}'")) .Should().Be("[\"redb.Tests.Integration.Models.SchemeRenameV1\"]", "precondition: the scheme rename is recorded"); (await ScalarAsync(source, "SELECT COUNT(*) FROM _structures WHERE _renamed_from IS NOT NULL")) .Should().Be("2", "precondition: Title and the nested City are recorded"); return source; } /// Every row with a history, as table:id=text, in id order. private async Task> HistoryAsync(string cs) { var rows = new List(); foreach (var table in new[] { "_schemes", "_structures" }) { var pairs = await PairsAsync(cs, $"SELECT _id, _renamed_from FROM {table} WHERE _renamed_from IS NOT NULL ORDER BY _id"); rows.AddRange(pairs.Select(p => $"{table}:{p.First}={p.Second}")); } rows.Should().HaveCount(4, "two renamed schemes and two renamed properties"); return rows; } /// The classes of the renamed version find everything in place: no structure or scheme changes. private async Task NewClassesAreANoOpAsync(string cs) { const string structuresSql = "SELECT COUNT(*) FROM _structures"; var structures = await ScalarAsync(cs, structuresSql); var hash = await ScalarAsync(cs, $"SELECT _structure_hash FROM _schemes WHERE _name = '{PropertyScheme}'"); var history = await HistoryAsync(cs); await using var provider = Build(cs); var redb = provider.GetRequiredService(); await InitializeAsync(redb); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); (await ScalarAsync(cs, structuresSql)).Should().Be(structures); (await ScalarAsync(cs, $"SELECT _structure_hash FROM _schemes WHERE _name = '{PropertyScheme}'")).Should().Be(hash); (await HistoryAsync(cs)).Should().Equal(history); (await ScalarAsync(cs, $"SELECT COUNT(*) FROM _schemes WHERE _name = '{typeof(SchemeRenameV1).FullName}'")).Should().Be("0"); var loaded = await redb.Query().Where(x => x.Heading == "t").ToListAsync(); loaded.Should().ContainSingle().Which.Props.Address.Town.Should().Be("Paris", "the values stay under the renamed fields"); } /// The classes of the version before the rename stop at their sync instead of adding the old names again. private async Task OldClassesStopAsync(string cs) { await using var provider = Build(cs); var redb = provider.GetRequiredService(); await InitializeAsync(redb); var oldProperties = async () => await redb.SyncSchemeAsync(); await oldProperties.Should().ThrowAsync(); var oldScheme = async () => await redb.SyncSchemeAsync(); (await oldScheme.Should().ThrowAsync()).Which.StoredNames.Should().Equal(GhostScheme); (await ScalarAsync(cs, $"SELECT COUNT(*) FROM _structures WHERE _name IN ('Title', 'City') AND _id_scheme IN " + $"(SELECT _id FROM _schemes WHERE _name = '{PropertyScheme}')")).Should().Be("0", "the refused syncs added nothing"); (await ScalarAsync(cs, $"SELECT COUNT(*) FROM _schemes WHERE _name = '{typeof(SchemeRenameGuardV1).FullName}'")) .Should().Be("0", "the old scheme is not created again"); } private async Task NewEmptyAsync(string suffix) { var cs = await NewDatabaseAsync(suffix); await using var provider = Build(cs); await provider.GetRequiredService().InitializeAsync(ensureCreated: true, typeof(ExportService).Assembly); return cs; } /// /// Start-up without the scheme scan of the test assembly: it would sync every attributed test class, the renamed /// versions included, before the scenario's older classes. /// private static Task InitializeAsync(IRedbService redb) => redb.InitializeAsync(typeof(ExportService).Assembly); private async Task ExportAsync(string cs, long[]? schemeIds) { var file = NewFile(); await using var provider = ProviderFactory.Create(ProviderName); await provider.OpenAsync(cs); await new ExportService(provider, verbose: false, batchSize: 1000).ExportAsync(file, schemeIds, compress: false, dryRun: false); return file; } private async Task ImportAsync(string cs, string file) { await using var provider = ProviderFactory.Create(ProviderName); await provider.OpenAsync(cs); await new ImportService(provider, verbose: false, batchSize: 1000).ImportAsync(file, clean: true, dryRun: false); // The service that created the empty target took a block of ids into the process-wide key cache before the // import reset the sequence: an application is stopped while a database is restored under it, this process // goes on, so it drops the ids it holds. Without it a sync that adds a scheme (the scheme-filtered file has // no UserConfigurationProps) took an id the import had written. RedbKeyGeneratorBase.ClearAllCaches(); } } Path: redb/redb.Tests.Integration/Tests/Base/ExportSchemaGateTestsBase.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/ExportSchemaGateTestsBase.cs ---- using Microsoft.Extensions.DependencyInjection; using redb.Core; using redb.Core.Data; using redb.Core.Exceptions; using redb.Core.Models.Entities; using redb.Export.Providers; using redb.Export.Services; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// redb.Export checks the schema of its database before it reads or writes anything, with the exceptions a redb service /// throws at start. An older source or target stops with ; a newer source is /// refused for an export whatever it serves, since the file would leave out what this build does not know; a newer /// target passes for an import only when it says it serves this build. Before, the first statement naming a column the /// database lacked failed with a driver error, and a parallel import had already committed its cleaning by then. /// "Older" is staged as the previous schema really is (the newest columns dropped) under an older version; "newer" as a /// newer version with or without the compatibility statement. Every test runs on scratch databases of its own. /// public abstract class ExportSchemaGateTestsBase { /// The provider name of : postgres, mssql or sqlite. protected abstract string ProviderName { get; } /// Whether the provider loads over several connections (--parallel). protected abstract bool SupportsParallel { get; } /// A text the remedy of an older database names on this provider. protected abstract string OutdatedRemedy { get; } /// A new empty database of this run; the subclass drops it afterwards. protected abstract Task NewDatabaseAsync(string suffix); /// A redb service over with a cache domain of its own. protected abstract ServiceProvider Build(string cs); /// A file the subclass deletes afterwards. protected abstract string NewFile(); /// The database as the previous schema left it: its newest columns missing, an older version stated. protected abstract Task StageOlderAsync(string cs); /// A newer version stated, serving this build or not. protected abstract Task StageNewerAsync(string cs, bool servesThisBuild); /// The first column of the first row as text. protected abstract Task ScalarAsync(string cs, string sql); /// /// The provider's part of what a load changes: the indexes with their state, the foreign keys with theirs, the table /// the parallel import keeps dropped index definitions in. /// protected abstract Task> ProviderStateAsync(string cs); private static readonly string[] Tables = [ "_types", "_lists", "_list_items", "_schemes", "_structures", "_objects", "_values", "_users", "_roles", "_users_roles", "_permissions", ]; /// What an import may change: the row count of every redb table, then . private async Task> SnapshotAsync(string cs) { var lines = new List(); foreach (var table in Tables) lines.Add($"{table}={await ScalarAsync(cs, $"SELECT COUNT(*) FROM {table}")}"); lines.AddRange(await ProviderStateAsync(cs)); return lines; } /// Runs a statement on . protected abstract Task ExecuteSqlAsync(string cs, string sql); /// The statement that reads the schema version of a database, as the gate reads it. protected abstract string SchemaVersionSql { get; } [Fact] public async Task AnExport_NamesTheSchemaVersionOfItsSource_InTheHeader() { var (file, source) = await ExportOfSeededAsync(); var expected = await ScalarAsync(source, SchemaVersionSql); expected.Should().NotBeNullOrEmpty("precondition: the seeded source states its schema version"); using var header = System.Text.Json.JsonDocument.Parse(File.ReadLines(file).First()); header.RootElement.TryGetProperty("source_schema", out var sourceSchema).Should().BeTrue(); sourceSchema.GetString().Should().Be(expected); header.RootElement.GetProperty("version").GetString().Should().Be("1.0", "the property is an addition to format 1.0"); } [Fact] public async Task AFileWithoutTheSourceSchema_ImportsAsBefore() { var (file, source) = await ExportOfSeededAsync(); var lines = File.ReadAllLines(file); var header = System.Text.Json.Nodes.JsonNode.Parse(lines[0])!.AsObject(); header.Remove("source_schema"); lines[0] = header.ToJsonString(); File.WriteAllLines(file, lines); var target = await SeededAsync("dst"); await ImportAsync(target, file, SupportsParallel ? 2 : 1); var objects = (await SnapshotAsync(source)).Single(l => l.StartsWith("_objects=", StringComparison.Ordinal)); (await SnapshotAsync(target)).Should().Contain(objects, "a file of an earlier version has no such property"); } private const string TimeOnlyTypeId = "-9223372036854775685"; private const string TimeSpanTypeId = "-9223372036854775684"; [Fact] public async Task AFileOfTheTextTimeVersion_KeepsTheTargetsTypes_AndTheImportNamesTheTextValues() { // A file of a version that stored TimeSpan and TimeOnly as text: its _types say String, its values are text. var source = await NewDatabaseAsync("old"); await using (var provider = Build(source)) { var redb = provider.GetRequiredService(); await redb.InitializeAsync(ensureCreated: true, typeof(ExportService).Assembly); await redb.SyncSchemeAsync(); await redb.SaveAsync(new RedbObject { name = "times", Props = new ContainsTypesProps { Time = new TimeOnly(10, 30), Span = TimeSpan.FromMinutes(90) }, }); } await ExecuteSqlAsync(source, $"UPDATE _types SET _db_type = 'String' WHERE _id IN ({TimeOnlyTypeId}, {TimeSpanTypeId})"); await ExecuteSqlAsync(source, $"UPDATE _values SET _String = 'text', _Long = NULL WHERE _id_structure IN " + $"(SELECT _id FROM _structures WHERE _id_type IN ({TimeOnlyTypeId}, {TimeSpanTypeId}))"); var file = NewFile(); await ExportAsync(source, file); var target = await SeededAsync("dst"); var (_, output) = await CapturedAsync(() => ImportAsync(target, file, SupportsParallel ? 2 : 1)); (await ScalarAsync(target, $"SELECT COUNT(*) FROM _types WHERE _id IN ({TimeOnlyTypeId}, {TimeSpanTypeId}) AND _db_type = 'Long'")) .Should().Be("2", "the target keeps its own built-in types whatever the file says"); output.Should().Contain("Note: 2 imported TimeSpan or TimeOnly value(s) are stored as text by an older version") .And.Contain("TimeSpan and TimeOnly are stored as ticks"); (await ScalarAsync(target, "SELECT COUNT(*) FROM _values WHERE _String = 'text'")).Should().Be("2", "the values stay as the file has them; the upgrade statement converts them"); } [Fact] public async Task AnImport_BuildsTheSchemeMetadataCache_AsTheSchemeSyncDoes() { var (file, source) = await ExportOfSeededAsync(); const string cacheSql = "SELECT COUNT(*) FROM _scheme_metadata_cache WHERE _scheme_id IN (SELECT _id FROM _schemes WHERE _name LIKE '%SimpleProps%')"; var expected = await ScalarAsync(source, cacheSql); expected.Should().NotBe("0", "precondition: the scheme sync of the source built the cache"); var target = await SeededAsync("dst"); await ExecuteSqlAsync(target, "DELETE FROM _scheme_metadata_cache"); await ImportAsync(target, file, SupportsParallel ? 2 : 1); (await ScalarAsync(target, cacheSql)).Should().Be(expected); } private static async Task<(int Code, string Output)> CapturedAsync(Func run) { var console = Console.Out; var output = new StringWriter(); Console.SetOut(output); try { await run(); return (0, output.ToString()); } finally { Console.SetOut(console); } } /// How many tables named _schemes the database has: 0 for one without the redb schema. protected virtual string SchemesTableCountSql => "SELECT COUNT(*) FROM information_schema.tables WHERE table_name = '_schemes'"; [Fact] public async Task AnExport_FromADatabaseWithoutTheRedbSchema_SaysThereIsNothingToExport() { var empty = await NewDatabaseAsync("empty"); var file = NewFile(); var exporting = async () => await ExportAsync(empty, file); (await exporting.Should().ThrowAsync()).Which.Message .Should().Contain("holds no redb schema").And.Contain("there is nothing to export") .And.NotContain("outdated", "a database without the schema is not an older one"); File.Exists(file).Should().BeFalse(); } [Fact] public async Task AnImport_IntoADatabaseWithoutTheRedbSchema_NamesRedbInit_AndTouchesNothing() { var (file, _) = await ExportOfSeededAsync(); var empty = await NewDatabaseAsync("empty"); var importing = async () => await ImportAsync(empty, file, SupportsParallel ? 2 : 1); (await importing.Should().ThrowAsync()).Which.Message .Should().Contain("holds no redb schema").And.Contain($"`redb init --provider {ProviderName}`") .And.NotContain("outdated"); (await ScalarAsync(empty, SchemesTableCountSql)).Should().Be("0", "nothing was created"); } [Fact] public async Task AnExport_FromAnOlderSource_IsRefused_BeforeTheFileIsWritten() { var source = await SeededAsync("src"); await StageOlderAsync(source); var file = NewFile(); var exporting = async () => await ExportAsync(source, file); var error = (await exporting.Should().ThrowAsync()).Which; error.Message.Should().Contain("the redb CLI does not upgrade a database").And.Contain(OutdatedRemedy) .And.Contain("then export from it again"); File.Exists(file).Should().BeFalse("nothing is read for a file from a database of another schema"); } [Fact] public async Task ASerialImport_IntoAnOlderTarget_IsRefused_AndTouchesNothing() { await ImportIntoOlderTargetAsync(parallelism: 1); } [Fact] public async Task AParallelImport_IntoAnOlderTarget_IsRefused_AndTouchesNothing() { if (!SupportsParallel) return; await ImportIntoOlderTargetAsync(parallelism: 2); } [Fact] public async Task AnExport_FromANewerSource_IsRefused_EvenWhenItServesThisBuild() { var source = await SeededAsync("src"); await StageNewerAsync(source, servesThisBuild: true); var file = NewFile(); var exporting = async () => await ExportAsync(source, file); (await exporting.Should().ThrowAsync()).Which.Message .Should().Contain("would leave out what its build does not know"); File.Exists(file).Should().BeFalse(); } [Fact] public async Task AnImport_IntoANewerTarget_ThatServesThisBuild_Passes() { var (file, source) = await ExportOfSeededAsync(); var target = await TargetWithOneObjectAsync(); await StageNewerAsync(target, servesThisBuild: true); await ImportAsync(target, file, parallelism: 1); var objects = (await SnapshotAsync(source)).Single(l => l.StartsWith("_objects=", StringComparison.Ordinal)); (await SnapshotAsync(target)).Should().Contain(objects, "the import replaced the target's rows with the file's"); (await SnapshotAsync(target)).Should().Contain(l => l.StartsWith("_values=", StringComparison.Ordinal) && l != "_values=0"); } [Fact] public async Task AnImport_IntoANewerTarget_ThatDoesNotServeThisBuild_IsRefused_AndTouchesNothing() { var (file, _) = await ExportOfSeededAsync(); var target = await TargetWithOneObjectAsync(); await StageNewerAsync(target, servesThisBuild: false); var before = await SnapshotAsync(target); var importing = async () => await ImportAsync(target, file, SupportsParallel ? 2 : 1); (await importing.Should().ThrowAsync()).Which.Message .Should().Contain("Import with a redb CLI of the version whose packages run on this database"); (await SnapshotAsync(target)).Should().Equal(before); } private async Task ImportIntoOlderTargetAsync(int parallelism) { var (file, _) = await ExportOfSeededAsync(); var target = await TargetWithOneObjectAsync(); await StageOlderAsync(target); var before = await SnapshotAsync(target); before.Should().NotContain("_objects=0", "precondition: the target holds rows the cleaning would remove"); var importing = async () => await ImportAsync(target, file, parallelism); (await importing.Should().ThrowAsync()).Which.Message .Should().Contain(OutdatedRemedy).And.Contain("then import into it again"); (await SnapshotAsync(target)).Should().Equal(before, "the check runs before the cleaning, the index drop and the constraint change of the load"); } /// A database holding one object of . private async Task SeededAsync(string suffix) { var cs = await NewDatabaseAsync(suffix); await using var provider = Build(cs); var redb = provider.GetRequiredService(); await redb.InitializeAsync(ensureCreated: true, typeof(ExportService).Assembly); await redb.SyncSchemeAsync(); await redb.SaveAsync(new RedbObject { name = $"{suffix}-object", Props = new SimpleProps { Title = suffix } }); return cs; } private async Task<(string File, string Source)> ExportOfSeededAsync() { var source = await SeededAsync("src"); var file = NewFile(); await ExportAsync(source, file); return (file, source); } private Task TargetWithOneObjectAsync() => SeededAsync("dst"); private async Task ExportAsync(string cs, string file) { await using var provider = ProviderFactory.Create(ProviderName); await provider.OpenAsync(cs); await new ExportService(provider, verbose: false, batchSize: 1000).ExportAsync(file, null, compress: false, dryRun: false); } private async Task ImportAsync(string cs, string file, int parallelism) { await using (var provider = ProviderFactory.Create(ProviderName)) { await provider.OpenAsync(cs); await new ImportService(provider, verbose: false, batchSize: 1000, parallelism: parallelism) .ImportAsync(file, clean: true, dryRun: false); } // The service that seeded the target holds a block of ids from before the import (see the CLI README). RedbKeyGeneratorBase.ClearAllCaches(); } } Path: redb/redb.Tests.Integration/Tests/Base/FieldNamedLikeAFunctionTestsBase.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/FieldNamedLikeAFunctionTestsBase.cs ---- using redb.Core; using redb.Core.Attributes; using redb.Core.Models.Entities; using redb.Core.Query; namespace redb.Tests.Integration.Tests.Base; /// A model whose fields carry the names of collection members and LINQ functions. [RedbScheme("TestFieldNamedLikeAFunction")] public class FieldNamedLikeAFunctionProps { public string Tag { get; set; } = string.Empty; public int Count { get; set; } public int Length { get; set; } public decimal Sum { get; set; } public int Min { get; set; } public int Max { get; set; } public bool Any { get; set; } public string First { get; set; } = string.Empty; public double Average { get; set; } public string Key { get; set; } = string.Empty; public string Value { get; set; } = string.Empty; public FieldNamedLikeAFunctionInner Inner { get; set; } = new(); public List Tags { get; set; } = []; } public class FieldNamedLikeAFunctionInner { public int Count { get; set; } public int Length { get; set; } } /// /// A field of the model named Count or Length is a field: a filter, a sort and an aggregate read it like any other. /// Every member of those names was taken for the size function of a collection or a string, and a filter on such a /// field failed. The other names a LINQ query uses (Sum, Min, Max, Any, First, Average, Key, Value) are checked too. /// Count of a real collection stays its size. /// public abstract class FieldNamedLikeAFunctionTestsBase { protected readonly IRedbService Redb; protected FieldNamedLikeAFunctionTestsBase(IRedbService redb) => Redb = redb; private async Task SeedAsync() { await Redb.SyncSchemeAsync(); var tag = "fnf-" + Guid.NewGuid().ToString("N")[..8]; for (var i = 1; i <= 3; i++) { await Redb.SaveAsync(new RedbObject { name = $"{tag}-{i}", Props = new FieldNamedLikeAFunctionProps { Tag = tag, Count = i * 10, Length = i * 100, Sum = i * 1.5m, Min = i, Max = i * 7, Any = i == 2, First = $"f{i}", Average = i * 0.25, Key = $"k{i}", Value = $"v{i}", Inner = new FieldNamedLikeAFunctionInner { Count = i, Length = i * 2 }, Tags = Enumerable.Range(0, i).Select(n => $"t{n}").ToList() } }); } return tag; } private IRedbQueryable Q(string tag) => Redb.Query().Where(p => p.Tag == tag); private static async Task MinOf(IRedbQueryable q) => (await q.ToListAsync()).Select(o => o.Props.Min).OrderBy(x => x).ToArray(); [Fact] public async Task Filters_OnFieldsNamedLikeFunctions_ReadTheFields() { var tag = await SeedAsync(); using var scope = new AwesomeAssertions.Execution.AssertionScope(); (await MinOf(Q(tag).Where(p => p.Count == 20))).Should().Equal([2], "Count"); (await MinOf(Q(tag).Where(p => p.Count > 10))).Should().Equal([2, 3], "Count >"); (await MinOf(Q(tag).Where(p => p.Length >= 200))).Should().Equal([2, 3], "Length"); (await MinOf(Q(tag).Where(p => p.Sum == 4.5m))).Should().Equal([3], "Sum"); (await MinOf(Q(tag).Where(p => p.Min == 1))).Should().Equal([1], "Min"); (await MinOf(Q(tag).Where(p => p.Max < 14))).Should().Equal([1], "Max"); (await MinOf(Q(tag).Where(p => p.Any))).Should().Equal([2], "Any"); (await MinOf(Q(tag).Where(p => p.First == "f3"))).Should().Equal([3], "First"); (await MinOf(Q(tag).Where(p => p.Average > 0.3))).Should().Equal([2, 3], "Average"); (await MinOf(Q(tag).Where(p => p.Key == "k1"))).Should().Equal([1], "Key"); (await MinOf(Q(tag).Where(p => p.Value == "v2"))).Should().Equal([2], "Value"); (await MinOf(Q(tag).Where(p => p.Inner.Count == 3))).Should().Equal([3], "Inner.Count"); (await MinOf(Q(tag).Where(p => p.Inner.Length == 2))).Should().Equal([1], "Inner.Length"); (await MinOf(Q(tag).Where(p => p.Tags.Count == 2))).Should().Equal([2], "Count of a list is its size"); (await MinOf(Q(tag).Where(p => p.First.Length == 2))).Should().Equal([1, 2, 3], "Length of a string is its length"); } [Fact] public async Task SortAndAggregates_OnFieldsNamedLikeFunctions_ReadTheFields() { var tag = await SeedAsync(); using var scope = new AwesomeAssertions.Execution.AssertionScope(); (await Q(tag).OrderByDescending(p => p.Count).ToListAsync()).Select(o => o.Props.Min).Should().Equal([3, 2, 1], "sort by Count"); (await Q(tag).OrderBy(p => p.Length).ToListAsync()).Select(o => o.Props.Min).Should().Equal([1, 2, 3], "sort by Length"); (await Q(tag).SumAsync(p => p.Count)).Should().Be(60, "sum of Count"); (await Q(tag).SumAsync(p => p.Length)).Should().Be(600, "sum of Length"); (await Q(tag).CountAsync()).Should().Be(3); } } Path: redb/redb.Tests.Integration/Tests/Base/FilterFieldPathTestsBase.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/FilterFieldPathTestsBase.cs ---- using System.Linq.Expressions; using redb.Core; using redb.Core.Models.Entities; using redb.Core.Query; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// The field path of a filter is a chain of fields of the queried object. A method call inside the path is refused with /// one message, and so is an array or list element by index on the free providers: the parser used to drop the part /// before them, so Items[0].Name == "top" filtered by the field Name of the object itself and returned it. /// redb Pro reads the element (ElementIndexFilterTestsBase has the full set). /// The paths that are supported keep answering: a field, a field of a nested class, Nullable Value and HasValue, /// Length and Count, a dictionary entry by key (Contains over an array of simple values and Any over an array of list /// items have their own classes: ArrayTestsBase, ListTestsBase). /// /// One object per test, read by its id: Name "top", Rank 1; Items[0] and Parts[0] have Name "inner", Rank 7. /// public abstract class FilterFieldPathTestsBase { protected readonly IRedbService Redb; protected FilterFieldPathTestsBase(IRedbService redb) => Redb = redb; private async Task> SeedAsync() { await Redb.SyncSchemeAsync(); var obj = new RedbObject { name = "fp-" + Guid.NewGuid().ToString("N")[..8], Props = new FieldPathProps { Name = "top", Rank = 1, Items = [new FieldPathItem { Name = "inner", Rank = 7 }], Parts = [new FieldPathItem { Name = "inner", Rank = 7 }], ByKey = new Dictionary { ["k"] = new() { Name = "entry", Rank = 5 } }, Main = new FieldPathItem { Name = "main", Rank = 3, Score = 4 }, Scores = new Dictionary { ["a"] = 1, ["n"] = null } } }; var id = await Redb.SaveAsync(obj); return Redb.Query().WhereRedb(o => o.Id == id); } /// redb Pro reads an element by index in a filter; the free providers refuse it. protected virtual bool ReadsElementsByIndex => false; public static IEnumerable ElementPaths() { // Each of these compared the top-level field of the same name and returned the object. The free providers // refuse them; redb Pro reads the element, whose Name is "inner", Rank 7 and Score null. yield return ["array-index", (Expression>)(p => p.Items![0].Name == "top"), "Items", false]; yield return ["list-index", (Expression>)(p => p.Parts![0].Rank == 1), "Parts", false]; yield return ["array-index-null", (Expression>)(p => p.Items![0].Score == null), "Items", true]; yield return ["array-index-string-method", (Expression>)(p => p.Items![0].Name.StartsWith("to")), "Items", false]; yield return ["array-index-element-field", (Expression>)(p => p.Items![0].Name == "inner"), "Items", true]; } [Theory] [MemberData(nameof(ElementPaths))] public async Task ElementByIndex_IsReadInPro_AndRefusedInFree( string kind, Expression> predicate, string named, bool matchesInPro) { var q = await SeedAsync(); if (ReadsElementsByIndex) { (await q.Where(predicate).ToListAsync()).Should().HaveCount(matchesInPro ? 1 : 0, $"case {kind}"); return; } var act = () => q.Where(predicate).ToListAsync(); var ex = (await act.Should().ThrowAsync($"case {kind}")).Which; ex.Message.Should().Contain(named).And.Contain("Contains(").And.Contain("Any(").And.Contain("dictionary"); } public static IEnumerable RefusedPaths() { yield return ["first", (Expression>)(p => p.Items!.First().Name == "top"), "First()"]; // Not a field of the queried object under the dictionary or the string method: refused with the same // NotSupportedException and message (these three threw ArgumentException with wordings of their own). yield return ["contains-key-not-on-a-field", (Expression>)(p => (p.ByKey ?? new Dictionary()).ContainsKey("k")), "ByKey"]; yield return ["dictionary-indexer-not-on-a-field", (Expression>)(p => (p.ByKey ?? new Dictionary())["k"].Name == "entry"), "ByKey"]; yield return ["string-method-not-on-a-field", (Expression>)(p => (p.Main ?? new FieldPathItem()).Name.StartsWith("ma")), "Main"]; yield return ["dictionary-entry-not-on-a-field", (Expression>)(p => (p.ByKey ?? new Dictionary())["k"] != null), "ByKey"]; } [Theory] [MemberData(nameof(RefusedPaths))] public async Task ElementByIndexOrMethodCallInThePath_IsRefused_NamingThePathAndTheWayOut( string kind, Expression> predicate, string named) { var q = await SeedAsync(); var act = () => q.Where(predicate).ToListAsync(); var ex = (await act.Should().ThrowAsync($"case {kind}")).Which; ex.Message.Should().Contain(named).And.Contain("Contains(").And.Contain("Any(").And.Contain("dictionary"); } public static IEnumerable SupportedPaths() { yield return ["field", (Expression>)(p => p.Name == "top"), true]; yield return ["field-miss", (Expression>)(p => p.Name == "inner"), false]; yield return ["nested-class", (Expression>)(p => p.Main!.Name == "main"), true]; yield return ["nested-class-miss", (Expression>)(p => p.Main!.Name == "top"), false]; yield return ["nullable-value", (Expression>)(p => p.Main!.Score!.Value == 4), true]; yield return ["nullable-has-value", (Expression>)(p => p.Main!.Score.HasValue), true]; yield return ["string-length", (Expression>)(p => p.Name.Length == 3), true]; // A field of a dictionary entry without a value (the entry's Score is null). yield return ["dictionary-entry-field-null", (Expression>)(p => p.ByKey!["k"].Score == null), true]; yield return ["dictionary-entry-field-not-null", (Expression>)(p => p.ByKey!["k"].Score != null), false]; yield return ["array-length", (Expression>)(p => p.Items!.Length == 1), true]; yield return ["list-count", (Expression>)(p => p.Parts!.Count == 1), true]; yield return ["dictionary-entry", (Expression>)(p => p.ByKey!["k"].Name == "entry"), true]; yield return ["dictionary-entry-miss", (Expression>)(p => p.ByKey!["k"].Name == "top"), false]; yield return ["coalesce-then-string-function", (Expression>)(p => (p.Name ?? "").ToLower() == "top"), true]; // Nullable Value and HasValue over a dictionary entry: the path is the entry, not a member chain. yield return ["dictionary-nullable-value", (Expression>)(p => p.Scores!["a"].Value == 1), true]; yield return ["dictionary-nullable-value-miss", (Expression>)(p => p.Scores!["a"].Value == 2), false]; yield return ["dictionary-nullable-has-value", (Expression>)(p => p.Scores!["a"].HasValue), true]; yield return ["dictionary-nullable-has-value-null", (Expression>)(p => p.Scores!["n"].HasValue), false]; yield return ["dictionary-nullable-not-null-null", (Expression>)(p => p.Scores!["n"] != null), false]; yield return ["dictionary-nullable-is-null-null", (Expression>)(p => p.Scores!["n"] == null), true]; yield return ["dictionary-nullable-not-has-value-null", (Expression>)(p => !p.Scores!["n"].HasValue), true]; } public static IEnumerable RefusedOrderingPaths() { // Each of these sorted by the top-level field of the same name, or sent an empty path. The key keeps its own // type, as in an application (a boxed key is a conversion, refused for another reason). yield return ["array-index", (Func, Task>)(q => q.OrderBy(p => p.Items![0].Name).ToListAsync()), "Items"]; yield return ["dictionary-entry-field", (Func, Task>)(q => q.OrderBy(p => p.ByKey!["k"].Name).ToListAsync()), "ByKey"]; yield return ["dictionary-nullable-value", (Func, Task>)(q => q.OrderBy(p => p.Scores!["a"]!.Value).ToListAsync()), "Scores"]; } [Theory] [MemberData(nameof(RefusedOrderingPaths))] public async Task OrderBy_ThroughAnEntryOrAnElement_IsRefused_NamingThePath( string kind, Func, Task> sort, string named) { var q = await SeedAsync(); var act = () => sort(q); var ex = (await act.Should().ThrowAsync($"case {kind}")).Which; ex.Message.Should().Contain(named); } [Theory] [MemberData(nameof(SupportedPaths))] public async Task SupportedPath_KeepsAnswering(string kind, Expression> predicate, bool matches) { var q = await SeedAsync(); var rows = await q.Where(predicate).ToListAsync(); rows.Should().HaveCount(matches ? 1 : 0, $"case {kind}"); } } Path: redb/redb.Tests.Integration/Tests/Base/FreeAnyExistsTestsBase.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/FreeAnyExistsTestsBase.cs ---- using redb.Core; using redb.Core.Models.Entities; using redb.Core.Query; using redb.Tests.Integration.Helpers; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// Free AnyAsync runs the inner statement of the v2-pvt module under EXISTS, which stops at the first match; it used to /// count every match. Every form gives the answer it gave, the count above zero. /// public abstract class FreeAnyExistsTestsBase { protected readonly IRedbService Redb; protected FreeAnyExistsTestsBase(IRedbService redb) => Redb = redb; private async Task SeedEmployeesAsync() { await Redb.SyncSchemeAsync(); var tag = "any-" + Guid.NewGuid().ToString("N")[..8]; await Redb.SaveAsync(Enumerable.Range(0, 5) .Select(i => TestDataFactory.CreateEmployee(i, salary: 100m * (i + 1), department: $"{tag}-D{i % 2}")).ToList()); return tag; } public static IEnumerable FlatCases() => new[] { new object[] { "filter", true }, new object[] { "filter-none", false }, new object[] { "order", true }, new object[] { "distinct", true }, new object[] { "distinct-by", true }, new object[] { "distinct-none", false }, new object[] { "where-in-empty", false }, new object[] { "take-0", false }, new object[] { "skip-past", false }, new object[] { "skip-inside", true }, new object[] { "predicate", true }, new object[] { "predicate-none", false } }; [Theory] [MemberData(nameof(FlatCases))] public async Task AnyAsync_FlatQuery_GivesTheAnswerOfTheCount(string kind, bool expected) { var tag = await SeedEmployeesAsync(); IRedbQueryable Tagged() => Redb.Query().Where(e => e.Department.StartsWith(tag)); var query = kind switch { "filter" => Tagged().Where(e => e.Salary > 300m), "filter-none" => Tagged().Where(e => e.Salary > 10_000m), "order" => Tagged().OrderByDescending(e => e.Salary), "distinct" => Tagged().Distinct(), "distinct-by" => Tagged().DistinctBy(e => e.Department), "distinct-none" => Tagged().Where(e => e.Salary < 0m).DistinctBy(e => e.Department), "where-in-empty" => Tagged().WhereIn(e => e.Department, Array.Empty()), "take-0" => Tagged().Take(0), "skip-past" => Tagged().OrderBy(e => e.Salary).Skip(5), "skip-inside" => Tagged().OrderBy(e => e.Salary).Skip(4), "predicate" => Tagged(), "predicate-none" => Tagged(), _ => throw new ArgumentOutOfRangeException(nameof(kind)) }; var any = kind switch { "predicate" => await query.AnyAsync(e => e.Salary == 500m), "predicate-none" => await query.AnyAsync(e => e.Salary == 501m), _ => await query.AnyAsync() }; var count = kind switch { "predicate" => await query.Where(e => e.Salary == 500m).CountAsync(), "predicate-none" => await query.Where(e => e.Salary == 501m).CountAsync(), _ => await query.CountAsync() }; any.Should().Be(expected); any.Should().Be(count > 0, "AnyAsync answers as the count above zero did"); } public static IEnumerable TreeCases() => new[] { new object[] { "subtree", true }, new object[] { "subtree-filter-none", false }, new object[] { "level-1", true }, new object[] { "level-5", false }, new object[] { "children", true }, new object[] { "leaf-children", false }, new object[] { "unrooted", true }, new object[] { "has-ancestor", true }, new object[] { "has-ancestor-none", false } }; [Theory] [MemberData(nameof(TreeCases))] public async Task AnyAsync_TreeQuery_GivesTheAnswerOfTheCount(string kind, bool expected) { await Redb.SyncSchemeAsync(); var tag = "anyt-" + Guid.NewGuid().ToString("N")[..8]; var root = new TreeRedbObject { name = tag + "-r", Props = new SimpleProps { Title = tag } }; root.id = await Redb.SaveAsync(root); var child = new TreeRedbObject { name = tag + "-c", Props = new SimpleProps { Title = tag, Count = 1 } }; child.id = await Redb.CreateChildAsync(child, root); var leaf = new TreeRedbObject { name = tag + "-l", Props = new SimpleProps { Title = tag, Count = 2 } }; leaf.id = await Redb.CreateChildAsync(leaf, child); var query = kind switch { "subtree" => Redb.TreeQuery(root.id), "subtree-filter-none" => Redb.TreeQuery(root.id).Where(p => p.Count > 10), "level-1" => Redb.TreeQuery(root.id).WhereLevel(1), "level-5" => Redb.TreeQuery(root.id).WhereLevel(5), "children" => Redb.TreeQuery().WhereChildrenOf(root.id), "leaf-children" => Redb.TreeQuery().WhereChildrenOf(leaf.id), "unrooted" => Redb.TreeQuery().Where(p => p.Title == tag), "has-ancestor" => Redb.TreeQuery().Where(p => p.Title == tag).WhereHasAncestor(a => a.Count == 1), "has-ancestor-none" => Redb.TreeQuery().Where(p => p.Title == tag).WhereHasAncestor(a => a.Count == 99), _ => throw new ArgumentOutOfRangeException(nameof(kind)) }; var any = await query.AnyAsync(); any.Should().Be(expected); any.Should().Be(await query.CountAsync() > 0, "AnyAsync answers as the count above zero did"); } } Path: redb/redb.Tests.Integration/Tests/Base/FreeListItemJsonTestsBase.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/FreeListItemJsonTestsBase.cs ---- using System.Text.Json; 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; /// /// The Free in-database JSON builders wrote a list /// item as {id, idList, value, alias[, object]}, while the model reads id_list and id_object: every /// Free load lost both the list link and the object link of the list items in Props, and PostgreSQL / SQLite built the /// whole linked object for a key the deserializer ignores. Owner decision 2026-09-15: a list item is /// {id, id_list, value, alias, id_object}, with no nested object. /// public abstract class FreeListItemJsonTestsBase { protected abstract void UseProvider(RedbOptionsBuilder options); private ServiceProvider Build() { var services = new ServiceCollection(); services.AddLogging(b => b.SetMinimumLevel(LogLevel.Warning)); services.AddRedb(options => { UseProvider(options); options.Configure(c => { c.EnablePropsCache = false; c.CacheDomain = "free-listitem-json"; }); }); return services.BuildServiceProvider(); } private sealed record Seed(long RootId, long ListId, long LinkedItemId, long PlainItemId, long LinkedObjectId); private static async Task SeedAsync(ServiceProvider sp) { var tag = Guid.NewGuid().ToString("N")[..8]; var redb = sp.GetRequiredService(); await redb.InitializeAsync(ensureCreated: true); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.InitializeTypeRegistryAsync(); var linkedObjectId = await redb.SaveAsync(new RedbObject { name = $"lijson-linked-{tag}", Props = new SimpleProps { Title = "linked" } }); var list = await redb.ListProvider.SaveListAsync(RedbList.Create($"lijson-{tag}", "lijson")); var linked = await redb.ListProvider.SaveListItemAsync(new RedbListItem { IdList = list.Id, Value = "linked", IdObject = linkedObjectId }); var plain = await redb.ListProvider.SaveListItemAsync(new RedbListItem { IdList = list.Id, Value = "plain" }); var rootId = await redb.SaveAsync(new RedbObject { name = $"lijson-root-{tag}", Props = new CtProbeProps { Label = "root", Status = linked, Roles = [linked, plain] } }); return new Seed(rootId, list.Id, linked.Id, plain.Id, linkedObjectId); } private static void AssertLinks(string path, CtProbeProps props, Seed seed) { AssertItem($"{path}, Status", props.Status, seed.LinkedItemId, seed.ListId, "linked", seed.LinkedObjectId); props.Roles.Should().HaveCount(2, $"{path}: both list items are materialized"); AssertItem($"{path}, Roles[0]", props.Roles![0], seed.LinkedItemId, seed.ListId, "linked", seed.LinkedObjectId); AssertItem($"{path}, Roles[1]", props.Roles[1], seed.PlainItemId, seed.ListId, "plain", null); } private static void AssertItem(string path, RedbListItem? item, long id, long listId, string value, long? objectId) { item.Should().NotBeNull($"{path}: the list item is materialized"); item!.Id.Should().Be(id, $"{path}: id"); item.Value.Should().Be(value, $"{path}: value"); item.IdList.Should().Be(listId, $"{path}: the item keeps the list it belongs to"); item.IdObject.Should().Be(objectId, $"{path}: the item keeps its object link"); } private static readonly string[] ItemJsonKeys = ["id", "id_list", "value", "alias", "id_object"]; private static void AssertItemJson(string path, JsonElement item, long? objectId) { item.EnumerateObject().Select(p => p.Name).Should().BeEquivalentTo(ItemJsonKeys, $"{path}: a list item in the object JSON is exactly id, id_list, value, alias, id_object - no idList, no nested object"); var link = item.GetProperty("id_object"); if (objectId == null) link.ValueKind.Should().Be(JsonValueKind.Null, $"{path}: the item has no object link"); else link.GetInt64().Should().Be(objectId.Value, $"{path}: the object link"); } [Fact] public async Task LoadAsync_ListItems_KeepListAndObjectLinks() { await using var sp = Build(); var seed = await SeedAsync(sp); await using var scope = sp.CreateAsyncScope(); var root = await scope.ServiceProvider.GetRequiredService().LoadAsync(seed.RootId, depth: 10); AssertLinks("async load", root!.Props, seed); } [Fact] public async Task SyncLoad_ListItems_KeepListAndObjectLinks() { await using var sp = Build(); var seed = await SeedAsync(sp); await using var scope = sp.CreateAsyncScope(); var root = scope.ServiceProvider.GetRequiredService().Load(seed.RootId, depth: 10); AssertLinks("sync load", root!.Props, seed); } [Fact] public async Task ObjectJson_ListItem_IsIdListValueAliasObjectLink_WithoutNestedObject() { await using var sp = Build(); var seed = await SeedAsync(sp); await using var scope = sp.CreateAsyncScope(); var json = await scope.ServiceProvider.GetRequiredService().LoadJsonAsync(seed.RootId, depth: 10); using var doc = JsonDocument.Parse(json!); var properties = doc.RootElement.GetProperty("properties"); AssertItemJson("Status", properties.GetProperty("Status"), seed.LinkedObjectId); var roles = properties.GetProperty("Roles"); AssertItemJson("Roles[0]", roles[0], seed.LinkedObjectId); AssertItemJson("Roles[1]", roles[1], null); } } Path: redb/redb.Tests.Integration/Tests/Base/FreeOrderPositionTestsBase.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/FreeOrderPositionTestsBase.cs ---- using redb.Core; using redb.Core.Query; using redb.Tests.Integration.Helpers; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// The inner statement of a Free query returns _ord next to _id, the position of the row in the order of the query, /// and the list read sorts by it after the join. Numbering the rows outside the statement (ROW_NUMBER() OVER (ORDER BY /// (SELECT NULL)) on SQL Server, row_number() OVER () on PostgreSQL) relied on the plan reading them in order: on SQL /// Server OrderByDescending(key).DistinctBy(key) came back ascending. /// public abstract class FreeOrderPositionTestsBase { protected readonly IRedbService Redb; protected FreeOrderPositionTestsBase(IRedbService redb) => Redb = redb; public static IEnumerable Cases() => new[] { "order", "order-desc", "distinct-by", "page", "no-order", "distinct" }.Select(c => new object[] { c }); [Theory] [MemberData(nameof(Cases))] public async Task InnerStatement_OrdGivesTheOrderOfTheListRead(string kind) { await Redb.SyncSchemeAsync(); var tag = Guid.NewGuid().ToString("N")[..8]; // Salaries out of id order, three departments. var salaries = new[] { 500m, 100m, 900m, 300m, 700m, 200m, 800m }; await Redb.SaveAsync(salaries.Select((s, i) => TestDataFactory.CreateEmployee(i, salary: s, department: $"{tag}-D{i % 3}")).ToList()); IRedbQueryable Tagged() => Redb.Query().Where(e => e.Department.StartsWith(tag)); var query = kind switch { "order" => Tagged().OrderBy(e => e.Salary), "order-desc" => Tagged().OrderByDescending(e => e.Salary), "distinct-by" => Tagged().OrderByDescending(e => e.Department).DistinctBy(e => e.Department), "page" => Tagged().OrderBy(e => e.Salary).Skip(2).Take(3), "no-order" => Tagged(), "distinct" => Tagged().Distinct(), _ => throw new ArgumentOutOfRangeException(nameof(kind)) }; var listed = (await query.ToListAsync()).Select(o => o.Id).ToList(); var inner = await query.ToSqlStringAsync(); var byOrd = await Redb.Context.QueryScalarListAsync( "SELECT t._id FROM (\n" + inner + "\n) t ORDER BY t._ord", Array.Empty()); listed.Should().NotBeEmpty(); byOrd.Should().Equal(listed, "_ord of the inner statement is the order the list read returns"); } } Path: redb/redb.Tests.Integration/Tests/Base/FreeQueryPlannerBlockTestsBase.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/FreeQueryPlannerBlockTestsBase.cs ---- using redb.Core; using redb.Core.Query; namespace redb.Tests.Integration.Tests.Base; /// Free has no query planner: redb.WithQueryPlanner(bool) opens a block that changes nothing. public abstract class FreeQueryPlannerBlockTestsBase { protected readonly IRedbService Redb; protected FreeQueryPlannerBlockTestsBase(IRedbService redb) => Redb = redb; [Fact] public void Block_OnFree_ChangesNothing() { using (Redb.WithQueryPlanner(false)) { QueryPlannerScope.BlockValue.Should().BeNull("Free has no planner to switch"); using (Redb.WithQueryPlanner(true)) QueryPlannerScope.BlockValue.Should().BeNull(); } } } Path: redb/redb.Tests.Integration/Tests/Base/GroupByHavingTestsBase.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/GroupByHavingTestsBase.cs ---- using redb.Core; using redb.Core.Query.Aggregation; using redb.Tests.Integration.Helpers; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// HAVING-clause regression suite for GroupBy and GroupByArray queries. /// /// Runs on all six hosts (PostgreSQL, SQL Server, SQLite; Free and Pro). SQL Server Free joined on /// 2026-09-24: until then it had no HAVING at all - the provider passed NULL and every group came back - /// and the missing wrapper is why nobody saw it. /// /// The seeded fixture is shared across tests; cleanup is performed once at /// fixture init. To stay stable against accumulated rows the assertions use /// thresholds (> 0, > 1_000_000) rather than exact counts. /// public abstract class GroupByHavingTestsBase { protected readonly IRedbService Redb; protected GroupByHavingTestsBase(IRedbService redb) => Redb = redb; // Queries read only the objects their test seeded: other test classes share the database and may leave // employees without salary or department behind. private redb.Core.Query.IRedbQueryable Seeded(List ids) => Redb.Query().WhereRedb(o => ids.Contains(o.Id)); private Task> SeedAsync() => TestDataFactory.SeedEmployees(Redb, 20); // ────────────────────────────────────────────────────────────────── // Regular GroupBy + HAVING // ────────────────────────────────────────────────────────────────── [Fact] public async Task GroupBy_Having_CountGt_PassThrough() { var ids = await SeedAsync(); var results = await Seeded(ids) .GroupBy(e => e.Department) .Having(g => Agg.Count(g) > 0) .SelectAsync(g => new { Department = g.Key, Count = Agg.Count(g) }); results.Should().NotBeEmpty(); results.Should().AllSatisfy(r => { r.Department.Should().NotBeNullOrEmpty(); r.Count.Should().BeGreaterThan(0); }); } [Fact] public async Task Having_Branching_DoesNotContaminateSiblingQueries() { // G-4 (ревью 2026-09-03): Having мутировал this - ветвление заражало сестринскую // ветку обоими предикатами. var ids = await SeedAsync(); var grouped = Seeded(ids).GroupBy(e => e.Department); var strict = grouped.Having(g => Agg.Count(g) > 1_000_000); var loose = grouped.Having(g => Agg.Count(g) > 0); var looseRows = await loose.SelectAsync(g => new { Department = g.Key, Cnt = Agg.Count(g) }); looseRows.Should().NotBeEmpty("предикат сестринской ветки не должен протекать в эту"); var strictRows = await strict.SelectAsync(g => new { Department = g.Key, Cnt = Agg.Count(g) }); strictRows.Should().BeEmpty(); } [Fact] public async Task Having_NullConstant_IsLoud() { // G-5 (ревью 2026-09-03): null-константа превращалась в СТРОКУ "null". var ids = await SeedAsync(); long? nothing = null; var act = async () => await Seeded(ids) .GroupBy(e => e.Department) .Having(g => Agg.Count(g) == nothing) .SelectAsync(g => new { g.Key }); await act.Should().ThrowAsync( "сравнение с текстом \"null\" - тихо неверный результат"); } [Fact] public async Task GroupBy_Having_CountGt_FiltersAll() { var ids = await SeedAsync(); var results = await Seeded(ids) .GroupBy(e => e.Department) .Having(g => Agg.Count(g) > 1_000_000) .SelectAsync(g => new { Department = g.Key, Count = Agg.Count(g) }); results.Should().BeEmpty(); } [Fact] public async Task GroupBy_Having_SumSalary_Threshold() { var ids = await SeedAsync(); var results = await Seeded(ids) .GroupBy(e => e.Department) .Having(g => Agg.Sum(g, e => e.Salary) > 0m) .SelectAsync(g => new { Department = g.Key, Total = Agg.Sum(g, e => e.Salary) }); results.Should().NotBeEmpty(); results.Should().AllSatisfy(r => r.Total.Should().BeGreaterThan(0m)); } [Fact] public async Task GroupBy_Having_AndCombinator() { var ids = await SeedAsync(); var results = await Seeded(ids) .GroupBy(e => e.Department) .Having(g => Agg.Count(g) > 0 && Agg.Average(g, e => e.Age) > 0.0) .SelectAsync(g => new { Department = g.Key, C = Agg.Count(g) }); results.Should().NotBeEmpty(); } [Fact] public async Task GroupBy_Having_OrCombinator() { var ids = await SeedAsync(); var results = await Seeded(ids) .GroupBy(e => e.Department) .Having(g => Agg.Count(g) > 1_000_000 || Agg.Count(g) > 0) .SelectAsync(g => new { Department = g.Key, C = Agg.Count(g) }); results.Should().NotBeEmpty(); } [Fact] public async Task GroupBy_Having_NotCombinator() { var ids = await SeedAsync(); var results = await Seeded(ids) .GroupBy(e => e.Department) .Having(g => !(Agg.Count(g) > 1_000_000)) .SelectAsync(g => new { Department = g.Key, C = Agg.Count(g) }); results.Should().NotBeEmpty(); } // ────────────────────────────────────────────────────────────────── // Array GroupBy + HAVING (Phase 2.G.3) // ────────────────────────────────────────────────────────────────── [Fact] public async Task GroupByArray_Having_CountGt_PassThrough() { var ids = await SeedAsync(); var results = await Seeded(ids) .GroupByArray(e => e.Contacts!, c => c.Type) .Having(g => Agg.Count(g) > 0) .SelectAsync(g => new { Type = g.Key, Count = Agg.Count(g) }); results.Should().NotBeEmpty(); results.Should().AllSatisfy(r => { r.Type.Should().NotBeNullOrEmpty(); r.Count.Should().BeGreaterThan(0); }); results.Select(r => r.Type).Should() .Contain("email", "TestContact.Type=email group must survive HAVING"); results.Select(r => r.Type).Should() .Contain("phone", "TestContact.Type=phone group must survive HAVING"); } [Fact] public async Task GroupByArray_Having_CountGt_FiltersAll() { var ids = await SeedAsync(); var results = await Seeded(ids) .GroupByArray(e => e.Contacts!, c => c.Type) .Having(g => Agg.Count(g) > 1_000_000) .SelectAsync(g => new { Type = g.Key, Count = Agg.Count(g) }); results.Should().BeEmpty(); } [Fact] public async Task GroupByArray_Having_OnAnItemField_FiltersTheGroups() { // The HAVING aggregates an item field the select does not read. SQL Server Free wrote it as // MAX([Value]) - a column the query does not have - and failed. var ids = await SeedAsync(); var results = await Seeded(ids) .GroupByArray(e => e.Contacts!, c => c.Type) .Having(g => Agg.Max(g, c => c.Value) == "no-such-contact-value") .SelectAsync(g => new { Type = g.Key, Count = Agg.Count(g) }); results.Should().BeEmpty("no contact has that value, so no group's maximum equals it"); } [Fact] public async Task GroupByArray_Having_OnAnItemField_KeepsTheMatchingGroups() { // The same field in the select and in the HAVING: both read one joined column. var ids = await SeedAsync(); var results = await Seeded(ids) .GroupByArray(e => e.Contacts!, c => c.Type) .Having(g => Agg.Max(g, c => c.Value) != "no-such-contact-value") .SelectAsync(g => new { Type = g.Key, MaxValue = Agg.Max(g, c => c.Value) }); results.Select(r => r.Type).Should().Contain(new[] { "email", "phone" }); results.Should().AllSatisfy(r => r.MaxValue.Should().NotBeNullOrEmpty()); } [Fact] public async Task GroupByArray_Having_AndCombinator() { var ids = await SeedAsync(); var results = await Seeded(ids) .GroupByArray(e => e.Contacts!, c => c.Type) .Having(g => Agg.Count(g) > 0 && Agg.Count(g) < 1_000_000) .SelectAsync(g => new { Type = g.Key, Count = Agg.Count(g) }); results.Should().NotBeEmpty(); } [Fact] public async Task GroupByArray_Having_OrCombinator() { var ids = await SeedAsync(); var results = await Seeded(ids) .GroupByArray(e => e.Contacts!, c => c.Type) .Having(g => Agg.Count(g) > 1_000_000 || Agg.Count(g) > 0) .SelectAsync(g => new { Type = g.Key, Count = Agg.Count(g) }); results.Should().NotBeEmpty(); } [Fact] public async Task GroupByArray_Having_NotCombinator() { var ids = await SeedAsync(); var results = await Seeded(ids) .GroupByArray(e => e.Contacts!, c => c.Type) .Having(g => !(Agg.Count(g) > 1_000_000)) .SelectAsync(g => new { Type = g.Key, Count = Agg.Count(g) }); results.Should().NotBeEmpty(); } // ────────────────────────────────────────────────────────────────── // Array GroupBy WITHOUT HAVING (regression for PVT/inline migration) // // Verifies that array GroupBy aggregation works when no HAVING clause // is provided. Historically this path bypassed PVT/inline SQL and went // to the legacy `aggregate_array_grouped` SQL function. After the // migration both branches (HAVING + no-HAVING) share the same code // path; these tests guard against regressions in that change. // ────────────────────────────────────────────────────────────────── [Fact] public async Task GroupByArray_NoHaving_CountOnly() { var ids = await SeedAsync(); var results = await Seeded(ids) .GroupByArray(e => e.Contacts!, c => c.Type) .SelectAsync(g => new { Type = g.Key, Count = Agg.Count(g) }); results.Should().NotBeEmpty(); results.Should().AllSatisfy(r => { r.Type.Should().NotBeNullOrEmpty(); r.Count.Should().BeGreaterThan(0); }); results.Select(r => r.Type).Should() .Contain("email", "TestContact.Type=email group must be present without HAVING"); results.Select(r => r.Type).Should() .Contain("phone", "TestContact.Type=phone group must be present without HAVING"); } [Fact] public async Task GroupByArray_NoHaving_MultipleAggregates() { var ids = await SeedAsync(); var results = await Seeded(ids) .GroupByArray(e => e.Contacts!, c => c.Type) .SelectAsync(g => new { Type = g.Key, Count = Agg.Count(g), MinValue = Agg.Min(g, c => c.Value), MaxValue = Agg.Max(g, c => c.Value) }); results.Should().NotBeEmpty(); results.Should().AllSatisfy(r => { r.Type.Should().NotBeNullOrEmpty(); r.Count.Should().BeGreaterThan(0); }); } [Fact] public async Task GroupBy_Having_ConditionalCount() { var ids = await SeedAsync(); var objects = await Seeded(ids).ToListAsync(); var rows = await Seeded(ids) .GroupBy(e => e.Department) .Having(g => Agg.Count(g, e => e.IsRemote) >= 2) .SelectAsync(g => new { Dept = g.Key, C = Agg.Count(g) }); var expected = objects.GroupBy(o => o.Props.Department).Where(g => g.Count(o => o.Props.IsRemote) >= 2).Select(g => g.Key); rows.Select(r => r.Dept).Should().BeEquivalentTo(expected); } [Fact] public async Task GroupBy_Having_ThenWindow_RunsOverTheGroupsThatPass() { // A18: WithWindow did not receive the HAVING, so every group came back. var ids = await SeedAsync(); var none = await Seeded(ids) .GroupBy(e => e.Department) .Having(g => Agg.Count(g) > 1_000_000) .WithWindow(w => w.OrderBy(g => g.Key)) .SelectAsync(g => new { Dept = g.Key, Row = Win.RowNumber() }); none.Should().BeEmpty(); var objects = await Seeded(ids).ToListAsync(); var some = await Seeded(ids) .GroupBy(e => e.Department) .Having(g => Agg.Count(g, e => e.IsRemote) >= 2) .WithWindow(w => w.OrderBy(g => g.Key)) .SelectAsync(g => new { Dept = g.Key, Row = Win.RowNumber() }); var expected = objects.GroupBy(o => o.Props.Department).Where(g => g.Count(o => o.Props.IsRemote) >= 2).Select(g => g.Key); some.Select(r => r.Dept).Should().BeEquivalentTo(expected); some.Select(r => r.Row).Should().BeEquivalentTo(Enumerable.Range(1, some.Count).Select(i => (long)i)); } } Path: redb/redb.Tests.Integration/Tests/Base/GroupBySelectShapesTestsBase.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/GroupBySelectShapesTestsBase.cs ---- using redb.Core; using redb.Core.Query.Aggregation; using redb.Tests.Integration.Helpers; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// Формы селектора GroupBy(...).SelectAsync(...) (ревью 2026-09-03, G-1/G-2/G-3; решения /// владельца: DTO/MemberInit поддерживаем, всё нераспознанное - громко). До этого набора: /// DTO-класс в SelectAsync молча давал строки из default-значений, вычисление вокруг Agg /// молча возвращало null, а вычисляемый ключ группировки молча давал пустой GROUP BY. /// public abstract class GroupBySelectShapesTestsBase { protected readonly IRedbService Redb; protected GroupBySelectShapesTestsBase(IRedbService redb) => Redb = redb; // Queries read only the objects their test seeded: other test classes share the database and may leave // employees without salary or department behind. private redb.Core.Query.IRedbQueryable Seeded(List ids) => Redb.Query().WhereRedb(o => ids.Contains(o.Id)); private Task> SeedAsync() => TestDataFactory.SeedEmployees(Redb, 20); public class DeptRowDto { public string? Dept { get; set; } public long Cnt { get; set; } public decimal Total { get; set; } } [Fact] public async Task SelectAsync_IntoDtoMemberInit_MaterializesEveryMember() { // G-1: MemberInit раньше не разбирался - каждая строка приходила как default!. var ids = await SeedAsync(); var rows = await Seeded(ids) .GroupBy(e => e.Department) .SelectAsync(g => new DeptRowDto { Dept = g.Key, Cnt = Agg.Count(g), Total = Agg.Sum(g, x => x.Salary), }); rows.Should().NotBeEmpty(); rows.Should().AllSatisfy(r => { r.Should().NotBeNull("DTO-строка обязана материализоваться, а не приходить null"); r.Dept.Should().NotBeNullOrEmpty(); r.Cnt.Should().BeGreaterThan(0); r.Total.Should().BeGreaterThan(0); }); } [Fact] public async Task SelectAsync_ComputedAroundAgg_IsLoud() { // G-2: вычисление вокруг агрегата не заказывается у сервера - раньше член молча // оставался null/0. Контракт: громкий отказ с именем члена. var ids = await SeedAsync(); var act = async () => await Seeded(ids) .GroupBy(e => e.Department) .SelectAsync(g => new { Doubled = Agg.Count(g) * 2 }); (await act.Should().ThrowAsync( "молча вернуть null вместо вычисления - худший исход")) .WithMessage("*Doubled*"); } [Fact] public async Task GroupBy_ComputedKey_IsLoud() { // G-3: вычисляемый ключ группировки раньше молча давал пустой GROUP BY. var ids = await SeedAsync(); var act = async () => await Seeded(ids) .GroupBy(e => e.Age + 1) .SelectAsync(g => new { Cnt = Agg.Count(g) }); await act.Should().ThrowAsync( "группировка по вычисляемому ключу не поддерживается и обязана отказывать громко"); } public class ArrayGroupRowDto { public string? Type { get; set; } public long Cnt { get; set; } } [Fact] public async Task ArrayGroupBy_SelectAsync_IntoDtoMemberInit() { // G-1 доехал до GroupByArray (решение владельца 2026-09-04): раньше здесь стоял // громкий отказ на DTO. var ids = await SeedAsync(); var rows = await Seeded(ids) .GroupByArray(e => e.Contacts!, c => c.Type) .SelectAsync(g => new ArrayGroupRowDto { Type = g.Key, Cnt = Agg.Count(g) }); rows.Should().NotBeEmpty(); rows.Should().AllSatisfy(r => { r.Type.Should().NotBeNullOrEmpty(); r.Cnt.Should().BeGreaterThan(0); }); } [Fact] public async Task SelectAsync_ClientConstantMember_IsEvaluated() { // Член, не ссылающийся на группу, - клиентская константа: вычисляется на клиенте, // а не молча null (раньше материализатор искал его в JSON и не находил). var ids = await SeedAsync(); var tag = "fixed-tag"; var rows = await Seeded(ids) .GroupBy(e => e.Department) .SelectAsync(g => new { Dept = g.Key, Tag = tag, Cnt = Agg.Count(g) }); rows.Should().NotBeEmpty(); rows.Should().AllSatisfy(r => r.Tag.Should().Be("fixed-tag")); } [Fact] public async Task ConditionalCount_InAGroupBy() { var ids = await SeedAsync(); var objects = await Seeded(ids).ToListAsync(); var rows = await Seeded(ids) .GroupBy(e => e.Department) .SelectAsync(g => new { Dept = g.Key, All = Agg.Count(g), Remote = Agg.Count(g, e => e.IsRemote), Rated = Agg.Count(g, e => e.Rating != null), RichRemote = Agg.Count(g, e => e.IsRemote && e.Salary >= 100000m) }); rows.Should().HaveCount(objects.Select(o => o.Props.Department).Distinct().Count()); foreach (var r in rows) { var group = objects.Where(o => o.Props.Department == r.Dept).Select(o => o.Props).ToList(); r.All.Should().Be(group.Count); r.Remote.Should().Be(group.Count(e => e.IsRemote)); r.Rated.Should().Be(group.Count(e => e.Rating != null)); r.RichRemote.Should().Be(group.Count(e => e.IsRemote && e.Salary >= 100000m)); } } [Fact] public async Task ComputedAggregate_InAGroupBy_IsRefused() { var act = async () => await Redb.Query() .GroupBy(e => e.Department) .SelectAsync(g => new { Dept = g.Key, Twice = Agg.Sum(g, e => e.Salary * 2) }); await act.Should().ThrowAsync(); } [Fact] public async Task GroupedWindow_Ntile_UsesItsBucketCount() { // A21: the bucket count never reached the provider; every NTILE was NTILE(4). var ids = await SeedAsync(); var departments = (await Seeded(ids).ToListAsync()).Select(o => o.Props.Department).Distinct().Count(); departments.Should().BeGreaterThan(2, "precondition: more groups than buckets"); var rows = await Seeded(ids) .GroupBy(e => e.Department) .WithWindow(w => w.OrderBy(g => g.Key)) .SelectAsync(g => new { Dept = g.Key, Bucket = Win.Ntile(2) }); rows.Select(r => r.Bucket).Distinct().Should().BeEquivalentTo(new[] { 1, 2 }); } } Path: redb/redb.Tests.Integration/Tests/Base/GroupByTestsBase.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/GroupByTestsBase.cs ---- using redb.Core; using redb.Core.Models.Entities; using redb.Core.Query.Aggregation; using redb.Tests.Integration.Helpers; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; public abstract class GroupByTestsBase { protected readonly IRedbService Redb; protected GroupByTestsBase(IRedbService redb) => Redb = redb; // Queries read only the objects their test seeded: other test classes share the database and may leave // employees without salary or department behind. private redb.Core.Query.IRedbQueryable Seeded(List ids) => Redb.Query().WhereRedb(o => ids.Contains(o.Id)); private async Task> SeedAsync() { return await TestDataFactory.SeedEmployees(Redb, 20); } [Fact] public async Task GroupBy_SingleField_GroupsCorrectly() { var ids = await SeedAsync(); var results = await Seeded(ids) .GroupBy(e => e.Department) .SelectAsync(g => new { Department = g.Key, Count = Agg.Count(g), TotalSalary = Agg.Sum(g, e => e.Salary) }); results.Should().NotBeEmpty(); results.Should().AllSatisfy(r => { r.Department.Should().NotBeEmpty(); r.Count.Should().BeGreaterThan(0); r.TotalSalary.Should().BeGreaterThan(0m); }); var totalCount = results.Sum(r => r.Count); totalCount.Should().BeGreaterThanOrEqualTo(20); } [Fact] public async Task GroupBy_WithFilter_GroupsFiltered() { var ids = await SeedAsync(); var results = await Seeded(ids) .Where(e => e.IsRemote) .GroupBy(e => e.Department) .SelectAsync(g => new { Department = g.Key, AvgSalary = Agg.Average(g, e => e.Salary), Count = Agg.Count(g) }); results.Should().NotBeEmpty(); results.Should().AllSatisfy(r => { r.AvgSalary.Should().BeGreaterThan(0.0); r.Count.Should().BeGreaterThan(0); }); } [Fact] public async Task GroupBy_WithAggregations_MultipleAggs() { var ids = await SeedAsync(); var results = await Seeded(ids) .GroupBy(e => e.Department) .SelectAsync(g => new { Department = g.Key, MinSalary = Agg.Min(g, e => e.Salary), MaxSalary = Agg.Max(g, e => e.Salary), AvgAge = Agg.Average(g, e => e.Age), Count = Agg.Count(g) }); results.Should().NotBeEmpty(); results.Should().AllSatisfy(r => { r.MinSalary.Should().BeLessThanOrEqualTo(r.MaxSalary); r.AvgAge.Should().BeGreaterThan(0); r.Count.Should().BeGreaterThan(0); }); } [Fact] public async Task GroupBy_BoolField_GroupsByBoolean() { var ids = await SeedAsync(); var results = await Seeded(ids) .GroupBy(e => e.IsRemote) .SelectAsync(g => new { IsRemote = g.Key, Count = Agg.Count(g), AvgSalary = Agg.Average(g, e => e.Salary) }); results.Should().HaveCountGreaterThanOrEqualTo(1); results.Should().HaveCountLessThanOrEqualTo(2); results.Sum(r => r.Count).Should().BeGreaterThanOrEqualTo(20); } [Fact] public async Task GroupBy_AliasedKey_ReturnsCorrectValues() { var ids = await SeedAsync(); // Key: anonymous property name "Dept" differs from field name "Department" var results = await Seeded(ids) .GroupBy(e => e.Department) .SelectAsync(g => new { Dept = g.Key, Count = Agg.Count(g) }); results.Should().NotBeEmpty(); results.Should().AllSatisfy(r => { r.Dept.Should().NotBeNullOrEmpty("GroupBy key must resolve even when alias differs from field name"); r.Count.Should().BeGreaterThan(0); }); results.Sum(r => r.Count).Should().BeGreaterThanOrEqualTo(20); } [Fact] public async Task GroupBy_BoolKey_AliasedKey_Works() { var ids = await SeedAsync(); // Key: "Remote" differs from field "IsRemote" var results = await Seeded(ids) .GroupBy(e => e.IsRemote) .SelectAsync(g => new { Remote = g.Key, Total = Agg.Count(g) }); results.Should().HaveCountGreaterThanOrEqualTo(1); results.Should().HaveCountLessThanOrEqualTo(2); results.Sum(r => r.Total).Should().BeGreaterThanOrEqualTo(20); } #region ListItem GroupBy private async Task<(List Ids, RedbListItem Active, RedbListItem Blocked)> SeedPersonsWithStatusAsync() { // Create list with items var existing = await Redb.ListProvider.GetListByNameAsync("GroupByTestStatuses"); if (existing != null) { var oldItems = await Redb.ListProvider.GetListItemsAsync(existing.Id); if (oldItems.Count > 0) await Redb.Context.Bulk.BulkDeleteValuesByListItemIdsAsync(oldItems.Select(i => i.Id).ToList()); await Redb.ListProvider.DeleteListAsync(existing.Id); } var list = RedbList.Create("GroupByTestStatuses", "GroupByTestStatuses"); list = await Redb.ListProvider.SaveListAsync(list); var statuses = await Redb.ListProvider.AddItemsAsync(list, ["Active", "Blocked"]); var active = statuses.First(s => s.Value == "Active"); var blocked = statuses.First(s => s.Value == "Blocked"); var persons = Enumerable.Range(0, 10).Select(i => new RedbObject { name = $"GroupByPerson_{i}", Props = new PersonProps { Name = $"Person{i}", Age = 20 + i, Email = $"p{i}@test.com", Status = i % 3 == 0 ? blocked : active } }).ToList(); var ids = await Redb.SaveAsync(persons); for (int i = 0; i < persons.Count; i++) persons[i].id = ids[i]; return (ids, active, blocked); } private async Task CleanupPersonsWithStatusAsync(List ids) { if (ids.Count > 0) await Redb.DeleteAsync(ids); var existing = await Redb.ListProvider.GetListByNameAsync("GroupByTestStatuses"); if (existing != null) { var items = await Redb.ListProvider.GetListItemsAsync(existing.Id); if (items.Count > 0) await Redb.Context.Bulk.BulkDeleteValuesByListItemIdsAsync(items.Select(i => i.Id).ToList()); await Redb.ListProvider.DeleteListAsync(existing.Id); } } [Fact] public async Task GroupBy_ListItemField_KeyId_ReturnsNonZero() { var (ids, active, blocked) = await SeedPersonsWithStatusAsync(); try { var idSet = ids.ToHashSet(); var results = await Redb.Query() .WhereRedb(p => idSet.Contains(p.Id)) .GroupBy(p => p.Status) .SelectAsync(g => new { StatusId = g.Key!.Id, Count = Agg.Count(g) }); results.Should().NotBeEmpty(); results.Should().HaveCountGreaterThanOrEqualTo(2, "should have Active and Blocked groups"); results.Should().AllSatisfy(r => { r.StatusId.Should().BeGreaterThan(0, "ListItem Id must not be 0 — was the bug before fix"); r.Count.Should().BeGreaterThan(0); }); // Verify the Ids match our seeded list items var allStatusIds = results.Select(r => r.StatusId).ToList(); allStatusIds.Should().Contain(active.Id); allStatusIds.Should().Contain(blocked.Id); results.Sum(r => r.Count).Should().Be(10); } finally { await CleanupPersonsWithStatusAsync(ids); } } [Fact] public async Task GroupBy_ListItemField_KeyId_AliasedProperty_Works() { var (ids, active, blocked) = await SeedPersonsWithStatusAsync(); try { var idSet = ids.ToHashSet(); // Anonymous property "Id" differs from what we name it ("StatusCode") var results = await Redb.Query() .WhereRedb(p => idSet.Contains(p.Id)) .GroupBy(p => p.Status) .SelectAsync(g => new { StatusCode = g.Key!.Id, Total = Agg.Count(g) }); results.Should().NotBeEmpty(); results.Should().AllSatisfy(r => { r.StatusCode.Should().BeGreaterThan(0); r.Total.Should().BeGreaterThan(0); }); results.Sum(r => r.Total).Should().Be(10); } finally { await CleanupPersonsWithStatusAsync(ids); } } #endregion } Path: redb/redb.Tests.Integration/Tests/Base/HashCanonCollisionTestsBase.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/HashCanonCollisionTestsBase.cs ---- using System.Globalization; using redb.Core; using redb.Core.Models.Entities; using redb.Core.Utils; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// Changes the hash canon must see. Under ChangeTracking with AutoRecomputeHash an object whose recomputed hash equals /// the stored one skips the whole value pipeline, and a collection or nested class whose hash equals the stored one is /// skipped by the diff. Two different values with the same canon string therefore lose the change: these tests edit an /// object from the first value into the second, save and load, and expect the second. The pairs collide on the /// separators of the canon ('|' between class properties, ',' between elements and entries, '=' between a key and its /// value) and on dictionary keys canonicalised through ToString(). Run on the ChangeTracking fixtures. /// public abstract class HashCanonCollisionTestsBase : IAsyncLifetime { protected readonly IRedbService Redb; protected HashCanonCollisionTestsBase(IRedbService redb) => Redb = redb; public async Task InitializeAsync() => await ResetAsync(); public async Task DisposeAsync() => await ResetAsync(); private async Task ResetAsync() { foreach (var scheme in new[] { "HashCanonProbe", "HashCanonClassKeyProbe", "HashCanonTupleKeyProbe" }) await Redb.Context.ExecuteAsync( $"DELETE FROM _objects WHERE _id_scheme IN (SELECT _id FROM _schemes WHERE _name = '{scheme}')"); } /// Saves , loads it, applies , saves, and loads again. private async Task> SaveEditLoadAsync(TProps first, Action edit) where TProps : class, new() { await Redb.SyncSchemeAsync(); var id = await Redb.SaveAsync(new RedbObject { name = "hash-canon", Props = first }); var loaded = await Redb.LoadAsync(id, depth: 2); edit(loaded!.Props); await Redb.SaveAsync(loaded); return (await Redb.LoadAsync(id, depth: 2))!; } [Fact] public async Task PipeInsideAString_ChangeIsSaved() { // Canon of both: "x|y|" followed by the same tail. var after = await SaveEditLoadAsync( new HashCanonProbeProps { A = "x|y", B = "" }, p => { p.A = "x"; p.B = "y|"; }); after.Props.A.Should().Be("x"); after.Props.B.Should().Be("y|"); } [Fact] public async Task CommaInsideAnElement_ChangeIsSaved() { // Canon of both: "[a,b]". var after = await SaveEditLoadAsync( new HashCanonProbeProps { Tags = ["a,b"] }, p => p.Tags = ["a", "b"]); after.Props.Tags.Should().Equal("a", "b"); } [Fact] public async Task EqualsAndCommaInsideADictionaryValue_ChangeIsSaved() { // Canon of both: "{a=1,b=2}". var after = await SaveEditLoadAsync( new HashCanonProbeProps { Dict = new() { ["a"] = "1,b=2" } }, p => p.Dict = new() { ["a"] = "1", ["b"] = "2" }); after.Props.Dict.Should().Equal(new Dictionary { ["a"] = "1", ["b"] = "2" }); } [Fact] public async Task CollectionHeadCollision_WithAnotherChange_CollectionIsSaved() { // The root hash differs (Label), so the object takes the value pipeline; the head hash of Tags collides and // the diff skips the collection. var after = await SaveEditLoadAsync( new HashCanonProbeProps { Label = "one", Tags = ["a,b"] }, p => { p.Label = "two"; p.Tags = ["a", "b"]; }); after.Props.Label.Should().Be("two"); after.Props.Tags.Should().Equal("a", "b"); } [Fact] public async Task ClassElementCollision_WithAnotherChange_ElementIsSaved() { var after = await SaveEditLoadAsync( new HashCanonProbeProps { Label = "one", Items = [new HashCanonPair { A = "x|y", B = "" }] }, p => { p.Label = "two"; p.Items = [new HashCanonPair { A = "x", B = "y|" }]; }); after.Props.Label.Should().Be("two"); after.Props.Items.Should().ContainSingle(); after.Props.Items![0].A.Should().Be("x"); after.Props.Items[0].B.Should().Be("y|"); } [Fact] public async Task NestedClassCollision_WithAnotherChange_NestedClassIsSaved() { var after = await SaveEditLoadAsync( new HashCanonProbeProps { Label = "one", Inner = new HashCanonPair { A = "x|y", B = "" } }, p => { p.Label = "two"; p.Inner = new HashCanonPair { A = "x", B = "y|" }; }); after.Props.Label.Should().Be("two"); after.Props.Inner!.A.Should().Be("x"); after.Props.Inner.B.Should().Be("y|"); } [Fact] public async Task NullElementAgainstTheStringNull_ChangeIsSaved() { // Canon of both: "[null]". var after = await SaveEditLoadAsync( new HashCanonProbeProps { Tags = [null] }, p => p.Tags = ["null"]); after.Props.Tags.Should().Equal("null"); } [Fact] public async Task NullPropertyAgainstAnEmptyString_ChangeIsSaved() { // Canon of both: "" in the place of A. var after = await SaveEditLoadAsync( new HashCanonProbeProps { A = null, B = "b" }, p => p.A = ""); after.Props.A.Should().Be(""); } [Fact] public async Task EmptyCollectionAgainstOneEmptyString_ChangeIsSaved() { // Canon of both: "[]". var after = await SaveEditLoadAsync( new HashCanonProbeProps { Tags = [] }, p => p.Tags = [""]); after.Props.Tags.Should().Equal(""); } [Fact] public async Task NullDictionaryValueAgainstTheStringNull_ChangeIsSaved() { // Canon of both: "{a=null}". var after = await SaveEditLoadAsync( new HashCanonProbeProps { Dict = new() { ["a"] = null! } }, p => p.Dict = new() { ["a"] = "null" }); after.Props.Dict.Should().Equal(new Dictionary { ["a"] = "null" }); } [Fact] public async Task ClassKeyWithoutToString_KeyOnlyChangeIsSaved() { // Canon of both keys through ToString(): the type name. var after = await SaveEditLoadAsync( new HashCanonClassKeyProps { ByKey = new() { [new HashCanonKey { Code = "a", Rank = 1 }] = "v" } }, p => p.ByKey = new() { [new HashCanonKey { Code = "b", Rank = 2 }] = "v" }); after.Props.ByKey.Should().ContainSingle(); after.Props.ByKey!.Keys.Single().Code.Should().Be("b"); after.Props.ByKey.Keys.Single().Rank.Should().Be(2); } [Fact] public async Task TupleKeyOfDoubleAndDate_HashDoesNotDependOnTheCulture() { await Redb.SyncSchemeAsync(); var at = new DateTime(2026, 9, 16, 12, 30, 15, DateTimeKind.Utc); var props = new HashCanonTupleKeyProps { ByTuple = new() { [(1.5, at)] = "v" } }; var id = await Under("ru-RU", () => Redb.SaveAsync(new RedbObject { name = "hash-canon", Props = props })); var loaded = await Under("en-US", () => Redb.LoadAsync(id, depth: 2)); var recomputed = Under("en-US", () => Task.FromResult(RedbHash.ComputeFor(loaded!))).Result; recomputed.Should().Be(loaded!.hash, "a node with another culture must recompute the hash the first node stored, or every save rewrites the object"); } private static async Task Under(string culture, Func> action) { var previous = CultureInfo.CurrentCulture; CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo(culture); try { return await action(); } finally { CultureInfo.CurrentCulture = previous; } } } Path: redb/redb.Tests.Integration/Tests/Base/IgnoredPropertyWalkTestsBase.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/IgnoredPropertyWalkTestsBase.cs ---- using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Core; using redb.Core.Extensions; using redb.Core.Models.Configuration; using redb.Core.Models.Entities; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// No /// graph walk of a load reads a [RedbIgnore] property - the scheme and the save never do. Covers the walkers that /// need a database: Pro reference substitution and trashed-target nulling, the stub collector of lazy references, the /// props-cache collector and dirty guard, and the loader installers of both tiers. The unit twin is /// WalkerPropertyRuleTests. /// public abstract class IgnoredPropertyWalkTestsBase { protected abstract void UseProvider(RedbOptionsBuilder options); protected virtual void Register(IServiceCollection services, Action configure) => services.AddRedb(configure); private ServiceProvider Build(Action configure) { var services = new ServiceCollection(); services.AddLogging(b => b.SetMinimumLevel(LogLevel.Warning)); Register(services, options => { UseProvider(options); options.Configure(c => { c.EnablePropsCache = false; c.CacheDomain = "ignored-property-walk"; configure(c); }); }); return services.BuildServiceProvider(); } private sealed record Seed(long RootId, string Label); private static async Task SeedAsync(ServiceProvider sp, bool trashSecondTarget, bool withReferences = true) { var tag = Guid.NewGuid().ToString("N")[..8]; var redb = sp.GetRequiredService(); await redb.InitializeAsync(ensureCreated: true); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.InitializeTypeRegistryAsync(); var c1 = await redb.SaveAsync(new RedbObject { name = $"ignored-c1-{tag}", Props = new CtProbeChildProps { Tag = "one" } }); var c2 = await redb.SaveAsync(new RedbObject { name = $"ignored-c2-{tag}", Props = new CtProbeChildProps { Tag = "two" } }); var label = $"ignored-root-{tag}"; var rootId = await redb.SaveAsync(new RedbObject { name = label, Props = new IgnoredGetterProbeProps { Label = label, Refs = withReferences ? [new RedbObject { id = c1 }, new RedbObject { id = c2 }] : null } }); if (trashSecondTarget) await redb.SoftDeleteAsync(new[] { c2 }); return new Seed(rootId, label); } private static int Reads(string label) => IgnoredGetterProbeProps.TechnicalReads.GetValueOrDefault(label); private async Task AssertLoadReadsNoIgnoredPropertyAsync(string path, Action configure, bool trashSecondTarget, Func load, bool withReferences = true) { await using var sp = Build(configure); var seed = await SeedAsync(sp, trashSecondTarget, withReferences); var before = Reads(seed.Label); await using var scope = sp.CreateAsyncScope(); await load(scope.ServiceProvider.GetRequiredService(), seed.RootId); Reads(seed.Label).Should().Be(before, $"{path}: no walk of a load reads a [RedbIgnore] property"); } [Fact] public Task Load_WithReferences_ReadsNoRedbIgnoreProperty() => AssertLoadReadsNoIgnoredPropertyAsync("load with references", _ => { }, trashSecondTarget: false, async (redb, id) => (await redb.LoadAsync(id, depth: 10)).Should().NotBeNull()); [Fact] public Task Load_WithTrashedReferenceTarget_ReadsNoRedbIgnoreProperty() => AssertLoadReadsNoIgnoredPropertyAsync("load with a trashed reference target", _ => { }, trashSecondTarget: true, async (redb, id) => (await redb.LoadAsync(id, depth: 10)).Should().NotBeNull()); [Fact] public Task Load_WithLazyReferences_ReadsNoRedbIgnoreProperty() => AssertLoadReadsNoIgnoredPropertyAsync("load with lazy references", c => c.EnableLazyReferences = true, trashSecondTarget: false, async (redb, id) => (await redb.LoadAsync(id, depth: 1)).Should().NotBeNull()); [Fact] public Task Load_ThroughThePropsCache_ReadsNoRedbIgnoreProperty() => AssertLoadReadsNoIgnoredPropertyAsync("props cache set and hit", c => c.EnablePropsCache = true, trashSecondTarget: false, async (redb, id) => { ((RedbServiceBase)redb).PropsCache.Instance!.Clear(); var first = await redb.LoadAsync(id, depth: 10); var hit = await redb.LoadAsync(id, depth: 10); hit.Should().BeSameAs(first, "the second load is served from the cache"); }); } Path: redb/redb.Tests.Integration/Tests/Base/IndexCatalogTestsBase.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/IndexCatalogTestsBase.cs ---- using System.Runtime.CompilerServices; using System.Text; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Core; using redb.Core.Data; using redb.Core.Models; using redb.Core.Models.Configuration; using redb.Core.Query; namespace redb.Tests.Integration.Tests.Base; /// /// The table of expected indexes (the base schema, or a Pro module's indexes) against a fresh database of this build: /// the same names, columns and uniqueness, and the same statements, both ways. The table is generated: run this test with /// REDB_WRITE_INDEX_CATALOG=1 and it rewrites the file from the fresh database instead of failing, then review the /// diff. A schema change that adds, drops or redefines an index fails here until the table follows it. /// public abstract class IndexCatalogTestsBase { /// Creates an empty database of the given name and returns its connection string. protected abstract Task CreateDatabaseAsync(string name); /// Drops the database by its exact name. protected abstract Task DropDatabaseAsync(string name); /// Registers the provider (Free or Pro) on the connection string. protected abstract void AddRedb(IServiceCollection services, string connectionString, Action configure); /// The statement that creates each index of the fresh database, by index name. protected abstract Task> ReadCreateStatementsAsync(IRedbContext context); /// The table under test. protected abstract IReadOnlyList Catalog { get; } /// Indexes another table already holds (the base table, for a Pro module's): left out of this one. protected virtual IReadOnlyList CoveredElsewhere => Array.Empty(); /// Indexes of the fresh database that no table holds (built by an option, not by the schema). protected virtual bool Ignore(string indexName) => indexName.StartsWith("IX__values__String_pattern", StringComparison.OrdinalIgnoreCase); /// The generated file, relative to redb.DB/src, with the namespace, class and member it declares. protected abstract (string File, string Namespace, string Class, string Member, RedbIndexOrigin Origin) Target { get; } [Fact] public async Task FreshDatabase_HasExactlyTheIndexesOfTheTable() { var name = $"redb_idxcat_{Guid.NewGuid():N}"[..24]; var connectionString = await CreateDatabaseAsync(name); try { var services = new ServiceCollection(); services.AddLogging(b => b.SetMinimumLevel(LogLevel.Warning)); AddRedb(services, connectionString, c => { c.EnablePropsCache = false; c.EnablePvtPrefilter = true; c.CheckBaseIndexesOnStart = false; }); await using var sp = services.BuildServiceProvider(); var redb = sp.GetRequiredService(); await redb.InitializeAsync(ensureCreated: true); var context = sp.GetRequiredService(); var dialect = sp.GetRequiredService(); var shapes = await context.QueryAsync(dialect.Schema_SelectIndexShapes()!); var statements = await ReadCreateStatementsAsync(context); var covered = CoveredElsewhere.Select(e => e.Name).ToHashSet(StringComparer.OrdinalIgnoreCase); var fresh = shapes .Where(s => !covered.Contains(s.Name!) && !Ignore(s.Name!)) .OrderBy(s => s.Table, StringComparer.Ordinal).ThenBy(s => s.Name, StringComparer.Ordinal) .Select(s => new RedbExpectedIndex(s.Name!, s.Table!, s.IsUnique, Split(s.KeyColumnsCsv), Split(s.IncludedColumnsCsv), RedbExpectedIndex.OneLine(statements[s.Name!]), Target.Origin)) .ToList(); if (Environment.GetEnvironmentVariable("REDB_WRITE_INDEX_CATALOG") == "1") { var path = Path.Combine(SourceRoot(), Target.File); await File.WriteAllTextAsync(path, Render(fresh)); return; } // On a difference the message carries the file as a fresh database gives it, between markers: a run on a test // host that cannot write the source tree hands the table back this way. if (!Describe(Catalog).SequenceEqual(Describe(fresh))) Assert.Fail($"The table of {Target.File} does not match a fresh database of this build; regenerate it with " + $"REDB_WRITE_INDEX_CATALOG=1, or take it from here:\n===BEGIN {Target.File}===\n{Render(fresh)}===END==="); // The fresh database passes the check that reads the same table. var report = await redb.CheckBaseIndexesAsync(); report.Findings.Should().BeEmpty("a fresh database has every expected index as expected"); } finally { await DropDatabaseAsync(name); } } private static IReadOnlyList Split(string? csv) => string.IsNullOrWhiteSpace(csv) ? Array.Empty() : csv.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).Select(c => c.ToLowerInvariant()).ToArray(); private static IEnumerable Describe(IEnumerable indexes) => indexes .OrderBy(i => i.Table, StringComparer.Ordinal).ThenBy(i => i.Name, StringComparer.Ordinal) .Select(i => $"{i.Table}.{i.Name} unique={i.IsUnique} key=({string.Join(",", i.KeyColumns)}) " + $"include=({string.Join(",", i.IncludedColumns.OrderBy(c => c, StringComparer.Ordinal))}) sql={i.CreateSql}"); private string Render(IReadOnlyList indexes) { static string Str(string s) => "@\"" + s.Replace("\"", "\"\"") + "\""; static string List(IReadOnlyList l) => l.Count == 0 ? "[]" : "[" + string.Join(", ", l.Select(c => "\"" + c + "\"")) + "]"; var sb = new StringBuilder(); sb.AppendLine("// "); sb.AppendLine("// Written by IndexCatalogTests (REDB_WRITE_INDEX_CATALOG=1) from a fresh database of this build; the same"); sb.AppendLine("// test fails while this table and a fresh database differ. Do not edit by hand."); sb.AppendLine("// "); sb.AppendLine("using redb.Core.Models;"); sb.AppendLine(); sb.AppendLine($"namespace {Target.Namespace};"); sb.AppendLine(); sb.AppendLine("/// The indexes a fresh database of this build has (the index check and its repair read this table)."); sb.AppendLine($"public static partial class {Target.Class}"); sb.AppendLine("{"); sb.AppendLine($" public static readonly IReadOnlyList {Target.Member} ="); sb.AppendLine(" ["); foreach (var i in indexes) sb.AppendLine($" new(\"{i.Name}\", \"{i.Table}\", {(i.IsUnique ? "true" : "false")}, {List(i.KeyColumns)}, " + $"{List(i.IncludedColumns)},\n {Str(i.CreateSql)}, RedbIndexOrigin.{Target.Origin}),"); sb.AppendLine(" ];"); sb.AppendLine("}"); return sb.ToString().Replace("\r\n", "\n"); } private static string SourceRoot([CallerFilePath] string path = "") { // tests/Tests/Base/IndexCatalogTestsBase.cs -> redb.DB/src var db = Directory.GetParent(path)!.Parent!.Parent!.Parent!.FullName; return Path.Combine(db, "src"); } private sealed class ShapeRow { public string? Name { get; set; } public string? Table { get; set; } public bool IsUnique { get; set; } public string? KeyColumnsCsv { get; set; } public string? IncludedColumnsCsv { get; set; } public bool IsValid { get; set; } = true; } } Path: redb/redb.Tests.Integration/Tests/Base/IndexRepairTestsBase.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/IndexRepairTestsBase.cs ---- using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Core; using redb.Core.Data; using redb.Core.Models; using redb.Core.Models.Configuration; using redb.Core.Models.Entities; using redb.Tests.Integration.Fixtures; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// The index check and its repair on a database of its own: a dropped base index is reported Missing with what it serves, /// the start-up logs one Warning and builds nothing, the repair builds it again; an index of a base name defined otherwise /// is reported Differs and left as it is. /// public abstract class IndexRepairTestsBase { protected abstract Task CreateDatabaseAsync(string name); protected abstract Task DropDatabaseAsync(string name); protected abstract void AddRedb(IServiceCollection services, string connectionString, Action configure); /// Drops the named index of the table. protected abstract string DropIndexSql(string table, string index); /// Creates an index of the given name over another column of _objects. protected abstract string CreateOtherIndexSql(string index); private const string Dropped = "IX__values__array_key"; private const string Redefined = "IX__objects__name"; [Fact] public async Task DroppedIndex_IsReported_NotBuiltAtStart_AndRepaired() { var name = $"redb_idxfix_{Guid.NewGuid():N}"[..24]; var connectionString = await CreateDatabaseAsync(name); try { await using (var sp = Build(connectionString, null)) { var redb = sp.GetRequiredService(); await redb.InitializeAsync(ensureCreated: true); var context = sp.GetRequiredService(); await context.ExecuteAsync(DropIndexSql("_values", Dropped)); await context.ExecuteAsync(DropIndexSql("_objects", Redefined)); await context.ExecuteAsync(CreateOtherIndexSql(Redefined)); } var logs = new CapturingLoggerProvider(); await using (var sp = Build(connectionString, logs)) { var redb = sp.GetRequiredService(); await redb.InitializeAsync(); logs.Warnings.Should().ContainSingle(w => w.Contains(Dropped) && w.Contains(Redefined), "the start names every index that differs in one Warning"); var report = await redb.CheckBaseIndexesAsync(); var missing = report.Findings.Single(f => f.Name == Dropped); missing.State.Should().Be(RedbIndexState.Missing, "the start builds nothing"); missing.Expected.Origin.Should().Be(RedbIndexOrigin.Base); missing.Serves.Should().Contain("dictionary key", "the finding says what the index serves"); report.Findings.Single(f => f.Name == Redefined).State.Should().Be(RedbIndexState.Differs); var result = await redb.RepairBaseIndexesAsync(allowOffline: true); result.Built.Should().Equal([Dropped], "the repair builds the missing index and nothing else"); result.NotBuilt.Select(f => f.Name).Should().Equal([Redefined], "an index defined otherwise is never touched"); var after = await redb.CheckBaseIndexesAsync(); after.Findings.Select(f => f.Name).Should().Equal([Redefined]); } } finally { await DropDatabaseAsync(name); } } private const string PlaceIndex = "UIX__values__structure_object"; [Fact] public async Task DuplicateRows_KeepTheIndexUnbuilt_AreListed_AndNothingIsDeleted() { var name = $"redb_idxdup_{Guid.NewGuid():N}"[..24]; var connectionString = await CreateDatabaseAsync(name); try { await using var sp = Build(connectionString, null); var redb = sp.GetRequiredService(); await redb.InitializeAsync(ensureCreated: true); await redb.SyncSchemeAsync(); var id = await redb.SaveAsync(new RedbObject { name = "duplicate probe", Props = new IndexDuplicateProbeProps { Name = "dup-probe" }, }); var context = sp.GetRequiredService(); await context.ExecuteAsync(DropIndexSql("_values", PlaceIndex)); await context.ExecuteAsync( "INSERT INTO _values (_id, _id_structure, _id_object, _String) " + "SELECT (SELECT MAX(_id) + 1 FROM _values), _id_structure, _id_object, _String FROM _values " + $"WHERE _id_object = {id} AND _String = 'dup-probe' AND _array_index IS NULL AND _array_parent_id IS NULL"); var rowsBefore = await context.ExecuteScalarAsync($"SELECT COUNT(*) FROM _values WHERE _id_object = {id}"); var result = await redb.RepairBaseIndexesAsync(allowOffline: true); result.Built.Should().NotContain(PlaceIndex, "a unique index over duplicate rows is not built"); result.NotBuilt.Select(f => f.Name).Should().Contain(PlaceIndex); result.Reason.Should().Contain(PlaceIndex); var duplicate = result.Duplicates.Should().ContainSingle().Subject; duplicate.Index.Should().Be(PlaceIndex); duplicate.ObjectId.Should().Be(id); duplicate.Rows.Should().Be(2); (await context.ExecuteScalarAsync($"SELECT COUNT(*) FROM _values WHERE _id_object = {id}")) .Should().Be(rowsBefore, "the repair deletes nothing"); (await redb.CheckBaseIndexesAsync()).Findings.Single(f => f.Name == PlaceIndex).State .Should().Be(RedbIndexState.Missing); await context.ExecuteAsync("DELETE FROM _values WHERE _id = (SELECT MAX(_id) FROM _values)"); var again = await redb.RepairBaseIndexesAsync(allowOffline: true); again.Built.Should().Equal([PlaceIndex], "with the copy gone the index is built"); again.Duplicates.Should().BeEmpty(); (await redb.CheckBaseIndexesAsync()).IsClean.Should().BeTrue(); } finally { await DropDatabaseAsync(name); } } private ServiceProvider Build(string connectionString, CapturingLoggerProvider? logs) { var services = new ServiceCollection(); services.AddLogging(b => { b.SetMinimumLevel(LogLevel.Warning); if (logs != null) b.AddProvider(logs); }); AddRedb(services, connectionString, c => c.EnablePropsCache = false); return services.BuildServiceProvider(); } } Path: redb/redb.Tests.Integration/Tests/Base/IntegerAverageTestsBase.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/IntegerAverageTestsBase.cs ---- using redb.Core; using redb.Core.Models.Entities; using redb.Core.Query; using redb.Core.Query.Aggregation; using redb.Tests.Integration.Helpers; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// The average of an integer field keeps its fraction on every form: an engine that keeps the type of the operand /// (T-SQL AVG over bigint, integer division in a native function) returns 32 for 32.25. Each test compares with the /// same LINQ over the seeded objects in memory, flat and over a tree. /// /// Seed: two departments. Ages 30, 31, 33, 35 (average 32.25) and 40, 41, 43 (41.333...), all seven 36.142857... /// SkillLevels elements 1, 2, 2, 4, 2, 1, 3, 3 (average 2.25). None of these is a whole number or a half. /// public abstract class IntegerAverageTestsBase { protected readonly IRedbService Redb; protected IntegerAverageTestsBase(IRedbService redb) => Redb = redb; private static readonly (int Dept, int Age, int[] Levels)[] Rows = [ (0, 30, [1, 2]), (0, 31, [2]), (0, 33, [4]), (0, 35, [2]), (1, 40, [1]), (1, 41, [3, 3]), (1, 43, []), ]; private const double Precision = 1e-6; private sealed record Seeded(long RootId, List Ids, List Props); private async Task SeedAsync() { await Redb.SyncSchemeAsync(); var tag = "ia-" + Guid.NewGuid().ToString("N")[..8]; var root = new TreeRedbObject { name = $"{tag}-root", Props = TestDataFactory.CreateEmployee(0, department: $"{tag}-root").Props }; root.id = await Redb.SaveAsync(root); var ids = new List(); var props = new List(); for (var i = 0; i < Rows.Length; i++) { var p = TestDataFactory.CreateEmployee(i + 1, firstName: $"{tag}-{i}", department: $"{tag}-d{Rows[i].Dept}").Props; p.Age = Rows[i].Age; p.SkillLevels = Rows[i].Levels; ids.Add(await Redb.CreateChildAsync(new TreeRedbObject { name = $"{tag}-{i}", Props = p }, root)); props.Add(p); } return new Seeded(root.id, ids, props); } private IRedbQueryable Employees(Seeded s, bool tree) { if (tree) return Redb.TreeQuery(s.RootId).WhereRedb(o => o.Id != s.RootId); var idSet = s.Ids.ToHashSet(); return Redb.Query().WhereRedb(o => idSet.Contains(o.Id)); } [Theory] [InlineData(false)] [InlineData(true)] public async Task AverageAsync_IntegerField_KeepsTheFraction(bool tree) { var s = await SeedAsync(); var avg = await Employees(s, tree).AverageAsync(e => e.Age); ((double)avg).Should().BeApproximately(s.Props.Average(p => p.Age), Precision); } [Theory] [InlineData(false)] [InlineData(true)] public async Task AverageRedbAsync_BaseId_KeepsTheFraction(bool tree) { var s = await SeedAsync(); var avg = await Employees(s, tree).AverageRedbAsync(o => o.Id); ((double)avg).Should().BeApproximately(s.Ids.Average(), Precision); } [Theory] [InlineData(false)] [InlineData(true)] public async Task AggregateRedbAsync_BaseId_KeepsTheFraction(bool tree) { var s = await SeedAsync(); var r = await Employees(s, tree).AggregateRedbAsync(o => new { Avg = Agg.Average(o.Id) }); ((double)r.Avg).Should().BeApproximately(s.Ids.Average(), Precision); } [Theory] [InlineData(false)] [InlineData(true)] public async Task AggregateAsync_IntegerFieldAndArrayElements_KeepTheFraction(bool tree) { var s = await SeedAsync(); var r = await Employees(s, tree).AggregateAsync(x => new { AvgAge = Agg.Average(x.Props.Age), AvgLevel = Agg.Average(x.Props.SkillLevels!.Select(v => v)), Count = Agg.Count() }); r.Count.Should().Be(s.Props.Count); ((double)r.AvgAge).Should().BeApproximately(s.Props.Average(p => p.Age), Precision); ((double)r.AvgLevel).Should().BeApproximately(s.Props.SelectMany(p => p.SkillLevels!).Average(), Precision); } [Theory] [InlineData(false)] [InlineData(true)] public async Task GroupBy_AverageOfIntegerField_KeepsTheFraction(bool tree) { var s = await SeedAsync(); var groups = await Employees(s, tree).GroupBy(e => e.Department) .SelectAsync(g => new { Key = g.Key, Avg = Agg.Average(g, e => e.Age) }); AssertPerDepartment(s, groups.Select(g => (g.Key, (double)g.Avg))); } [Theory] [InlineData(false)] [InlineData(true)] public async Task GroupedWindow_AverageOfIntegerField_KeepsTheFraction(bool tree) { var s = await SeedAsync(); var groups = await Employees(s, tree).GroupBy(e => e.Department).WithWindow(w => w.OrderBy(g => g.Key)) .SelectAsync(g => new { Key = g.Key, Avg = Agg.Average(g, e => e.Age), Row = Win.RowNumber() }); AssertPerDepartment(s, groups.Select(g => (g.Key, (double)g.Avg))); } [Theory] [InlineData(false)] [InlineData(true)] public async Task Window_AverageOfIntegerField_KeepsTheFraction(bool tree) { var s = await SeedAsync(); var rows = await Employees(s, tree).WithWindow(w => w.PartitionBy(e => e.Department)) .SelectAsync(e => new { e.Props.Department, Avg = Win.Avg(e.Props.Age) }); rows.Should().HaveCount(s.Props.Count); AssertPerDepartment(s, rows.Select(r => (r.Department, (double)r.Avg))); } private static void AssertPerDepartment(Seeded s, IEnumerable<(string Department, double Avg)> actual) { var truth = s.Props.GroupBy(p => p.Department).ToDictionary(g => g.Key, g => g.Average(p => p.Age)); var list = actual.ToList(); list.Select(a => a.Department).Distinct().Should().BeEquivalentTo(truth.Keys); foreach (var (department, avg) in list) avg.Should().BeApproximately(truth[department], Precision, department); } } Path: redb/redb.Tests.Integration/Tests/Base/InterfaceCollectionsTestsBase.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/InterfaceCollectionsTestsBase.cs ---- using redb.Core; using redb.Core.Models.Entities; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// A list declared as IEnumerable<T>, ICollection<T> or IList<T> and a dictionary declared as /// IDictionary<K, V> read back as saved, with a numeric element narrower than the stored one, a nullable element, /// a class element and an empty list. The sync makes the same structure as for List<T> and the rows are right. /// public abstract class InterfaceCollectionsTestsBase { protected readonly IRedbService Redb; protected InterfaceCollectionsTestsBase(IRedbService redb) => Redb = redb; private async Task RoundTripAsync(TProps props, Func value) where TProps : class, new() { await Redb.SyncSchemeAsync(); var id = await Redb.SaveAsync(new RedbObject { name = "iface-" + Guid.NewGuid().ToString("N")[..8], Props = props }); var loaded = (await Redb.LoadAsync(id))!.Props; value(loaded).Should().BeEquivalentTo(value(props), o => o.WithStrictOrdering()); } [Fact] public Task IEnumerableOfInt() => RoundTripAsync(new IfaceIEnumerableOfIntProps { Value = new List { 3, -1, 2 } }, p => p.Value); [Fact] public Task IEnumerableOfShort() => RoundTripAsync(new IfaceIEnumerableOfShortProps { Value = new List { 3, -1, 2 } }, p => p.Value); [Fact] public Task IEnumerableOfByte() => RoundTripAsync(new IfaceIEnumerableOfByteProps { Value = new List { 3, 1, 255 } }, p => p.Value); [Fact] public Task IEnumerableOfFloat() => RoundTripAsync(new IfaceIEnumerableOfFloatProps { Value = new List { 1.5f, -2.25f } }, p => p.Value); [Fact] public Task IEnumerableOfDecimal() => RoundTripAsync(new IfaceIEnumerableOfDecimalProps { Value = new List { 1.5m, -2.25m, 12345678.901m } }, p => p.Value); [Fact] public Task ICollectionOfInt() => RoundTripAsync(new IfaceICollectionOfIntProps { Value = new List { 3, -1, 2 } }, p => p.Value); [Fact] public Task ICollectionOfShort() => RoundTripAsync(new IfaceICollectionOfShortProps { Value = new List { 3, -1, 2 } }, p => p.Value); [Fact] public Task ICollectionOfByte() => RoundTripAsync(new IfaceICollectionOfByteProps { Value = new List { 3, 1, 255 } }, p => p.Value); [Fact] public Task ICollectionOfFloat() => RoundTripAsync(new IfaceICollectionOfFloatProps { Value = new List { 1.5f, -2.25f } }, p => p.Value); [Fact] public Task ICollectionOfDecimal() => RoundTripAsync(new IfaceICollectionOfDecimalProps { Value = new List { 1.5m, -2.25m, 12345678.901m } }, p => p.Value); [Fact] public Task IListOfInt() => RoundTripAsync(new IfaceIListOfIntProps { Value = new List { 3, -1, 2 } }, p => p.Value); [Fact] public Task IListOfShort() => RoundTripAsync(new IfaceIListOfShortProps { Value = new List { 3, -1, 2 } }, p => p.Value); [Fact] public Task IListOfByte() => RoundTripAsync(new IfaceIListOfByteProps { Value = new List { 3, 1, 255 } }, p => p.Value); [Fact] public Task IListOfFloat() => RoundTripAsync(new IfaceIListOfFloatProps { Value = new List { 1.5f, -2.25f } }, p => p.Value); [Fact] public Task IListOfDecimal() => RoundTripAsync(new IfaceIListOfDecimalProps { Value = new List { 1.5m, -2.25m, 12345678.901m } }, p => p.Value); [Fact] public Task IDictionaryOfInt() => RoundTripAsync(new IfaceIDictionaryOfIntProps { Value = new Dictionary { ["a"] = -1, ["b"] = 2 } }, p => p.Value); [Fact] public Task IDictionaryOfShort() => RoundTripAsync(new IfaceIDictionaryOfShortProps { Value = new Dictionary { ["a"] = -1, ["b"] = 2 } }, p => p.Value); [Fact] public Task IDictionaryOfByte() => RoundTripAsync(new IfaceIDictionaryOfByteProps { Value = new Dictionary { ["a"] = 255, ["b"] = 1 } }, p => p.Value); [Fact] public Task IDictionaryOfFloat() => RoundTripAsync(new IfaceIDictionaryOfFloatProps { Value = new Dictionary { ["a"] = 1.5f, ["b"] = -2.25f } }, p => p.Value); [Fact] public Task IDictionaryOfDecimal() => RoundTripAsync(new IfaceIDictionaryOfDecimalProps { Value = new Dictionary { ["a"] = 1.5m, ["b"] = -2.25m } }, p => p.Value); [Fact] public Task IListOfNullableInt_KeepsTheNull() => RoundTripAsync(new IfaceIListOfNullableIntProps { Value = new List { 1, null, 3 } }, p => p.Value); [Fact] public Task IListOfInt_Empty() => RoundTripAsync(new IfaceIListOfIntProps { Value = new List() }, p => p.Value); [Fact] public Task IEnumerableOfShort_Empty() => RoundTripAsync(new IfaceIEnumerableOfShortProps { Value = new List() }, p => p.Value); [Fact] public Task IListOfClass() => RoundTripAsync(new IfaceIListOfClassProps { Value = new List { new() { Name = "a", Count = 1 }, new() { Name = "b", Count = 2 } } }, p => p.Value); [Fact] public Task ICollectionOfClass() => RoundTripAsync(new IfaceICollectionOfClassProps { Value = new List { new() { Name = "a", Count = 1 } } }, p => p.Value); [Fact] public Task IEnumerableOfClass() => RoundTripAsync(new IfaceIEnumerableOfClassProps { Value = new List { new() { Name = "a", Count = 1 } } }, p => p.Value); private async Task ReferencesReadBackAsync(Func>, TProps> make, Func>?> value) where TProps : class, new() { await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); var a = new RedbObject { name = "iface-ref-a", Props = new() { Name = "a", Count = 1 } }; var b = new RedbObject { name = "iface-ref-b", Props = new() { Name = "b", Count = 2 } }; await Redb.SaveAsync(a); await Redb.SaveAsync(b); var id = await Redb.SaveAsync(new RedbObject { name = "iface-" + Guid.NewGuid().ToString("N")[..8], Props = make([a, b]) }); var loaded = value((await Redb.LoadAsync(id))!.Props)!.ToList(); loaded.Select(r => r.id).Should().Equal(a.id, b.id); loaded.Select(r => r.Props?.Name).Should().Equal("a", "b"); } [Fact] public Task IListOfReference() => ReferencesReadBackAsync(l => new IfaceIListOfReferenceProps { Value = l }, p => p.Value); [Fact] public Task IEnumerableOfReference() => ReferencesReadBackAsync(l => new IfaceIEnumerableOfReferenceProps { Value = l }, p => p.Value); } Path: redb/redb.Tests.Integration/Tests/Base/KeyCacheRepeatTestsBase.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/KeyCacheRepeatTestsBase.cs ---- using Microsoft.Extensions.DependencyInjection; using redb.Core; using redb.Core.Models.Entities; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// The key cache of a process hands out an id another row already has: the database got rows since this process cached /// its block (a restore of an older backup sets the sequence back, another process takes the same range). The save of a /// new object then fails on the primary key of _objects. It must fail once with the clear error, reset the key /// cache and give the object its id 0 back, so the next save takes a fresh id; on PostgreSQL and SQL Server the primary /// key violation is also a unique violation and was translated as one, the cache kept its stale block and every next /// create failed again. /// /// The restore is reproduced in one database: process A (its own connection string, so its own key cache) takes its /// block, the sequence is set back below it, process B (another connection string) takes the same range and saves. /// The sequence is put back at least to its old top afterwards, so nothing else of the collection meets the range. /// /// public abstract class KeyCacheRepeatTestsBase { /// A Pro service on the test database under a connection string of its own (its own key cache domain). protected abstract ServiceProvider Build(string applicationName); /// The value the sequence handed out last. protected abstract string SequenceTopSql { get; } /// Sets the sequence so that its next value is . protected abstract string SequenceRestartSql(long next); [Fact] public async Task ARestoredRange_TheNextSave_FailsOnceResetsTheCacheAndLeavesTheOtherRows() => await RunAsync(async (a, created) => await a.SaveAsync(created), inCallersTransaction: false); [Fact] public async Task ARestoredRange_TheNextSaveInTheCallersTransaction_FailsOnceAndTheTransactionGoesOn() => await RunAsync(async (a, created) => await a.SaveAsync(created), inCallersTransaction: true); [Fact] public async Task ARestoredRange_TheNextAddNewObjects_FailsOnceResetsTheCacheAndLeavesTheOtherRows() => await RunAsync(async (a, created) => (await a.AddNewObjectsAsync(new[] { created }))[0], inCallersTransaction: false); private async Task RunAsync(Func, Task> create, bool inCallersTransaction) { await using var providerA = Build($"keycache-a-{Guid.NewGuid():N}"); await using var providerB = Build($"keycache-b-{Guid.NewGuid():N}"); var a = providerA.GetRequiredService(); var b = providerB.GetRequiredService(); await a.InitializeAsync(); await a.SyncSchemeAsync(); await b.InitializeAsync(); await b.SyncSchemeAsync(); // A takes its block: the first id of it is handed out, the rest stays in A's cache. var held = (await a.Context.NextObjectIdBatchAsync(1))[0]; var top = await a.Context.ExecuteScalarAsync(SequenceTopSql); top.Should().BeGreaterThan(held, "precondition: A cached a block above the id it took"); var bIds = new List(); long id = 0; try { // The restore: the sequence goes back below A's block, B takes the same range and saves. await a.Context.ExecuteAsync(SequenceRestartSql(held + 1)); for (var i = 0; i < 5; i++) bIds.Add(await b.SaveAsync(new RedbObject { name = $"keycache-b-{i}", Props = new SimpleProps { Title = $"b{i}" } })); bIds.Should().Contain(held + 1, "precondition: B took the ids A holds next"); var created = new RedbObject { name = "keycache-a-new", Props = new SimpleProps { Title = "after the restore" } }; if (inCallersTransaction) { await using var tx = await a.Context.BeginTransactionAsync(); var first = async () => await create(a, created); await first.Should().ThrowAsync().WithMessage("*key cache*restore or an import*"); created.Id.Should().Be(0, "the failed save gives the object its id 0 back"); id = await create(a, created); await tx.CommitAsync(); } else { var first = async () => await create(a, created); await first.Should().ThrowAsync().WithMessage("*key cache*restore or an import*"); created.Id.Should().Be(0, "the failed save gives the object its id 0 back"); id = await create(a, created); } bIds.Should().NotContain(id, "the reset cache takes a fresh range"); (await a.LoadAsync(id))!.Props.Title.Should().Be("after the restore"); for (var i = 0; i < bIds.Count; i++) (await b.LoadAsync(bIds[i]))!.name.Should().Be($"keycache-b-{i}", "B's rows are left as they were"); } finally { var now = await a.Context.ExecuteScalarAsync(SequenceTopSql); await a.Context.ExecuteAsync(SequenceRestartSql(Math.Max(top, now) + 1)); await b.DeleteAsync(id == 0 ? bIds : bIds.Append(id)); } } } Path: redb/redb.Tests.Integration/Tests/Base/KeyDrawTestsBase.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/KeyDrawTestsBase.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; /// /// How many keys a save draws from the key generator. A ChangeTracking save of an existing object draws keys only for /// the value rows it really inserts; it used to draw one for every value row it built, and the diff then threw most of /// them away (a changed object burnt one key per value row on every save). DeleteInsert inserts every row again and /// draws a key for each, as before. Keys are counted by drawing one before and one after the save: the generator hands /// them out in order, and the tests of a collection run one at a time. /// public abstract class KeyDrawTestsBase { protected readonly IRedbService Redb; protected KeyDrawTestsBase(IRedbService redb) => Redb = redb; private static KeyDrawProps Props() => new() { Tag = "t", Score = 1, Levels = [1, 2, 3], Lines = [new KeyDrawLine { Name = "a", Rank = 1 }, new KeyDrawLine { Name = "b", Rank = 2 }], Main = new KeyDrawLine { Name = "m", Rank = 9 } }; private async Task KeysDrawnBy(Func save) { var before = await Redb.Context.NextObjectIdAsync(); await save(); var after = await Redb.Context.NextObjectIdAsync(); return after - before - 1; } private Task ValueRowsAsync(long id) => Redb.Context.ExecuteScalarAsync($"SELECT CAST(COUNT(*) AS BIGINT) FROM _values WHERE _id_object = {id}"); private async Task WithStrategy(PropsSaveStrategy strategy, Func> act) { var saving = Redb.Configuration.PropsSaveStrategy; try { Redb.Configuration.PropsSaveStrategy = strategy; return await act(); } finally { Redb.Configuration.PropsSaveStrategy = saving; } } private async Task> SeedAsync() { await Redb.SyncSchemeAsync(); var id = await Redb.SaveAsync(new RedbObject { name = "kd", Props = Props() }); return (await Redb.LoadAsync(id))!; } [Fact] public async Task ChangeTracking_OneScalarChanged_DrawsNoKey() { var obj = await SeedAsync(); obj.Props.Score = 2; var drawn = await WithStrategy(PropsSaveStrategy.ChangeTracking, () => KeysDrawnBy(() => Redb.SaveAsync(obj))); drawn.Should().Be(0, "the changed row is updated in place"); (await Redb.LoadAsync(obj.id))!.Props.Score.Should().Be(2); } [Fact] public async Task ChangeTracking_OneArrayElementAdded_DrawsOneKey() { var obj = await SeedAsync(); obj.Props.Levels = [1, 2, 3, 4]; var drawn = await WithStrategy(PropsSaveStrategy.ChangeTracking, () => KeysDrawnBy(() => Redb.SaveAsync(obj))); drawn.Should().Be(1, "one element row is inserted"); (await Redb.LoadAsync(obj.id))!.Props.Levels.Should().Equal(1, 2, 3, 4); } [Fact] public async Task ChangeTracking_OneClassElementAdded_DrawsAKeyPerInsertedRow() { var obj = await SeedAsync(); obj.Props.Lines!.Add(new KeyDrawLine { Name = "c", Rank = 3 }); var drawn = await WithStrategy(PropsSaveStrategy.ChangeTracking, () => KeysDrawnBy(() => Redb.SaveAsync(obj))); drawn.Should().Be(3, "the element row and its two fields are inserted"); var lines = (await Redb.LoadAsync(obj.id))!.Props.Lines!; lines.Select(l => (l.Name, l.Rank)).Should().Equal(("a", 1), ("b", 2), ("c", 3)); } [Fact] public async Task ChangeTracking_NothingChanged_DrawsNoKey() { var obj = await SeedAsync(); var drawn = await WithStrategy(PropsSaveStrategy.ChangeTracking, () => KeysDrawnBy(() => Redb.SaveAsync(obj))); drawn.Should().Be(0); } [Fact] public async Task DeleteInsert_DrawsAKeyPerRow_AsItInsertsThemAll() { var obj = await SeedAsync(); obj.Props.Score = 2; var drawn = await WithStrategy(PropsSaveStrategy.DeleteInsert, () => KeysDrawnBy(() => Redb.SaveAsync(obj))); drawn.Should().Be((await ValueRowsAsync(obj.id))!.Value, "DeleteInsert inserts every value row again"); (await Redb.LoadAsync(obj.id))!.Props.Score.Should().Be(2); } [Fact] public async Task NewObject_DrawsAKeyPerRowAndOneForTheObject() { await Redb.SyncSchemeAsync(); long id = 0; var drawn = await KeysDrawnBy(async () => id = await Redb.SaveAsync(new RedbObject { name = "kd-new", Props = Props() })); drawn.Should().Be((await ValueRowsAsync(id))!.Value + 1); } } Path: redb/redb.Tests.Integration/Tests/Base/KeywordNamesTestsBase.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/KeywordNamesTestsBase.cs ---- using redb.Core; using redb.Core.Models.Entities; using redb.Core.Query; using redb.Core.Query.Aggregation; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// A scheme whose property names differ from C# keywords only by case (Ref, Default, Event, String, Object) works end to /// end: sync, save, load, Where, OrderBy, GroupBy, with the planner off and on. The names reach the SQL of every provider /// as structure ids and quoted aliases, never folded to lower case. /// public abstract class KeywordNamesTestsBase { protected readonly IRedbService Redb; protected KeywordNamesTestsBase(IRedbService redb) => Redb = redb; private async Task> SeedAsync(string tag) { var start = new DateTime(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc); var objects = Enumerable.Range(0, 6).Select(i => new RedbObject { name = $"{tag}_{i}", Props = new KeywordNamesProps { Ref = 100 + i, Default = i % 2 == 0 ? $"{tag}-even" : $"{tag}-odd", Event = start.AddDays(i), String = i == 5 ? null : $"{tag}-s{i}", Object = 10.5m * i } }).ToList(); return await Redb.SaveAsync(objects); } private async Task EachFormAsync(Func check) { var restore = Redb.Configuration.EnablePvtPrefilter; try { foreach (var on in new[] { false, true }) { Redb.UpdateConfiguration(c => c.EnablePvtPrefilter = on); await check(on ? "planner on" : "planner off"); } } finally { Redb.UpdateConfiguration(c => c.EnablePvtPrefilter = restore); } } [Fact] public async Task KeywordLikeNames_SaveAndLoad() { var tag = $"kwl{Guid.NewGuid():N}"[..12]; var ids = await SeedAsync(tag); var loaded = await Redb.LoadAsync(ids[3]); loaded.Should().NotBeNull(); loaded!.Props.Ref.Should().Be(103); loaded.Props.Default.Should().Be($"{tag}-odd"); loaded.Props.Event.Should().Be(new DateTime(2026, 1, 4, 0, 0, 0, DateTimeKind.Utc)); loaded.Props.String.Should().Be($"{tag}-s3"); loaded.Props.Object.Should().Be(31.5m); } [Fact] public async Task KeywordLikeNames_WhereOrderByGroupBy() { var tag = $"kwq{Guid.NewGuid():N}"[..12]; await SeedAsync(tag); await EachFormAsync(async form => { IRedbQueryable Mine() => Redb.Query().Where(p => p.Default.StartsWith(tag)); var byRef = await Mine().Where(p => p.Ref >= 102 && p.Object < 40m).OrderByDescending(p => p.Event).ToListAsync(); byRef.Select(o => o.Props.Ref).Should().Equal(new long[] { 103, 102 }, form); var byDefault = await Mine().Where(p => p.Default == $"{tag}-even").OrderBy(p => p.Object).ToListAsync(); byDefault.Select(o => o.Props.Ref).Should().Equal(new long[] { 100, 102, 104 }, form); var byString = await Mine().Where(p => p.String == null).ToListAsync(); byString.Select(o => o.Props.Ref).Should().Equal(new long[] { 105 }, form); var byEvent = await Mine().Where(p => p.Event > new DateTime(2026, 1, 4, 0, 0, 0, DateTimeKind.Utc)).OrderBy(p => p.String).ToListAsync(); byEvent.Select(o => o.Props.Ref).Should().Equal(new long[] { 105, 104 }, form); var groups = await Mine() .GroupBy(p => p.Default) .SelectAsync(g => new { g.Key, Count = Agg.Count(g), Sum = Agg.Sum(g, p => p.Object), Max = Agg.Max(g, p => p.Ref) }); groups.OrderBy(g => g.Key).Select(g => (g.Key, g.Count, g.Sum, g.Max)).Should().Equal( new[] { ($"{tag}-even", 3, 63m, 104L), ($"{tag}-odd", 3, 94.5m, 105L) }, form); }); } } Path: redb/redb.Tests.Integration/Tests/Base/LazyHostTestsBase.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/LazyHostTestsBase.cs ---- using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Core; using redb.Core.Data; using redb.Core.Extensions; using redb.Core.Models.Configuration; using redb.Core.Exceptions; using redb.Core.Models.Entities; using redb.Core.Providers; using redb.Core.Utils; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// V4 (Л2, review): what the shared-database fixtures cannot see. They hold one context for the /// whole run and never return its connection to the pool, so (a) the GLOBAL lazy option armed at /// connection open was never checked on a second scope - and on PostgreSQL DISCARD ALL wiped /// it on every pooled hand-out - and (b) EnablePropsCache is off everywhere, so the props-cache /// walker was never run over a graph with stubs. Every test here builds its own host. /// public abstract class LazyHostTestsBase { /// Registers the provider on the options builder (Free or Pro, see ). protected abstract void UseProvider(RedbOptionsBuilder options); /// Reads the session flag the builders consult; "1" when armed. protected abstract string ReadFlagSql { get; } /// /// The Free builders read the session flag; the Pro materializer reads the global option live /// and its registrations do not arm the flag (a recorded Л2 boundary). /// protected virtual bool SessionFlagIsTheChannel => true; protected virtual void Register(IServiceCollection services, Action configure) => services.AddRedb(configure); private ServiceProvider Build(Action configure) { var services = new ServiceCollection(); services.AddLogging(b => b.SetMinimumLevel(LogLevel.Warning)); Register(services, options => { UseProvider(options); options.Configure(c => { c.EnablePropsCache = false; c.SkipHashValidationOnCacheCheck = false; // Own cache domain per suite: this process also holds the shared fixtures on the same database, and the // hosts of the six suites run in parallel - one database is registered per domain. c.CacheDomain = $"lazy-host-{GetType().Name}"; configure(c); }); }); return services.BuildServiceProvider(); } private static async Task SaveTriangleAsync(IRedbService redb, string tag) { var nextId = await redb.SaveAsync(new RedbObject { name = $"lhost-next-{tag}", Props = new LazyOptionNodeProps { Label = $"next-{tag}" } }); var plainId = await redb.SaveAsync(new RedbObject { name = $"lhost-plain-{tag}", Props = new LazyOptionNodeProps { Label = $"plain-{tag}" } }); return await redb.SaveAsync(new RedbObject { name = $"lhost-root-{tag}", Props = new LazyOptionNodeProps { Label = $"root-{tag}", Next = new RedbObject { id = nextId }, Plain = new RedbObject { id = plainId }, } }); } private static async Task SaveChainAsync(IRedbService redb, string tag) { var leafId = await redb.SaveAsync(new RedbObject { name = $"lhost-leaf-{tag}", Props = new LazyNodeProps { Label = $"leaf-{tag}" } }); var midId = await redb.SaveAsync(new RedbObject { name = $"lhost-mid-{tag}", Props = new LazyNodeProps { Label = $"mid-{tag}", Next = new RedbObject { id = leafId } } }); return await redb.SaveAsync(new RedbObject { name = $"lhost-root-{tag}", Props = new LazyNodeProps { Label = $"root-{tag}", Next = new RedbObject { id = midId } } }); } [Fact] public async Task GlobalOption_HoldsOnEveryScope_NotOnlyTheFirstPhysicalConnection() { await using var sp = Build(c => c.EnableLazyReferences = true); var boot = sp.GetRequiredService(); await boot.InitializeAsync(ensureCreated: true); await boot.SyncSchemeAsync(); await boot.InitializeTypeRegistryAsync(); long rootId; using (var seed = sp.CreateScope()) rootId = await SaveTriangleAsync(seed.ServiceProvider.GetRequiredService(), "scopes"); // Three scopes in a row: after the first one its connection went back to the pool and the // next scope gets it again. DISCARD ALL (PostgreSQL) / sp_reset_connection (MSSQL) wipe the // session state in between; the option must be armed again on every hand-out. for (var scope = 1; scope <= 3; scope++) { using var s = sp.CreateScope(); var redb = s.ServiceProvider.GetRequiredService(); if (SessionFlagIsTheChannel) { var flag = await redb.Context.ExecuteScalarAsync(ReadFlagSql); Convert.ToString(flag).Should().Be("1", $"scope {scope}: the session flag must be armed on the pooled connection, not only on a fresh backend"); } var root = await redb.LoadAsync(rootId, depth: 10); root!.Props.Next!.IsPropsLoaded.Should().BeFalse( $"scope {scope}: a virtual reference is a stub at any depth while the option is on"); root.Props.Plain!.IsPropsLoaded.Should().BeTrue("a non-virtual reference stays eager"); } } [Fact] public async Task PropsCacheOn_LazyLoadsStayLazy() { await using var sp = Build(c => c.EnablePropsCache = true); var redb = sp.GetRequiredService(); await redb.InitializeAsync(ensureCreated: true); await redb.SyncSchemeAsync(); await redb.InitializeTypeRegistryAsync(); var rootId = await SaveChainAsync(redb, "cache"); ((RedbServiceBase)redb).PropsCache.Instance.Should().NotBeNull("the props cache must be active, or this test proves nothing"); // The save itself caches what it wrote (the very in-memory instances); evict, so the loads // below really go to the database and through the caching walker. ((RedbServiceBase)redb).PropsCache.Instance!.Clear(); // The single load (the Pro path that walked the graph after attaching the loaders) and the // bulk load (the Free path that did the same), both at depth 1: caching the loaded graph // must never read a stub's Props - that read IS the lazy load, synchronous, for the whole // reachable graph. var single = await redb.LoadAsync(rootId, depth: 1); single!.Props.Next!.IsPropsLoaded.Should().BeFalse("the single load must not wake the boundary stub while caching"); // A second chain for the bulk form: the first root is already in the cache and would be // served from there, walker untouched. var bulkRootId = await SaveChainAsync(redb, "cache-bulk"); ((RedbServiceBase)redb).PropsCache.Instance!.Clear(); var bulk = (RedbObject)(await redb.LoadAsync(new[] { bulkRootId }, depth: 1))[0]; bulk.Props.Next!.IsPropsLoaded.Should().BeFalse("the bulk load must not wake the boundary stub while caching"); // And the cache serves the parent consistently: the live hash equals the persisted one. var again = await redb.LoadAsync(rootId, depth: 1); again!.hash.Should().Be(single.hash); RedbHash.ComputeFor(again).Should().Be(single.hash, "a cache entry whose live hash never matches its stored one is a miss for ever"); } // A reference of a cached object read inside a transaction: ReaderConnectionTestsBase (owner decision 2026-09-15 - // the load runs on the reader's connection and the shared instance keeps nothing). [Fact] public async Task ThrowMode_GetterRefuses_AsyncApisStillLoad() { await using var sp = Build(c => c.LazyReferenceAccess = LazyReferenceAccessMode.Throw); var redb = sp.GetRequiredService(); await redb.InitializeAsync(ensureCreated: true); await redb.SyncSchemeAsync(); await redb.InitializeTypeRegistryAsync(); var rootId = await SaveChainAsync(redb, "throw"); var root = await redb.LoadAsync(rootId, depth: 1); var stub = root!.Props.Next!; stub.IsPropsLoaded.Should().BeFalse(); Action act = () => _ = stub.Props; act.Should().Throw("the host declared a blocking load on property access a defect") .Which.ObjectId.Should().Be(stub.id); stub.IsPropsLoaded.Should().BeFalse("a refusal loads nothing and memoises nothing"); await stub.LoadPropsAsync(); stub.IsPropsLoaded.Should().BeTrue(); stub.Props.Label.Should().Be("mid-throw", "the explicit async load works in every mode"); } [Fact] public async Task BlockingGetter_DoesNotDeadlock_UnderASynchronizationContext() { await using var sp = Build(_ => { }); var redb = sp.GetRequiredService(); await redb.InitializeAsync(ensureCreated: true); await redb.SyncSchemeAsync(); await redb.InitializeTypeRegistryAsync(); var rootId = await SaveChainAsync(redb, "uictx"); var root = await redb.LoadAsync(rootId, depth: 1); var stub = root!.Props.Next!; // A UI-like context: continuations posted to it never run while its thread is blocked in // the getter - exactly Blazor Server, WPF, MAUI. Without the pool hand-off this deadlocks. string? label = null; Exception? error = null; var thread = new Thread(() => { SynchronizationContext.SetSynchronizationContext(new BlockedUiContext()); try { label = stub.Props?.Label; } catch (Exception ex) { error = ex; } }) { IsBackground = true }; thread.Start(); thread.Join(TimeSpan.FromSeconds(30)).Should().BeTrue( "the getter must finish on a host with a SynchronizationContext, not deadlock on its own continuations"); error.Should().BeNull(); label.Should().Be("mid-uictx"); } [Fact] public async Task SkipHashValidation_NeverServesTheCacheInsideATransaction() { // Bug report п.1 (2026-09-02): with EnablePropsCache + SkipHashValidationOnCacheCheck the // single load answered from the cache with ZERO database queries - even inside // ExecuteAtomicAsync + LockForUpdateAsync, where the re-read is the read of a // read-modify-write. A pre-lock cached copy there is the lost update the lock exists to // prevent. Inside a transaction the load now always consults the database. await using var sp = Build(c => { c.EnablePropsCache = true; c.SkipHashValidationOnCacheCheck = true; }); var redb = sp.GetRequiredService(); await redb.InitializeAsync(ensureCreated: true); await redb.SyncSchemeAsync(); await redb.InitializeTypeRegistryAsync(); var obj = new RedbObject { name = "rmw", Props = new LazyNodeProps { Label = "v1" } }; var id = await redb.SaveAsync(obj); (await redb.LoadAsync(id, depth: 1))!.Props.Label.Should().Be("v1"); // cached // Another node commits: the row changes behind this process's cache. var labelStructure = await redb.Context.ExecuteScalarAsync( $"SELECT _id FROM _structures WHERE _name = 'Label' AND _id_scheme = (SELECT _id_scheme FROM _objects WHERE _id = {id})"); await redb.Context.ExecuteAsync($"UPDATE _values SET _String = 'v2' WHERE _id_object = {id} AND _id_structure = {labelStructure}"); await redb.Context.ExecuteAsync($"UPDATE _objects SET _hash = NULL WHERE _id = {id}"); // Outside a transaction the zero-DB shortcut is the documented single-writer trade-off: // the stale copy is served. That contract stays. (await redb.LoadAsync(id, depth: 1))!.Props.Label.Should().Be("v1", "outside a transaction the flag trades freshness for zero-latency hits, as documented"); // Inside the transaction of a read-modify-write the database must be consulted. await redb.Context.ExecuteAtomicAsync(async () => { (await redb.LoadAsync(id, depth: 1))!.Props.Label.Should().Be("v2", "a load inside a transaction is the read of a read-modify-write and must see the database's row"); }); } [Fact] public async Task MutatedCachedInstance_AfterAFailedSave_IsNotServed() { // Bug report п.3 (2026-09-02) - pinned, not red-before: the dirty-snapshot guard already // refused a mutated root (pre-V4), and the graph walk of this review covers nested edits. // The scenario from the report: read from cache, mutate the shared Props, save FAILS // (unique violation) - the next read must serve the committed state, not the mutation. await using var sp = Build(c => c.EnablePropsCache = true); var redb = sp.GetRequiredService(); await redb.InitializeAsync(ensureCreated: true); await redb.SyncSchemeAsync(); await redb.InitializeTypeRegistryAsync(); // Keys are per run: the Free and Pro fixtures share one database, and a fixed key would // trip over the previous run's row at setup. var k1 = $"PIN-{Guid.NewGuid():N}"; await redb.SaveAsync(new RedbObject { name = "pin-a", ValueUnique = k1, Props = new LazyNodeProps { Label = "a" } }); var b = new RedbObject { name = "pin-b", ValueUnique = $"PIN-{Guid.NewGuid():N}", Props = new LazyNodeProps { Label = "committed" } }; var bId = await redb.SaveAsync(b); var cached = await redb.LoadAsync(bId, depth: 1); cached!.Props.Label = "phantom"; // mutate the SHARED cached instance cached.ValueUnique = k1; // and make the save fail on the unique index var act = async () => await redb.SaveAsync(cached); await act.Should().ThrowAsync(); var served = await redb.LoadAsync(bId, depth: 1); served!.Props.Label.Should().Be("committed", "a failed save must not leave the mutated copy answering from the cache"); } [Fact] public async Task CachedGraph_WithAnUnsavedNestedEdit_IsNotServed() { await using var sp = Build(c => c.EnablePropsCache = true); var redb = sp.GetRequiredService(); await redb.InitializeAsync(ensureCreated: true); await redb.SyncSchemeAsync(); await redb.InitializeTypeRegistryAsync(); var rootId = await SaveChainAsync(redb, "dirtyguard"); ((RedbServiceBase)redb).PropsCache.Instance!.Clear(); // Eager load, so the nested object is LOADED inside the cached graph; an untouched graph // is served as a hit - the same shared instance. var cached = await redb.LoadAsync(rootId, depth: 10); (await redb.LoadAsync(rootId, depth: 10)).Should().BeSameAs(cached, "an untouched graph is a hit"); // The bug the guard exists for, one level down: edit the nested object, do not save. cached!.Props.Next!.Props.Label = "phantom"; var served = await redb.LoadAsync(rootId, depth: 10); served.Should().NotBeSameAs(cached, "a graph with an unsaved nested edit must not be served from the cache"); served!.Props.Next!.Props.Label.Should().Be("mid-dirtyguard", "the caller gets the committed state"); // The batch path refuses it the same way (served is the cached instance now). served.Props.Next.Props.Label = "phantom-2"; var batch = (RedbObject)(await redb.LoadAsync(new[] { rootId }, depth: 10))[0]; batch.Props.Next!.Props.Label.Should().Be("mid-dirtyguard"); // The inspection never wakes a stub: a depth-1 graph stays lazy through a hit. ((RedbServiceBase)redb).PropsCache.Instance!.Clear(); var lazyRoot = await redb.LoadAsync(rootId, depth: 1); var again = await redb.LoadAsync(rootId, depth: 1); again.Should().BeSameAs(lazyRoot); again!.Props.Next!.IsPropsLoaded.Should().BeFalse("the walk must not wake a stub"); } // A reference of a cached object read in another live scope: ReaderConnectionTestsBase (owner decision 2026-09-15 - // the load runs on the reader's connection, no scope of its own). /// /// The writer keeps its own cached instance - an application-level cache - and touches a reference after its scope /// ended. A data object owns no connection (owner decision 2026-09-15): with no live redb scope reading, the load is /// refused by default and runs in a fresh scope only when the configuration asks for it. Seeding and the writer's scope /// run in this helper, so nothing it resolves stays current for the caller. /// private async Task> WritersCachedInstanceAfterItsScopeEndedAsync(ServiceProvider sp, string tag) { long rootId; await using (var seed = sp.CreateAsyncScope()) { var redb = seed.ServiceProvider.GetRequiredService(); await redb.InitializeAsync(ensureCreated: true); await redb.SyncSchemeAsync(); await redb.InitializeTypeRegistryAsync(); rootId = await SaveChainAsync(redb, tag); ((RedbServiceBase)redb).PropsCache.Instance!.Clear(); } RedbObject cachedRoot; await using (var writer = sp.CreateAsyncScope()) cachedRoot = (await writer.ServiceProvider.GetRequiredService().LoadAsync(rootId, depth: 1))!; cachedRoot.Props.Next!.IsPropsLoaded.Should().BeFalse("precondition: the reference is a stub"); return cachedRoot; } [Fact] public async Task CachedObject_WriterScopeEnded_ReadRefuses_WithoutALiveScope() { await using var sp = Build(c => c.EnablePropsCache = true); var cachedRoot = await WritersCachedInstanceAfterItsScopeEndedAsync(sp, "writer-ended-refuse"); var stub = cachedRoot.Props.Next!; Action read = () => _ = stub.Props; read.Should().Throw( "no live redb scope reads here, and no scope is opened behind the reader's back"); stub.IsPropsLoaded.Should().BeFalse("a refusal loads nothing and memoises nothing"); } [Fact] public async Task CachedObject_WriterScopeEnded_SyncGetter_LoadsInAFreshScope_WhenConfigured() { await using var sp = Build(c => { c.EnablePropsCache = true; c.LazyLoadWithoutScope = LazyLoadWithoutScopeMode.FreshScope; }); var cachedRoot = await WritersCachedInstanceAfterItsScopeEndedAsync(sp, "writer-ended-sync"); cachedRoot.Props.Next!.Props.Label.Should().Be("mid-writer-ended-sync", "the configuration asks for a fresh scope when no live scope reads"); } [Fact] public async Task CachedObject_WriterScopeEnded_AsyncLoad_LoadsInAFreshScope_WhenConfigured() { await using var sp = Build(c => { c.EnablePropsCache = true; c.LazyLoadWithoutScope = LazyLoadWithoutScopeMode.FreshScope; }); var cachedRoot = await WritersCachedInstanceAfterItsScopeEndedAsync(sp, "writer-ended-async"); await cachedRoot.Props.Next!.LoadPropsAsync(); cachedRoot.Props.Next.IsPropsLoaded.Should().BeTrue(); cachedRoot.Props.Next.Props.Label.Should().Be("mid-writer-ended-async", "the configuration asks for a fresh scope when no live scope reads"); } /// Seeds a chain and loads its root in a scope that ends - both in this helper, so nothing stays current. private async Task> StubFromAScopeThatEndsAsync(ServiceProvider sp) { long rootId; await using (var seed = sp.CreateAsyncScope()) { var boot = seed.ServiceProvider.GetRequiredService(); await boot.InitializeAsync(ensureCreated: true); await boot.SyncSchemeAsync(); await boot.InitializeTypeRegistryAsync(); rootId = await SaveChainAsync(boot, "scope-ended"); } await using var a = sp.CreateAsyncScope(); var root = (await a.ServiceProvider.GetRequiredService().LoadAsync(rootId, depth: 1))!; return root.Props.Next!; } [Fact] public async Task ScopeEnded_ReferenceNotCached_GetterRefusesLoudly() { await using var sp = Build(_ => { }); var stub = await StubFromAScopeThatEndsAsync(sp); // The scope that loaded the object is gone, and no other redb scope reads here. Action act = () => _ = stub.Props; act.Should().Throw("no resurrected pooled connection, a clear refusal instead") .Which.ObjectId.Should().Be(stub.id); var actAsync = async () => await stub.LoadPropsAsync(); await actAsync.Should().ThrowAsync(); stub.IsPropsLoaded.Should().BeFalse("a refusal loads nothing and memoises nothing"); // The way out the message names: read it inside a live scope - the very same stub. await using var b = sp.CreateAsyncScope(); b.ServiceProvider.GetRequiredService().Should().NotBeNull("this scope is now current for the reads below"); stub.Props.Label.Should().Be("mid-scope-ended"); } /// A message loop that is busy blocking: whatever is posted to it never runs. private sealed class BlockedUiContext : SynchronizationContext { public override void Post(SendOrPostCallback d, object? state) { } public override void Send(SendOrPostCallback d, object? state) => throw new InvalidOperationException("Send on a blocked UI context"); } } Path: redb/redb.Tests.Integration/Tests/Base/LazyReferenceTestsBase.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/LazyReferenceTestsBase.cs ---- using System.Text.Json; using redb.Core; using redb.Core.Models.Entities; using redb.Core.Serialization; using redb.Core.Utils; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// V4 wave 4 (Л1, LAZY_REFERENCES_PLAN §3.6/§6): with the old Props-level lazy mechanism removed, /// `LoadAsync(depth: 1)` gives working lazy references for free — every reference at the boundary /// is a stub (W1 contract) that now carries a loader (L.3). First access to its Props loads exactly /// that object, with depth 1, so its own references are stubs again: laziness is transitive and /// independent of the original depth. The parent's hash takes each reference's own hash (L.2), so /// eager and lazy hashes agree and computing one never wakes the graph. Serialization goes through /// the SerializedProps bridge (L.4) and never wakes it either. /// public abstract class LazyReferenceTestsBase { protected readonly IRedbService Redb; protected LazyReferenceTestsBase(IRedbService redb) => Redb = redb; /// root → mid → leaf, references by id (never re-saved by the parent — W1). private async Task<(long rootId, long midId, long leafId)> SaveChainAsync(string tag) { var leafId = await Redb.SaveAsync(new RedbObject { name = $"lazy-leaf-{tag}", Props = new LazyNodeProps { Label = $"leaf-{tag}" } }); var midId = await Redb.SaveAsync(new RedbObject { name = $"lazy-mid-{tag}", Props = new LazyNodeProps { Label = $"mid-{tag}", Next = new RedbObject { id = leafId } } }); var rootId = await Redb.SaveAsync(new RedbObject { name = $"lazy-root-{tag}", Props = new LazyNodeProps { Label = $"root-{tag}", Next = new RedbObject { id = midId } } }); return (rootId, midId, leafId); } [Fact] public async Task FirstAccess_LoadsThatObject_ItsReferencesAreStubsAgain() { var (rootId, midId, leafId) = await SaveChainAsync("transitive"); var root = await Redb.LoadAsync(rootId, depth: 1); var midStub = root!.Props.Next!; midStub.IsPropsLoaded.Should().BeFalse("at depth 1 the reference is a stub"); midStub.id.Should().Be(midId); // First access loads exactly this object… var midProps = midStub.Props; midProps.Should().NotBeNull(); midProps!.Label.Should().Be("mid-transitive"); midStub.IsPropsLoaded.Should().BeTrue(); // …and the references under it are stubs again (the loader passes depth 1 — §4.7), // which are themselves loadable: laziness is transitive. var leafStub = midProps.Next!; leafStub.Should().NotBeNull("the boundary yields a stub, never null (W1 contract)"); leafStub.IsPropsLoaded.Should().BeFalse("the reloaded object's own references are stubs again"); leafStub.id.Should().Be(leafId); leafStub.Props!.Label.Should().Be("leaf-transitive"); } [Fact] public async Task FirstAccess_LoadsNestedClassesCompletely() { var leafId = await Redb.SaveAsync(new RedbObject { name = "lazy-leaf-meta", Props = new LazyNodeProps { Label = "leaf-meta" } }); var midId = await Redb.SaveAsync(new RedbObject { name = "lazy-mid-meta", Props = new LazyNodeProps { Label = "mid-meta", Meta = new LazyNodeMeta { Tag = "m" }, Next = new RedbObject { id = leafId } } }); var rootId = await Redb.SaveAsync(new RedbObject { name = "lazy-root-meta", Props = new LazyNodeProps { Label = "root-meta", Meta = new LazyNodeMeta { Tag = "r" }, Next = new RedbObject { id = midId } } }); // depth counts reference hops, not class nesting: a class field is loaded completely at // any depth by every builder, and the Pro materializer must agree. var root = await Redb.LoadAsync(rootId, depth: 1); root!.Props.Meta.Should().NotBeNull(); root.Props.Meta!.Tag.Should().Be("r", "a nested class is not a reference hop"); var mid = root.Props.Next!; mid.IsPropsLoaded.Should().BeFalse("the reference at the boundary is a stub"); mid.Props!.Meta.Should().NotBeNull(); mid.Props.Meta!.Tag.Should().Be("m", "the lazy reload (depth 1) must not cut the nested class either"); mid.Props.Next!.IsPropsLoaded.Should().BeFalse("while the reference under it is a stub again"); } [Fact] public async Task HashParity_EagerAndLazy_AndComputingNeverWakesTheStub() { var (rootId, _, _) = await SaveChainAsync("hashparity"); var lazyRoot = await Redb.LoadAsync(rootId, depth: 1); var lazyHash = RedbHash.ComputeFor(lazyRoot!); lazyHash.Should().NotBeNull(); lazyRoot!.Props.Next!.IsPropsLoaded.Should().BeFalse("computing the parent's hash must not wake the reference (L.2)"); var eagerRoot = await Redb.LoadAsync(rootId, depth: 10); var eagerHash = RedbHash.ComputeFor(eagerRoot!); eagerHash.Should().Be(lazyHash, "the parent hashes the reference's own hash, present on stub and full object alike"); } [Fact] public async Task FirstSave_WritesTheHashEveryReloadComputes_AndResavesKeepIt() { var (rootId, _, _) = await SaveChainAsync("stablehash"); // The chain is saved with hand-made `{ id = x }` references that carry no hash in memory; // the save resolves their persisted hashes, so the very first _objects._hash is the one // every reload computes - the props cache lives on exactly that equality. var persisted = (await Redb.LoadAsync(rootId, depth: 1))!.hash; persisted.Should().NotBeNull(); RedbHash.ComputeFor((await Redb.LoadAsync(rootId, depth: 10))!) .Should().Be(persisted, "the persisted hash must be reproducible from the loaded object"); // An eager re-save… var eager = await Redb.LoadAsync(rootId, depth: 10); await Redb.SaveAsync(eager!); (await Redb.LoadAsync(rootId, depth: 1))!.hash .Should().Be(persisted, "re-saving an unmodified object must not shift _objects._hash"); // …and a lazy re-save agree byte for byte: the stub carries the same id and hash. var lazy = await Redb.LoadAsync(rootId, depth: 1); await Redb.SaveAsync(lazy!); (await Redb.LoadAsync(rootId, depth: 1))!.hash .Should().Be(persisted, "the lazy and the eager form must write the same parent hash"); } [Fact] public async Task NewNestedObjectInOneSave_ParentHashIsReproducible() { var root = new RedbObject { name = "lazy-root-newnested", Props = new LazyNodeProps { Label = "root-newnested", Next = new RedbObject { name = "lazy-mid-newnested", Props = new LazyNodeProps { Label = "mid-newnested" } } } }; var rootId = await Redb.SaveAsync(root); root.Props.Next!.id.Should().BeGreaterThan(0, "the cascade save assigned the nested id"); // The parent hashes "id:hash" of its reference; both exist only after the ids are handed // out, so the hashes are computed then, children first - never with "0:" inside. var persisted = (await Redb.LoadAsync(rootId, depth: 1))!.hash; RedbHash.ComputeFor((await Redb.LoadAsync(rootId, depth: 10))!) .Should().Be(persisted, "the persisted parent hash must be reproducible from a reload"); root.hash.Should().Be(persisted, "the in-memory object carries what was written"); } [Fact] public async Task CollectionWithOneTargetTwice_EveryInstanceLoads() { var leafId = await Redb.SaveAsync(new RedbObject { name = "lazy-leaf-dup", Props = new LazyNodeProps { Label = "leaf-dup" } }); var rootId = await Redb.SaveAsync(new RedbObject { name = "lazy-root-dup", Props = new LazyNodeProps { Label = "root-dup", Children = Enumerable.Range(0, 6).Select(_ => new RedbObject { id = leafId }).ToList() } }); // Batch form: one target referenced six times is six stub instances - all of them load. var root = await Redb.LoadAsync(rootId, depth: 1); root!.Props.Children.Should().HaveCount(6); root.Props.Children.Should().OnlyContain(c => !c.IsPropsLoaded); await Redb.LoadReferencesAsync(root, p => p.Children); root.Props.Children.Should().OnlyContain(c => c.IsPropsLoaded && c.Props.Label == "leaf-dup", "the batch de-duplicates by id, but every instance in the graph must end up loaded"); // Getter form: the same six stubs touched one after another through the sync getter. (One // context is one connection; concurrent use of it is refused by the connection guard, so // the parallel variant is not a supported shape.) var again = await Redb.LoadAsync(rootId, depth: 1); again!.Props.Children!.Select(c => c.Props?.Label).Should().HaveCount(6).And.OnlyContain(l => l == "leaf-dup", "every stub of one target loads on first access, whichever instance goes first"); } [Fact] public async Task LoadReferencesAsync_ReloadsAtDepthOne_LikeFirstAccess() { var (rootId, midId, _) = await SaveChainAsync("batchdepth"); var holderId = await Redb.SaveAsync(new RedbObject { name = "lazy-holder-batchdepth", Props = new LazyNodeProps { Label = "holder-batchdepth", Children = new List> { new() { id = rootId } } } }); var holder = await Redb.LoadAsync(holderId, depth: 1); await Redb.LoadReferencesAsync(holder!, p => p.Children); var rootRef = holder!.Props.Children![0]; rootRef.IsPropsLoaded.Should().BeTrue(); rootRef.Props.Next!.id.Should().Be(midId); rootRef.Props.Next.IsPropsLoaded.Should().BeFalse( "the batch reload passes depth 1 like a stub's first access: laziness stays transitive (§4.7)"); } [Fact] public async Task SavingTheParent_DoesNotWakeOrDamageTheReference() { var (rootId, midId, _) = await SaveChainAsync("nowake"); var root = await Redb.LoadAsync(rootId, depth: 1); root!.Props.Label = "renamed-nowake"; await Redb.SaveAsync(root); root.Props.Next!.IsPropsLoaded.Should().BeFalse("saving the parent must not wake its references (§4.2)"); (await Redb.LoadAsync(rootId, depth: 1))!.Props.Label.Should().Be("renamed-nowake"); var midReloaded = await Redb.LoadAsync(midId, depth: 1); midReloaded!.Props.Should().NotBeNull("the referenced object must be untouched (W1 reference-wipe guard)"); midReloaded.Props!.Label.Should().Be("mid-nowake"); } [Fact] public async Task Serialization_WritesTheStub_AndDoesNotLoadIt() { var (rootId, midId, _) = await SaveChainAsync("serialize"); var root = await Redb.LoadAsync(rootId, depth: 1); var json = JsonSerializer.Serialize(root, SystemTextJsonRedbSerializer.Options); root!.Props.Next!.IsPropsLoaded.Should().BeFalse("serializing the parent must not pull the graph (§4.3)"); json.Should().Contain($"\"id\":{midId}", "the stub serializes as its base fields"); json.Should().NotContain("\"Label\":\"mid-serialize\"", "the reference's CONTENT is not serialized (its name base field is)"); json.Should().Contain("root-serialize", "the loaded root serializes in full"); } [Fact] public async Task Deserialization_NullProperties_IsNotLoaded_AndSavingTheParentKeepsTheTarget() { var (rootId, midId, _) = await SaveChainAsync("nullprops"); var root = await Redb.LoadAsync(rootId, depth: 1); var json = JsonSerializer.Serialize(root, SystemTextJsonRedbSerializer.Options); // What a foreign serializer makes of a loader-less stub: the getter answers null, so the // JSON carries "properties": null for the reference. var node = System.Text.Json.Nodes.JsonNode.Parse(json)!; node["properties"]!["Next"]!["properties"] = null; var foreign = node.ToJsonString(); foreign.Should().Contain("\"properties\":null"); var back = JsonSerializer.Deserialize>(foreign, SystemTextJsonRedbSerializer.Options)!; back.Props.Next!.IsPropsLoaded.Should().BeFalse("null Props after reading mean not loaded, never loaded-with-nothing"); // A client round-trip: the parent comes back edited and is saved. back.Props.Label = "root-nullprops-edited"; await Redb.SaveAsync(back); var target = await Redb.LoadAsync(midId, depth: 1); target!.Props.Label.Should().Be("mid-nullprops", "saving the parent must not wipe a reference that arrived without Props"); (await Redb.LoadAsync(rootId, depth: 1))!.Props.Label.Should().Be("root-nullprops-edited"); } [Fact] public async Task CollectionOfReferences_ArrivesAsStubs_EachLoadable() { var tag = "collection"; var child1 = await Redb.SaveAsync(new RedbObject { name = $"lazy-c1-{tag}", Props = new LazyNodeProps { Label = $"c1-{tag}" } }); var child2 = await Redb.SaveAsync(new RedbObject { name = $"lazy-c2-{tag}", Props = new LazyNodeProps { Label = $"c2-{tag}" } }); var parentId = await Redb.SaveAsync(new RedbObject { name = $"lazy-parent-{tag}", Props = new LazyNodeProps { Label = $"parent-{tag}", Children = [ new RedbObject { id = child1 }, new RedbObject { id = child2 }, ] } }); var parent = await Redb.LoadAsync(parentId, depth: 1); var children = parent!.Props.Children!; children.Should().HaveCount(2); children.Should().OnlyContain(c => !c.IsPropsLoaded, "a collection of references arrives as a list of stubs"); children.Select(c => c.id).Should().BeEquivalentTo(new[] { child1, child2 }); children.First(c => c.id == child1).Props!.Label.Should().Be($"c1-{tag}"); children.First(c => c.id == child2).Props!.Label.Should().Be($"c2-{tag}"); } [Fact] public async Task TargetInTheTrash_StubReloadsAsNull_NotAnException() { var (rootId, midId, _) = await SaveChainAsync("trash"); var root = await Redb.LoadAsync(rootId, depth: 1); var stub = root!.Props.Next!; stub.IsPropsLoaded.Should().BeFalse(); await Redb.SoftDeleteAsync(new[] { midId }); // The stub was obtained before the deletion; loading it now must yield null Props (§4.8). var props = stub.Props; props.Should().BeNull("a reference whose target left for the trash reloads as null, not an exception"); stub.IsPropsLoaded.Should().BeTrue("the answer is definite — no retry storm on every access"); } } Path: redb/redb.Tests.Integration/Tests/Base/LazyReferencesOptionTestsBase.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/LazyReferencesOptionTestsBase.cs ---- using redb.Core; using redb.Core.Models.Entities; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// V4 wave 5 (Л2): the `virtual` marker + the lazy-references option. The marker lands in /// `_structures._lazy` at synchronisation (the code is the source of truth); with the option on the /// builders emit a stub for a marked reference REGARDLESS of depth, while a non-virtual reference /// stays eager. The per-query override `WithLazyReferences(bool)` rides the session flag of the /// context's connection — the Free builders honour it; the Pro materializer reads only the global /// option (a recorded Л2 boundary), which subclasses express via . /// public abstract class LazyReferencesOptionTestsBase { protected readonly IRedbService Redb; protected LazyReferencesOptionTestsBase(IRedbService redb) => Redb = redb; /// Free builders read the session flag; the Pro materializer does not (Л2 boundary). protected virtual bool PerQueryOverrideWorks => true; /// Pro reads the GLOBAL option live from the configuration object; the Free channel is armed at connection open. protected virtual bool GlobalMutationAffects => false; private async Task<(long rootId, long nextId, long plainId)> SaveTriangleAsync(string tag) { var nextId = await Redb.SaveAsync(new RedbObject { name = $"lopt-next-{tag}", Props = new LazyOptionNodeProps { Label = $"next-{tag}" } }); var plainId = await Redb.SaveAsync(new RedbObject { name = $"lopt-plain-{tag}", Props = new LazyOptionNodeProps { Label = $"plain-{tag}" } }); var rootId = await Redb.SaveAsync(new RedbObject { name = $"lopt-root-{tag}", Props = new LazyOptionNodeProps { Label = $"root-{tag}", Next = new RedbObject { id = nextId }, Plain = new RedbObject { id = plainId }, Children = new List> { new() { id = nextId } }, } }); return (rootId, nextId, plainId); } private Task StructureLazyAsync(string fieldName) => Redb.Context.ExecuteScalarAsync( "SELECT CAST(_lazy AS INT) FROM _structures WHERE _name = '" + fieldName + "' AND _id_scheme = " + "(SELECT _id FROM _schemes WHERE _name = '" + typeof(LazyOptionNodeProps).FullName + "')"); [Fact] public async Task Sync_WritesLazyFromVirtual_AndRestoresItOverManualEdits() { await Redb.SyncSchemeAsync(); (await StructureLazyAsync("Next")).Should().Be(1, "virtual reference -> _lazy"); (await StructureLazyAsync("Children")).Should().Be(1, "virtual collection of references -> _lazy"); ((await StructureLazyAsync("Plain")) ?? 0).Should().Be(0, "a non-virtual reference is not lazy"); ((await StructureLazyAsync("Label")) ?? 0).Should().Be(0, "virtual matters only on references"); // The code is the source of truth: a hand-flipped flag is restored on the next sync. await Redb.Context.ExecuteAsync( "UPDATE _structures SET _lazy = NULL WHERE _name = 'Next' AND _id_scheme = " + "(SELECT _id FROM _schemes WHERE _name = '" + typeof(LazyOptionNodeProps).FullName + "')"); Redb.Cache.Clear(); await Redb.SyncSchemeAsync(); (await StructureLazyAsync("Next")).Should().Be(1); } [Fact] public async Task PerQueryOverride_VirtualBecomesStub_PlainStaysEager() { var (rootId, nextId, plainId) = await SaveTriangleAsync("override"); var results = await Redb.Query() .WhereRedb(o => o.Id == rootId) .WithLazyReferences(true) .ToListAsync(); results.Should().HaveCount(1); var root = results[0]; root.Props.Should().NotBeNull(); var next = root.Props.Next!; var plain = root.Props.Plain!; next.Should().NotBeNull(); plain.Should().NotBeNull(); plain.id.Should().Be(plainId); next.id.Should().Be(nextId); if (PerQueryOverrideWorks) { next.IsPropsLoaded.Should().BeFalse("a virtual reference under WithLazyReferences(true) is a stub"); next.hash.Should().NotBeNull("the stub carries the hash (W1 shape)"); plain.IsPropsLoaded.Should().BeTrue("a non-virtual reference stays eager whatever the option says"); root.Props.Children![0].IsPropsLoaded.Should().BeFalse("the collection branch of the builders' gate honours the marker too"); next.Props!.Label.Should().Be("next-override", "the stub is loadable on first access"); } else { // Pro: the materializer reads only the global option — the override is a recorded boundary. next.IsPropsLoaded.Should().BeTrue("the per-query override does not reach the Pro materializer (Л2 boundary)"); } } [Fact] public async Task GlobalOption_ProMaterializerEmitsEnrichedStubs() { if (!GlobalMutationAffects) { // The Free channel is armed when the context's connection opens; mutating the shared // configuration here cannot re-arm it. The Free global path is covered by // LazyHostTestsBase.GlobalOption_HoldsOnEveryScope (own host, option on from the start). return; } var (rootId, nextId, plainId) = await SaveTriangleAsync("global"); Redb.Configuration.EnableLazyReferences = true; try { var root = await Redb.LoadAsync(rootId, depth: 10); var next = root!.Props.Next!; next.Should().NotBeNull(); next.IsPropsLoaded.Should().BeFalse("with the option on, a virtual reference is a stub at ANY depth"); next.hash.Should().NotBeNull("the loader enriches the placeholder to the W1 stub shape"); root.Props.Plain!.IsPropsLoaded.Should().BeTrue("non-virtual stays eager"); root.Props.Children![0].IsPropsLoaded.Should().BeFalse("the array branch of the materializer gate honours the marker too"); next.Props!.Label.Should().Be("next-global", "the stub is loadable on first access"); } finally { Redb.Configuration.EnableLazyReferences = false; } } [Fact] public async Task CollectionOfVirtualReferences_LoadReferencesAsync_OneBatch() { var tag = "batch"; var c1 = await Redb.SaveAsync(new RedbObject { name = $"lopt-c1-{tag}", Props = new LazyOptionNodeProps { Label = $"c1-{tag}" } }); var c2 = await Redb.SaveAsync(new RedbObject { name = $"lopt-c2-{tag}", Props = new LazyOptionNodeProps { Label = $"c2-{tag}" } }); var parentId = await Redb.SaveAsync(new RedbObject { name = $"lopt-parent-{tag}", Props = new LazyOptionNodeProps { Label = $"parent-{tag}", Children = [ new RedbObject { id = c1 }, new RedbObject { id = c2 }, ] } }); // depth 1 gives stubs by depth alone — the reload API must work without the option too. var parent = await Redb.LoadAsync(parentId, depth: 1); var children = parent!.Props.Children!; children.Should().OnlyContain(c => !c.IsPropsLoaded); await Redb.LoadReferencesAsync(parent, p => p.Children); children.Should().OnlyContain(c => c.IsPropsLoaded, "one batch loads the whole collection (§4.6)"); children.Select(c => c.Props!.Label).Should().BeEquivalentTo($"c1-{tag}", $"c2-{tag}"); } [Fact] public async Task OptionOff_BehaviourUnchanged() { var (rootId, _, _) = await SaveTriangleAsync("off"); var root = await Redb.LoadAsync(rootId, depth: 2); root!.Props.Next!.IsPropsLoaded.Should().BeTrue("without the option, depth alone decides"); root.Props.Plain!.IsPropsLoaded.Should().BeTrue(); } } Path: redb/redb.Tests.Integration/Tests/Base/LikeEscapingTestsBase.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/LikeEscapingTestsBase.cs ---- using redb.Core; using redb.Core.Models.Entities; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// BR-7 (Tsak report, fixed 2026-09-02): the StartsWith/EndsWith/Contains sugar built LIKE /// patterns with the operand spliced raw - '%'/'_' in the operand matched as wildcards (a /// superset), '[' on MSSQL opened a character class (a WRONG SUBSET no post-filter can restore), /// and a backslash on PostgreSQL acted as LIKE's own escape character. The contract now: the /// operand of every sugar operator is a LITERAL, identically on all three providers - escaping /// happens where the pattern is assembled (the SQL/native builders), so direct facet-JSON callers /// are covered too. The raw $like/$ilike/$arrayMatches operators keep /// interpreting the caller's pattern on purpose. /// public abstract class LikeEscapingTestsBase : IAsyncLifetime { protected readonly IRedbService Redb; protected LikeEscapingTestsBase(IRedbService redb) => Redb = redb; public async Task InitializeAsync() => await ResetAsync(); public async Task DisposeAsync() => await ResetAsync(); private async Task ResetAsync() => await Redb.Context.ExecuteAsync( "DELETE FROM _objects WHERE _id_scheme IN (SELECT _id FROM _schemes WHERE _name = 'LikeProbe')"); private async Task SeedAsync(params string[] values) { await Redb.SyncSchemeAsync(); foreach (var v in values) await Redb.SaveAsync(new RedbObject { name = "probe", Props = new LikeProbeProps { S = v } }); } [Fact] public async Task StartsWith_PercentInTheOperand_IsLiteral() { await SeedAsync("100%x", "1000x"); var rs = await Redb.Query().Where(p => p.S!.StartsWith("100%")).ToListAsync(); rs.Select(r => r.Props.S).Should().Equal("100%x"); } [Fact] public async Task Contains_Underscore_IsLiteral() { await SeedAsync("a_c", "abc"); var rs = await Redb.Query().Where(p => p.S!.Contains("_")).ToListAsync(); rs.Select(r => r.Props.S).Should().Equal("a_c"); } [Fact] public async Task EndsWith_Underscore_IsLiteral() { await SeedAsync("x_", "xy"); var rs = await Redb.Query().Where(p => p.S!.EndsWith("_")).ToListAsync(); rs.Select(r => r.Props.S).Should().Equal("x_"); } [Fact] public async Task StartsWith_OpeningBracket_IsLiteral() { // '[' opens a character class in T-SQL LIKE: StartsWith("x[1]") used to return 'x1y' and // not 'x[1]y' on MSSQL - a wrong subset. PostgreSQL and SQLite treat '[' literally anyway. await SeedAsync("x[1]y", "x1y"); var rs = await Redb.Query().Where(p => p.S!.StartsWith("x[1]")).ToListAsync(); rs.Select(r => r.Props.S).Should().Equal("x[1]y"); } [Fact] public async Task Contains_Backslash_IsLiteral() { // On PostgreSQL a backslash in the operand used to act as LIKE's own escape character: // Contains("\") built '%\%' - "everything containing a PERCENT". await SeedAsync("a\\b", "a%b"); var rs = await Redb.Query().Where(p => p.S!.Contains("\\")).ToListAsync(); rs.Select(r => r.Props.S).Should().Equal("a\\b"); } [Fact] public async Task StartsWithIgnoreCase_Metacharacters_AreLiteral() { await SeedAsync("100%X", "1000X"); var rs = await Redb.Query() .Where(p => p.S!.StartsWith("100%x", StringComparison.OrdinalIgnoreCase)).ToListAsync(); rs.Select(r => r.Props.S).Should().Equal("100%X"); } } Path: redb/redb.Tests.Integration/Tests/Base/ListItemArrayAnyTestsBase.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/ListItemArrayAnyTestsBase.cs ---- using System.Linq.Expressions; using redb.Core; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// p.Roles.Any(r => r.Value == x) over a list of list items asks whether some item has that value, on every /// provider. The parser used to read any comparison as ==, so r.Value != x or r.Id > n answered the /// question for == without a word; such an operator is now refused before any SQL. /// public abstract class ListItemArrayAnyTestsBase { protected readonly IRedbService Redb; protected ListItemArrayAnyTestsBase(IRedbService redb) => Redb = redb; private async Task<(string Tag, RedbListItem Admin, RedbListItem User, RedbList List)> SeedAsync() { await Redb.SyncSchemeAsync(); var tag = "lia-" + Guid.NewGuid().ToString("N")[..8]; var list = await Redb.ListProvider.SaveListAsync(RedbList.Create(tag, tag)); var items = await Redb.ListProvider.AddItemsAsync(list, ["Admin", "User"]); var admin = items.First(i => i.Value == "Admin"); var user = items.First(i => i.Value == "User"); var people = new List { new() { Name = "1", Age = 40, Email = tag, Roles = [admin, user] }, new() { Name = "2", Age = 20, Email = tag, Roles = [user] }, new() { Name = "3", Age = 50, Email = tag, Roles = [] }, new() { Name = "4", Age = 60, Email = tag }, }; await Redb.SaveAsync(people.Select(p => (IRedbObject)new RedbObject { name = $"{tag}-{p.Name}", Props = p }).ToList()); return (tag, admin, user, list); } private async Task CleanupAsync(RedbList list) { var items = await Redb.ListProvider.GetListItemsAsync(list.Id); await Redb.Context.Bulk.BulkDeleteValuesByListItemIdsAsync(items.Select(i => i.Id).ToList()); await Redb.ListProvider.DeleteListAsync(list.Id); } private async Task NamesAsync(string tag, Expression> filter) => (await Redb.Query().Where(p => p.Email == tag).Where(filter).ToListAsync()) .Select(o => o.Props.Name).OrderBy(n => n).ToArray(); [Fact] public async Task AnyOverListItems_AsksForAnItemWithThatValue() { var (tag, admin, user, list) = await SeedAsync(); try { (await NamesAsync(tag, p => p.Roles!.Any(r => r.Value == "Admin"))).Should().Equal("1"); (await NamesAsync(tag, p => p.Roles!.Any(r => "User" == r.Value))).Should().Equal("1", "2"); var userId = user.Id; (await NamesAsync(tag, p => p.Roles!.Any(r => r.Id == userId))).Should().Equal("1", "2"); // No item with that value: an empty or a missing list included. (await NamesAsync(tag, p => !p.Roles!.Any(r => r.Value == "Admin"))).Should().Equal("2", "3", "4"); (await NamesAsync(tag, p => p.Age > 30 && p.Roles!.Any(r => r.Value == "User"))).Should().Equal("1"); (await NamesAsync(tag, p => p.Age > 30 && !p.Roles!.Any(r => r.Value == "User"))).Should().Equal("3", "4"); } finally { await CleanupAsync(list); } } [Fact] public async Task AnyOverListItems_RefusesAnOperatorOtherThanEquality() { var (tag, admin, _, list) = await SeedAsync(); try { var adminId = admin.Id; var names = new List { "Admin" }; var refused = new Expression>[] { p => p.Roles!.Any(r => r.Value != "Admin"), p => p.Roles!.Any(r => r.Id > adminId), p => p.Roles!.Any(r => adminId <= r.Id), p => !p.Roles!.Any(r => r.Id != adminId), }; foreach (var filter in refused) { var run = async () => await NamesAsync(tag, filter); (await run.Should().ThrowAsync()).Which.Message.Should().Contain("only with =="); } var contains = async () => await NamesAsync(tag, p => p.Roles!.Any(r => names.Contains(r.Value))); await contains.Should().ThrowAsync(); } finally { await CleanupAsync(list); } } } Path: redb/redb.Tests.Integration/Tests/Base/ListItemObjectWalkTestsBase.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/ListItemObjectWalkTestsBase.cs ---- using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Core; using redb.Core.Extensions; using redb.Core.Models.Configuration; using redb.Core.Models.Entities; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// Reading /// IS a database load, so no reflective walk of a loaded graph may read it: a walk /// that does fires one load per linked list item on every materialization (the production phantom-load class of /// 2026-09-09) and, on Pro SQLite, throws through the sync path. The core walkers were closed then; the Pro /// materialization walkers and the props-cache dirty guard were not. /// /// Detector: . A read of Object on the live scope loads the object and keeps it /// (owner decision 2026-09-15), and no walk swallows a failed read any more (plan, item 4). Every test isolates ONE walker /// and ends with its positive control - one explicit read loads the object - so a road the detector does not cover fails /// the test instead of hiding. /// /// /// Free hosts depend on plan part C: until then the Free JSON builders dropped IdObject of list items and the /// "carries its object link" precondition failed before any walker was judged. /// /// public abstract class ListItemObjectWalkTestsBase { protected abstract void UseProvider(RedbOptionsBuilder options); protected virtual void Register(IServiceCollection services, Action configure) => services.AddRedb(configure); private ServiceProvider Build(Action configure) { var services = new ServiceCollection(); services.AddLogging(b => b.SetMinimumLevel(LogLevel.Warning)); Register(services, options => { UseProvider(options); options.Configure(c => { c.EnablePropsCache = false; c.SkipHashValidationOnCacheCheck = false; // Own cache domain: this process also holds the shared fixtures on the same database. c.CacheDomain = "listitem-walk"; configure(c); }); }); return services.BuildServiceProvider(); } private sealed record Seed(long RootId, long LinkedObjectId); private static async Task BootAsync(ServiceProvider sp) { var boot = sp.GetRequiredService(); await boot.InitializeAsync(ensureCreated: true); await boot.SyncSchemeAsync(); await boot.SyncSchemeAsync(); await boot.SyncSchemeAsync(); await boot.SyncSchemeAsync(); await boot.InitializeTypeRegistryAsync(); return boot; } private static async Task<(RedbListItem Linked, RedbListItem Plain, long LinkedObjectId)> SeedListAsync(IRedbService redb, string tag) { var linkedObjectId = await redb.SaveAsync(new RedbObject { name = $"liwalk-linked-{tag}", Props = new SimpleProps { Title = "linked" } }); var list = await redb.ListProvider.SaveListAsync(RedbList.Create($"liwalk-{tag}", "liwalk")); var linked = await redb.ListProvider.SaveListItemAsync(new RedbListItem { IdList = list.Id, Value = "linked", IdObject = linkedObjectId }); var plain = await redb.ListProvider.SaveListItemAsync(new RedbListItem { IdList = list.Id, Value = "plain" }); return (linked, plain, linkedObjectId); } /// Props with references AND list items, one of them linked to an object. private static async Task SeedWithReferencesAsync(ServiceProvider sp, string tag, bool onlyTrashedReference = false) { var redb = await BootAsync(sp); var (linked, plain, linkedObjectId) = await SeedListAsync(redb, tag); var c1 = await redb.SaveAsync(new RedbObject { name = $"liwalk-c1-{tag}", Props = new CtProbeChildProps { Tag = "one" } }); var c2 = await redb.SaveAsync(new RedbObject { name = $"liwalk-c2-{tag}", Props = new CtProbeChildProps { Tag = "two" } }); var props = new CtProbeProps { Label = "root", Status = linked, Roles = [linked, plain] }; if (onlyTrashedReference) { // The only reference points at an object trashed below: nothing is substituted (the substitution walk // returns at once on an empty set) and the null-missing walk is the one that runs. props.Refs = [new RedbObject { id = c2 }]; } else { props.Refs = [new RedbObject { id = c1 }, new RedbObject { id = c2 }]; props.RefDict = new() { ["first"] = new RedbObject { id = c1 } }; } var rootId = await redb.SaveAsync(new RedbObject { name = $"liwalk-root-{tag}", Props = props }); if (onlyTrashedReference) await redb.SoftDeleteAsync(new[] { c2 }); return new Seed(rootId, linkedObjectId); } /// Props with list items and no references: its first load runs none of the materialization walkers. private static async Task SeedPersonAsync(ServiceProvider sp, string tag) { var redb = await BootAsync(sp); var (linked, plain, linkedObjectId) = await SeedListAsync(redb, tag); var rootId = await redb.SaveAsync(new RedbObject { name = $"liwalk-person-{tag}", Props = new PersonProps { Name = "Person", Age = 30, Email = "p@example.com", Status = linked, Roles = [linked, plain] } }); return new Seed(rootId, linkedObjectId); } private static string NewTag() => Guid.NewGuid().ToString("N")[..8]; /// /// No walk read Object: every given instance still carries its link and is not loaded; then one explicit read loads it. /// private static void AssertNotWoken(string path, long linkedObjectId, params RedbListItem?[] linkedItems) { foreach (var item in linkedItems) { item.Should().NotBeNull($"{path}: the linked list item must be materialized"); item!.IdObject.Should().Be(linkedObjectId, $"{path}: precondition - the item carries its object link, or 'not woken' proves nothing"); item.IsObjectLoaded.Should().BeFalse( $"{path}: no walk may read RedbListItem.Object - reading it IS a database load per linked item"); } linkedItems[0]!.Object.Should().NotBeNull( $"{path}: positive control - an explicit read of Object loads it, so the detector is live"); linkedItems[0]!.IsObjectLoaded.Should().BeTrue(); } [Fact] public async Task Load_WithReferences_SubstitutionWalk_DoesNotWakeLinkedListItems() { await using var sp = Build(_ => { }); var seed = await SeedWithReferencesAsync(sp, NewTag()); await using var scope = sp.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); var root = await redb.LoadAsync(seed.RootId, depth: 10); root!.Props.Refs.Should().HaveCount(2).And.OnlyContain(r => r != null && r.IsPropsLoaded, "the references are materialized, so the substitution walk ran"); AssertNotWoken("load with references", seed.LinkedObjectId, root.Props.Status, root.Props.Roles![0]); } [Fact] public async Task Load_WithTrashedReferenceTarget_NullMissingWalk_DoesNotWakeLinkedListItems() { await using var sp = Build(_ => { }); var seed = await SeedWithReferencesAsync(sp, NewTag(), onlyTrashedReference: true); await using var scope = sp.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); var root = await redb.LoadAsync(seed.RootId, depth: 10); root!.Props.Refs.Should().ContainSingle().Which.Should().BeNull("the trashed target is nulled, so the null-missing walk ran"); AssertNotWoken("load with a trashed reference target", seed.LinkedObjectId, root.Props.Status, root.Props.Roles![0]); } [Fact] public async Task Load_WithLazyReferences_StubWalk_DoesNotWakeLinkedListItems() { await using var sp = Build(c => c.EnableLazyReferences = true); var seed = await SeedWithReferencesAsync(sp, NewTag()); await using var scope = sp.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); var root = await redb.LoadAsync(seed.RootId, depth: 1); root!.Props.Refs.Should().HaveCount(2).And.OnlyContain(r => r != null && !r.IsPropsLoaded && r.hash != null, "the references are enriched stubs, so the stub walk ran"); AssertNotWoken("load with lazy references", seed.LinkedObjectId, root.Props.Status, root.Props.Roles![0]); } /// First load fills the cache without any walker; the second is served from it. private async Task CacheHitAsync(Action configure, string path, Func?>> secondLoad) { await using var sp = Build(c => { c.EnablePropsCache = true; configure(c); }); var seed = await SeedPersonAsync(sp, NewTag()); ((RedbServiceBase)sp.GetRequiredService()).PropsCache.Instance!.Clear(); await using (var first = sp.CreateAsyncScope()) { var cached = await first.ServiceProvider.GetRequiredService().LoadAsync(seed.RootId, depth: 10); cached.Should().NotBeNull(); cached!.Props.Status!.IsObjectLoaded.Should().BeFalse($"{path}: precondition - the load that fills the cache wakes nothing"); } await using var second = sp.CreateAsyncScope(); var served = await secondLoad(second.ServiceProvider.GetRequiredService(), seed.RootId); AssertNotWoken(path, seed.LinkedObjectId, served!.Props.Status, served.Props.Roles![0]); } [Fact] public Task CacheHit_PointLoad_DirtyGuard_DoesNotWakeLinkedListItems() => CacheHitAsync(_ => { }, "cache hit, point load", (redb, id) => redb.LoadAsync(id, depth: 10)); [Fact] public Task CacheHit_WithoutHashValidation_DirtyGuard_DoesNotWakeLinkedListItems() => CacheHitAsync(c => c.SkipHashValidationOnCacheCheck = true, "cache hit without hash validation", (redb, id) => redb.LoadAsync(id, depth: 10)); [Fact] public Task CacheHit_BulkLoad_DirtyGuard_DoesNotWakeLinkedListItems() => CacheHitAsync(_ => { }, "cache hit, bulk load", async (redb, id) => (RedbObject)(await redb.LoadAsync(new[] { id }, depth: 10))[0]); [Fact] public Task CacheHit_SyncPointLoad_DirtyGuard_DoesNotWakeLinkedListItems() => CacheHitAsync(_ => { }, "cache hit, sync point load", (redb, id) => Task.FromResult(redb.Load(id, depth: 10))); } Path: redb/redb.Tests.Integration/Tests/Base/ListReadPropsOnceTestsBase.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/ListReadPropsOnceTestsBase.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 read and a tree read read the values of the objects found in one statement, and hand out what loading the /// objects one by one hands out, in the order asked for. Free used to build the JSON of every object twice: once in /// the statement that found the objects (get_object_json per row) and once more in the lazy loader, which then /// replaced the first copy. Pro reads the values in one bulk statement. The SQL is seen through the test context. /// public abstract class ListReadPropsOnceTestsBase { private readonly SqlRecorder _recorder = new(); protected abstract void UseProvider(RedbOptionsBuilder options); protected virtual void Register(IServiceCollection services, Action configure) => services.AddRedb(configure); private ServiceProvider Build() { var services = new ServiceCollection(); services.AddLogging(b => b.SetMinimumLevel(LogLevel.Warning)); Register(services, options => { UseProvider(options); options.Configure(c => { c.EnablePropsCache = false; c.CacheDomain = $"props-once-{GetType().Name}-{Guid.NewGuid():N}"; }); }); RecordingRedbContext.Decorate(services, _recorder); return services.BuildServiceProvider(); } /// A statement that reads the values of objects: Free's get_object_json, Pro's bulk read of _values. private static bool ReadsValues(string sql) => sql.Contains("get_object_json", StringComparison.OrdinalIgnoreCase) || (sql.Contains("_array_parent_id, _array_index", StringComparison.Ordinal) && sql.Contains("FROM _values", StringComparison.Ordinal)); private static async Task<(IRedbService Redb, string Tag, long RootId)> SeedAsync(IRedbService redb) { await redb.InitializeAsync(ensureCreated: true); await redb.SyncSchemeAsync(); var tag = "once-" + Guid.NewGuid().ToString("N")[..8]; var rootId = await redb.SaveAsync(new RedbObject { name = $"{tag}-root", Props = new SimpleProps { Title = $"{tag}-root", Price = 100 } }); for (var i = 1; i <= 5; i++) { await redb.SaveAsync(new RedbObject { name = $"{tag}-{i}", parent_id = rootId, Props = new SimpleProps { Title = $"{tag}-{i}", Count = i, Price = 10.5m * i, IsActive = i % 2 == 0, Code = Guid.NewGuid(), CreatedAt = new DateTime(2026, 1, i, 8, 30, 0, DateTimeKind.Utc), Description = i == 3 ? null : $"d{i}", OptionalNumber = i == 2 ? null : i * 1000L } }); } return (redb, tag, rootId); } private async Task AssertMatchesSingleLoadsAsync(IRedbService redb, IReadOnlyList> page) { foreach (var obj in page) { var single = await redb.LoadAsync(obj.id); obj.Props.Should().BeEquivalentTo(single!.Props, "a list hands out what a single load hands out (object {0})", obj.id); obj.name.Should().Be(single.name); obj.hash.Should().Be(single.hash); obj.parent_id.Should().Be(single.parent_id); } } [Fact] public async Task ListRead_ReadsTheValuesInOneStatement_InTheOrderAsked() { await using var host = Build(); var (redb, tag, _) = await SeedAsync(host.GetRequiredService()); var children = tag + "-"; _recorder.Start(); var page = await redb.Query().Where(p => p.Title.StartsWith(children) && p.Price < 100) .OrderByDescending(p => p.Price).Take(4).ToListAsync(); var commands = _recorder.Stop(); page.Select(o => o.Props.Count).Should().Equal(5, 4, 3, 2); commands.Count(c => ReadsValues(c.Sql)).Should().Be(1, "the values of the page are read once:\n" + string.Join("\n---\n", commands.Select(c => c.Sql))); await AssertMatchesSingleLoadsAsync(redb, page); } [Fact] public async Task TreeRead_ReadsTheValuesInOneStatement_InTheOrderAsked() { await using var host = Build(); var (redb, _, rootId) = await SeedAsync(host.GetRequiredService()); _recorder.Start(); var nodes = await redb.TreeQuery(rootId).WhereRedb(o => o.Id != rootId) .OrderBy(p => p.Price).ToListAsync(); var commands = _recorder.Stop(); nodes.Select(o => o.Props.Count).Should().Equal(1, 2, 3, 4, 5); commands.Count(c => ReadsValues(c.Sql)).Should().Be(1, "the values of the tree are read once:\n" + string.Join("\n---\n", commands.Select(c => c.Sql))); await AssertMatchesSingleLoadsAsync(redb, nodes.Cast>().ToList()); } } 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}"); } } } Path: redb/redb.Tests.Integration/Tests/Base/ListTestsBase.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/ListTestsBase.cs ---- using redb.Core; using redb.Core.Models.Entities; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// RedbList (lookup/dictionary) CRUD and query tests. /// public abstract class ListTestsBase { protected readonly IRedbService Redb; protected virtual bool IsPro => false; /// /// True if the underlying provider supports OrderBy/Where on `ListItem.Value` / `ListItem.Alias` /// (requires a JOIN to `_list_items` or equivalent). All Postgres tiers (Free PVT + Pro) and /// MsSql Pro support it; MsSql Free currently does not (ORDER BY is ignored, rows come back /// in insertion order). Override to opt-in. /// protected virtual bool SupportsListItemValueAliasOrdering => IsPro; protected ListTestsBase(IRedbService redb) => Redb = redb; private async Task CreateTestListAsync(string name = "TestStatuses") { // Cleanup if exists var existing = await Redb.ListProvider.GetListByNameAsync(name); if (existing != null) { var items = await Redb.ListProvider.GetListItemsAsync(existing.Id); var itemIds = items.Select(i => i.Id).ToList(); if (itemIds.Count > 0) await Redb.Context.Bulk.BulkDeleteValuesByListItemIdsAsync(itemIds); await Redb.ListProvider.DeleteListAsync(existing.Id); } var list = RedbList.Create(name, $"{name} alias"); return await Redb.ListProvider.SaveListAsync(list); } private async Task CleanupListAsync(string name) { var existing = await Redb.ListProvider.GetListByNameAsync(name); if (existing != null) { var items = await Redb.ListProvider.GetListItemsAsync(existing.Id); var itemIds = items.Select(i => i.Id).ToList(); if (itemIds.Count > 0) await Redb.Context.Bulk.BulkDeleteValuesByListItemIdsAsync(itemIds); await Redb.ListProvider.DeleteListAsync(existing.Id); } } [Fact] public async Task CreateList_Persists() { var saved = await CreateTestListAsync("ListTest_Create"); saved.Id.Should().BeGreaterThan(0); saved.Name.Should().Be("ListTest_Create"); await CleanupListAsync("ListTest_Create"); } [Fact] public async Task GetListByName_ReturnsExisting() { var saved = await CreateTestListAsync("ListTest_GetByName"); var found = await Redb.ListProvider.GetListByNameAsync("ListTest_GetByName"); found.Should().NotBeNull(); found!.Id.Should().Be(saved.Id); await CleanupListAsync("ListTest_GetByName"); } [Fact] public async Task AddItems_PersistsItems() { var list = await CreateTestListAsync("ListTest_Items"); var values = new[] { "Active", "Inactive", "Pending" }; var aliases = new[] { "Active status", "Inactive status", "Pending review" }; var added = await Redb.ListProvider.AddItemsAsync(list, values, aliases); added.Should().HaveCount(3); added.Select(i => i.Value).Should().BeEquivalentTo(values); await CleanupListAsync("ListTest_Items"); } [Fact] public async Task GetListItems_ReturnsAll() { var list = await CreateTestListAsync("ListTest_GetItems"); await Redb.ListProvider.AddItemsAsync(list, ["A", "B", "C"]); var items = await Redb.ListProvider.GetListItemsAsync(list.Id); items.Should().HaveCount(3); await CleanupListAsync("ListTest_GetItems"); } [Fact] public async Task GetListWithItems_LoadsItemsToo() { var list = await CreateTestListAsync("ListTest_WithItems"); await Redb.ListProvider.AddItemsAsync(list, ["X", "Y"]); var loaded = await Redb.ListProvider.GetListWithItemsAsync(list.Id); loaded.Should().NotBeNull(); loaded!.Items.Should().HaveCount(2); await CleanupListAsync("ListTest_WithItems"); } [Fact] public async Task GetListItemByValue_FindsMatch() { var list = await CreateTestListAsync("ListTest_ByValue"); await Redb.ListProvider.AddItemsAsync(list, ["Alpha", "Beta"]); var item = await Redb.ListProvider.GetListItemByValueAsync(list.Id, "Alpha"); item.Should().NotBeNull(); item!.Value.Should().Be("Alpha"); await CleanupListAsync("ListTest_ByValue"); } [Fact] public async Task DeleteList_Removes() { var list = await CreateTestListAsync("ListTest_Delete"); var deleted = await Redb.ListProvider.DeleteListAsync(list.Id); deleted.Should().BeTrue(); var found = await Redb.ListProvider.GetListByNameAsync("ListTest_Delete"); found.Should().BeNull(); } [Fact] public async Task ListItemOnProps_SaveAndQuery() { // Setup: create a list with items var list = await CreateTestListAsync("ListTest_Props"); var statuses = await Redb.ListProvider.AddItemsAsync(list, ["Active", "Blocked"]); var activeItem = statuses.First(s => s.Value == "Active"); var blockedItem = statuses.First(s => s.Value == "Blocked"); // Save a Person with Status = Active var person = new RedbObject { name = "Test Person", Props = new PersonProps { Name = "John", Age = 30, Email = "john@test.com", Status = activeItem, Roles = [activeItem, blockedItem] } }; person.id = await Redb.SaveAsync(person); // Load and verify var loaded = await Redb.LoadAsync(person.id); loaded.Should().NotBeNull(); loaded!.Props.Status.Should().NotBeNull(); loaded.Props.Status!.Value.Should().Be("Active"); loaded.Props.Roles.Should().HaveCount(2); await CleanupListAsync("ListTest_Props"); } [Fact] public async Task ListItemArray_QueryAny() { // Setup var list = await CreateTestListAsync("ListTest_QueryAny"); var items = await Redb.ListProvider.AddItemsAsync(list, ["Admin", "User", "Viewer"]); var adminItem = items.First(i => i.Value == "Admin"); var userItem = items.First(i => i.Value == "User"); var person = new RedbObject { name = "Admin User", Props = new PersonProps { Name = "AdminPerson", Age = 35, Email = "admin@test.com", Roles = [adminItem, userItem] } }; person.id = await Redb.SaveAsync(person); // Query: find persons with Admin role var results = await Redb.Query() .Where(p => p.Roles!.Any(r => r.Value == "Admin")) .ToListAsync(); results.Should().NotBeEmpty(); results.Should().Contain(r => r.id == person.id); await CleanupListAsync("ListTest_QueryAny"); } [Fact] public async Task SyncListFromEnum_CreatesItems() { // Cleanup if exists await CleanupListAsync("TestPriority"); var list = await Redb.ListProvider.SyncListFromEnumAsync(); list.Should().NotBeNull(); list.Id.Should().BeGreaterThan(0); var items = await Redb.ListProvider.GetListItemsAsync(list.Id); items.Select(i => i.Value).Should().BeEquivalentTo(["Low", "Medium", "High", "Critical"]); await CleanupListAsync("TestPriority"); } [Fact] public async Task ListItem_ClosureContains_FiltersCorrectly() { // Setup: create list with items and save persons with different statuses var list = await CreateTestListAsync("ListTest_ClosureContains"); var statuses = await Redb.ListProvider.AddItemsAsync(list, ["Active", "Blocked", "Pending"]); var activeItem = statuses.First(s => s.Value == "Active"); var blockedItem = statuses.First(s => s.Value == "Blocked"); var pendingItem = statuses.First(s => s.Value == "Pending"); var person1 = new RedbObject { name = "Person Active", Props = new PersonProps { Name = "Alice", Age = 25, Email = "alice@test.com", Status = activeItem } }; var person2 = new RedbObject { name = "Person Blocked", Props = new PersonProps { Name = "Bob", Age = 30, Email = "bob@test.com", Status = blockedItem } }; var person3 = new RedbObject { name = "Person Pending", Props = new PersonProps { Name = "Carol", Age = 35, Email = "carol@test.com", Status = pendingItem } }; var batchIds = await Redb.SaveAsync(new[] { person1, person2, person3 }); person1.id = batchIds[0]; person2.id = batchIds[1]; person3.id = batchIds[2]; // Query: find persons where Status IN (Active, Pending) — closure Contains pattern var selected = new List { activeItem, pendingItem }; var results = await Redb.Query() .Where(p => selected.Contains(p.Status!)) .ToListAsync(); results.Should().NotBeEmpty(); results.Should().Contain(r => r.id == person1.id, "Active person should be found"); results.Should().Contain(r => r.id == person3.id, "Pending person should be found"); results.Should().NotContain(r => r.id == person2.id, "Blocked person should NOT be found"); await CleanupListAsync("ListTest_ClosureContains"); } [Fact] public async Task ListItem_ArrayContains_FiltersCorrectly() { // Setup: create list with items and save person with Roles array var list = await CreateTestListAsync("ListTest_ArrayContains"); var roles = await Redb.ListProvider.AddItemsAsync(list, ["Admin", "User", "Viewer"]); var adminItem = roles.First(r => r.Value == "Admin"); var userItem = roles.First(r => r.Value == "User"); var viewerItem = roles.First(r => r.Value == "Viewer"); var person1 = new RedbObject { name = "Admin User", Props = new PersonProps { Name = "Dave", Age = 40, Email = "dave@test.com", Roles = [adminItem, userItem] } }; var person2 = new RedbObject { name = "Viewer Only", Props = new PersonProps { Name = "Eve", Age = 28, Email = "eve@test.com", Roles = [viewerItem] } }; var batchIds = await Redb.SaveAsync(new[] { person1, person2 }); person1.id = batchIds[0]; person2.id = batchIds[1]; // Query: x.Roles.Contains(adminItem) — array Contains pattern var results = await Redb.Query() .Where(p => p.Roles!.Contains(adminItem)) .ToListAsync(); results.Should().NotBeEmpty(); results.Should().Contain(r => r.id == person1.id, "Person with Admin role should be found"); results.Should().NotContain(r => r.id == person2.id, "Viewer-only person should NOT be found"); await CleanupListAsync("ListTest_ArrayContains"); } [Fact] public async Task ListItem_OrderByValue_SortsAlphabetically() { // Setup: create list with items that have known alphabetical order var list = await CreateTestListAsync("ListTest_OrderByValue"); // Values: Alpha < Beta < Gamma (alphabetical order) var statuses = await Redb.ListProvider.AddItemsAsync(list, ["Gamma", "Alpha", "Beta"]); var gammaItem = statuses.First(s => s.Value == "Gamma"); var alphaItem = statuses.First(s => s.Value == "Alpha"); var betaItem = statuses.First(s => s.Value == "Beta"); // Use unique per-run prefix to avoid cross-test pollution in PersonProps scheme var tag = $"OrderByValue_{Guid.NewGuid():N}"; var person1 = new RedbObject { name = "Person Gamma", Props = new PersonProps { Name = $"{tag}_P1", Age = 20, Email = "p1@test.com", Status = gammaItem } }; var person2 = new RedbObject { name = "Person Alpha", Props = new PersonProps { Name = $"{tag}_P2", Age = 30, Email = "p2@test.com", Status = alphaItem } }; var person3 = new RedbObject { name = "Person Beta", Props = new PersonProps { Name = $"{tag}_P3", Age = 40, Email = "p3@test.com", Status = betaItem } }; var batchIds = await Redb.SaveAsync(new[] { person1, person2, person3 }); person1.id = batchIds[0]; person2.id = batchIds[1]; person3.id = batchIds[2]; // Query: OrderBy Status.Value — should sort alphabetically by list item text var results = await Redb.Query() .Where(p => p.Name == $"{tag}_P1" || p.Name == $"{tag}_P2" || p.Name == $"{tag}_P3") .OrderBy(p => p.Status!.Value) .ToListAsync(); results.Should().HaveCount(3); if (SupportsListItemValueAliasOrdering) { // Provider supports JOIN to _list_items (Postgres Free + Pro, MsSql Pro): // OrderBy Status.Value must sort alphabetically by the list item text. var values = results.Select(r => r.Props.Status!.Value).ToList(); values.Should().BeEquivalentTo(["Alpha", "Beta", "Gamma"], opts => opts.WithStrictOrdering(), "OrderBy Status.Value should sort alphabetically by list item text"); } await CleanupListAsync("ListTest_OrderByValue"); } [Fact] public async Task ListItem_OrderByAlias_SortsAlphabetically() { // Setup: create list with items that have known aliases in reverse alphabetical order var list = await CreateTestListAsync("ListTest_OrderByAlias"); var values = new[] { "Status1", "Status2", "Status3" }; var aliases = new[] { "Cherry", "Apple", "Banana" }; var statuses = await Redb.ListProvider.AddItemsAsync(list, values, aliases); var s1 = statuses.First(s => s.Alias == "Cherry"); var s2 = statuses.First(s => s.Alias == "Apple"); var s3 = statuses.First(s => s.Alias == "Banana"); // Use unique per-run prefix to avoid cross-test pollution in PersonProps scheme var aliasTag = $"OrderByAlias_{Guid.NewGuid():N}"; var person1 = new RedbObject { name = "Person Cherry", Props = new PersonProps { Name = $"{aliasTag}_A1", Age = 20, Email = "a1@test.com", Status = s1 } }; var person2 = new RedbObject { name = "Person Apple", Props = new PersonProps { Name = $"{aliasTag}_A2", Age = 30, Email = "a2@test.com", Status = s2 } }; var person3 = new RedbObject { name = "Person Banana", Props = new PersonProps { Name = $"{aliasTag}_A3", Age = 40, Email = "a3@test.com", Status = s3 } }; var batchIds = await Redb.SaveAsync(new[] { person1, person2, person3 }); person1.id = batchIds[0]; person2.id = batchIds[1]; person3.id = batchIds[2]; // Query: OrderBy Status.Alias — should sort alphabetically by alias var results = await Redb.Query() .Where(p => p.Name == $"{aliasTag}_A1" || p.Name == $"{aliasTag}_A2" || p.Name == $"{aliasTag}_A3") .OrderBy(p => p.Status!.Alias) .ToListAsync(); results.Should().HaveCount(3); if (SupportsListItemValueAliasOrdering) { // Provider supports JOIN to _list_items (Postgres Free + Pro, MsSql Pro): // OrderBy Status.Alias must sort alphabetically by alias. var resultAliases = results.Select(r => r.Props.Status!.Alias).ToList(); resultAliases.Should().BeEquivalentTo(["Apple", "Banana", "Cherry"], opts => opts.WithStrictOrdering(), "OrderBy Status.Alias should sort alphabetically by list item alias"); } await CleanupListAsync("ListTest_OrderByAlias"); } } public enum TestPriority { Low, Medium, High, Critical } Path: redb/redb.Tests.Integration/Tests/Base/LiteralStructureIdsTestsBase.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/LiteralStructureIdsTestsBase.cs ---- using System.Text.RegularExpressions; using redb.Core; using redb.Core.Query.Aggregation; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// SQL Server Pro and SQLite Pro write the structure id of a field into the statement text, never as a parameter: on /// SQL Server a plan compiled for one field was reused for another of the same statement shape (12 rows against 100 000, /// 404 000 reads against 1 700), and filtered or partial indexes serve only a statement that names the structure id. /// The statements below cover the forms that passed it as a parameter before: the filter and its prefilter, a sort, an /// array, a dictionary entry, a list item and a grouping. Values stay parameters. /// public abstract class LiteralStructureIdsTestsBase { protected readonly IRedbService Redb; protected LiteralStructureIdsTestsBase(IRedbService redb) => Redb = redb; // A structure id compared with or listed against a parameter (@p0, $1, :p0), or read from a JSON array parameter. private static readonly Regex StructureIdAsParameter = new(@"_id_structure\s*(=|IN\s*\()\s*(\(?\s*SELECT\s+value\s+FROM\s+json_each\s*\()?\s*[@$:]", RegexOptions.IgnoreCase); private static readonly Regex StructureIdAsLiteral = new(@"_id_structure\s*(=\s*-?\d+|IN\s*\(\s*-?\d+)", RegexOptions.IgnoreCase); private static void ShouldNameStructureIdsInTheText(string sql, string what) { StructureIdAsParameter.Matches(sql).Select(m => m.Value).Should().BeEmpty($"{what}: a structure id is metadata, written into the text"); StructureIdAsLiteral.IsMatch(sql).Should().BeTrue($"{what}: the statement names its structures"); } [Fact] public async Task FilterAndSort_NameTheirStructuresInTheText() { await Redb.SyncSchemeAsync(); var sql = await Redb.Query() .Where(e => e.Salary > 50000m && e.Age >= 30) .OrderBy(e => e.Department).ThenByDescending(e => e.HireDate) .Take(10) .ToSqlStringAsync(); ShouldNameStructureIdsInTheText(sql, "filter, sort and page"); } [Fact] public async Task ArrayAndDictionaryFilters_NameTheirStructuresInTheText() { await Redb.SyncSchemeAsync(); var array = await Redb.Query().Where(e => e.Skills!.Contains("C#")).Take(10).ToSqlStringAsync(); ShouldNameStructureIdsInTheText(array, "array Contains"); var entry = await Redb.Query().Where(e => e.PhoneDirectory!["home"] == "555").Take(10).ToSqlStringAsync(); ShouldNameStructureIdsInTheText(entry, "dictionary entry"); } [Fact] public async Task ListItemFilter_NamesItsStructureInTheText() { await Redb.SyncSchemeAsync(); var sql = await Redb.Query().Where(p => p.Status!.Value == "Active").Take(10).ToSqlStringAsync(); ShouldNameStructureIdsInTheText(sql, "list item"); } [Fact] public async Task Grouping_NamesItsStructuresInTheText() { await Redb.SyncSchemeAsync(); var sql = await Redb.Query() .Where(e => e.Salary > 50000m) .GroupBy(e => e.Department) .ToSqlStringAsync(g => new { Department = g.Key, Count = Agg.Count(g), Total = Agg.Sum(g, e => e.Salary) }); ShouldNameStructureIdsInTheText(sql, "grouping"); } } Path: redb/redb.Tests.Integration/Tests/Base/LockForUpdateTestsBase.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/LockForUpdateTestsBase.cs ---- using redb.Core; using redb.Core.Exceptions; using redb.Core.Models.Entities; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// BR-9 (Tsak report, fixed 2026-09-02): LockForUpdateAsync on a deleted id used to be a silent /// no-op - zero rows locked, no signal - and with the default MissingObjectStrategy.AutoSwitchToInsert /// a CAS pattern (lock -> re-read -> save) could run on an unlocked row or resurrect a deleted /// object. The lenient form now reports how many of the requested rows exist (and are locked); the /// Required form throws naming the missing ids and refuses to run outside a transaction. /// public abstract class LockForUpdateTestsBase { protected readonly IRedbService Redb; protected LockForUpdateTestsBase(IRedbService redb) => Redb = redb; private async Task NewObjectAsync() { await Redb.SyncSchemeAsync(); return await Redb.SaveAsync(new RedbObject { name = "lock-probe", Props = new SimpleProps { Title = "lock" } }); } [Fact] public async Task LockForUpdate_ReportsHowManyRequestedRowsExist() { var id = await NewObjectAsync(); await Redb.Context.ExecuteAtomicAsync(async () => { (await Redb.LockForUpdateAsync(id)).Should().Be(1); (await Redb.LockForUpdateAsync(id, -987654321L)).Should().Be(1, "a deleted or never-created id locks nothing - the count is the caller's signal"); (await Redb.LockForUpdateAsync(id, id)).Should().Be(1, "the count is of DISTINCT existing ids, not of the argument list"); (await Redb.LockForUpdateAsync()).Should().Be(0); }); } [Fact] public async Task LockForUpdateRequired_NamesTheMissingIds() { var id = await NewObjectAsync(); await Redb.Context.ExecuteAtomicAsync(async () => { await Redb.LockForUpdateRequiredAsync(id); // every id exists - no throw var act = async () => await Redb.LockForUpdateRequiredAsync(id, -987654321L, -987654322L); (await act.Should().ThrowAsync( "a CAS must not proceed on an unlocked row")) .Which.MissingIds.Should().Equal(-987654322L, -987654321L); }); } [Fact] public async Task LockForUpdateRequired_RefusesToRunOutsideATransaction() { var id = await NewObjectAsync(); var act = async () => await Redb.LockForUpdateRequiredAsync(id); await act.Should().ThrowAsync( "a lock outside a transaction releases immediately and protects nothing"); } } Path: redb/redb.Tests.Integration/Tests/Base/LongBaseFilterTestsBase.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/LongBaseFilterTestsBase.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.Models; namespace redb.Tests.Integration.Tests.Base; /// /// A filter on a base field whose SQL is long, here ParentId in some hundreds of ids, next to a filter on a field /// of the props. The answer is the children of the listed parents, on every provider. On SQL Server Free the base /// condition is moved out of the props filter as SQL text inside a JSON value and read back with JSON_VALUE, which gives /// NULL for a text over 4,000 characters: the condition vanished and the query returned every object the props filter /// let through. Short lists were right. /// public abstract class LongBaseFilterTestsBase { protected readonly IRedbService Redb; protected LongBaseFilterTestsBase(IRedbService redb) => Redb = redb; private const int Parents = 600; [Fact] public async Task ParentIdInHundredsOfIds_WithAPropsFilter_ReturnsOnlyTheirChildren() { await Redb.SyncSchemeAsync(); var tag = "lbf-" + Guid.NewGuid().ToString("N")[..8]; // Parents, and one more root whose children are not asked for. var roots = Enumerable.Range(0, Parents + 1) .Select(i => (IRedbObject)new RedbObject { name = $"{tag}-p{i}", Props = new NullComparisonProps { Tag = tag } }) .ToList(); var rootIds = await Redb.SaveAsync(roots); var listed = rootIds.Take(Parents).ToList(); var other = rootIds[^1]; // One child per listed parent, every third without a value for N; ten children of the other root. var children = listed.Select((pid, i) => (IRedbObject)new RedbObject { name = $"{tag}-c{i}", parent_id = pid, Props = new NullComparisonProps { Tag = tag, N = i % 3 == 0 ? null : i % 4 } }) .Concat(Enumerable.Range(0, 10).Select(i => (IRedbObject)new RedbObject { name = $"{tag}-o{i}", parent_id = other, Props = new NullComparisonProps { Tag = tag, N = 1 } })) .ToList(); await Redb.SaveAsync(children); var withValue = Enumerable.Range(0, Parents).Count(i => i % 3 != 0); IRedbQueryable Query() => Redb.Query() .WhereRedb(o => o.ParentId != null && listed.Contains(o.ParentId.Value)) .Where(p => p.Tag == tag); (await Query().CountAsync()).Should().Be(Parents, "the children of the listed parents, not every object of the tag"); (await Query().ToListAsync()).Should().HaveCount(Parents); (await Query().Where(p => p.N != null).CountAsync()).Should().Be(withValue); var groups = await Query().GroupBy(p => p.N).SelectAsync(g => new { g.Key, Count = Agg.Count(g) }); groups.Sum(g => g.Count).Should().Be(Parents, "the groups cover the listed parents' children only"); var sum = Enumerable.Range(0, Parents).Where(i => i % 3 != 0).Sum(i => i % 4); var agg = await Query().AggregateAsync(x => new { Total = Agg.Sum(x.Props.N), Count = Agg.Count() }); agg.Total.Should().Be(sum, "an aggregate over the listed parents' children"); agg.Count.Should().Be(Parents); var rows = await Query().WithWindow(w => w.OrderBy(p => p.N)).SelectAsync(x => new { x.Id, Row = Win.RowNumber() }); rows.Should().HaveCount(Parents, "a window over the listed parents' children"); var tree = await Redb.TreeQuery() .WhereRedb(o => o.ParentId != null && listed.Contains(o.ParentId.Value)) .Where(p => p.Tag == tag) .ToListAsync(); tree.Should().HaveCount(Parents, "a tree query over the listed parents' children"); } } Path: redb/redb.Tests.Integration/Tests/Base/MaintenanceTestsBase.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/MaintenanceTestsBase.cs ---- using redb.Core; using redb.Core.Models.Entities; using redb.Core.Providers; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// The maintenance facade: one base implementation, /// all provider variability in three dialect SQL texts normalized to one alias contract. /// AnalyzeAsync refreshes planner statistics; GetIndexStatsAsync reads the /// engine's catalogs. Fields an engine cannot report are null - the pins below assert only /// what every provider guarantees, plus per-suite capability flags. /// public abstract class MaintenanceTestsBase { protected readonly IRedbService Redb; protected MaintenanceTestsBase(IRedbService redb) => Redb = redb; /// Whether the engine reports on-disk index sizes (SQLite only via dbstat). protected virtual bool ReportsSizes => true; /// Whether the engine has schemas at all (SQLite does not). protected virtual bool HasSchemas => true; /// Whether the engine keeps index usage counters (SQLite does not). protected virtual bool ReportsUsageCounters => true; /// Whether the engine records WHEN statistics were last refreshed (SQLite does not). protected virtual bool ReportsAnalyzeTime => true; /// Whether a primary key has an index object of its own (SQLite's INTEGER PRIMARY KEY is the rowid). protected virtual bool ReportsPrimaryKeyIndexes => true; [Fact] public async Task Analyze_Succeeds() { // The whole point of the facade: one call, no provider-specific incantations. On a // test-sized database every engine completes in well under a second. await Redb.Maintenance.AnalyzeAsync(); } [Fact] public async Task IndexStats_SeeTheRedbSchema() { var stats = await Redb.Maintenance.GetIndexStatsAsync(); stats.Should().NotBeEmpty("the redb schema alone carries dozens of indexes"); stats.Should().OnlyContain(s => s.Table.Length > 0 && s.Name.Length > 0, "the alias contract guarantees table and index names on every engine"); // A schema-delivery cross-check for free: the FK-column indexes shipped by the // versioned upgrade must be visible to the stats surface. stats.Should().Contain(s => s.Name == "IX__values__ListItem_not_null" && s.Table == "_values"); stats.Should().Contain(s => s.Name == "IX__values__Object_not_null" && s.Table == "_values"); if (ReportsSizes) { stats.Should().Contain(s => s.SizeBytes > 0, "engines that report sizes must show at least one non-empty index"); } } [Fact] public async Task IndexStats_CarryTheSchemaOfTheirTable() { var stats = await Redb.Maintenance.GetIndexStatsAsync(); if (HasSchemas) { // Without it public.orders and archive.orders are one indistinguishable row, and any // grouping by table lies (redb.Tsak request, 2026-09-21). stats.Should().OnlyContain(s => !string.IsNullOrEmpty(s.Schema), "an engine with schemas must say which one the table is in"); } else { stats.Should().OnlyContain(s => s.Schema == null, "SQLite has no schemas: null, not an invented name"); } } [Fact] public async Task IndexStats_ListTheColumnsOfEachIndex() { var stats = await Redb.Maintenance.GetIndexStatsAsync(); // "Which fields is it on?" is the first question an operator asks, and duplicates and // overlaps cannot be computed from names alone. stats.Should().OnlyContain(s => s.Columns.Count > 0, "every engine can report index columns"); var valuesObject = stats.First(s => s.Name == "IX__values__Object_not_null"); valuesObject.Columns.Should().ContainSingle() .Which.Should().BeEquivalentTo("_Object", "the index is on that one column"); } [Fact] public async Task EveryIndexOfTheRedbSchema_IsSystemCritical() { var stats = await Redb.Maintenance.GetIndexStatsAsync(); // Owner decision 2026-09-21: an index of a redb table is never a drop candidate, whatever // its usage counters say - some of them serve uniqueness or a key check and are never // scanned. The reason travels along so a dashboard can explain the refusal. var redbIndexes = stats.Where(s => s.Table.StartsWith("_")).ToList(); redbIndexes.Should().NotBeEmpty(); redbIndexes.Should().OnlyContain(s => s.IsRedbOwned && s.IsSystemCritical); redbIndexes.Should().OnlyContain(s => s.CriticalReason != IndexCriticality.None); stats.Should().Contain(s => s.Table == "_structures" && s.CriticalReason == IndexCriticality.RedbMetadata); stats.Should().Contain(s => s.Table == "_permissions" && s.CriticalReason == IndexCriticality.RedbSecurity); stats.Should().Contain(s => s.Table == "_values" && s.CriticalReason == IndexCriticality.RedbData); if (ReportsPrimaryKeyIndexes) stats.Should().Contain(s => s.Table == "_objects" && s.IsPrimaryKey, "the primary key of the object table is reported as one"); } [Fact] public async Task StatisticsWindow_SaysSinceWhenTheCountersCount() { var window = await Redb.Maintenance.GetStatisticsWindowAsync(); if (ReportsUsageCounters) { // Zero uses means nothing without the window: the counters may have been reset or the // server restarted a minute ago. window.CountersSince.Should().NotBeNull(); window.CountersSince!.Value.Should().BeBefore(DateTimeOffset.UtcNow.AddMinutes(1)); } else { window.CountersSince.Should().BeNull("SQLite keeps no usage counters, so there is no window"); } } [Fact] public async Task TableStats_ReportTheRedbTables() { var tables = await Redb.Maintenance.GetTableStatsAsync(); tables.Should().NotBeEmpty(); tables.Should().Contain(t => t.Table == "_objects" && t.IsRedbOwned); tables.Should().Contain(t => t.Table == "_values" && t.IsRedbOwned); if (HasSchemas) tables.Should().OnlyContain(t => !string.IsNullOrEmpty(t.Schema)); } [Fact] public async Task AnalyzeTable_RefreshesThatTableAlone() { // An engine samples nothing on an empty table - SQL Server honestly keeps STATS_DATE null // there - so the table must hold a row before the refresh means anything. await Redb.SyncSchemeAsync(); await Redb.SaveAsync(new RedbObject { name = "analyze-" + Guid.NewGuid().ToString("N")[..8], Props = new SimpleProps { Title = "analyze" } }); // The operator usually knows the table that brought them here, and a whole-database pass // runs for minutes on a real database. await Redb.Maintenance.AnalyzeTableAsync("_objects"); var tables = await Redb.Maintenance.GetTableStatsAsync(); var objects = tables.First(t => t.Table == "_objects"); if (ReportsAnalyzeTime) objects.LastAnalyze.Should().NotBeNull("the engine records when statistics were refreshed"); else objects.HasStatistics.Should().BeTrue("SQLite has no date, only the fact that ANALYZE has run"); } [Fact] public async Task AnalyzeTable_OfAnUnknownTable_IsRefused() { // The name comes from a dashboard and cannot be a query parameter, so it is checked // against the catalogs instead of being pasted into SQL. var analyzing = async () => await Redb.Maintenance.AnalyzeTableAsync("no_such_table_" + Guid.NewGuid().ToString("N")[..8]); await analyzing.Should().ThrowAsync(); } } Path: redb/redb.Tests.Integration/Tests/Base/MaterializationFidelityTestsBase.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/MaterializationFidelityTestsBase.cs ---- using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Core; using redb.Core.Extensions; using redb.Core.Models.Configuration; using redb.Core.Models.Entities; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// A load returns what it was asked for: the Props depth a query names, the unique key of an object served as a tree node, /// and the Props of a reference that carries no hash while the props cache is on. /// public abstract class MaterializationFidelityTestsBase { protected abstract void UseProvider(RedbOptionsBuilder options); protected virtual void Register(IServiceCollection services, Action configure) => services.AddRedb(configure); private ServiceProvider Build(Action configure) { var services = new ServiceCollection(); services.AddLogging(b => b.SetMinimumLevel(LogLevel.Warning)); Register(services, options => { UseProvider(options); options.Configure(c => { c.EnablePropsCache = false; c.SkipHashValidationOnCacheCheck = false; configure(c); // A props cache lives per domain for the process: one domain per suite and per cache setting. c.CacheDomain = $"fidelity-{GetType().Name}-{(c.EnablePropsCache ? "cache" : "nocache")}"; }); }); return services.BuildServiceProvider(); } private static string NewTag() => Guid.NewGuid().ToString("N")[..8]; private static async Task BootAsync(IRedbService redb) { await redb.InitializeAsync(ensureCreated: true); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.InitializeTypeRegistryAsync(); } /// root → mid → leaf. private static async Task<(long RootId, long MidId)> SeedChainAsync(IRedbService redb, string tag) { var leafId = await redb.SaveAsync(new RedbObject { name = $"fidelity-leaf-{tag}", Props = new LazyNodeProps { Label = $"leaf-{tag}" } }); var midId = await redb.SaveAsync(new RedbObject { name = $"fidelity-mid-{tag}", Props = new LazyNodeProps { Label = $"mid-{tag}", Next = new RedbObject { id = leafId } } }); var rootId = await redb.SaveAsync(new RedbObject { name = $"fidelity-root-{tag}", Props = new LazyNodeProps { Label = $"root-{tag}", Next = new RedbObject { id = midId } } }); return (rootId, midId); } private static void AssertDepth(RedbObject root, int depth, string tag, string road) { root.Props.Label.Should().Be($"root-{tag}", $"{road}: the object's own Props are loaded"); var mid = root.Props.Next!; if (depth == 1) { mid.IsPropsLoaded.Should().BeFalse($"{road}: depth 1 stops at the object's own Props - the reference is a stub"); return; } mid.IsPropsLoaded.Should().BeTrue($"{road}: depth {depth} loads the first reference"); mid.Props.Next!.IsPropsLoaded.Should().BeFalse($"{road}: depth {depth} stops before the second reference"); } [Theory] [InlineData(1)] [InlineData(2)] public async Task Query_WithPropsDepth_LoadsTheDepthItNames(int depth) { await using var sp = Build(_ => { }); await using var scope = sp.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); await BootAsync(redb); var tag = NewTag(); var (rootId, _) = await SeedChainAsync(redb, tag); var rows = await redb.Query().WhereRedb(o => o.Id == rootId).WithPropsDepth(depth).ToListAsync(); AssertDepth(rows.Should().ContainSingle().Subject, depth, tag, "Query"); } [Theory] [InlineData(1)] [InlineData(2)] public async Task TreeQuery_WithPropsDepth_LoadsTheDepthItNames(int depth) { await using var sp = Build(_ => { }); await using var scope = sp.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); await BootAsync(redb); var tag = NewTag(); var (rootId, _) = await SeedChainAsync(redb, tag); var rows = await redb.TreeQuery().WhereRedb(o => o.Id == rootId).WithPropsDepth(depth).ToListAsync(); AssertDepth(rows.Should().ContainSingle().Subject, depth, tag, "TreeQuery"); } [Fact] public async Task TreeNodes_CarryTheirUniqueKey_OnEveryTreeRoad() { await using var sp = Build(_ => { }); await using var scope = sp.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); await BootAsync(redb); var tag = NewTag(); var parent = new TreeRedbObject { name = $"fidelity-parent-{tag}", ValueUnique = $"P-{tag}", Props = new TreeNodeProps { Name = "parent", Code = $"P-{tag}" } }; parent.id = await redb.SaveAsync(parent); var child = new TreeRedbObject { name = $"fidelity-child-{tag}", ValueUnique = $"C-{tag}", Props = new TreeNodeProps { Name = "child", Code = $"C-{tag}" } }; child.id = await redb.CreateChildAsync(child, parent); var children = (await redb.GetChildrenAsync(parent)).ToList(); children.Should().ContainSingle().Which.ValueUnique.Should().Be($"C-{tag}", "GetChildrenAsync"); var tree = await redb.LoadTreeAsync(parent.id); tree.ValueUnique.Should().Be($"P-{tag}", "LoadTreeAsync: the root"); tree.Children.Should().ContainSingle().Which.Should().BeAssignableTo() .Which.ValueUnique.Should().Be($"C-{tag}", "LoadTreeAsync: a child"); var queried = await redb.TreeQuery(parent.id).ToListAsync(); queried.Should().Contain(o => o.id == child.id, "precondition: the tree query reaches the child"); queried.Single(o => o.id == child.id).ValueUnique.Should().Be($"C-{tag}", "TreeQuery"); } [Fact] public async Task ReferenceWithoutAHash_LoadsItsProps_WhileThePropsCacheIsOn() { await using var sp = Build(c => c.EnablePropsCache = true); await using var scope = sp.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); await BootAsync(redb); var tag = NewTag(); var (_, midId) = await SeedChainAsync(redb, tag); // A reference built in user code: an id and no hash - nothing the cache could match it by. var holder = new RedbObject { Props = new LazyNodeProps { Next = new RedbObject { id = midId } } }; holder.Props.Next!.hash.Should().BeNull("precondition: the reference carries no hash"); await redb.LoadReferencesAsync(holder, p => p.Next); holder.Props.Next.IsPropsLoaded.Should().BeTrue("a reference the cache cannot match is loaded from the database, not dropped"); holder.Props.Next.Props.Label.Should().Be($"mid-{tag}"); } } Path: redb/redb.Tests.Integration/Tests/Base/MigrationTargetAddressingTestsBase.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/MigrationTargetAddressingTestsBase.cs ---- using Microsoft.Extensions.DependencyInjection; using redb.Core; using redb.Core.Models.Entities; using redb.Core.Pro.Migration; using redb.Core.Pro.Query; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// Establishes whether the Pro migration DSL can ADDRESS a nested-class member or an array-element /// member at all, and records what happens when it is asked to. /// /// Review finding PR-32 says the compiled migration SQL carries no _array_index and no /// _parent_value_id, so a target inside a collection would either fail or write one value to /// every row of that structure. That finding matters only if such a target is reachable from user /// code; this suite answers that first, on each provider, without touching any existing test. /// /// public abstract class MigrationTargetAddressingTestsBase { protected readonly IRedbService Redb; private readonly ISqlDialectPro _dialect; protected MigrationTargetAddressingTestsBase(IRedbService redb, IServiceProvider services) { Redb = redb; _dialect = services.GetRequiredService(); } /// Known state for each test: the executor is idempotent, so a leftover history row would skip. private async Task ResetAsync() { var scheme = await Redb.SyncSchemeAsync(); await Redb.Context.ExecuteAsync($"DELETE FROM _migrations WHERE _scheme_id = {scheme.Id}"); await Redb.Context.ExecuteAsync( $"DELETE FROM _values WHERE _id_object IN (SELECT _id FROM _objects WHERE _id_scheme = {scheme.Id})"); await Redb.Context.ExecuteAsync($"DELETE FROM _objects WHERE _id_scheme = {scheme.Id}"); return scheme.Id; } /// One object carrying BOTH shapes: a nested class member and a one-element array of the same class. private async Task SeedAsync() { var obj = new RedbObject { name = "migration-target-probe", Props = new MigrationTargetProbeProps { Base = 4, Multiplier = 2.5, GrandTotal = 0, Details = new LineTargetProps { Qty = 3, Price = 7, LineTotal = 0 }, Items = new List { new() { Qty = 5, Price = 2, LineTotal = 0 } } } }; obj.id = await Redb.SaveAsync(obj); return obj.id; } private static string Describe(IEnumerable results) => string.Join(" | ", results.Select(r => $"'{r.PropertyName}': Success={r.Success}, Skipped={r.Skipped}, Error={r.Error ?? ""}")); [Fact] public async Task Target_RootFields_AreAddressedAndWritten() { await ResetAsync(); var id = await SeedAsync(); var results = await Redb.MigrateAsync(_dialect); results.Should().OnlyContain(r => r.Success, $"the root-field shape is the control; observed: {Describe(results)}"); var loaded = await Redb.LoadAsync(id); loaded!.Props.GrandTotal.Should().BeApproximately(10, 0.0001, "4 * 2.5"); } [Fact] public async Task NestedAndArrayValues_ArePersisted_SoTheTargetShapeIsReal() { await ResetAsync(); var id = await SeedAsync(); var loaded = await Redb.LoadAsync(id); loaded!.Props.Details!.LineTotal.Should().Be(0, "seed value, proves the nested member round-trips"); loaded.Props.Details.Qty.Should().Be(3); loaded.Props.Items.Should().ContainSingle(); loaded.Props.Items[0].Qty.Should().Be(5); loaded.Props.Items[0].Price.Should().Be(2); } [Fact] public async Task Target_NestedClassField_CurrentBehaviour() { await ResetAsync(); var id = await SeedAsync(); var results = await Redb.MigrateAsync(_dialect); // Characterisation of today's behaviour: if the DSL flattens a dotted path to its leaf name, // the resolver cannot find a ROOT field called LineTotal and the migration must refuse loudly. // A green run here means refusal; a red run prints what actually happened in its message. results.Should().OnlyContain(r => !r.Success, $"expected a loud refusal for a nested target if paths are flattened; observed: {Describe(results)}"); var loaded = await Redb.LoadAsync(id); loaded!.Props.Details!.LineTotal.Should().Be(0, "a refused migration must not have written anything"); } [Fact] public async Task Target_ArrayElementField_CurrentBehaviour() { await ResetAsync(); var id = await SeedAsync(); var results = await Redb.MigrateAsync(_dialect); results.Should().OnlyContain(r => !r.Success, $"expected a loud refusal for an array-element target if paths are flattened; observed: {Describe(results)}"); var loaded = await Redb.LoadAsync(id); loaded!.Props.Items[0].LineTotal.Should().Be(0, "a refused migration must not have written anything"); } } Path: redb/redb.Tests.Integration/Tests/Base/MigrationTestsBase.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/MigrationTestsBase.cs ---- using System.Globalization; using Microsoft.Extensions.DependencyInjection; using redb.Core; using redb.Core.Exceptions; using redb.Core.Models.Entities; using redb.Core.Pro.Migration; using redb.Core.Pro.Query; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// Pro data-migration suite (ComputedFrom): apply, idempotency, dry-run and history. /// /// Written because this feature had no test coverage on any provider, which is why a real defect /// went unnoticed: on SQLite the _migrations history table was never created (PG/MSSql get it /// from the concatenated redb_init.sql, SQLite has no such concatenation), so the executor's very /// first statement — the idempotency probe — failed with "no such table". /// /// public abstract class MigrationTestsBase { protected readonly IRedbService Redb; private readonly ISqlDialectPro _dialect; protected MigrationTestsBase(IRedbService redb, IServiceProvider services) { Redb = redb; _dialect = services.GetRequiredService(); } /// /// Clears the migration history for this scheme so each test starts from a known state /// (the executor is idempotent by design — a leftover row would make it skip). /// private async Task ResetAsync() { var scheme = await Redb.SyncSchemeAsync(); await Redb.Context.ExecuteAsync($"DELETE FROM _migrations WHERE _scheme_id = {scheme.Id}"); await Redb.Context.ExecuteAsync( $"DELETE FROM _values WHERE _id_object IN (SELECT _id FROM _objects WHERE _id_scheme = {scheme.Id})"); await Redb.Context.ExecuteAsync($"DELETE FROM _objects WHERE _id_scheme = {scheme.Id}"); return scheme.Id; } private async Task SeedAsync(long quantity, double price) { var obj = new RedbObject { name = $"migration-probe-{quantity}x{price}", Props = new MigrationProbeProps { Quantity = quantity, Price = price, TotalPrice = 0 } }; obj.id = await Redb.SaveAsync(obj); return obj.id; } private Task HistoryCountAsync(long schemeId) => Redb.Context.ExecuteScalarAsync( $"SELECT COUNT(*) FROM _migrations WHERE _scheme_id = {schemeId}"); [Fact] public async Task Migrate_ComputedFrom_RecalculatesTheField() { await ResetAsync(); var id = await SeedAsync(quantity: 3, price: 10.5); var results = await Redb.MigrateAsync(_dialect); results.Should().NotBeEmpty(); results.Should().OnlyContain(r => r.Success, "a failing migration reports Success=false with Error set"); var loaded = await Redb.LoadAsync(id); loaded!.Props.TotalPrice.Should().BeApproximately(31.5, 0.0001); } [Fact] public async Task Migrate_WritesHistoryRow() { var schemeId = await ResetAsync(); await SeedAsync(quantity: 2, price: 4); (await HistoryCountAsync(schemeId)).Should().Be(0); await Redb.MigrateAsync(_dialect, appliedBy: "tests"); (await HistoryCountAsync(schemeId)).Should().Be(1, "applying a migration must record it in _migrations"); } [Fact] public async Task Migrate_Twice_IsIdempotent() { var schemeId = await ResetAsync(); await SeedAsync(quantity: 5, price: 2); await Redb.MigrateAsync(_dialect); var second = await Redb.MigrateAsync(_dialect); second.Should().OnlyContain(r => r.Success); second.Should().Contain(r => r.Skipped, "the history row must make the second run a no-op"); (await HistoryCountAsync(schemeId)).Should().Be(1, "a skipped run must not add a second row"); } [Fact] public async Task Migrate_DryRun_ChangesNothing() { var schemeId = await ResetAsync(); var id = await SeedAsync(quantity: 7, price: 3); var results = await Redb.MigrateAsync(_dialect, dryRun: true); results.Should().OnlyContain(r => r.Success); var loaded = await Redb.LoadAsync(id); loaded!.Props.TotalPrice.Should().Be(0, "dry-run must not touch the data"); (await HistoryCountAsync(schemeId)).Should().Be(0, "dry-run must not record an applied migration"); } // ---- DefaultValue, Transform, and ComputedFrom onto a [RedbUnique] field ---- /// Empties a scheme of the suite: its history, values and objects. private async Task ResetSchemeAsync() where TProps : class, new() { var scheme = await Redb.SyncSchemeAsync(); await Redb.Context.ExecuteAsync($"DELETE FROM _migrations WHERE _scheme_id = {scheme.Id}"); await Redb.Context.ExecuteAsync( $"DELETE FROM _values WHERE _id_object IN (SELECT _id FROM _objects WHERE _id_scheme = {scheme.Id})"); await Redb.Context.ExecuteAsync($"DELETE FROM _objects WHERE _id_scheme = {scheme.Id}"); return scheme.Id; } private async Task RootStructureIdAsync(long schemeId, string name) => (await Redb.Context.ExecuteScalarAsync( $"SELECT _id FROM _structures WHERE _id_scheme = {schemeId} AND _name = '{name}' AND _id_parent IS NULL"))!.Value; /// The stored string of a root field, read from the row itself (no cache in between). private Task StoredStringAsync(long objectId, long structureId) => Redb.Context.ExecuteScalarAsync( $"SELECT _String FROM _values WHERE _id_object = {objectId} AND _id_structure = {structureId}"); private async Task SaveEditProbeAsync(string? status, string? phone) { var obj = new RedbObject { name = "migration-edit-probe", Props = new MigrationEditProbeProps { Status = status, Phone = phone } }; obj.id = await Redb.SaveAsync(obj); return obj.id; } private async Task SaveUniqueProbeAsync(long quantity, double price, double totalPrice) { var obj = new RedbObject { name = $"migration-unique-probe-{quantity}x{price}", Props = new MigrationUniqueProbeProps { Quantity = quantity, Price = price, TotalPrice = totalPrice } }; obj.id = await Redb.SaveAsync(obj); return obj.id; } [Fact] public async Task Migrate_DefaultValue_FillsTheStoredRowsWithoutAValue() { var schemeId = await ResetSchemeAsync(); var empty = await SaveEditProbeAsync(status: "Pending", phone: null); var kept = await SaveEditProbeAsync(status: "Closed", phone: null); var status = await RootStructureIdAsync(schemeId, nameof(MigrationEditProbeProps.Status)); // A stored row without a value: what a SQL-side writer or a field that stores nulls leaves behind. await Redb.Context.ExecuteAsync($"UPDATE _values SET _String = NULL WHERE _id_object = {empty} AND _id_structure = {status}"); var results = await Redb.MigrateAsync(_dialect); results.Should().OnlyContain(r => r.Success, "a failing migration reports Success=false with Error set: {0}", string.Join(" | ", results.Select(r => r.Error))); (await StoredStringAsync(empty, status)).Should().Be("Active"); (await StoredStringAsync(kept, status)).Should().Be("Closed", "DefaultValue fills only rows that hold no value"); } [Fact] public async Task Migrate_DefaultValue_OfABool_FillsTheStoredRowsWithoutAValue() { var schemeId = await ResetSchemeAsync(); var empty = await SaveEditProbeAsync(status: "Pending", phone: null); var enabled = await RootStructureIdAsync(schemeId, nameof(MigrationEditProbeProps.Enabled)); (await Redb.Context.ExecuteAsync($"UPDATE _values SET _Boolean = NULL WHERE _id_object = {empty} AND _id_structure = {enabled}")) .Should().Be(1, "the save stored a row for Enabled"); var results = await Redb.MigrateAsync(_dialect); results.Should().OnlyContain(r => r.Success, "a failing migration reports Success=false with Error set: {0}", string.Join(" | ", results.Select(r => r.Error))); (await Redb.Context.ExecuteScalarAsync( $"SELECT _Boolean FROM _values WHERE _id_object = {empty} AND _id_structure = {enabled}")) .Should().BeTrue(); } [Fact] public async Task Migrate_DefaultValue_OfADateTimeAndADateTimeOffset_ReadsBackThroughTheApi() { var schemeId = await ResetSchemeAsync(); var id = await Redb.SaveAsync(new RedbObject { name = "migration-date-probe", Props = new MigrationEditProbeProps { Due = new DateTime(2020, 1, 2, 3, 4, 5, DateTimeKind.Utc), Seen = new DateTimeOffset(2020, 1, 2, 3, 4, 5, TimeSpan.Zero), } }); foreach (var field in new[] { nameof(MigrationEditProbeProps.Due), nameof(MigrationEditProbeProps.Seen) }) { var structure = await RootStructureIdAsync(schemeId, field); (await Redb.Context.ExecuteAsync( $"UPDATE _values SET _DateTimeOffset = NULL WHERE _id_object = {id} AND _id_structure = {structure}")) .Should().Be(1, "the save stored a row for {0}", field); } var results = await Redb.MigrateAsync(_dialect); results.Should().OnlyContain(r => r.Success, "a failing migration reports Success=false with Error set: {0}", string.Join(" | ", results.Select(r => r.Error))); var loaded = await Redb.LoadAsync(id, depth: 1); loaded.Props.Due.Should().NotBeNull(); loaded.Props.Due!.Value.ToUniversalTime().Should().Be(MigrationDateDefaultValueMigration.DueDefault); loaded.Props.Seen.Should().NotBeNull(); loaded.Props.Seen!.Value.UtcDateTime.Should().Be(MigrationDateDefaultValueMigration.SeenDefault.UtcDateTime); // A filter compares the stored value as the engine stores dates: a value written in another form is not found. var due = MigrationDateDefaultValueMigration.DueDefault; var seen = MigrationDateDefaultValueMigration.SeenDefault; (await Redb.Query().Where(p => p.Due == due).CountAsync()) .Should().Be(1, "the filled DateTime is found by an equality filter"); (await Redb.Query().Where(p => p.Seen == seen).CountAsync()) .Should().Be(1, "the filled DateTimeOffset is found by an equality filter"); (await Redb.Query().Where(p => p.Due < due.AddDays(1)).CountAsync()) .Should().Be(1, "the filled DateTime orders below a later date"); } [Fact] public async Task Migrate_Transform_RewritesTheFieldInPlace() { var schemeId = await ResetSchemeAsync(); var first = await SaveEditProbeAsync(status: null, phone: "555-01-02"); var second = await SaveEditProbeAsync(status: null, phone: "777"); var phone = await RootStructureIdAsync(schemeId, nameof(MigrationEditProbeProps.Phone)); var results = await Redb.MigrateAsync(_dialect); results.Should().OnlyContain(r => r.Success, "a failing migration reports Success=false with Error set: {0}", string.Join(" | ", results.Select(r => r.Error))); (await StoredStringAsync(first, phone)).Should().Be("5550102"); (await StoredStringAsync(second, phone)).Should().Be("777"); } [Fact] public async Task Migrate_ComputedFrom_OnAUniqueField_LeavesNoKeyOfTheOldValue() { await ResetSchemeAsync(); var migrated = await SaveUniqueProbeAsync(quantity: 3, price: 10.5, totalPrice: 0); var results = await Redb.MigrateAsync(_dialect); results.Should().OnlyContain(r => r.Success, "a failing migration reports Success=false with Error set: {0}", string.Join(" | ", results.Select(r => r.Error))); // The migrated object no longer holds 0: another object may take it. var act = () => SaveUniqueProbeAsync(quantity: 1, price: 1, totalPrice: 0); await act.Should().NotThrowAsync("the key of the value the migration replaced must not stay behind"); // The new value gets its key back by the recomputation the sync runs for keyless rows. var report = await Redb.RecomputeUniqueAsync(nameof(MigrationUniqueProbeProps.TotalPrice)); report.HasDuplicates.Should().BeFalse(); var taken = () => SaveUniqueProbeAsync(quantity: 2, price: 2, totalPrice: 31.5); await taken.Should().ThrowAsync($"object {migrated} holds 31.5 after the recomputation"); } // ===== Literals: every kind of value the migration compiler writes into its SQL ===== public static TheoryData LiteralKinds => new() { { nameof(MigrationLiteralProbeProps.Text), null }, { nameof(MigrationLiteralProbeProps.Real), null }, { nameof(MigrationLiteralProbeProps.Real), "sv-SE" }, { nameof(MigrationLiteralProbeProps.Money), null }, { nameof(MigrationLiteralProbeProps.Money), "sv-SE" }, { nameof(MigrationLiteralProbeProps.Count), null }, { nameof(MigrationLiteralProbeProps.Count), "sv-SE" }, { nameof(MigrationLiteralProbeProps.Key), null }, { nameof(MigrationLiteralProbeProps.At), null }, { nameof(MigrationLiteralProbeProps.Seen), null }, { nameof(MigrationLiteralProbeProps.Day), null }, { nameof(MigrationLiteralProbeProps.Clock), null }, { nameof(MigrationLiteralProbeProps.Span), null }, { nameof(MigrationLiteralProbeProps.Kind), null }, { nameof(MigrationLiteralProbeProps.Blob), null }, }; [Theory] [MemberData(nameof(LiteralKinds))] public Task Migrate_DefaultValue_WritesTheValueAsASaveDoes(string kind, string? culture) => LiteralProbeAsync(kind, culture); [Theory] [MemberData(nameof(LiteralKinds))] public Task Migrate_ComputedFrom_WritesAConstantAsASaveDoes(string kind, string? culture) => LiteralProbeAsync(kind, culture); [Fact] public async Task Migrate_DefaultValue_OfNull_LeavesTheRowsWithoutAValue() { await ResetSchemeAsync(); var empty = await SaveLiteralProbeAsync(nameof(MigrationLiteralProbeProps.Text), clear: true); MigrationLiteralValues.Current.Value = "Null"; var results = await Redb.MigrateAsync(_dialect); results.Should().OnlyContain(r => r.Success, "a failing migration reports Success=false with Error set: {0}", string.Join(" | ", results.Select(r => r.Error))); (await Redb.LoadAsync(empty, depth: 1)).Props.Text.Should().BeNull(); } /// /// One object saved with the value (the reference: how a save stores it), one whose stored row was emptied by SQL. /// After the migration the emptied one reads back the value through the API, and a filter on the value finds both. /// private async Task LiteralProbeAsync(string kind, string? culture) where TMigration : IRedbMigration, new() { var before = CultureInfo.CurrentCulture; try { var schemeId = await ResetSchemeAsync(); await SaveLiteralProbeAsync(kind, clear: false); var empty = await SaveLiteralProbeAsync(kind, clear: true); if (culture != null) CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo(culture); MigrationLiteralValues.Current.Value = kind; var results = await Redb.MigrateAsync(_dialect); CultureInfo.CurrentCulture = before; results.Should().OnlyContain(r => r.Success, "a failing migration reports Success=false with Error set: {0}", string.Join(" | ", results.Select(r => r.Error))); var loaded = (await Redb.LoadAsync(empty, depth: 1)).Props; AssertLiteral(kind, loaded); if (kind == nameof(MigrationLiteralProbeProps.Kind)) // The query parser takes no == on a nullable enum: the stored name is counted directly. (await Redb.Context.ExecuteScalarAsync( "SELECT COUNT(*) FROM _values WHERE _String = 'Second' AND _id_object IN " + $"(SELECT _id FROM _objects WHERE _id_scheme = {schemeId})")) .Should().Be(2, "the filled enum is stored by name, as the saved one"); else if (kind != nameof(MigrationLiteralProbeProps.Blob)) (await Redb.Query().Where(LiteralFilter(kind)).CountAsync()) .Should().Be(2, "a filter on the value finds the saved object and the filled one"); } finally { CultureInfo.CurrentCulture = before; MigrationLiteralValues.Current.Value = null; } } private async Task SaveLiteralProbeAsync(string kind, bool clear) { var props = new MigrationLiteralProbeProps(); switch (kind) { case nameof(MigrationLiteralProbeProps.Text): props.Text = MigrationLiteralValues.Text; break; case nameof(MigrationLiteralProbeProps.Real): props.Real = MigrationLiteralValues.Real; break; case nameof(MigrationLiteralProbeProps.Money): props.Money = MigrationLiteralValues.Money; break; case nameof(MigrationLiteralProbeProps.Count): props.Count = MigrationLiteralValues.Count; break; case nameof(MigrationLiteralProbeProps.Key): props.Key = MigrationLiteralValues.Key; break; case nameof(MigrationLiteralProbeProps.At): props.At = MigrationLiteralValues.At; break; case nameof(MigrationLiteralProbeProps.Seen): props.Seen = MigrationLiteralValues.Seen; break; case nameof(MigrationLiteralProbeProps.Day): props.Day = MigrationLiteralValues.Day; break; case nameof(MigrationLiteralProbeProps.Clock): props.Clock = MigrationLiteralValues.Clock; break; case nameof(MigrationLiteralProbeProps.Span): props.Span = MigrationLiteralValues.Span; break; case nameof(MigrationLiteralProbeProps.Kind): props.Kind = MigrationLiteralValues.Kind; break; case nameof(MigrationLiteralProbeProps.Blob): props.Blob = MigrationLiteralValues.Blob; break; } var id = await Redb.SaveAsync(new RedbObject { name = $"literal-{kind}", Props = props }); if (clear) (await Redb.Context.ExecuteAsync( "UPDATE _values SET _String = NULL, _Long = NULL, _Guid = NULL, _Double = NULL, _DateTimeOffset = NULL, " + $"_ByteArray = NULL, _Numeric = NULL WHERE _id_object = {id}")) .Should().Be(1, "the save stored one row for {0}", kind); return id; } private static void AssertLiteral(string kind, MigrationLiteralProbeProps p) { switch (kind) { case nameof(MigrationLiteralProbeProps.Text): p.Text.Should().Be(MigrationLiteralValues.Text); break; case nameof(MigrationLiteralProbeProps.Real): p.Real.Should().Be(MigrationLiteralValues.Real); break; case nameof(MigrationLiteralProbeProps.Money): p.Money.Should().Be(MigrationLiteralValues.Money); break; case nameof(MigrationLiteralProbeProps.Count): p.Count.Should().Be(MigrationLiteralValues.Count); break; case nameof(MigrationLiteralProbeProps.Key): p.Key.Should().Be(MigrationLiteralValues.Key); break; case nameof(MigrationLiteralProbeProps.At): p.At!.Value.ToUniversalTime().Should().Be(MigrationLiteralValues.At); break; case nameof(MigrationLiteralProbeProps.Seen): p.Seen!.Value.UtcDateTime.Should().Be(MigrationLiteralValues.Seen.UtcDateTime); break; case nameof(MigrationLiteralProbeProps.Day): p.Day.Should().Be(MigrationLiteralValues.Day); break; case nameof(MigrationLiteralProbeProps.Clock): p.Clock.Should().Be(MigrationLiteralValues.Clock); break; case nameof(MigrationLiteralProbeProps.Span): p.Span.Should().Be(MigrationLiteralValues.Span); break; case nameof(MigrationLiteralProbeProps.Kind): p.Kind.Should().Be(MigrationLiteralValues.Kind); break; case nameof(MigrationLiteralProbeProps.Blob): p.Blob.Should().Equal(MigrationLiteralValues.Blob); break; } } private static System.Linq.Expressions.Expression> LiteralFilter(string kind) { var key = MigrationLiteralValues.Key; var at = MigrationLiteralValues.At; var seen = MigrationLiteralValues.Seen; var day = MigrationLiteralValues.Day; var clock = MigrationLiteralValues.Clock; var span = MigrationLiteralValues.Span; return kind switch { nameof(MigrationLiteralProbeProps.Text) => p => p.Text == MigrationLiteralValues.Text, nameof(MigrationLiteralProbeProps.Real) => p => p.Real == MigrationLiteralValues.Real, nameof(MigrationLiteralProbeProps.Money) => p => p.Money == MigrationLiteralValues.Money, nameof(MigrationLiteralProbeProps.Count) => p => p.Count == MigrationLiteralValues.Count, nameof(MigrationLiteralProbeProps.Key) => p => p.Key == key, nameof(MigrationLiteralProbeProps.At) => p => p.At == at, nameof(MigrationLiteralProbeProps.Seen) => p => p.Seen == seen, nameof(MigrationLiteralProbeProps.Day) => p => p.Day == day, nameof(MigrationLiteralProbeProps.Clock) => p => p.Clock == clock, nameof(MigrationLiteralProbeProps.Span) => p => p.Span == span, _ => throw new ArgumentOutOfRangeException(nameof(kind), kind, null), }; } } Path: redb/redb.Tests.Integration/Tests/Base/MigrationTransformArithmeticTestsBase.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/MigrationTransformArithmeticTestsBase.cs ---- using AwesomeAssertions.Execution; using Microsoft.Extensions.DependencyInjection; using redb.Core; using redb.Core.Attributes; using redb.Core.Models.Entities; using redb.Core.Pro.Migration; using redb.Core.Pro.Query; namespace redb.Tests.Integration.Tests.Base; [RedbScheme("Migrations: transform arithmetic probe", Name = "migration_transform_arithmetic_probe")] public class MigrationTransformArithmeticProbeProps { public long Amount { get; set; } public long? Bonus { get; set; } public long Total { get; set; } } public class MigrationTransformMultiply : IRedbMigration { public void Configure(IMigrationBuilder builder) => builder.Property(p => p.Amount).Transform(v => v * 2); } public class MigrationTransformAdd : IRedbMigration { public void Configure(IMigrationBuilder builder) => builder.Property(p => p.Amount).Transform(v => v + 1); } public class MigrationTransformParameterOnTheRight : IRedbMigration { public void Configure(IMigrationBuilder builder) => builder.Property(p => p.Amount).Transform(v => 100 - v); } public class MigrationTransformMixed : IRedbMigration { public void Configure(IMigrationBuilder builder) => builder.Property(p => p.Amount).Transform(v => 2 * (v + 3) - 1); } public class MigrationComputedWithCoalesce : IRedbMigration { public void Configure(IMigrationBuilder builder) => builder.Property(p => p.Total).ComputedFrom(p => p.Amount + (p.Bonus ?? 0)); } /// /// A Transform whose value takes part in arithmetic: the value is the lambda's parameter itself, and every place it /// appears must read the property's column. /// public abstract class MigrationTransformArithmeticTestsBase { private readonly IRedbService _redb; private readonly ISqlDialectPro _dialect; protected MigrationTransformArithmeticTestsBase(IRedbService redb, IServiceProvider services) { _redb = redb; _dialect = services.GetRequiredService(); } [Fact] public async Task Transform_Multiply_DoublesTheValue() { var (results, amount) = await RunAsync(); using (new AssertionScope()) { results.Should().OnlyContain(r => r.Success, "the transform compiles and runs"); amount.Should().Be(10); } } [Fact] public async Task Transform_Add_AddsOne() { var (results, amount) = await RunAsync(); using (new AssertionScope()) { results.Should().OnlyContain(r => r.Success, "the transform compiles and runs"); amount.Should().Be(6); } } [Fact] public async Task Transform_ParameterOnTheRight_SubtractsTheValue() { var (results, amount) = await RunAsync(); using (new AssertionScope()) { results.Should().OnlyContain(r => r.Success, "the transform compiles and runs"); amount.Should().Be(95); } } [Fact] public async Task Transform_MixedWithAConstantOnEachSide_ComputesTheValue() { var (results, amount) = await RunAsync(); using (new AssertionScope()) { results.Should().OnlyContain(r => r.Success, "the transform compiles and runs"); amount.Should().Be(15); } } [Fact] public async Task ComputedFrom_CoalesceInsideAnOperator_KeepsWhatCameBeforeIt() { var (results, _) = await RunAsync(); var total = (await _redb.LoadAsync(_lastId))!.Props.Total; using (new AssertionScope()) { results.Should().OnlyContain(r => r.Success, "the computation compiles and runs"); total.Should().Be(8, "Amount 5 plus Bonus 3"); } } private long _lastId; private async Task<(List Results, long Amount)> RunAsync() where TMigration : IRedbMigration, new() { var scheme = await _redb.SyncSchemeAsync(); await _redb.Context.ExecuteAsync($"DELETE FROM _migrations WHERE _scheme_id = {scheme.Id}"); await _redb.Context.ExecuteAsync( $"DELETE FROM _values WHERE _id_object IN (SELECT _id FROM _objects WHERE _id_scheme = {scheme.Id})"); await _redb.Context.ExecuteAsync($"DELETE FROM _objects WHERE _id_scheme = {scheme.Id}"); var id = await _redb.SaveAsync(new RedbObject { name = "transform-arithmetic", Props = new MigrationTransformArithmeticProbeProps { Amount = 5, Bonus = 3, Total = -1 } }); _lastId = id; var results = await _redb.MigrateAsync(_dialect); var amount = (await _redb.LoadAsync(id))!.Props.Amount; return (results, amount); } } Path: redb/redb.Tests.Integration/Tests/Base/MsSqlStringMatchContractTestsBase.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/MsSqlStringMatchContractTestsBase.cs ---- using redb.Core; using redb.Core.Models.Entities; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// String matching on SQL Server against the contract in COLLATION.md (BR-6): plain Contains / StartsWith / /// EndsWith follow the column collation, and the *IgnoreCase forms fold case - not diacritics. SQL Server Pro broke /// both (review MP-10): the plain forms were forced case-sensitive (COLLATE Latin1_General_CS_AS) and the /// IgnoreCase forms accent-insensitive (COLLATE Latin1_General_CI_AI), so Free and Pro answered the same query /// differently on the same database. The facts assume the default case-insensitive, accent-sensitive collation of /// the test database and check it first. /// public abstract class MsSqlStringMatchContractTestsBase { protected readonly IRedbService Redb; protected MsSqlStringMatchContractTestsBase(IRedbService redb) => Redb = redb; private async Task SeedAsync() { var collation = await Redb.Context.ExecuteScalarAsync( "SELECT CONVERT(nvarchar(128), DATABASEPROPERTYEX(DB_NAME(), 'Collation'))"); collation.Should().Contain("_CI_AS", "precondition: the test database folds case and keeps accents"); await Redb.SyncSchemeAsync(); var tag = Guid.NewGuid().ToString("N")[..8]; await Redb.SaveAsync(new RedbObject { name = $"zebra-{tag}", Props = new SimpleProps { Title = $"ZEBRA-{tag}" } }); await Redb.SaveAsync(new RedbObject { name = $"muller-{tag}", Props = new SimpleProps { Title = $"Müller-{tag}" } }); return tag; } [Fact] public async Task PlainContains_FollowsTheColumnCollation() { var tag = await SeedAsync(); var found = await Redb.Query().Where(x => x.Title.Contains($"zebra-{tag}")).ToListAsync(); found.Should().ContainSingle("a case-insensitive column matches regardless of case"); } [Fact] public async Task ContainsIgnoreCase_FoldsCaseButNotAccents() { var tag = await SeedAsync(); var withUmlaut = await Redb.Query() .Where(x => x.Title.Contains($"MÜLLER-{tag}", StringComparison.OrdinalIgnoreCase)).ToListAsync(); var withoutUmlaut = await Redb.Query() .Where(x => x.Title.Contains($"muller-{tag}", StringComparison.OrdinalIgnoreCase)).ToListAsync(); withUmlaut.Should().ContainSingle("case is folded"); withoutUmlaut.Should().BeEmpty("diacritics are not folded - that is a different feature (COLLATION.md)"); } } Path: redb/redb.Tests.Integration/Tests/Base/NestedCollectionsRefusalTestsBase.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/NestedCollectionsRefusalTestsBase.cs ---- using redb.Core; using redb.Core.Exceptions; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// A collection directly inside a collection (a list of lists, jagged and multi-dimensional arrays, a list or array of /// dictionaries, a list of arrays, a dictionary of lists or of dictionaries). Before, each inner collection was stored as /// the name of its type (a multi-dimensional array flat) and the object could not be loaded. Now the scheme sync refuses /// the property before it writes anything, naming the class, the property and its type; a save against a scheme synced /// before the refusal existed refuses the same way before any row is written. byte[] as an element or value and a /// collection inside a class element keep working. /// public abstract class NestedCollectionsRefusalTestsBase { protected readonly IRedbService Redb; protected NestedCollectionsRefusalTestsBase(IRedbService redb) => Redb = redb; private async Task SyncIsRefusedAsync(string owner, string property, string typeName) where TProps : class, new() { var act = () => Redb.SyncSchemeAsync(); var refusal = (await act.Should().ThrowAsync()).Which; refusal.OwnerName.Should().Be(owner); refusal.PropertyName.Should().Be(property); refusal.PropertyTypeName.Should().Be(typeName); refusal.Message.Should().Contain("Wrap the inner collection in a class"); var schemes = await Redb.Context.ExecuteScalarAsync( $"SELECT COUNT(*) FROM _schemes WHERE _name = '{typeof(TProps).FullName}'"); schemes.Should().Be(0, "the sync refuses before it writes the scheme row"); } [Fact] public Task ListOfLists_SyncIsRefused() => SyncIsRefusedAsync("NestedListOfListsProps", "Value", "List>"); [Fact] public Task JaggedArray_SyncIsRefused() => SyncIsRefusedAsync("NestedJaggedArrayProps", "Value", "Int32[][]"); [Fact] public Task ListOfArrays_SyncIsRefused() => SyncIsRefusedAsync("NestedListOfArraysProps", "Value", "List"); [Fact] public Task ListOfDictionaries_SyncIsRefused() => SyncIsRefusedAsync("NestedListOfDictionariesProps", "Value", "List>"); [Fact] public Task ArrayOfDictionaries_SyncIsRefused() => SyncIsRefusedAsync("NestedArrayOfDictionariesProps", "Value", "Dictionary[]"); [Fact] public Task DictionaryOfLists_SyncIsRefused() => SyncIsRefusedAsync("NestedDictionaryOfListsProps", "Value", "Dictionary>"); [Fact] public Task DictionaryOfDictionaries_SyncIsRefused() => SyncIsRefusedAsync("NestedDictionaryOfDictionariesProps", "Value", "Dictionary>"); [Fact] public Task MultidimensionalArray_SyncIsRefused() => SyncIsRefusedAsync("NestedMultidimensionalArrayProps", "Value", "Int32[,]"); [Fact] public Task NestedCollectionInsideAClassElement_SyncIsRefused_NamingTheElementClass() => SyncIsRefusedAsync("NestedGridHolder", "Grid", "List>"); // --- allowed shapes, pinned --- [Fact] public async Task BytesAsElementOrValue_ReadBackAsSaved() { await Redb.SyncSchemeAsync(); var saved = new NestedBytesCollectionsProps { Chunks = [[1, 2, 3], [], [255]], Blobs = new() { ["a"] = [9, 8], ["b"] = [] } }; var id = await Redb.SaveAsync(new RedbObject { name = "nested-bytes", Props = saved }); var loaded = (await Redb.LoadAsync(id))!.Props; loaded.Chunks.Should().BeEquivalentTo(saved.Chunks, o => o.WithStrictOrdering()); loaded.Blobs.Should().BeEquivalentTo(saved.Blobs); } [Fact] public async Task CollectionInsideAClassElement_ReadsBackAsSaved() { await Redb.SyncSchemeAsync(); var saved = new NestedCollectionInElementProps { Items = [ new() { Name = "x", Tags = ["a", "b"], Scores = new() { ["s"] = 1 } }, new() { Name = "y", Tags = ["c"] } ], ByKey = new() { ["k"] = new() { Name = "z", Tags = ["d", "e"], Scores = new() { ["t"] = 2 } } } }; var id = await Redb.SaveAsync(new RedbObject { name = "nested-in-element", Props = saved }); var loaded = (await Redb.LoadAsync(id))!.Props; loaded.Should().BeEquivalentTo(saved, o => o.WithStrictOrdering()); } // --- save against a scheme synced before the refusal existed --- private async Task SaveIsRefusedAsync(TProps props, string found) where TShape : class, new() where TProps : class, new() { var scheme = await Redb.SyncSchemeAsync(); var name = "nested-guard-" + Guid.NewGuid().ToString("N")[..8]; var obj = new RedbObject { name = name, Props = props }; ((IRedbObject)obj).SchemeId = scheme.Id; var act = () => Redb.SaveAsync(obj); var refusal = (await act.Should().ThrowAsync()).Which; refusal.PropertyName.Should().Be("Value"); refusal.PropertyTypeName.Should().Be(found); var objects = await Redb.Context.ExecuteScalarAsync($"SELECT COUNT(*) FROM _objects WHERE _name = '{name}'"); objects.Should().Be(0, "the save refuses while the value rows are built, before anything is written"); } [Fact] public Task ListOfLists_OnASchemeSyncedBefore_SaveIsRefused() => SaveIsRefusedAsync( new() { Value = [[1, 2], [3]] }, "a collection element of type List"); [Fact] public Task DictionaryOfLists_OnASchemeSyncedBefore_SaveIsRefused() => SaveIsRefusedAsync( new() { Value = new() { ["a"] = [1] } }, "a collection element of type List"); [Fact] public Task MultidimensionalArray_OnASchemeSyncedBefore_SaveIsRefused() => SaveIsRefusedAsync( new() { Value = new[,] { { 1, 2 }, { 3, 4 } } }, "a multi-dimensional array Int32[,]"); } Path: redb/redb.Tests.Integration/Tests/Base/NestedDictionaryFilterTestsBase.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/NestedDictionaryFilterTestsBase.cs ---- using System.Linq.Expressions; using redb.Core; using redb.Core.Models.Entities; using redb.Tests.Integration.Helpers; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// Filters on a field of a class stored as a dictionary value (DepartmentHistory["2024"].Name, /// OfficeLocations["HQ"].City), compared with the same LINQ over the seeded objects in memory. The entry of a /// dictionary has children of several structures under one parent row: scalars (Name, HeadCount), an array /// (Projects), a nested class (Building). The engines join the children of the entry by parent and structure; each /// case here has children of other structures next to the one it reads, so a join that picked the wrong child or lost /// the entry would change the answer. A condition on the array of an entry (Projects) is refused by every engine and is /// not part of this set. /// public abstract class NestedDictionaryFilterTestsBase { protected readonly IRedbService Redb; protected NestedDictionaryFilterTestsBase(IRedbService redb) => Redb = redb; private async Task<(string Tag, List Props)> SeedAsync() { await Redb.SyncSchemeAsync(); var tag = "nd-" + Guid.NewGuid().ToString("N")[..8]; var props = new List(); for (var i = 0; i < 6; i++) { var p = TestDataFactory.CreateEmployee(i + 1, firstName: $"{tag}-{i}", department: tag).Props; p.DepartmentHistory = new Dictionary { ["2024"] = new() { Name = i % 2 == 0 ? $"{tag}-even" : $"{tag}-odd", HeadCount = i * 10, Projects = i % 3 == 0 ? ["p1", "p2"] : ["p3"] }, ["2023"] = new() { Name = $"{tag}-even", HeadCount = 100 + i, Projects = ["p1"] } }; p.OfficeLocations = new Dictionary { ["HQ"] = new() { City = i < 4 ? $"{tag}-city" : $"{tag}-other", Street = $"s{i}", Building = new TestBuildingInfo { Floor = i, Name = $"b{i}" } }, ["Branch"] = new() { City = $"{tag}-city", Street = "branch" } }; await Redb.SaveAsync(new RedbObject { name = $"{tag}-{i}", Props = p }); props.Add(p); } return (tag, props); } private async Task MatchesLinqAsync(string tag, List seeded, Expression> filter, int expectedCount) { var expected = seeded.Where(filter.Compile()).Select(p => p.FirstName).ToList(); expected.Should().HaveCount(expectedCount, "precondition"); var query = Redb.Query().Where(e => e.Department == tag).Where(filter); (await query.ToListAsync()).Select(o => o.Props.FirstName).Should().BeEquivalentTo(expected); (await query.CountAsync()).Should().Be(expectedCount); } [Fact] public async Task ScalarOfEntry_NextToChildrenOfOtherStructures() { var (tag, seeded) = await SeedAsync(); var even = tag + "-even"; await MatchesLinqAsync(tag, seeded, e => e.DepartmentHistory!["2024"].Name == even, 3); } [Fact] public async Task TwoScalarsOfOneEntry() { var (tag, seeded) = await SeedAsync(); var even = tag + "-even"; await MatchesLinqAsync(tag, seeded, e => e.DepartmentHistory!["2024"].Name == even && e.DepartmentHistory!["2024"].HeadCount > 10, 2); } [Fact] public async Task ScalarsOfTwoEntriesOfOneDictionary() { var (tag, seeded) = await SeedAsync(); var odd = tag + "-odd"; await MatchesLinqAsync(tag, seeded, e => e.DepartmentHistory!["2024"].Name == odd && e.DepartmentHistory!["2023"].HeadCount > 102, 2); } [Fact] public async Task FieldOfNestedClassValue_NextToNestedClassAndOtherEntry() { var (tag, seeded) = await SeedAsync(); var city = tag + "-city"; await MatchesLinqAsync(tag, seeded, e => e.OfficeLocations!["HQ"].City == city, 4); } } Path: redb/redb.Tests.Integration/Tests/Base/NullComparisonTestsBase.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/NullComparisonTestsBase.cs ---- using System.Linq.Expressions; using redb.Core; using redb.Core.Models.Entities; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// Comparisons follow SQL's three-valued logic, the same on every provider, in Free and Pro, with the planner on and /// off: an object without a value for a field matches neither F == v nor F != v. The same holds for /// !(F == v), for F != G when either side has no value, and for !list.Contains(F). It differs from /// LINQ to objects and from EF Core's default (both count such an object as "not equal"); the README says so, and these /// tests keep the providers and the planner modes from drifting apart. F != v || F == null is the documented way /// to include the objects without a value: it returns exactly the complement of F == v. /// /// Every expectation is computed in memory from the seed with SQL's rule. /// public abstract class NullComparisonTestsBase { protected readonly IRedbService Redb; protected NullComparisonTestsBase(IRedbService redb) => Redb = redb; /// /// Known difference, SQL Server Free: the module tests a list item's Id, Value or Alias with EXISTS, so /// !(p.L.Id == item) and !ids.Contains(p.L.Id) also return the objects without a list item, as LINQ does (Free parity, the list-item /// accessor branch of 13_pvt_condition.sql). Asserted as it is today, to stay visible until the module is fixed. /// protected virtual bool NegatedListItemTakesObjectsWithoutItem => false; private static readonly DateTime Day = new(2026, 3, 1, 0, 0, 0, DateTimeKind.Utc); private sealed record Seeded(string Tag, List Rows, long ItemA, long ItemB); /// /// 42 objects. Each field is empty at a period of its own (the second field of a pair at another), so the pairs /// hold both sides set, one side empty and both sides empty. /// private async Task SeedAsync() { await Redb.SyncSchemeAsync(); var tag = "nc-" + Guid.NewGuid().ToString("N")[..8]; var list = await Redb.ListProvider.SaveListAsync(RedbList.Create(tag, tag)); var items = await Redb.ListProvider.AddItemsAsync(list, ["A", "B"]); var rows = Enumerable.Range(1, 42).Select(i => new NullComparisonProps { Tag = tag, N = i % 3 == 0 ? null : i % 4, N2 = i % 5 == 0 ? null : i % 3, S = i % 4 == 0 ? null : "s" + (i % 3), S2 = i % 6 == 0 ? null : "s" + (i % 2), D = i % 5 == 0 ? null : Day.AddDays(i % 3), D2 = i % 7 == 0 ? null : Day.AddDays(i % 2), B = i % 3 == 0 ? null : i % 2 == 0, B2 = i % 4 == 0 ? null : i % 3 == 0, L = i % 4 == 0 ? null : items[i % 2], L2 = i % 3 == 0 ? null : items[(i / 2) % 2], }).ToList(); await Redb.SaveAsync(rows.Select((p, i) => new RedbObject { name = $"{tag}-{i}", Props = p }).ToList()); return new Seeded(tag, rows, items[0].Id, items[1].Id); } private async Task EachPlannerModeAsync(Func check) { var restore = Redb.Configuration.EnablePvtPrefilter; try { foreach (var on in new[] { false, true }) { Redb.UpdateConfiguration(c => c.EnablePvtPrefilter = on); await check(on ? "planner on" : "planner off"); } } finally { Redb.UpdateConfiguration(c => c.EnablePvtPrefilter = restore); } } /// /// One form: the filter, SQL's answer computed in memory, and C#'s where the filter itself cannot run in memory /// (p.L!.Id on an object without a list item). /// private sealed record Case(string Name, Expression> Filter, Func Sql, Func? CSharp = null, bool NegatedListItem = false); private static IEnumerable Cases(Seeded s) { int? n = 1; string? text = "s1"; DateTime? d = Day.AddDays(1); bool? b = true; var item = s.ItemA; var numbers = new List { 1, 2 }; var texts = new List { "s0", "s1" }; var days = new List { Day, Day.AddDays(1) }; var flags = new List { true }; var itemIds = new List { s.ItemA }; // F != v yield return new("number !=", p => p.N != n, p => p.N.HasValue && p.N != n); yield return new("text !=", p => p.S != text, p => p.S != null && p.S != text); yield return new("date !=", p => p.D != d, p => p.D.HasValue && p.D != d); yield return new("flag !=", p => p.B != b, p => p.B.HasValue && p.B != b); yield return new("list item !=", p => p.L!.Id != item, p => p.L != null && p.L.Id != item, p => p.L?.Id != item); // !(F == v) yield return new("number !(==)", p => !(p.N == n), p => p.N.HasValue && p.N != n); yield return new("text !(==)", p => !(p.S == text), p => p.S != null && p.S != text); yield return new("date !(==)", p => !(p.D == d), p => p.D.HasValue && p.D != d); yield return new("flag !(==)", p => !(p.B == b), p => p.B.HasValue && p.B != b); yield return new("list item !(==)", p => !(p.L!.Id == item), p => p.L != null && p.L.Id != item, p => !(p.L?.Id == item), NegatedListItem: true); // F != G yield return new("number field != field", p => p.N != p.N2, p => p.N.HasValue && p.N2.HasValue && p.N != p.N2); yield return new("text field != field", p => p.S != p.S2, p => p.S != null && p.S2 != null && p.S != p.S2); yield return new("date field != field", p => p.D != p.D2, p => p.D.HasValue && p.D2.HasValue && p.D != p.D2); yield return new("flag field != field", p => p.B != p.B2, p => p.B.HasValue && p.B2.HasValue && p.B != p.B2); yield return new("list item field != field", p => p.L!.Id != p.L2!.Id, p => p.L != null && p.L2 != null && p.L.Id != p.L2.Id, p => p.L?.Id != p.L2?.Id); // !list.Contains(F) yield return new("number !Contains", p => !numbers.Contains(p.N), p => p.N.HasValue && !numbers.Contains(p.N)); yield return new("text !Contains", p => !texts.Contains(p.S), p => p.S != null && !texts.Contains(p.S)); yield return new("date !Contains", p => !days.Contains(p.D), p => p.D.HasValue && !days.Contains(p.D)); yield return new("flag !Contains", p => !flags.Contains(p.B), p => p.B.HasValue && !flags.Contains(p.B)); yield return new("list item !Contains", p => !itemIds.Contains(p.L!.Id), p => p.L != null && !itemIds.Contains(p.L.Id), p => p.L == null || !itemIds.Contains(p.L.Id), NegatedListItem: true); } /// /// Each form against the expectation and, where SQL's rule leaves objects out, against LINQ's: the two must differ /// on this seed, or the test would not show which rule the provider follows. /// [Fact] public async Task NotEqualForms_LeaveOutObjectsWithoutAValue_AsSqlDoes() { var s = await SeedAsync(); await EachPlannerModeAsync(async mode => { foreach (var c in Cases(s)) { var expected = s.Rows.Where(c.Sql).Count(); var linq = s.Rows.Where(c.CSharp ?? c.Filter.Compile()).Count(); linq.Should().BeGreaterThan(expected, $"the seed must tell SQL's rule from LINQ's for {c.Name}"); if (c.NegatedListItem && NegatedListItemTakesObjectsWithoutItem) expected = linq; // the known difference above var tag = s.Tag; var got = await Redb.Query().Where(p => p.Tag == tag).Where(c.Filter).CountAsync(); got.Should().Be(expected, $"{c.Name}, {mode}: an object without a value matches neither == nor !="); var page = await Redb.Query().Where(p => p.Tag == tag).Where(c.Filter).ToListAsync(); page.Should().HaveCount(expected, $"{c.Name}, {mode}, ToListAsync agrees with CountAsync"); } }); } /// /// Contains over a list of dates or flags reads the values. On SQLite the list went to the driver as a DateTime[] /// or bool[], which it cannot bind ("No mapping exists from object type System.DateTime[]"). /// [Fact] public async Task ContainsOverAListOfDatesOrFlags_ReadsTheValues() { var s = await SeedAsync(); var tag = s.Tag; var days = new List { Day, Day.AddDays(2) }; var flags = new List { false }; await EachPlannerModeAsync(async mode => { (await Redb.Query().Where(p => p.Tag == tag && days.Contains(p.D)).CountAsync()) .Should().Be(s.Rows.Count(p => p.D.HasValue && days.Contains(p.D)), $"dates, {mode}"); (await Redb.Query().Where(p => p.Tag == tag && flags.Contains(p.B)).CountAsync()) .Should().Be(s.Rows.Count(p => p.B.HasValue && flags.Contains(p.B)), $"flags, {mode}"); }); } /// /// Contains and !Contains over a list of every value type a field can have: a list of two values, a list with a /// null among them, a list of nulls only and an empty list. A null in the list is dropped ([a, null] filters as [a], /// a list of nulls as an empty list). Contains matches the objects whose value is in the list; !Contains the objects /// whose value is not, never an object without a value (the != rule); with an empty list Contains matches nothing /// and !Contains every object that has a value. /// [Fact] public async Task ContainsOverAListOfEachValueType_DropsTheNullsOfTheList() { await Redb.SyncSchemeAsync(); var tag = "ct-" + Guid.NewGuid().ToString("N")[..8]; var g = new[] { Guid.Parse("11111111-1111-1111-1111-111111111111"), Guid.Parse("22222222-2222-2222-2222-222222222222"), Guid.Parse("33333333-3333-3333-3333-333333333333") }; var dto = new DateTimeOffset(2026, 3, 1, 10, 0, 0, TimeSpan.Zero); // Object i holds value i % 3 of each type, or no value when i % 4 == 3. var rows = Enumerable.Range(0, 12).Select(i => { var k = i % 3; var empty = i % 4 == 3; return new ContainsTypesProps { Tag = tag, I64 = empty ? null : 5_000_000_000L + k, I32 = empty ? null : 10 + k, I16 = empty ? null : (short)(20 + k), U8 = empty ? null : (byte)(30 + k), F64 = empty ? null : 1.5 + k, F32 = empty ? null : 2.5f + k, Dec = empty ? null : 3.25m + k, Flag = empty ? null : k == 1, Ch = empty ? null : (char)('a' + k), Text = empty ? null : "t" + k, Id = empty ? null : g[k], Dt = empty ? null : Day.AddDays(k), Dto = empty ? null : dto.AddHours(k), Day = empty ? null : DateOnly.FromDateTime(Day).AddDays(k), Time = empty ? null : new TimeOnly(8 + k, 30), Span = empty ? null : TimeSpan.FromMinutes(90 + k), Color = empty ? null : (ContainsColor)k }; }).ToList(); await Redb.SaveAsync(rows.Select((p, i) => new RedbObject { name = $"{tag}-{i}", Props = p }).ToList()); var failures = new List(); await EachPlannerModeAsync(async mode => { await CheckAsync(p => p.I64, 5_000_000_000L, 5_000_000_001L); await CheckAsync(p => p.I32, 10, 11); await CheckAsync(p => p.I16, (short)20, (short)21); await CheckAsync(p => p.U8, (byte)30, (byte)31); await CheckAsync(p => p.F64, 1.5, 2.5); await CheckAsync(p => p.F32, 2.5f, 3.5f); await CheckAsync(p => p.Dec, 3.25m, 4.25m); await CheckAsync(p => p.Flag, false, true); await CheckAsync(p => p.Ch, 'a', 'b'); await CheckTextAsync(); await CheckAsync(p => p.Id, g[0], g[1]); await CheckAsync(p => p.Dt, Day, Day.AddDays(1)); await CheckAsync(p => p.Dto, dto, dto.AddHours(1)); await CheckAsync(p => p.Day, DateOnly.FromDateTime(Day), DateOnly.FromDateTime(Day).AddDays(1)); await CheckAsync(p => p.Time, new TimeOnly(8, 30), new TimeOnly(9, 30)); await CheckAsync(p => p.Span, TimeSpan.FromMinutes(90), TimeSpan.FromMinutes(91)); await CheckAsync(p => p.Color, ContainsColor.Red, ContainsColor.Green); async Task CheckAsync(Expression> field, TV a, TV b) where TV : struct { var read = field.Compile(); var name = ((MemberExpression)field.Body).Member.Name; foreach (var (label, list) in new (string, List)[] { ("two values", [a, b]), ("a null in the list", [a, null]), ("nulls only", [null, null]), ("empty", []) }) { var present = list.Where(v => v.HasValue).Select(v => v!.Value).ToList(); var expectedIn = rows.Count(r => read(r) is { } v && present.Contains(v)); var expectedNotIn = rows.Count(r => read(r) is { } v && !present.Contains(v)); await CountAsync($"{name} Contains, {label}, {mode}", Contains(field, list, negate: false), expectedIn); await CountAsync($"{name} !Contains, {label}, {mode}", Contains(field, list, negate: true), expectedNotIn); } } async Task CheckTextAsync() { foreach (var (label, list) in new (string, List)[] { ("two values", ["t0", "t1"]), ("a null in the list", ["t0", null]), ("nulls only", [null]), ("empty", []) }) { var present = list.OfType().ToList(); await CountAsync($"Text Contains, {label}, {mode}", p => list.Contains(p.Text), rows.Count(r => r.Text != null && present.Contains(r.Text))); await CountAsync($"Text !Contains, {label}, {mode}", p => !list.Contains(p.Text), rows.Count(r => r.Text != null && !present.Contains(r.Text))); } } }); failures.Should().BeEmpty(string.Join("; ", failures)); async Task CountAsync(string what, Expression> filter, int expected) { try { var got = await Redb.Query().Where(p => p.Tag == tag).Where(filter).CountAsync(); if (got != expected) failures.Add($"{what}: {got}, expected {expected}"); } catch (Exception ex) { failures.Add($"{what}: {ex.GetType().Name}: {ex.Message.Split('\n')[0]}"); } } } /// A null list itself is refused with ArgumentNullException, not taken for an unsupported expression. [Fact] public async Task Contains_OfANullList_IsRefusedAsNull() { List? list = null; var act = async () => await Redb.Query().Where(p => list!.Contains(p.I32)).CountAsync(); (await act.Should().ThrowAsync()).Which.Message.Should().Contain("The list of a Contains filter is null"); } private static Expression> Contains(Expression> field, List list, bool negate) where TV : struct { var contains = typeof(List).GetMethod(nameof(List.Contains))!; Expression body = Expression.Call(Expression.Constant(list), contains, field.Body); if (negate) body = Expression.Not(body); return Expression.Lambda>(body, field.Parameters); } /// The documented way to include the objects without a value: the exact complement of F == v. [Fact] public async Task NotEqualOrNull_IsTheComplementOfEqual() { var s = await SeedAsync(); var tag = s.Tag; int? n = 1; string? text = "s1"; DateTime? d = Day.AddDays(1); bool? b = true; var item = s.ItemA; var pairs = new (string Name, Expression> Equal, Expression> NotEqualOrNull, Func EqualInMemory)[] { ("number", p => p.N == n, p => p.N != n || p.N == null, p => p.N == n), ("text", p => p.S == text, p => p.S != text || p.S == null, p => p.S == text), ("date", p => p.D == d, p => p.D != d || p.D == null, p => p.D == d), ("flag", p => p.B == b, p => p.B != b || p.B == null, p => p.B == b), ("list item", p => p.L!.Id == item, p => p.L!.Id != item || p.L == null, p => p.L?.Id == item), }; await EachPlannerModeAsync(async mode => { foreach (var (name, equal, rest, equalInMemory) in pairs) { var a = (await Redb.Query().Where(p => p.Tag == tag).Where(equal).ToListAsync()).Select(o => o.Id).ToHashSet(); var r = (await Redb.Query().Where(p => p.Tag == tag).Where(rest).ToListAsync()).Select(o => o.Id).ToHashSet(); a.Overlaps(r).Should().BeFalse($"{name}, {mode}: no object is both equal and not equal"); (a.Count + r.Count).Should().Be(s.Rows.Count, $"{name}, {mode}: together they are every object"); a.Count.Should().Be(s.Rows.Count(equalInMemory), $"{name}, {mode}: == is the same in SQL and in LINQ"); } }); } } Path: redb/redb.Tests.Integration/Tests/Base/NullableCollectionsTestsBase.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/NullableCollectionsTestsBase.cs ---- using redb.Core; using redb.Core.Models.Entities; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// A round trip of collections of nullable value types: dictionaries of int?, long?, decimal?, DateTime?, bool? and /// Guid?, arrays and lists of nullable numbers and flags, and a dictionary of a class with nullable fields. Each holds /// a null among its values; the null keeps its key or its position, every other value reads back as saved. /// public abstract class NullableCollectionsTestsBase { protected readonly IRedbService Redb; protected NullableCollectionsTestsBase(IRedbService redb) => Redb = redb; private static readonly DateTime At = new(2026, 11, 18, 10, 30, 0, DateTimeKind.Utc); private static readonly Guid Id = Guid.Parse("6f1c2a4e-0b7d-4c55-9a3e-2f8d1b9c7e01"); private static NullableCollectionsProps Sample(string tag) => new() { Tag = tag, Ints = new() { ["a"] = 1, ["n"] = null, ["z"] = -7 }, Longs = new() { ["a"] = 5_000_000_000L, ["n"] = null }, Decimals = new() { ["a"] = 12.345m, ["n"] = null }, Dates = new() { ["a"] = At, ["n"] = null }, Flags = new() { ["t"] = true, ["f"] = false, ["n"] = null }, Guids = new() { ["a"] = Id, ["n"] = null }, IntArray = [1, null, 3], LongList = [null, 5_000_000_000L], DecimalList = [1.5m, null, -2.25m], FlagArray = [true, null, false], Entries = new() { ["x"] = new NullableCollectionsEntry { Name = "x", Score = 4, At = At, Marks = [2, null, 5] }, ["y"] = new NullableCollectionsEntry { Name = "y", Score = null, At = null } } }; private static DateTime? Utc(DateTime? d) => d?.Kind == DateTimeKind.Local ? d.Value.ToUniversalTime() : d; private async Task RoundTripAsync() { await Redb.SyncSchemeAsync(); var tag = "nc-" + Guid.NewGuid().ToString("N")[..8]; var id = await Redb.SaveAsync(new RedbObject { name = tag, Props = Sample(tag) }); var loaded = await Redb.LoadAsync(id); loaded.Should().NotBeNull(); return loaded!.Props; } [Fact] public async Task DictionariesOfNullableValueTypes_ReadBackAsSaved_TheNullEntryKept() { var p = await RoundTripAsync(); var expected = Sample(p.Tag); p.Ints.Should().BeEquivalentTo(expected.Ints); p.Longs.Should().BeEquivalentTo(expected.Longs); p.Decimals.Should().BeEquivalentTo(expected.Decimals); p.Dates!.ToDictionary(kv => kv.Key, kv => Utc(kv.Value)).Should().BeEquivalentTo(expected.Dates); p.Flags.Should().BeEquivalentTo(expected.Flags); p.Guids.Should().BeEquivalentTo(expected.Guids); } [Fact] public async Task ArraysAndListsOfNullableValueTypes_ReadBackAsSaved_TheNullInPlace() { var p = await RoundTripAsync(); p.IntArray.Should().Equal(1, null, 3); p.LongList.Should().Equal(null, 5_000_000_000L); p.DecimalList.Should().Equal(1.5m, null, -2.25m); p.FlagArray.Should().Equal(true, null, false); } [Fact] public async Task DictionaryOfAClassWithNullableFields_ReadsBackAsSaved() { var p = await RoundTripAsync(); p.Entries.Should().HaveCount(2); p.Entries!["x"].Score.Should().Be(4); Utc(p.Entries["x"].At).Should().Be(At); p.Entries["y"].Score.Should().BeNull(); p.Entries["y"].At.Should().BeNull(); p.Entries["x"].Marks.Should().Equal(2, null, 5); p.Entries["y"].Marks.Should().BeNull(); } } 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); } } Path: redb/redb.Tests.Integration/Tests/Base/OrderAbsentValueTestsBase.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/OrderAbsentValueTestsBase.cs ---- using redb.Core; using redb.Core.Models.Entities; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// Sorting by a field returns every object the filter selects, also those without a value for that field (they sort /// first ascending and last descending, as LINQ orders null), and OrderBy then ThenBy sorts by both keys. /// public abstract class OrderAbsentValueTestsBase { protected readonly IRedbService Redb; protected OrderAbsentValueTestsBase(IRedbService redb) => Redb = redb; private async Task SeedAsync() { await Redb.SyncSchemeAsync(); var tag = "oa-" + Guid.NewGuid().ToString("N")[..8]; var rows = new (string? Label, int? Rank, int Group, string Name)[] { ("b", 2, 1, "d"), (null, null, 2, "a"), ("a", 1, 1, "b"), ("c", 3, 2, "c"), (null, null, 1, "a"), }; foreach (var r in rows) { await Redb.SaveAsync(new RedbObject { name = $"{tag}-{r.Name}-{r.Group}", Props = new OrderAbsentProps { Tag = tag, Label = r.Label, Rank = r.Rank, Group = r.Group, Name = r.Name } }); } return tag; } [Fact] public async Task OrderBy_AStringFieldSomeObjectsLack_ReturnsEveryObject_AbsentFirst() { var tag = await SeedAsync(); var rows = await Redb.Query().Where(p => p.Tag == tag).OrderBy(p => p.Label).ToListAsync(); rows.Select(r => r.Props.Label).Should().Equal(new string?[] { null, null, "a", "b", "c" }); } [Fact] public async Task OrderByDescending_AStringFieldSomeObjectsLack_ReturnsEveryObject_AbsentLast() { var tag = await SeedAsync(); var rows = await Redb.Query().Where(p => p.Tag == tag).OrderByDescending(p => p.Label).ToListAsync(); rows.Select(r => r.Props.Label).Should().Equal(new string?[] { "c", "b", "a", null, null }); } [Fact] public async Task OrderBy_ANumberFieldSomeObjectsLack_ReturnsEveryObject_AbsentFirst() { var tag = await SeedAsync(); var rows = await Redb.Query().Where(p => p.Tag == tag).OrderBy(p => p.Rank).ToListAsync(); rows.Select(r => r.Props.Rank).Should().Equal(new int?[] { null, null, 1, 2, 3 }); } [Fact] public async Task OrderBy_ThenByAString_SortsByBothKeys() { var tag = await SeedAsync(); var rows = await Redb.Query().Where(p => p.Tag == tag) .OrderBy(p => p.Group).ThenBy(p => p.Name).ToListAsync(); rows.Select(r => $"{r.Props.Group}{r.Props.Name}").Should().Equal("1a", "1b", "1d", "2a", "2c"); } [Fact] public async Task OrderBy_ThenByDescendingAString_SortsByBothKeys() { var tag = await SeedAsync(); var rows = await Redb.Query().Where(p => p.Tag == tag) .OrderBy(p => p.Group).ThenByDescending(p => p.Name).ToListAsync(); rows.Select(r => $"{r.Props.Group}{r.Props.Name}").Should().Equal("1d", "1b", "1a", "2c", "2a"); } [Fact] public async Task ThenBy_AFieldSomeObjectsLack_PutsThemFirstInTheirGroup() { var tag = await SeedAsync(); var asc = await Redb.Query().Where(p => p.Tag == tag).OrderBy(p => p.Group).ThenBy(p => p.Label).ToListAsync(); asc.Select(r => $"{r.Props.Group}{r.Props.Label ?? "-"}").Should().Equal("1-", "1a", "1b", "2-", "2c"); var desc = await Redb.Query().Where(p => p.Tag == tag).OrderBy(p => p.Group).ThenByDescending(p => p.Label).ToListAsync(); desc.Select(r => $"{r.Props.Group}{r.Props.Label ?? "-"}").Should().Equal("1b", "1a", "1-", "2c", "2-"); } [Fact] public async Task Page_OverAFieldSomeObjectsLack_StartsWithThem() { var tag = await SeedAsync(); var page = await Redb.Query().Where(p => p.Tag == tag).OrderBy(p => p.Rank).ThenByRedb(o => o.Id).Skip(1).Take(2).ToListAsync(); page.Select(r => r.Props.Rank).Should().Equal(new int?[] { null, 1 }); var last = await Redb.Query().Where(p => p.Tag == tag).OrderByDescending(p => p.Rank).ThenByRedb(o => o.Id).Skip(3).Take(2).ToListAsync(); last.Select(r => r.Props.Rank).Should().Equal(new int?[] { null, null }); } [Fact] public async Task DistinctBy_OrderedByAFieldSomeObjectsLack_KeepsTheEmptyKeyFirst() { var tag = await SeedAsync(); var rows = await Redb.Query().Where(p => p.Tag == tag).OrderBy(p => p.Label).DistinctBy(p => p.Label).ToListAsync(); rows.Select(r => r.Props.Label).Should().Equal(new string?[] { null, "a", "b", "c" }); } [Fact] public async Task TreeQuery_OrderedByAFieldSomeChildrenLack_PutsThemFirst() { await Redb.SyncSchemeAsync(); var tag = "oat-" + Guid.NewGuid().ToString("N")[..8]; var root = new TreeRedbObject { name = tag + "-root", Props = new OrderAbsentProps { Tag = tag + "-root", Rank = 100 } }; root.id = await Redb.SaveAsync(root); foreach (var rank in new int?[] { 2, null, 1, null }) await Redb.CreateChildAsync(new TreeRedbObject { name = $"{tag}-{rank}", Props = new OrderAbsentProps { Tag = tag, Rank = rank } }, root); var asc = await Redb.TreeQuery(root.id).Where(p => p.Tag == tag).OrderBy(p => p.Rank).ToListAsync(); asc.Select(r => r.Props.Rank).Should().Equal(new int?[] { null, null, 1, 2 }); var desc = await Redb.TreeQuery(root.id).Where(p => p.Tag == tag).OrderByDescending(p => p.Rank).ToListAsync(); desc.Select(r => r.Props.Rank).Should().Equal(new int?[] { 2, 1, null, null }); } [Fact] public async Task Window_OrderedByAFieldSomeObjectsLack_NumbersThemFirst() { var tag = await SeedAsync(); var rows = await Redb.Query().Where(p => p.Tag == tag) .WithWindow(w => w.OrderBy(p => p.Rank)) .SelectAsync(x => new { x.Props.Rank, Row = redb.Core.Query.Aggregation.Win.RowNumber() }); rows.Where(r => r.Rank == null).Select(r => r.Row).OrderBy(r => r).Should().Equal(1L, 2L); var desc = await Redb.Query().Where(p => p.Tag == tag) .WithWindow(w => w.OrderByDesc(p => p.Rank)) .SelectAsync(x => new { x.Props.Rank, Row = redb.Core.Query.Aggregation.Win.RowNumber() }); desc.Where(r => r.Rank == null).Select(r => r.Row).OrderBy(r => r).Should().Equal(4L, 5L); } } Path: redb/redb.Tests.Integration/Tests/Base/OrderingTestsBase.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/OrderingTestsBase.cs ---- using redb.Core; using redb.Tests.Integration.Helpers; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; public abstract class OrderingTestsBase { protected readonly IRedbService Redb; protected OrderingTestsBase(IRedbService redb) => Redb = redb; private async Task> SeedAsync() { return await TestDataFactory.SeedEmployees(Redb, 10); } [Fact] public async Task OrderBy_Ascending_SortsByField() { var ids = await SeedAsync(); var results = await Redb.Query() .OrderBy(e => e.Age) .Take(50) .ToListAsync(); results.Should().HaveCountGreaterThanOrEqualTo(10); var ages = results.Select(r => r.Props.Age).ToList(); ages.Should().BeInAscendingOrder(); } [Fact] public async Task OrderByDescending_SortsByFieldDesc() { var ids = await SeedAsync(); var results = await Redb.Query() .OrderByDescending(e => e.Salary) .Take(50) .ToListAsync(); var salaries = results.Select(r => r.Props.Salary).ToList(); salaries.Should().BeInDescendingOrder(); } [Fact] public async Task OrderBy_ThenBy_MultipleSort() { var ids = await SeedAsync(); var results = await Redb.Query() .OrderBy(e => e.Department) .ThenBy(e => e.Age) .Take(50) .ToListAsync(); results.Should().NotBeEmpty(); // Within each department group, ages should be ascending var grouped = results.GroupBy(r => r.Props.Department); foreach (var group in grouped) { var ages = group.Select(r => r.Props.Age).ToList(); ages.Should().BeInAscendingOrder($"Ages in department {group.Key} should be sorted"); } } [Fact] public async Task Skip_Take_ReturnsPage() { var ids = await SeedAsync(); var page = await Redb.Query() .OrderBy(e => e.Age) .Skip(3) .Take(4) .ToListAsync(); page.Should().HaveCount(4); } // CountAsync and AnyAsync answer for the rows ToListAsync of the same query returns. They used // to answer for the whole filtered set: Take(3).CountAsync() over ten rows returned ten // (found 2026-10-12; every provider did it, the count SQL leaves LIMIT and OFFSET out). [Fact] public async Task CountAsync_FollowsTakeAndSkip() { var ids = await SeedAsync(); var query = Redb.Query().WhereRedb(o => ids.Contains(o.Id)); (await query.CountAsync()).Should().Be(10); (await query.Take(3).CountAsync()).Should().Be(3); (await query.Take(50).CountAsync()).Should().Be(10); (await query.Skip(4).CountAsync()).Should().Be(6); (await query.Skip(4).Take(3).CountAsync()).Should().Be(3); (await query.Skip(8).Take(5).CountAsync()).Should().Be(2); (await query.Skip(10).CountAsync()).Should().Be(0); (await query.Skip(100).Take(5).CountAsync()).Should().Be(0); (await query.Take(0).CountAsync()).Should().Be(0); } [Fact] public async Task CountAsync_Paged_MatchesToListAsync() { var ids = await SeedAsync(); var page = Redb.Query() .WhereRedb(o => ids.Contains(o.Id)) .Where(e => e.Age >= 0) .OrderBy(e => e.Age) .Skip(2) .Take(5); var rows = await page.ToListAsync(); (await page.CountAsync()).Should().Be(rows.Count); (await page.Select(o => o.Id).CountAsync()).Should().Be(rows.Count, "a projection counts the rows of its source"); } [Fact] public async Task AnyAsync_FollowsTakeAndSkip() { var ids = await SeedAsync(); var query = Redb.Query().WhereRedb(o => ids.Contains(o.Id)); (await query.AnyAsync()).Should().BeTrue(); (await query.Take(0).AnyAsync()).Should().BeFalse(); (await query.Skip(9).AnyAsync()).Should().BeTrue(); (await query.Skip(10).AnyAsync()).Should().BeFalse(); } [Fact] public async Task AllAsync_OnPagedQuery_StillChecksEveryRow() { // Counts cut to the same page size are equal as soon as enough rows match; All has to // compare the counts of the whole set. var ids = await SeedAsync(); var query = Redb.Query().WhereRedb(o => ids.Contains(o.Id)); var ages = (await query.ToListAsync()).Select(r => r.Props.Age).OrderBy(a => a).ToList(); var youngest = ages[0]; var threshold = ages[5]; (await query.Take(3).AllAsync(e => e.Age >= youngest)).Should().BeTrue(); (await query.Take(3).AllAsync(e => e.Age > threshold)).Should().Be(ages.All(a => a > threshold)); } } Path: redb/redb.Tests.Integration/Tests/Base/OrphanTransactionTestsBase.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/OrphanTransactionTestsBase.cs ---- using System.Diagnostics; using Microsoft.Extensions.DependencyInjection; using redb.Core; using redb.Core.Models.Entities; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// A command whose SQL text opens a transaction and fails before ending it must not leave that /// transaction on the connection (trash review, 2026-09-14). The connection wrapper does not own such a /// transaction, so nothing would ever end it: /// /// MSSQL - every later statement of the scope ran inside it and vanished with it when the pooled /// session was reset: a save reported success and its row was gone; /// SQLite - the handle went back to the pool holding the database write lock, and every writer /// of the process failed with "database is locked" for as long as that handle sat in the pool; /// PostgreSQL - the scope was stuck in an aborted transaction block and refused its next /// transaction. /// /// The connection layer is tier-independent, so the Free collections cover it. /// public abstract class OrphanTransactionTestsBase { private readonly IServiceProvider _services; protected OrphanTransactionTestsBase(IServiceProvider services) => _services = services; /// A batch that opens a transaction in its own text and then fails. protected abstract string FailingBatchThatOpensATransaction { get; } [Fact] public async Task FailedCommand_LeavesNoTransactionBehind() { var tag = Guid.NewGuid().ToString("N")[..12]; // A second scope with a live connection BEFORE the failure: a pooled handle that keeps a write // lock stays invisible to a scope that happens to receive that same handle again. await using var other = _services.CreateAsyncScope(); var otherRedb = other.ServiceProvider.GetRequiredService(); await otherRedb.SyncSchemeAsync(); await using (var scope = _services.CreateAsyncScope()) { var redb = scope.ServiceProvider.GetRequiredService(); var act = async () => await redb.Context.ExecuteAsync(FailingBatchThatOpensATransaction); await act.Should().ThrowAsync("the batch is built to fail"); // The caller handles the failure and keeps working in the same scope. await redb.SaveAsync(new RedbObject { name = $"orphan-same-{tag}", Props = new TrashTargetProps { Title = "same" } }); } var clock = Stopwatch.StartNew(); await otherRedb.SaveAsync(new RedbObject { name = $"orphan-other-{tag}", Props = new TrashTargetProps { Title = "other" } }); clock.Elapsed.Should().BeLessThan(TimeSpan.FromSeconds(4), "no connection may keep holding a lock after its command failed"); (await otherRedb.Context.ExecuteScalarAsync($"SELECT COUNT(*) FROM _objects WHERE _name = 'orphan-same-{tag}'")) .Should().Be(1, "the save made after the failure is committed, not held in a transaction the failed batch left open"); } } Path: redb/redb.Tests.Integration/Tests/Base/PageValuesGraphTestsBase.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/PageValuesGraphTestsBase.cs ---- using redb.Core; using redb.Core.Models.Entities; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// The Pro materializer reads the rows of a page through one index built once per read. A page of two objects of the /// same scheme with every lookup shape: the root fields, a root class, the fields of a class array element (a class /// field, a scalar array, a class array under the element), a null element, a dictionary of classes, a scalar array of /// twelve elements (index 10 and 11 after 9, not after 1), an empty array and an unset one. Each object reads back as it /// was saved, with nothing of the other object in it. /// public abstract class PageValuesGraphTestsBase { protected readonly IRedbService Redb; protected PageValuesGraphTestsBase(IRedbService redb) => Redb = redb; private static PageGraphProps Graph(string tag) => new() { Title = $"title-{tag}", Head = new PageGraphLine { Code = $"head-{tag}", Inner = new PageGraphInner { Level = 1, Note = $"head-inner-{tag}", Marks = new List { 3, 1, 2 } }, Tags = new List { $"h0-{tag}", $"h1-{tag}" }, }, Lines = new List { new() { Code = $"line0-{tag}", Inner = new PageGraphInner { Level = 10, Note = $"inner0-{tag}", Marks = new List { 7 } }, Tags = Enumerable.Range(0, 12).Select(i => $"t{i}-{tag}").ToList(), Parts = new List { new() { Level = 100, Note = $"part0-{tag}", Marks = new List { 1, 2 } }, new() { Level = 101, Note = $"part1-{tag}" }, }, }, null, new() { Code = $"line2-{tag}", Inner = new PageGraphInner { Level = 12, Note = $"inner2-{tag}" }, Tags = new List(), }, }, ByCode = new Dictionary { ["b"] = new() { Code = $"dict-b-{tag}", Inner = new PageGraphInner { Level = 2, Note = $"dict-inner-b-{tag}" } }, ["a"] = new() { Code = $"dict-a-{tag}", Parts = new List { new() { Level = 3, Note = $"dict-part-{tag}" } } }, }, Numbers = Enumerable.Range(0, 12).Select(i => 1000 - i).ToList(), Empty = new List(), Missing = null, }; [Fact] public async Task APageOfTwoObjects_EveryLookupShape_ReadsBackAsSaved() { await Redb.SyncSchemeAsync(); var tag = Guid.NewGuid().ToString("N")[..8]; var first = Graph($"{tag}-1"); var second = Graph($"{tag}-2"); var firstId = await Redb.SaveAsync(new RedbObject { name = $"page-values-1-{tag}", Props = first }); var secondId = await Redb.SaveAsync(new RedbObject { name = $"page-values-2-{tag}", Props = second }); var page = await Redb.Query() .WhereRedb(o => o.Id == firstId || o.Id == secondId) .OrderByRedb(o => o.Id) .ToListAsync(); page.Select(o => o.id).Should().Equal(firstId, secondId); page[0].Props.Should().BeEquivalentTo(first, o => o.WithStrictOrdering()); page[1].Props.Should().BeEquivalentTo(second, o => o.WithStrictOrdering()); page[0].Props.Lines![1].Should().BeNull("a null element keeps its position"); page[0].Props.Empty.Should().NotBeNull().And.BeEmpty("an empty array reads as empty, not as unset"); page[0].Props.Missing.Should().BeNull("an unset array reads as unset"); } } Path: redb/redb.Tests.Integration/Tests/Base/ParallelImportFinishTestsBase.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/ParallelImportFinishTestsBase.cs ---- using Microsoft.Extensions.DependencyInjection; using redb.Core; using redb.Core.Data; using redb.Core.Models.Entities; using redb.Export.Providers; using redb.Export.Services; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// The finishing steps of a parallel import (the id sequence, the index rebuild, the constraints) are each attempted /// whatever the others do, and their failures are reported together. A target that had lost its id sequence failed at /// the sequence step, and the steps after it never ran: every secondary index of the large tables stayed disabled /// (SQL Server) or dropped (PostgreSQL), and on SQL Server every constraint and trigger stayed off. /// public abstract class ParallelImportFinishTestsBase { protected abstract string ProviderName { get; } protected abstract Task NewDatabaseAsync(string suffix); protected abstract ServiceProvider Build(string cs); protected abstract string NewFile(); protected abstract Task ScalarAsync(string cs, string sql); /// Drops the id sequence, as a damaged database had lost it. protected abstract Task DropSequenceAsync(string cs); /// The indexes with their state, the foreign keys and triggers with theirs. protected abstract Task> ShapeAsync(string cs); [Fact] public async Task AFailingSequenceStep_StillRebuildsTheIndexes_AndRestoresTheConstraints_AndReportsTheStep() { var source = await SeededAsync("src"); var file = NewFile(); await using (var provider = ProviderFactory.Create(ProviderName)) { await provider.OpenAsync(source); await new ExportService(provider, verbose: false, batchSize: 1000).ExportAsync(file, null, compress: false, dryRun: false); } var target = await SeededAsync("dst"); await DropSequenceAsync(target); var shape = await ShapeAsync(target); Exception? failure = null; try { await using var provider = ProviderFactory.Create(ProviderName); await provider.OpenAsync(target); await new ImportService(provider, verbose: false, batchSize: 1000, parallelism: 2) .ImportAsync(file, clean: true, dryRun: false); } catch (Exception ex) { failure = ex; } RedbKeyGeneratorBase.ClearAllCaches(); (await ShapeAsync(target)).Should().Equal(shape, "the index rebuild and the constraints ran after the failed step"); failure.Should().BeOfType().Which.Message .Should().Contain("1 of its finishing steps failed; every step was attempted").And.Contain("- id sequence:"); (await ScalarAsync(target, "SELECT COUNT(*) FROM _values")) .Should().Be(await ScalarAsync(source, "SELECT COUNT(*) FROM _values"), "every row was written"); } private async Task SeededAsync(string suffix) { var cs = await NewDatabaseAsync(suffix); await using var provider = Build(cs); var redb = provider.GetRequiredService(); await redb.InitializeAsync(ensureCreated: true, typeof(ExportService).Assembly); await redb.SyncSchemeAsync(); for (var i = 0; i < 3; i++) await redb.SaveAsync(new RedbObject { name = $"{suffix}-{i}", Props = new SimpleProps { Title = $"{suffix}{i}" } }); return cs; } } Path: redb/redb.Tests.Integration/Tests/Base/PasswordHasherDefaultTestsBase.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/PasswordHasherDefaultTestsBase.cs ---- using redb.Core; using redb.Core.Models.Users; using redb.Core.Security; namespace redb.Tests.Integration.Tests.Base; /// /// Pins the default password hasher of a bare redb deployment (external security report, /// 2026-09-08): every provider's stock CreateUserProvider factory used the short UserProvider /// constructor, which hard-wired SimplePasswordHasher (salted SHA256) - BcryptPasswordHasher /// existed in the tree but nothing reached it. The default is bcrypt now; legacy SHA256+salt /// hashes keep validating (BcryptPasswordHasher recognizes both formats), so existing /// databases migrate naturally on the next password change. /// public abstract class PasswordHasherDefaultTestsBase { protected readonly IRedbService Redb; protected PasswordHasherDefaultTestsBase(IRedbService redb) => Redb = redb; private static string FreshLogin() => "hash_" + Guid.NewGuid().ToString("N")[..12]; [Fact] public async Task DefaultHasher_WritesBcrypt() { var login = FreshLogin(); var user = await Redb.UserProvider.CreateUserAsync( new CreateUserRequest { Login = login, Name = login, Password = "correct-horse" }); var stored = await Redb.Context.ExecuteScalarAsync( $"SELECT _password FROM _users WHERE _id = {user.Id}"); stored.Should().StartWith("$2", "a bare redb deployment must hash passwords with bcrypt by default, not salted SHA256"); } [Fact] public async Task LegacySha256Hash_StillValidates() { // An existing database carries SimplePasswordHasher-era hashes ("base64(salt):base64(hash)"). // The bcrypt default must keep accepting them - login survives the upgrade, and the hash // migrates to bcrypt whenever the user changes the password. var login = FreshLogin(); var user = await Redb.UserProvider.CreateUserAsync( new CreateUserRequest { Login = login, Name = login, Password = "placeholder" }); var legacy = new SimplePasswordHasher().HashPassword("old-password"); await Redb.Context.ExecuteAsync( $"UPDATE _users SET _password = '{legacy}' WHERE _id = {user.Id}"); var validated = await Redb.UserProvider.ValidateUserAsync(login, "old-password"); validated.Should().NotBeNull("a legacy SHA256+salt hash must still authenticate"); var rejected = await Redb.UserProvider.ValidateUserAsync(login, "wrong-password"); rejected.Should().BeNull("the legacy path must still reject a wrong password"); } [Fact] public async Task SetPasswordHash_StoresAHashMadeElsewhere() { // An administrator password given in configuration as a hash (htpasswd -B writes $2y$): // stored as is, and the default hasher accepts it at login. var login = FreshLogin(); var user = await Redb.UserProvider.CreateUserAsync( new CreateUserRequest { Login = login, Name = login, Password = "placeholder" }); var hash = BCrypt.Net.BCrypt.HashPassword("from-config", BCrypt.Net.BCrypt.GenerateSalt(4, 'y')); (await Redb.UserProvider.SetPasswordHashAsync(user, hash)).Should().BeTrue(); (await Redb.Context.ExecuteScalarAsync($"SELECT _password FROM _users WHERE _id = {user.Id}")) .Should().Be(hash, "the hash is written as given, not hashed again"); (await Redb.UserProvider.ValidateUserAsync(login, "from-config")).Should().NotBeNull(); (await Redb.UserProvider.ValidateUserAsync(login, "placeholder")).Should().BeNull(); await FluentActions.Awaiting(() => Redb.UserProvider.SetPasswordHashAsync(user, " ")) .Should().ThrowAsync(); } } Path: redb/redb.Tests.Integration/Tests/Base/PolymorphicTreeTestsBase.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/PolymorphicTreeTestsBase.cs ---- using redb.Core; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// Tests for polymorphic tree API: LoadPolymorphicTreeAsync, GetPolymorphicChildrenAsync, /// GetPolymorphicDescendantsAsync, GetPolymorphicPathToRootAsync. /// Uses 3 different scheme types in one tree: /// OrgRoot (level 0) → Division (level 1) → Team (level 2) /// public abstract class PolymorphicTreeTestsBase { protected readonly IRedbService Redb; protected PolymorphicTreeTestsBase(IRedbService redb) => Redb = redb; /// /// Build a polymorphic tree: /// Acme Corp (OrgRoot) /// ├── Engineering (Division) /// │ ├── Backend Team (Team) /// │ └── Frontend Team (Team) /// └── Sales (Division) /// └── EMEA Team (Team) /// private async Task SeedPolymorphicTreeAsync() { var root = new TreeRedbObject { name = "Acme Corp", Props = new OrgRootProps { OrgName = "Acme Corp", Country = "US", FoundedYear = 2010 } }; root.id = await Redb.SaveAsync(root); var engineering = new TreeRedbObject { name = "Engineering", Props = new DivisionProps { DivisionName = "Engineering", Head = "Alice", AnnualBudget = 500000m } }; engineering.id = await Redb.CreateChildAsync(engineering, root); var sales = new TreeRedbObject { name = "Sales", Props = new DivisionProps { DivisionName = "Sales", Head = "Bob", AnnualBudget = 300000m } }; sales.id = await Redb.CreateChildAsync(sales, root); var backend = new TreeRedbObject { name = "Backend Team", Props = new TeamProps { TeamName = "Backend Team", MemberCount = 8, Technologies = ["C#", "PostgreSQL", "Docker"] } }; backend.id = await Redb.CreateChildAsync(backend, engineering); var frontend = new TreeRedbObject { name = "Frontend Team", Props = new TeamProps { TeamName = "Frontend Team", MemberCount = 5, Technologies = ["TypeScript", "React"] } }; frontend.id = await Redb.CreateChildAsync(frontend, engineering); var emea = new TreeRedbObject { name = "EMEA Team", Props = new TeamProps { TeamName = "EMEA Team", MemberCount = 3, Technologies = ["CRM", "Salesforce"] } }; emea.id = await Redb.CreateChildAsync(emea, sales); return new PolyTreeIds(root.id, engineering.id, sales.id, backend.id, frontend.id, emea.id); } private record PolyTreeIds(long Root, long Engineering, long Sales, long Backend, long Frontend, long Emea); // ─── Helper to get typed Props from polymorphic tree nodes ─── private static TProps GetProps(ITreeRedbObject node) where TProps : class, new() { if (node is RedbObject typed) return typed.Props; // TreeRedbObjectDynamic wraps source object var sourceField = node.GetType().GetProperty("SourceObject"); if (sourceField?.GetValue(node) is RedbObject source) return source.Props; throw new InvalidOperationException( $"Cannot extract {typeof(TProps).Name} from {node.GetType().Name} (id={node.Id})"); } // ═══════════════════════════════════════════════════════ // LoadPolymorphicTreeAsync // ═══════════════════════════════════════════════════════ [Fact] public async Task LoadPolymorphicTree_ReturnsFullHierarchy() { var ids = await SeedPolymorphicTreeAsync(); var rootObj = await Redb.LoadAsync(ids.Root); var tree = await Redb.LoadPolymorphicTreeAsync(rootObj!); tree.Should().NotBeNull(); tree.Id.Should().Be(ids.Root); tree.Name.Should().Be("Acme Corp"); tree.Children.Should().HaveCount(2); } [Fact] public async Task LoadPolymorphicTree_ChildrenHaveDifferentSchemes() { var ids = await SeedPolymorphicTreeAsync(); var rootObj = await Redb.LoadAsync(ids.Root); var tree = await Redb.LoadPolymorphicTreeAsync(rootObj!); // Root scheme differs from children schemes var childSchemeIds = tree.Children.Select(c => c.SchemeId).Distinct().ToList(); childSchemeIds.Should().HaveCount(1); // both children are DivisionProps tree.SchemeId.Should().NotBe(childSchemeIds[0]); // root is OrgRootProps, different } [Fact] public async Task LoadPolymorphicTree_GrandchildrenAreTeams() { var ids = await SeedPolymorphicTreeAsync(); var rootObj = await Redb.LoadAsync(ids.Root); var tree = await Redb.LoadPolymorphicTreeAsync(rootObj!); var allGrandchildren = tree.Children.SelectMany(c => c.Children).ToList(); allGrandchildren.Should().HaveCount(3); // backend, frontend, emea var names = allGrandchildren.Select(g => g.Name).OrderBy(n => n).ToList(); names.Should().BeEquivalentTo(["Backend Team", "EMEA Team", "Frontend Team"]); } [Fact] public async Task LoadPolymorphicTree_WithMaxDepth1_LoadsOnlyDivisions() { var ids = await SeedPolymorphicTreeAsync(); var rootObj = await Redb.LoadAsync(ids.Root); var tree = await Redb.LoadPolymorphicTreeAsync(rootObj!, maxDepth: 1); tree.Children.Should().HaveCount(2); // At maxDepth=1, grandchildren should not be loaded tree.Children.Should().AllSatisfy(c => c.Children.Should().BeEmpty()); } [Fact] public async Task LoadPolymorphicTree_ParentReferencesAreSet() { var ids = await SeedPolymorphicTreeAsync(); var rootObj = await Redb.LoadAsync(ids.Root); var tree = await Redb.LoadPolymorphicTreeAsync(rootObj!); tree.Parent.Should().BeNull(); // root has no parent foreach (var division in tree.Children) { division.Parent.Should().BeSameAs(tree); foreach (var team in division.Children) { team.Parent.Should().BeSameAs(division); } } } [Fact] public async Task LoadPolymorphicTree_LevelIsCorrect() { var ids = await SeedPolymorphicTreeAsync(); var rootObj = await Redb.LoadAsync(ids.Root); var tree = await Redb.LoadPolymorphicTreeAsync(rootObj!); tree.Level.Should().Be(0); foreach (var division in tree.Children) { division.Level.Should().Be(1); foreach (var team in division.Children) { team.Level.Should().Be(2); } } } [Fact] public async Task LoadPolymorphicTree_IsLeafCorrectForLeaves() { var ids = await SeedPolymorphicTreeAsync(); var rootObj = await Redb.LoadAsync(ids.Root); var tree = await Redb.LoadPolymorphicTreeAsync(rootObj!); tree.IsLeaf.Should().BeFalse(); var allLeaves = tree.Children.SelectMany(c => c.Children).ToList(); allLeaves.Should().AllSatisfy(l => l.IsLeaf.Should().BeTrue()); } [Fact] public async Task LoadPolymorphicTree_PropsAreTyped() { var ids = await SeedPolymorphicTreeAsync(); var rootObj = await Redb.LoadAsync(ids.Root); var tree = await Redb.LoadPolymorphicTreeAsync(rootObj!); // Root has OrgRootProps var rootProps = GetProps(tree); rootProps.OrgName.Should().Be("Acme Corp"); rootProps.Country.Should().Be("US"); rootProps.FoundedYear.Should().Be(2010); // Engineering division has DivisionProps var engNode = tree.Children.First(c => c.Name == "Engineering"); var engProps = GetProps(engNode); engProps.DivisionName.Should().Be("Engineering"); engProps.Head.Should().Be("Alice"); engProps.AnnualBudget.Should().Be(500000m); // Backend team has TeamProps var backendNode = engNode.Children.First(c => c.Name == "Backend Team"); var backendProps = GetProps(backendNode); backendProps.TeamName.Should().Be("Backend Team"); backendProps.MemberCount.Should().Be(8); backendProps.Technologies.Should().BeEquivalentTo(["C#", "PostgreSQL", "Docker"]); } // ═══════════════════════════════════════════════════════ // GetPolymorphicChildrenAsync // ═══════════════════════════════════════════════════════ [Fact] public async Task GetPolymorphicChildren_ReturnsDirectChildren() { var ids = await SeedPolymorphicTreeAsync(); var rootObj = await Redb.LoadAsync(ids.Root); var children = (await Redb.GetPolymorphicChildrenAsync(rootObj!)).ToList(); children.Should().HaveCount(2); children.Select(c => c.Name).Should().BeEquivalentTo(["Engineering", "Sales"]); } [Fact] public async Task GetPolymorphicChildren_OfDivision_ReturnsTeams() { var ids = await SeedPolymorphicTreeAsync(); var engObj = await Redb.LoadAsync(ids.Engineering); var children = (await Redb.GetPolymorphicChildrenAsync(engObj!)).ToList(); children.Should().HaveCount(2); children.Select(c => c.Name).Should().BeEquivalentTo(["Backend Team", "Frontend Team"]); } [Fact] public async Task GetPolymorphicChildren_OfLeaf_ReturnsEmpty() { var ids = await SeedPolymorphicTreeAsync(); var backendObj = await Redb.LoadAsync(ids.Backend); var children = (await Redb.GetPolymorphicChildrenAsync(backendObj!)).ToList(); children.Should().BeEmpty(); } [Fact] public async Task GetPolymorphicChildren_PropsAreTyped() { var ids = await SeedPolymorphicTreeAsync(); var engObj = await Redb.LoadAsync(ids.Engineering); var children = (await Redb.GetPolymorphicChildrenAsync(engObj!)).ToList(); var backend = children.First(c => c.Name == "Backend Team"); var props = GetProps(backend); props.MemberCount.Should().Be(8); props.Technologies.Should().Contain("C#"); } // ═══════════════════════════════════════════════════════ // GetPolymorphicDescendantsAsync // ═══════════════════════════════════════════════════════ [Fact] public async Task GetPolymorphicDescendants_ReturnsAllBelow() { var ids = await SeedPolymorphicTreeAsync(); var rootObj = await Redb.LoadAsync(ids.Root); var descendants = (await Redb.GetPolymorphicDescendantsAsync(rootObj!)).ToList(); descendants.Should().HaveCount(5); // 2 divisions + 3 teams } [Fact] public async Task GetPolymorphicDescendants_OfDivision_ReturnsOnlySubtree() { var ids = await SeedPolymorphicTreeAsync(); var engObj = await Redb.LoadAsync(ids.Engineering); var descendants = (await Redb.GetPolymorphicDescendantsAsync(engObj!)).ToList(); descendants.Should().HaveCount(2); // backend + frontend descendants.Select(d => d.Name).Should().BeEquivalentTo(["Backend Team", "Frontend Team"]); } [Fact] public async Task GetPolymorphicDescendants_ContainsMixedSchemes() { var ids = await SeedPolymorphicTreeAsync(); var rootObj = await Redb.LoadAsync(ids.Root); var descendants = (await Redb.GetPolymorphicDescendantsAsync(rootObj!)).ToList(); var distinctSchemes = descendants.Select(d => d.SchemeId).Distinct().ToList(); distinctSchemes.Should().HaveCount(2); // DivisionProps + TeamProps } [Fact] public async Task GetPolymorphicDescendants_WithMaxDepth1_OnlyDirectChildren() { var ids = await SeedPolymorphicTreeAsync(); var rootObj = await Redb.LoadAsync(ids.Root); var descendants = (await Redb.GetPolymorphicDescendantsAsync(rootObj!, maxDepth: 1)).ToList(); descendants.Should().HaveCount(2); // only 2 divisions, no teams descendants.Select(d => d.Name).Should().BeEquivalentTo(["Engineering", "Sales"]); } // ═══════════════════════════════════════════════════════ // GetPolymorphicPathToRootAsync // ═══════════════════════════════════════════════════════ [Fact] public async Task GetPolymorphicPathToRoot_FromLeaf_ReturnsFullPath() { var ids = await SeedPolymorphicTreeAsync(); var backendObj = await Redb.LoadAsync(ids.Backend); var path = (await Redb.GetPolymorphicPathToRootAsync(backendObj!)).ToList(); // Path: Backend Team → Engineering → Acme Corp (or some subset depending on implementation) path.Should().HaveCountGreaterThanOrEqualTo(2); path.Select(p => p.Name).Should().Contain("Engineering"); path.Select(p => p.Name).Should().Contain("Acme Corp"); } [Fact] public async Task GetPolymorphicPathToRoot_CrossesSchemes() { var ids = await SeedPolymorphicTreeAsync(); var backendObj = await Redb.LoadAsync(ids.Backend); var path = (await Redb.GetPolymorphicPathToRootAsync(backendObj!)).ToList(); var distinctSchemes = path.Select(p => p.SchemeId).Distinct().ToList(); // Path crosses at least 2 scheme types: DivisionProps → OrgRootProps distinctSchemes.Should().HaveCountGreaterThanOrEqualTo(2); } [Fact] public async Task GetPolymorphicPathToRoot_FromRoot_ReturnsEmpty() { var ids = await SeedPolymorphicTreeAsync(); var rootObj = await Redb.LoadAsync(ids.Root); var path = (await Redb.GetPolymorphicPathToRootAsync(rootObj!)).ToList(); // Root has no ancestors — path should be empty or contain only root itself path.Should().HaveCountLessThanOrEqualTo(1); } // ═══════════════════════════════════════════════════════ // Navigation helpers on ITreeRedbObject // ═══════════════════════════════════════════════════════ [Fact] public async Task GetSubtree_ReturnsAllNodesInDepthFirst() { var ids = await SeedPolymorphicTreeAsync(); var rootObj = await Redb.LoadAsync(ids.Root); var tree = await Redb.LoadPolymorphicTreeAsync(rootObj!); var subtree = tree.GetSubtree().ToList(); subtree.Should().HaveCount(6); // root + 2 divisions + 3 teams } [Fact] public async Task SubtreeSize_ReturnsCorrectCount() { var ids = await SeedPolymorphicTreeAsync(); var rootObj = await Redb.LoadAsync(ids.Root); var tree = await Redb.LoadPolymorphicTreeAsync(rootObj!); tree.SubtreeSize.Should().Be(6); var engNode = tree.Children.First(c => c.Name == "Engineering"); engNode.SubtreeSize.Should().Be(3); // eng + backend + frontend } [Fact] public async Task MaxDepth_ReturnsCorrectValue() { var ids = await SeedPolymorphicTreeAsync(); var rootObj = await Redb.LoadAsync(ids.Root); var tree = await Redb.LoadPolymorphicTreeAsync(rootObj!); tree.MaxDepth.Should().Be(2); // root → division → team } [Fact] public async Task GetBreadcrumbs_FormatsCorrectly() { var ids = await SeedPolymorphicTreeAsync(); var rootObj = await Redb.LoadAsync(ids.Root); var tree = await Redb.LoadPolymorphicTreeAsync(rootObj!); var engNode = tree.Children.First(c => c.Name == "Engineering"); var backendNode = engNode.Children.First(c => c.Name == "Backend Team"); var breadcrumbs = backendNode.GetBreadcrumbs(); breadcrumbs.Should().Contain("Acme Corp"); breadcrumbs.Should().Contain("Engineering"); breadcrumbs.Should().Contain("Backend Team"); } [Fact] public async Task Ancestors_ReturnsPathUpToRoot() { var ids = await SeedPolymorphicTreeAsync(); var rootObj = await Redb.LoadAsync(ids.Root); var tree = await Redb.LoadPolymorphicTreeAsync(rootObj!); var engNode = tree.Children.First(c => c.Name == "Engineering"); var backendNode = engNode.Children.First(c => c.Name == "Backend Team"); var ancestors = backendNode.Ancestors.ToList(); ancestors.Should().HaveCount(2); ancestors[0].Name.Should().Be("Engineering"); ancestors[1].Name.Should().Be("Acme Corp"); } [Fact] public async Task Descendants_ReturnsAllBelow() { var ids = await SeedPolymorphicTreeAsync(); var rootObj = await Redb.LoadAsync(ids.Root); var tree = await Redb.LoadPolymorphicTreeAsync(rootObj!); var descendants = tree.Descendants.ToList(); descendants.Should().HaveCount(5); // 2 divisions + 3 teams } [Fact] public async Task IsDescendantOf_CorrectForCrossScheme() { var ids = await SeedPolymorphicTreeAsync(); var rootObj = await Redb.LoadAsync(ids.Root); var tree = await Redb.LoadPolymorphicTreeAsync(rootObj!); var engNode = tree.Children.First(c => c.Name == "Engineering"); var backendNode = engNode.Children.First(c => c.Name == "Backend Team"); backendNode.IsDescendantOf(tree).Should().BeTrue(); backendNode.IsDescendantOf(engNode).Should().BeTrue(); tree.IsDescendantOf(backendNode).Should().BeFalse(); } } Path: redb/redb.Tests.Integration/Tests/Base/PostgresListItemObjectLoaderLeakTestsBase.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/PostgresListItemObjectLoaderLeakTestsBase.cs ---- using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Npgsql; using redb.Core; using redb.Core.Extensions; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using redb.Core.Pro.Extensions; using redb.Tests.Integration.Helpers; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// The shape of a production leak (2026-09). Scope B is alive and serving a request; scope A /// was created after it, materialized a list item that links to an object, and died. B then touches /// on that item. Before the fix the item resolved its object through /// a process-global loader that pointed at whichever IRedbService was constructed LAST (A, /// already disposed); A's context re-opened a physical connection that no one would ever release. /// /// The container under test carries its own Application Name, so pg_stat_activity /// counts exactly its sessions. Disposing the data source closes every pooled connection; a session /// that survives it is one that was checked out of the pool and abandoned. /// /// public abstract class PostgresListItemObjectLoaderLeakTestsBase { protected abstract bool IsPro { get; } private static string BaseConnectionString() => new ConfigurationBuilder().AddJsonFile("appsettings.json").Build().GetConnectionString("Postgres")!; private ServiceProvider BuildContainer(string cs) { var services = new ServiceCollection(); services.AddLogging(b => b.SetMinimumLevel(LogLevel.Warning)); if (IsPro) { services.AddRedbPro(options => { redb.Postgres.Pro.Extensions.PostgresProOptionsExtensions.UsePostgres(options, cs); options.Configure(c => c.EnablePropsCache = false); }); } else { services.AddRedb(options => { redb.Postgres.Extensions.PostgresOptionsExtensions.UsePostgres(options, cs); options.Configure(c => c.EnablePropsCache = false); }); } return services.BuildServiceProvider(); } private static async Task CountSessionsAsync(string cs, string applicationName) { // The observer must not be counted and must not sit in a pool of its own. var observerCs = new NpgsqlConnectionStringBuilder(cs) { ApplicationName = "redb-leak-observer", Pooling = false }.ConnectionString; await using var conn = new NpgsqlConnection(observerCs); await conn.OpenAsync(); await using var cmd = new NpgsqlCommand( "SELECT count(*) FROM pg_stat_activity WHERE application_name = $1", conn); cmd.Parameters.Add(new NpgsqlParameter { Value = applicationName }); return Convert.ToInt32(await cmd.ExecuteScalarAsync()); } /// Server-side teardown of a closed socket is asynchronous; give it a moment. private static async Task WaitForSessionCountAsync(string cs, string applicationName, int expected) { var deadline = DateTime.UtcNow.AddSeconds(5); var count = await CountSessionsAsync(cs, applicationName); while (count != expected && DateTime.UtcNow < deadline) { await Task.Delay(200); count = await CountSessionsAsync(cs, applicationName); } return count; } [Fact] public async Task ListItemObject_TouchedFromAnotherScopeAfterOwnerDied_LeavesNoSessionBehind() { var baseCs = BaseConnectionString(); var applicationName = $"redb-leak-{Guid.NewGuid():N}"; var cs = new NpgsqlConnectionStringBuilder(baseCs) { ApplicationName = applicationName }.ConnectionString; var listName = $"LeakProbe_{Guid.NewGuid():N}"; var root = BuildContainer(cs); var dataSource = root.GetRequiredService(); long objectId = 0, listId = 0, itemId = 0; try { // Scope B: the long-running request that will touch the item later. var scopeB = root.CreateAsyncScope(); try { var redbB = scopeB.ServiceProvider.GetRequiredService(); await redbB.SyncSchemeAsync(); // Scope A: created AFTER B (so any "last service wins" global state points at A), // materializes the item, then dies. RedbListItem item; var scopeA = root.CreateAsyncScope(); try { var redbA = scopeA.ServiceProvider.GetRequiredService(); var obj = TestDataFactory.CreateSimple("leak-probe"); objectId = await redbA.SaveAsync(obj); var list = await redbA.ListProvider.SaveListAsync(RedbList.Create(listName, listName)); listId = list.Id; await redbA.ListProvider.AddItemsAsync(list, new IRedbListItem[] { RedbListItem.ForList(list, "linked", null, objectId) }); item = (await redbA.ListProvider.GetListItemsAsync(list.Id)).Single(); itemId = item.Id; } finally { await scopeA.DisposeAsync(); } // Back in B: the audit/response path touches the linked object of the item. var linked = item.Object; linked.Should().NotBeNull("a list item must still resolve its linked object after the scope that loaded it is gone"); linked!.Id.Should().Be(objectId); } finally { await scopeB.DisposeAsync(); } } finally { // Cleanup through a fresh scope, then tear the whole container down. await using (var cleanup = root.CreateAsyncScope()) { var redb = cleanup.ServiceProvider.GetRequiredService(); if (itemId != 0) await redb.ListProvider.DeleteListItemAsync(itemId); if (listId != 0) await redb.ListProvider.DeleteListAsync(listId); if (objectId != 0) await redb.DeleteAsync(objectId); } await root.DisposeAsync(); await dataSource.DisposeAsync(); } var survivors = await WaitForSessionCountAsync(baseCs, applicationName, expected: 0); survivors.Should().Be(0, "every connection the container opened must be back in the pool when the data source is disposed; " + "a survivor was opened on a disposed context and can never be returned"); } } Path: redb/redb.Tests.Integration/Tests/Base/ProMaterializerConversionTestsBase.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/ProMaterializerConversionTestsBase.cs ---- using redb.Core; using redb.Core.Attributes; using redb.Core.Models.Entities; namespace redb.Tests.Integration.Tests.Base; /// /// A stored collection element the Pro materializer cannot convert to the property's element type (review PR-10). /// The same failure had three silent outcomes, chosen by the shape of the collection: a dictionary entry vanished, /// an array element became 0, a list element was skipped. The row here is written by another writer (plain SQL), /// as a legacy row or a narrowed property type would leave it. /// public abstract class ProMaterializerConversionTestsBase { protected readonly IRedbService Redb; protected ProMaterializerConversionTestsBase(IRedbService redb) => Redb = redb; private const long TooBigForInt = 5_000_000_000L; private async Task SeedWithAnOversizedElementAsync(string field) { await Redb.SyncSchemeAsync(); var id = await Redb.SaveAsync(new RedbObject { name = "conversion-probe", Props = new ConversionProbeProps { IntList = [1, 7, 3], IntArray = [1, 7, 3], IntDict = new Dictionary { ["a"] = 1, ["b"] = 7 } } }); await Redb.Context.ExecuteAsync( $"UPDATE _values SET _Long = {TooBigForInt} WHERE _id_object = {id} AND _Long = 7 AND _id_structure = " + $"(SELECT _id FROM _structures WHERE _name = '{field}' AND _id_scheme = (SELECT _id_scheme FROM _objects WHERE _id = {id}))"); await Redb.Context.ExecuteAsync($"UPDATE _objects SET _hash = NULL WHERE _id = {id}"); return id; } [Theory] [InlineData(nameof(ConversionProbeProps.IntDict))] [InlineData(nameof(ConversionProbeProps.IntArray))] [InlineData(nameof(ConversionProbeProps.IntList))] public async Task AnElementThatDoesNotFitTheElementType_IsRefused(string field) { var id = await SeedWithAnOversizedElementAsync(field); var load = async () => await Redb.LoadAsync(id); await load.Should().ThrowAsync().WithMessage($"*{TooBigForInt}*"); } } [RedbScheme(Name = "ConversionProbe")] public class ConversionProbeProps { public List? IntList { get; set; } public int[]? IntArray { get; set; } public Dictionary? IntDict { get; set; } } Path: redb/redb.Tests.Integration/Tests/Base/ProPgPurityTestsBase.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/ProPgPurityTestsBase.cs ---- using System.Text.RegularExpressions; using redb.Core; using redb.Core.Query; using redb.Core.Query.Aggregation; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// PostgreSQL Pro purity tests: assert that inline SQL emitted by Pro PG provider /// does not delegate to legacy pvt_* server-side composer functions /// (audit 2026-05-24). The planner must see real parameterised SQL, not /// SELECT pvt_search_objects_with_facets(...). /// /// Targeted leaks (regex pvt_[a-z_]+\(): /// * pvt_search_objects_with_facets /// * pvt_aggregate_grouped /// * pvt_aggregate_array_grouped /// * pvt_build_query_sql /// * pvt_build_array_groupby_sql /// * pvt_query_with_window /// /// Wrap this base in a Pro PG fixture only. /// public abstract class ProPgPurityTestsBase { private static readonly Regex PvtFunctionCall = new(@"\bpvt_[a-z_]+\s*\(", RegexOptions.Compiled | RegexOptions.IgnoreCase); protected readonly IRedbService Redb; protected ProPgPurityTestsBase(IRedbService redb) => Redb = redb; private static void AssertNoLegacyPvtCalls(string sql, string queryDescription) { sql.Should().NotBeNullOrWhiteSpace($"SQL preview for {queryDescription} must be non-empty"); var matches = PvtFunctionCall.Matches(sql) .Select(m => m.Value) .Distinct() .ToArray(); matches.Should().BeEmpty( $"Pro PG must inline parameterised SQL for {queryDescription}; found legacy " + $"pvt_* function calls: {string.Join(", ", matches)}"); } [Fact] public async Task NoLegacyPvtCalls_PlainQuery() { var sql = await Redb.Query() .Where(e => e.IsRemote && e.Salary > 50_000m) .ToSqlStringAsync(); AssertNoLegacyPvtCalls(sql, "plain WHERE query"); } [Fact] public async Task NoLegacyPvtCalls_OrderBySkipTake() { var sql = await Redb.Query() .OrderBy(e => e.Salary) .Skip(5) .Take(10) .ToSqlStringAsync(); AssertNoLegacyPvtCalls(sql, "OrderBy + Skip/Take"); } [Fact] public async Task NoLegacyPvtCalls_AggregateOverArray() { var sql = await Redb.Query() .ToAggregateSqlStringAsync(x => new { Total = Agg.Sum(x.Props.SkillLevels.Select(s => s)), Avg = Agg.Average(x.Props.SkillLevels.Select(s => s)) }); AssertNoLegacyPvtCalls(sql, "aggregate over array"); } [Fact] public async Task NoLegacyPvtCalls_AggregateScalarWithFilter() { var sql = await Redb.Query() .Where(e => e.Department == "Engineering") .ToAggregateSqlStringAsync(x => new { TotalSalary = Agg.Sum(x.Props.Salary), Headcount = Agg.Count() }); AssertNoLegacyPvtCalls(sql, "scalar aggregate with WHERE"); } } Path: redb/redb.Tests.Integration/Tests/Base/ProPgPvtPickAggregateTestsBase.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/ProPgPvtPickAggregateTestsBase.cs ---- using System.Text.RegularExpressions; using redb.Core; using redb.Core.Models.Entities; using redb.Core.Query; using redb.Core.Query.Aggregation; using redb.Core.Query.Window; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// PostgreSQL Pro pivot: the value of a scalar field is taken with the cheapest aggregate its column type allows. /// /// (array_agg(x) FILTER (...))[1] builds an array per object and per field, which keeps the planner on a /// sorted GroupAggregate. max(x) FILTER (...) lets it hash-aggregate instead: on 200 000 objects the whole /// E015 page went from 1 106-1 367 ms to 838-975 ms. The FILTER leaves one row per /// object for a scalar field, so both return the same value. /// /// PostgreSQL has no max() for boolean, uuid or bytea: boolean takes bool_or (the same value on one row), /// uuid and bytea keep array_agg. The second half of the class runs such queries end to end, so a max() over a /// column that has none fails here and not in production. /// /// The class is about the aggregate pivot, so it runs with the planner off whatever the suite was started /// with (REDB_PVT_PREFILTER): with the planner on these queries take the streams form, which has no pivot /// and so nothing for the class to check. The setting is put back when the test ends. /// /// Wrap this base in a Pro PG fixture only. /// public abstract class ProPgPvtPickAggregateTestsBase : IDisposable { // array_agg(...)[1] over a column that has max() or bool_or(): the shape this class forbids. private static readonly Regex ArrayAggPickOverCheapColumn = new( @"\(array_agg\((?:\w+\.)?_(?:string|long|double|numeric|datetimeoffset|listitem|object|boolean)\)\s*FILTER\s*\(WHERE[^)]*\)\)\[1\]", RegexOptions.Compiled | RegexOptions.IgnoreCase); protected readonly IRedbService Redb; private readonly bool _plannerWas; protected ProPgPvtPickAggregateTestsBase(IRedbService redb) { Redb = redb; _plannerWas = redb.Configuration.EnablePvtPrefilter; redb.UpdateConfiguration(c => c.EnablePvtPrefilter = false); } public void Dispose() { Redb.UpdateConfiguration(c => c.EnablePvtPrefilter = _plannerWas); GC.SuppressFinalize(this); } private static void AssertCheapPick(string sql, string shape) { sql.Should().Contain("FILTER (WHERE", $"precondition: the {shape} SQL pivots Props fields"); ArrayAggPickOverCheapColumn.Matches(sql).Select(m => m.Value).Should().BeEmpty( $"the {shape} pivot must take a scalar with max()/bool_or(), not array_agg(...)[1]"); } // ── SQL text ──────────────────────────────────────────────────────────── [Fact] public async Task FlatQuery_Pivot_UsesMaxAndBoolOr() { var sql = await Redb.Query() .Where(e => e.Salary > 50_000m && e.Age >= 30 && e.Department != "" && e.IsRemote) .OrderByDescending(e => e.Salary) .Take(10) .ToSqlStringAsync(); AssertCheapPick(sql, "flat query"); sql.Should().Contain("max(").And.Contain("bool_or("); } [Fact] public async Task Aggregate_Pivot_UsesMax() { var sql = await Redb.Query() .Where(e => e.Department == "Engineering" && e.IsRemote) .ToAggregateSqlStringAsync(x => new { Total = Agg.Sum(x.Props.Salary), Headcount = Agg.Count() }); AssertCheapPick(sql, "aggregate"); } [Fact] public async Task Grouping_Pivot_UsesMax() { var sql = await Redb.Query() .Where(e => e.Age >= 30) .GroupBy(e => e.Department) .ToSqlStringAsync(g => new { Department = g.Key, Total = Agg.Sum(g, x => x.Salary) }); AssertCheapPick(sql, "grouping"); } [Fact] public async Task Window_Pivot_UsesMax() { var sql = await Redb.Query() .Where(e => e.Age >= 30) .WithWindow(w => w.PartitionBy(e => e.Department).OrderByDesc(e => e.Salary)) .ToSqlStringAsync(e => new { e.Props.Salary, RowNum = Win.RowNumber() }); AssertCheapPick(sql, "window"); } [Fact] public async Task TreeQuery_Pivot_UsesMax() { var sql = await Redb.TreeQuery() .Where(e => e.Salary > 50_000m && e.IsRemote) .OrderBy(e => e.Age) .ToSqlStringAsync(); AssertCheapPick(sql, "tree query"); } [Fact] public async Task GuidField_KeepsArrayAgg_BoolField_UsesBoolOr() { var code = Guid.NewGuid(); var sql = await Redb.Query() .Where(x => x.Code == code && x.IsActive) .OrderBy(x => x.Price) .ToSqlStringAsync(); AssertCheapPick(sql, "flat query with a Guid field"); sql.Should().MatchRegex(@"(?i)\(array_agg\((?:\w+\.)?_guid\)", "PostgreSQL has no max(uuid)"); sql.Should().Contain("bool_or(", "PostgreSQL has no max(boolean)"); } // ── Execution: types without max() must still run ────────────────────── private async Task SeedSimpleAsync() { await Redb.SyncSchemeAsync(); var tag = $"pick-{Guid.NewGuid():N}"[..13]; for (var i = 0; i < 4; i++) { await Redb.SaveAsync(new RedbObject { name = $"{tag}-{i}", Props = new SimpleProps { Title = tag, Count = i, Price = 10m * (i + 1), CreatedAt = new DateTime(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddDays(i), IsActive = i % 2 == 0, Code = Guid.NewGuid() } }); } return tag; } [Fact] public async Task FlatQuery_FiltersAndSortsOnBoolAndGuid() { var tag = await SeedSimpleAsync(); var rows = await Redb.Query() .Where(x => x.Title == tag && x.IsActive && x.Code != Guid.Empty) .OrderByDescending(x => x.Price) .ToListAsync(); rows.Select(r => r.Props.Price).Should().Equal(30m, 10m); } [Fact] public async Task Grouping_ByBool_WithGuidInFilter() { var tag = await SeedSimpleAsync(); var rows = await Redb.Query() .Where(x => x.Title == tag && x.Code != Guid.Empty) .GroupBy(x => x.IsActive) .SelectAsync(g => new { Active = g.Key, Count = Agg.Count(g), Total = Agg.Sum(g, x => x.Price) }); rows.Should().HaveCount(2); rows.Single(r => r.Active).Total.Should().Be(40m); rows.Single(r => !r.Active).Total.Should().Be(60m); } [Fact] public async Task Window_PartitionByBool_WithGuidInFilter() { var tag = await SeedSimpleAsync(); var rows = await Redb.Query() .Where(x => x.Title == tag && x.Code != Guid.Empty) .WithWindow(w => w.PartitionBy(x => x.IsActive).OrderByDesc(x => x.Price)) .SelectAsync(x => new { x.Props.Price, RowNum = Win.RowNumber() }); rows.Should().HaveCount(4); rows.Where(r => r.RowNum == 1).Select(r => r.Price).Should().BeEquivalentTo(new[] { 30m, 40m }); } [Fact] public async Task Aggregate_WithBoolAndGuidInFilter() { var tag = await SeedSimpleAsync(); var total = await Redb.Query() .Where(x => x.Title == tag && x.IsActive && x.Code != Guid.Empty) .SumAsync(x => x.Price); total.Should().Be(40m); } [Fact] public async Task TreeQuery_FiltersOnBool() { await Redb.SyncSchemeAsync(); var tag = $"pick-{Guid.NewGuid():N}"[..13]; var root = new TreeRedbObject { name = $"{tag}-root", Props = new TreeNodeProps { Name = tag, IsActive = true, Budget = 1m } }; root.id = await Redb.SaveAsync(root); for (var i = 0; i < 3; i++) await Redb.CreateChildAsync(new TreeRedbObject { name = $"{tag}-{i}", Props = new TreeNodeProps { Name = tag, IsActive = i != 1, Budget = 10m * (i + 1) } }, root); var rows = await Redb.TreeQuery(root.id) .Where(x => x.IsActive && x.Budget > 5m) .OrderByDescending(x => x.Budget) .ToListAsync(); rows.Select(r => r.Props.Budget).Should().Equal(30m, 10m); } } Path: redb/redb.Tests.Integration/Tests/Base/ProQueryTestsBase.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/ProQueryTestsBase.cs ---- using redb.Core; using redb.Core.Query; using redb.Tests.Integration.Helpers; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// Query features: deep nested, arithmetic, string functions, Math. /// Free and Pro must behave identically on the LINQ → query path /// (they differ only in materialization and save). /// public abstract class ProQueryTestsBase { protected readonly IRedbService Redb; protected readonly bool IsPro; protected ProQueryTestsBase(IRedbService redb, bool isPro) { Redb = redb; IsPro = isPro; } private async Task> SeedAsync() { return await TestDataFactory.SeedEmployees(Redb, 20); } [Fact] public async Task DeepNested_OneLevel_Filters() { var ids = await SeedAsync(); var results = await Redb.Query() .Where(e => e.HomeAddress!.City == "London") .Take(20) .ToListAsync(); results.Should().AllSatisfy(r => r.Props.HomeAddress!.City.Should().Be("London")); } [Fact] public async Task DeepNested_TwoLevels_Filters() { var ids = await SeedAsync(); var idSet = ids.ToHashSet(); var results = await Redb.Query() .WhereRedb(e => idSet.Contains(e.Id)) .Where(e => e.HomeAddress!.Building!.Floor > 10) .ToListAsync(); results.Should().AllSatisfy(r => r.Props.HomeAddress!.Building!.Floor.Should().BeGreaterThan(10)); } [Fact] public async Task Arithmetic_Multiply_AnnualSalary() { var ids = await SeedAsync(); var results = await Redb.Query() .Where(e => e.Salary * 12 > 1_000_000m) .Take(20) .ToListAsync(); results.Should().AllSatisfy(r => (r.Props.Salary * 12).Should().BeGreaterThan(1_000_000m)); } [Fact] public async Task Arithmetic_MultiField_Scoring() { var ids = await SeedAsync(); var results = await Redb.Query() .Where(e => e.Age * 1000 + e.Salary > 120_000m) .Take(20) .ToListAsync(); results.Should().NotBeEmpty(); results.Should().AllSatisfy(r => (r.Props.Age * 1000 + r.Props.Salary).Should().BeGreaterThan(120_000m)); } [Fact] public async Task Arithmetic_Division_MonthlySalary() { var ids = await SeedAsync(); var results = await Redb.Query() .Where(e => (e.Salary / 12m) > 7000m) .Take(20) .ToListAsync(); results.Should().AllSatisfy(r => (r.Props.Salary / 12m).Should().BeGreaterThan(7000m)); } [Fact] public async Task MathAbs_InWhere_Filters() { var ids = await SeedAsync(); var results = await Redb.Query() .Where(e => Math.Abs(e.Salary - 80000m) < 10000m) .Take(20) .ToListAsync(); results.Should().AllSatisfy(r => Math.Abs(r.Props.Salary - 80000m).Should().BeLessThan(10000m)); } [Fact] public async Task String_ToLower_Contains() { var ids = await SeedAsync(); var results = await Redb.Query() .Where(e => e.LastName.ToLower().Contains("last")) .Take(20) .ToListAsync(); results.Should().NotBeEmpty(); results.Should().AllSatisfy(r => r.Props.LastName.ToLower().Should().Contain("last")); } [Fact] public async Task String_Trim_Length() { var ids = await SeedAsync(); var results = await Redb.Query() .Where(e => e.FirstName.Trim().Length > 3) .Take(20) .ToListAsync(); results.Should().NotBeEmpty(); results.Should().AllSatisfy(r => r.Props.FirstName.Trim().Length.Should().BeGreaterThan(3)); } [Fact] public async Task String_ToUpper_Length() { var ids = await SeedAsync(); var results = await Redb.Query() .Where(e => e.Department.ToUpper().Length > 5) .Take(20) .ToListAsync(); results.Should().NotBeEmpty(); } [Fact] public async Task String_Length_Property() { var ids = await SeedAsync(); var results = await Redb.Query() .Where(e => e.LastName.Length > 6) .Take(20) .ToListAsync(); results.Should().AllSatisfy(r => r.Props.LastName.Length.Should().BeGreaterThan(6)); } [Fact] public async Task DistinctBy_KeepsTheOrderingByTheKeyAndByAnotherField_PagesAndCounts() { // OrderByDescending(key).DistinctBy(key) came back ascending on SQLite and in no order on SQL Server, and an // ordering by another Props field failed there ("pvt_cte.Salary"). Nine employees, three departments. var tag = Guid.NewGuid().ToString("N")[..8]; await Redb.SaveAsync(Enumerable.Range(0, 9) .Select(i => TestDataFactory.CreateEmployee(i, salary: 100m * (i + 1), department: $"{tag}-D{i % 3}")).ToList()); IRedbQueryable Tagged() => Redb.Query().Where(e => e.Department.StartsWith(tag)); string D(int k) => $"{tag}-D{k}"; async Task> Departments(IRedbQueryable q) => (await q.ToListAsync()).Select(e => e.Props.Department).ToList(); (await Departments(Tagged().OrderByDescending(e => e.Department).DistinctBy(e => e.Department))) .Should().Equal(new[] { D(2), D(1), D(0) }, "the key descending"); (await Departments(Tagged().OrderBy(e => e.Department).DistinctBy(e => e.Department))) .Should().Equal(new[] { D(0), D(1), D(2) }, "the key ascending"); (await Departments(Tagged().OrderBy(e => e.Salary).DistinctBy(e => e.Department))) .Should().Equal(new[] { D(0), D(1), D(2) }, "ordered by another field: DistinctBy sorts by its key first"); (await Departments(Tagged().Where(e => e.Salary > 700m).OrderByDescending(e => e.Department).DistinctBy(e => e.Department))) .Should().Equal(new[] { D(2), D(1) }, "the filter keeps employees 8 and 9 only"); (await Departments(Tagged().OrderByDescending(e => e.Department).DistinctBy(e => e.Department).Skip(1).Take(1))) .Should().Equal(new[] { D(1) }, "the page of the distinct rows"); (await Tagged().DistinctBy(e => e.Department).CountAsync()).Should().Be(3); (await Tagged().Where(e => e.Salary > 700m).DistinctBy(e => e.Department).CountAsync()).Should().Be(2); } [Fact] public async Task DistinctRedb_OnePerBaseFields_WithAPage() { // DistinctRedb partitions by a list of columns of the object, not one key (example E139). Six employees under two // names, everything else of the object equal: two rows. var tag = Guid.NewGuid().ToString("N")[..8]; var employees = Enumerable.Range(0, 6) .Select(i => TestDataFactory.CreateEmployee(i, salary: 100m * (i + 1), department: $"{tag}-dist")).ToList(); for (var i = 0; i < employees.Count; i++) employees[i].name = $"{tag}-name{i % 2}"; await Redb.SaveAsync(employees); IRedbQueryable Tagged() => Redb.Query().Where(e => e.Department == $"{tag}-dist"); var rows = await Tagged().DistinctRedb().Take(100).ToListAsync(); rows.Select(r => r.name).Should().BeEquivalentTo(new[] { $"{tag}-name0", $"{tag}-name1" }); (await Tagged().DistinctRedb().CountAsync()).Should().Be(2); } [Fact] public async Task Distinct_OnePerPropsHash_CountsOrdersAndPages() { // Distinct() keeps one object per Props hash (Pro; Free deduplicates by object). Three employees with the props // of index 0 and two with those of index 1: two rows. if (!IsPro) return; var tag = Guid.NewGuid().ToString("N")[..8]; await Redb.SaveAsync(new[] { 0, 0, 0, 1, 1 } .Select(k => TestDataFactory.CreateEmployee(k, department: $"{tag}-hash")).ToList()); IRedbQueryable Tagged() => Redb.Query().Where(e => e.Department == $"{tag}-hash"); var low = TestDataFactory.CreateEmployee(0).Props.Salary; var high = TestDataFactory.CreateEmployee(1).Props.Salary; (await Tagged().Distinct().ToListAsync()).Select(e => e.Props.Salary).Should().BeEquivalentTo(new[] { low, high }); (await Tagged().Distinct().CountAsync()).Should().Be(2); (await Tagged().Distinct().OrderByDescending(e => e.Salary).Take(1).ToListAsync()) .Select(e => e.Props.Salary).Should().Equal(high); (await Tagged().Distinct().OrderBy(e => e.Salary).Skip(1).ToListAsync()) .Select(e => e.Props.Salary).Should().Equal(high); } [Fact] public async Task DistinctRedb_WithAnOrderingAndSkip() { // Six employees under two names: one row per name, the first saved of each (salaries 100 and 200). var tag = Guid.NewGuid().ToString("N")[..8]; var employees = Enumerable.Range(0, 6) .Select(i => TestDataFactory.CreateEmployee(i, salary: 100m * (i + 1), department: $"{tag}-dr")).ToList(); for (var i = 0; i < employees.Count; i++) employees[i].name = $"{tag}-name{i % 2}"; await Redb.SaveAsync(employees); IRedbQueryable Tagged() => Redb.Query().Where(e => e.Department == $"{tag}-dr"); var ordered = await Tagged().DistinctRedb().OrderBy(e => e.Salary).ToListAsync(); ordered.Select(e => e.name).Should().Equal($"{tag}-name0", $"{tag}-name1"); (await Tagged().DistinctRedb().OrderBy(e => e.Salary).Skip(1).ToListAsync()) .Select(e => e.name).Should().Equal($"{tag}-name1"); } [Fact] public async Task DistinctByRedb_CountsOrdersAndPages() { // Six employees under three names: one per name, in the order of the key. var tag = Guid.NewGuid().ToString("N")[..8]; var employees = Enumerable.Range(0, 6) .Select(i => TestDataFactory.CreateEmployee(i, salary: 100m * (i + 1), department: $"{tag}-dbr")).ToList(); for (var i = 0; i < employees.Count; i++) employees[i].name = $"{tag}-n{i % 3}"; await Redb.SaveAsync(employees); IRedbQueryable Tagged() => Redb.Query().Where(e => e.Department == $"{tag}-dbr"); (await Tagged().DistinctByRedb(o => o.Name).CountAsync()).Should().Be(3); (await Tagged().DistinctByRedb(o => o.Name).ToListAsync()).Select(e => e.name) .Should().BeEquivalentTo(new[] { $"{tag}-n0", $"{tag}-n1", $"{tag}-n2" }); (await Tagged().OrderBy(e => e.Salary).DistinctByRedb(o => o.Name).Skip(1).Take(1).ToListAsync()) .Select(e => e.name).Should().Equal($"{tag}-n1"); } [Fact] public async Task DistinctBy_ThenAnyAllWindowGroupBy_CurrentBehaviour() { // What these combinations do today; the intended meaning is not defined yet (see BUGS_FOUND). Department A: the // first saved has salary 100, the second 900; department B: 900. var tag = Guid.NewGuid().ToString("N")[..8]; await Redb.SaveAsync(new[] { ("A", 100m), ("A", 900m), ("B", 900m) } .Select((x, i) => TestDataFactory.CreateEmployee(i, salary: x.Item2, department: $"{tag}-{x.Item1}")).ToList()); IRedbQueryable Tagged() => Redb.Query().Where(e => e.Department.StartsWith(tag)); (await Tagged().DistinctBy(e => e.Department).AnyAsync()).Should().BeTrue(); // AllAsync after DistinctBy is left out: the providers disagree today (BUGS_FOUND §9). PostgreSQL asks whether // every kept row passes (false here: the kept row of A has salary 100), SQL Server and SQLite whether every key // has a row that passes (true). // A window and a grouping read every row: the distinct is not applied. (await Tagged().DistinctBy(e => e.Department).WithWindow(w => w.OrderByDesc(x => x.Salary)) .SelectAsync(x => new { x.Id, R = global::redb.Core.Query.Aggregation.Win.RowNumber() })).Should().HaveCount(3); (await Tagged().DistinctBy(e => e.Department).GroupBy(x => x.Department) .SelectAsync(g => new { g.Key, N = global::redb.Core.Query.Aggregation.Agg.Count(g) })).Sum(g => g.N).Should().Be(3); } } Path: redb/redb.Tests.Integration/Tests/Base/ProSyncLoadTestsBase.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/ProSyncLoadTestsBase.cs ---- using System.Globalization; using System.Text; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Core; using redb.Core.Extensions; using redb.Core.Models.Configuration; using redb.Core.Models.Entities; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// The synchronous Load<T> is the /// thread-pool-free twin of LoadAsync (the sync getter of runs on it). On Pro it /// took the Free in-database JSON builder instead of the Pro C# materializer: Pro SQLite has no such function and /// failed, Pro MSSQL/PostgreSQL built a different object (list items lost their object link). /// /// Detector: the SQL recorded by - no command of the sync load may call /// get_object_json. It does not depend on the database lacking the function, so the suite is red on every /// provider in any run order (the Free native SQLite extension is process-wide state). Then the same object as the async /// load, field by field, and no list-item load on the way: the item is still not loaded, and an explicit read on the live /// scope loads it. /// /// public abstract class ProSyncLoadTestsBase { private readonly SqlRecorder _recorder = new(); protected abstract void UseProvider(RedbOptionsBuilder options); protected virtual void Register(IServiceCollection services, Action configure) => services.AddRedb(configure); private ServiceProvider Build(Action configure) { var services = new ServiceCollection(); services.AddLogging(b => b.SetMinimumLevel(LogLevel.Warning)); Register(services, options => { UseProvider(options); options.Configure(c => { // Cache off: every load materializes, on both roads. c.EnablePropsCache = false; c.CacheDomain = "pro-sync-load"; configure(c); }); }); RecordingRedbContext.Decorate(services, _recorder); return services.BuildServiceProvider(); } private sealed record Seed(long RootId, long LinkedObjectId); private static async Task SeedAsync(ServiceProvider sp, bool onlyTrashedReference) { var tag = Guid.NewGuid().ToString("N")[..8]; var redb = sp.GetRequiredService(); await redb.InitializeAsync(ensureCreated: true); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.InitializeTypeRegistryAsync(); var linkedObjectId = await redb.SaveAsync(new RedbObject { name = $"prosync-linked-{tag}", Props = new SimpleProps { Title = "linked" } }); var list = await redb.ListProvider.SaveListAsync(RedbList.Create($"prosync-{tag}", "prosync")); var linked = await redb.ListProvider.SaveListItemAsync(new RedbListItem { IdList = list.Id, Value = "linked", IdObject = linkedObjectId }); var plain = await redb.ListProvider.SaveListItemAsync(new RedbListItem { IdList = list.Id, Value = "plain" }); var c1 = await redb.SaveAsync(new RedbObject { name = $"prosync-c1-{tag}", Props = new CtProbeChildProps { Tag = "one" } }); var c2 = await redb.SaveAsync(new RedbObject { name = $"prosync-c2-{tag}", Props = new CtProbeChildProps { Tag = "two" } }); var props = new CtProbeProps { Label = "root", Longs = [3, 1, 2], Decimals = [1.5m, 2.25m], Tags = ["a", "b"], Dict = new() { ["k1"] = "v1", ["k2"] = "v2" }, TupleDict = new() { [(2024, "Q1")] = "first", [(2025, "Q2")] = "second" }, Items = [ new CtProbeItem { Name = "i1", Price = 9.99m, Codes = [7, 8], Meta = new() { ["m"] = "1" } }, new CtProbeItem { Name = "i2", Price = 0.5m } ], Status = linked, Roles = [linked, plain] }; if (onlyTrashedReference) { props.Refs = [new RedbObject { id = c2 }]; } else { props.Refs = [new RedbObject { id = c1 }, new RedbObject { id = c2 }]; props.RefDict = new() { ["first"] = new RedbObject { id = c1 } }; } var rootId = await redb.SaveAsync(new RedbObject { name = $"prosync-root-{tag}", Props = props }); if (onlyTrashedReference) await redb.SoftDeleteAsync(new[] { c2 }); return new Seed(rootId, linkedObjectId); } /// The loaded object field by field, without waking anything (a stub is described, never loaded). private static string Describe(RedbObject o) { var p = o.Props; var s = new StringBuilder(); s.AppendLine($"header: id={o.id} scheme={o.scheme_id} name={o.name} hash={o.hash}"); s.AppendLine($"label: {p.Label}"); s.AppendLine($"longs: {Seq(p.Longs)}"); s.AppendLine($"decimals: {Seq(p.Decimals?.Select(d => d.ToString(CultureInfo.InvariantCulture)))}"); s.AppendLine($"tags: {Seq(p.Tags?.Select(t => t ?? ""))}"); s.AppendLine($"dict: {Seq(Pairs(p.Dict))}"); s.AppendLine($"tupleDict: {Seq(p.TupleDict?.Select(e => $"{e.Key.Year}/{e.Key.Quarter}={e.Value}").OrderBy(x => x, StringComparer.Ordinal))}"); s.AppendLine($"items: {Seq(p.Items?.Select(i => i == null ? "" : $"{i.Name}:{i.Price.ToString(CultureInfo.InvariantCulture)}:[{Seq(i.Codes)}]:[{Seq(Pairs(i.Meta))}]"))}"); s.AppendLine($"refs: {Seq(p.Refs?.Select(Reference))}"); s.AppendLine($"refDict: {Seq(p.RefDict?.OrderBy(e => e.Key, StringComparer.Ordinal).Select(e => $"{e.Key}={Reference(e.Value)}"))}"); s.AppendLine($"status: {Item(p.Status)}"); s.AppendLine($"roles: {Seq(p.Roles?.Select(Item))}"); return s.ToString(); } private static string Seq(IEnumerable? items) => items == null ? "" : string.Join(",", items); private static IEnumerable? Pairs(Dictionary? dict) => dict?.OrderBy(e => e.Key, StringComparer.Ordinal).Select(e => $"{e.Key}={e.Value}"); private static string Reference(RedbObject? r) => r == null ? "" : r.IsPropsLoaded ? $"{r.id}:{r.name}:{r.Props.Tag}" : $"stub {r.id}:{r.name}:hash={r.hash != null}"; private static string Item(RedbListItem? i) => i == null ? "" : $"{i.Id}:{i.IdList}:{i.Value}:{i.Alias}:object={i.IdObject}"; private async Task SyncLoadMatchesAsyncLoadAsync(string path, Action configure, int depth, bool onlyTrashedReference = false) { await using var sp = Build(configure); var seed = await SeedAsync(sp, onlyTrashedReference); string expected; await using (var asyncScope = sp.CreateAsyncScope()) { var viaAsync = await asyncScope.ServiceProvider.GetRequiredService().LoadAsync(seed.RootId, depth); expected = Describe(viaAsync!); } expected.Should().Contain($"object={seed.LinkedObjectId}", $"{path}: precondition - the async load carries the list-item link, or comparing it proves nothing"); await using var scope = sp.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); var callingThread = Environment.CurrentManagedThreadId; _recorder.Start(); var loaded = redb.Load(seed.RootId, depth); var commands = _recorder.Stop(); AssertSyncRoad(path, commands, callingThread); loaded.Should().NotBeNull(); Describe(loaded!).Should().Be(expected, $"{path}: the sync load is the thread-pool-free twin of LoadAsync - the same object, list-item links included"); var status = loaded!.Props.Status!; status.IsObjectLoaded.Should().BeFalse($"{path}: the sync materialization reads no RedbListItem.Object"); status.Object.Should().NotBeNull($"{path}: positive control - an explicit read of Object loads it on the live scope"); status.IsObjectLoaded.Should().BeTrue(); } /// /// The synchronous road: commands went through the recording context (positive control), none of them is the Free /// JSON builder, and every one ran on the calling thread - a hop to the pool (Task.Run, Parallel.ForEach) parks the /// caller behind pool capacity, the anatomy of a production freeze (2026-09-09). /// private static void AssertSyncRoad(string path, IReadOnlyList commands, int callingThread) { commands.Should().NotBeEmpty($"{path}: positive control - the load runs its commands through the recording context"); commands.Should().NotContain(c => c.Sql.Contains("get_object_json", StringComparison.OrdinalIgnoreCase), $"{path}: Pro materializes Props in C#; the synchronous road must not take the Free in-database JSON builder (Pro SQLite has none)"); commands.Should().OnlyContain(c => c.ThreadId == callingThread, $"{path}: every command of the synchronous road runs on the calling thread, never on a thread-pool thread"); } [Fact] public async Task LazyStubPropsGetter_LoadsOnTheCallingThread_WithoutFreeJson() { // The synchronous Props getter of a lazy reference stub (the other synchronous road of Pro materialization). await using var sp = Build(c => { c.EnableLazyReferences = true; c.LazyReferenceAccess = LazyReferenceAccessMode.Blocking; // the transparent synchronous load, stated explicitly }); var seed = await SeedAsync(sp, onlyTrashedReference: false); await using var scope = sp.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); var root = await redb.LoadAsync(seed.RootId, depth: 1); var stub = root!.Props.Refs![0]; stub.IsPropsLoaded.Should().BeFalse("precondition: at depth 1 the reference is a lazy stub"); var callingThread = Environment.CurrentManagedThreadId; _recorder.Start(); var tag = stub.Props.Tag; var commands = _recorder.Stop(); tag.Should().BeOneOf("one", "two"); AssertSyncRoad("lazy stub Props getter", commands, callingThread); root.Props.Status!.IsObjectLoaded.Should().BeFalse("the stub load reads no RedbListItem.Object"); } [Fact] public Task SyncLoad_WithReferencesAndListItems_MatchesAsync_WithoutFreeJson() => SyncLoadMatchesAsyncLoadAsync("references and list items", _ => { }, depth: 10); [Fact] public Task SyncLoad_WithTrashedReferenceTarget_MatchesAsync_WithoutFreeJson() => SyncLoadMatchesAsyncLoadAsync("trashed reference target", _ => { }, depth: 10, onlyTrashedReference: true); [Fact] public Task SyncLoad_WithLazyReferences_MatchesAsync_WithoutFreeJson() => SyncLoadMatchesAsyncLoadAsync("lazy references", c => c.EnableLazyReferences = true, depth: 1); } Path: redb/redb.Tests.Integration/Tests/Base/ProTreeTestsBase.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/ProTreeTestsBase.cs ---- #pragma warning disable CS0618 // implements or uses the deprecated object permissions and roles (RedbDeprecation) using redb.Core; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using redb.Core.Models.Enums; using redb.Core.Models.Users; using redb.Core.Query; using redb.Core.Query.Aggregation; using redb.Tests.Integration.Helpers; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// The tree services that read a subtree or a chain of ancestors in one statement (TreeProviderBase): the same nodes in /// the same order as the walk one parent at a time, a cycle in _id_parent as an error, and the permission check of every /// node with its subtree left out under a refused one. /// public abstract class ProTreeTestsBase : TreeTestsBase { protected ProTreeTestsBase(IRedbService redb) : base(redb) { } /// /// root -> c, a, b (saved in that order, so the order of the children is by name, not by id), each with two /// children saved z then y. /// private async Task> SeedUnsortedTreeAsync(string tag) { var root = TestDataFactory.CreateTreeNode($"walk-{tag}", $"W-{tag}"); root.id = await Redb.SaveAsync(root); foreach (var name in new[] { "c", "a", "b" }) { var child = TestDataFactory.CreateTreeNode($"{name}-{tag}", $"{name}-{tag}"); child.id = await Redb.CreateChildAsync(child, root); foreach (var leaf in new[] { "z", "y" }) await Redb.CreateChildAsync(TestDataFactory.CreateTreeNode($"{name}{leaf}-{tag}", $"{name}{leaf}-{tag}"), child); } return root; } /// The walk one parent at a time, through GetChildrenAsync: a child, everything below it, the next child. private async Task> WalkByChildrenAsync(IRedbObject parent) { var ids = new List(); foreach (var child in await Redb.GetChildrenAsync(parent)) { ids.Add(child.id); ids.AddRange(await WalkByChildrenAsync(child)); } return ids; } [Fact] public async Task Descendants_AndLoadTree_AreTheWalkByChildren() { var root = await SeedUnsortedTreeAsync(Guid.NewGuid().ToString("N")[..8]); var expected = await WalkByChildrenAsync(root); expected.Should().HaveCount(9); (await Redb.GetDescendantsAsync(root)).Select(d => d.id).Should().Equal(expected); var tree = await Redb.LoadTreeAsync(root); IEnumerable Flatten(TreeRedbObject node) => node.Children.Cast>().SelectMany(c => Flatten(c).Prepend(c.id)); Flatten(tree).Should().Equal(expected); tree.Children.Cast>().Should().AllSatisfy(c => c.Parent.Should().BeSameAs(tree)); var depthOne = await Redb.LoadTreeAsync(root, maxDepth: 1); depthOne.Children.Should().HaveCount(3); depthOne.Children.Should().AllSatisfy(c => c.Children.Should().BeEmpty()); var polymorphic = await Redb.GetPolymorphicDescendantsAsync(root); polymorphic.Select(d => d.Id).Should().Equal(expected); } [Fact] public async Task Window_TakesSkipAndOrderOfTheQuery_ShownFieldsBelongToTheirRows() { // The window over a tree used to ignore Take, Skip and OrderBy and return every node. Now the rows are the // page of the query, in its order; the window values are those of the whole filtered subtree. var tag = Guid.NewGuid().ToString("N")[..8]; var root = TestDataFactory.CreateTreeNode($"win-{tag}", $"WIN-{tag}"); root.id = await Redb.SaveAsync(root); var nodes = new List>(); for (var i = 0; i < 12; i++) { var node = TestDataFactory.CreateTreeNode($"win-{tag}-{i:D2}", $"C{i:D2}-{tag}", 1000m * ((i * 7) % 12 + 1)); node.id = await Redb.CreateChildAsync(node, i < 6 || nodes.Count == 0 ? root : nodes[i % 6]); nodes.Add(node); } var set = nodes.Where(n => n.Props.Budget > 2000m).ToList(); var rows = await Redb.TreeQuery(root.id) .Where(n => n.Budget > 2000m) .OrderByDescending(n => n.Budget) .Skip(2).Take(4) .WithWindow(w => w.OrderByDesc(n => n.Budget)) .SelectAsync(n => new { n.Id, n.Props.Name, n.Props.Code, n.Props.Budget, Rank = Win.Rank() }); var expected = set.OrderByDescending(n => n.Props.Budget).Skip(2).Take(4).ToList(); rows.Select(r => r.Budget).Should().Equal(expected.Select(n => n.Props.Budget), "the page of the ordering"); foreach (var r in rows) { var node = nodes.Single(n => n.id == r.Id); r.Name.Should().Be(node.Props.Name); r.Code.Should().Be(node.Props.Code); r.Rank.Should().Be(1 + set.Count(n => n.Props.Budget > node.Props.Budget), "ranked over the whole filtered subtree"); } var buckets = await Redb.TreeQuery(root.id).Take(9) .WithWindow(w => w.OrderByDesc(n => n.Budget)) .SelectAsync(n => new { n.Id, Bucket = Win.Ntile(3) }); buckets.Should().HaveCount(9); buckets.Select(b => b.Bucket).Distinct().Should().BeEquivalentTo(new[] { 1, 2, 3 }, "Win.Ntile(3) gives three buckets"); } [Fact] public async Task Any_StopsAtTheFirstNode_AndAgreesWithCount() { // Any over a tree asks for one node instead of counting the subtree; the answer must stay the count above zero, // whatever the filter, ordering, distinct or page of the query. var tag = Guid.NewGuid().ToString("N")[..8]; var root = TestDataFactory.CreateTreeNode($"any-{tag}", $"ANY-{tag}"); root.id = await Redb.SaveAsync(root); var nodes = new List>(); for (var i = 0; i < 12; i++) { var node = TestDataFactory.CreateTreeNode($"any-{tag}-{i:D2}", $"C{i:D2}-{tag}", 1000m * ((i * 7) % 12 + 1)); node.id = await Redb.CreateChildAsync(node, i < 6 || nodes.Count == 0 ? root : nodes[i % 6]); nodes.Add(node); } var leaf = nodes[^1]; var queries = new (string Name, IRedbQueryable Query, bool Expected)[] { ("whole subtree", Redb.TreeQuery(root.id), true), ("a filter some nodes pass", Redb.TreeQuery(root.id).Where(n => n.Budget > 10000m), true), ("a filter no node passes", Redb.TreeQuery(root.id).Where(n => n.Budget > 1000000m), false), ("ordered", Redb.TreeQuery(root.id).Where(n => n.Budget > 2000m).OrderByDescending(n => n.Budget), true), ("distinct by a field", Redb.TreeQuery(root.id).DistinctBy(n => n.Budget), true), ("ordered, no node passes", Redb.TreeQuery(root.id).Where(n => n.Budget < 0m).OrderBy(n => n.Code), false), ("below a leaf", Redb.TreeQuery(leaf.id), false), ("skip to the last node", Redb.TreeQuery(root.id).Skip(nodes.Count - 1), true), ("skip past the last node", Redb.TreeQuery(root.id).Skip(nodes.Count), false), ("take none", Redb.TreeQuery(root.id).Take(0), false), }; foreach (var (name, query, expected) in queries) { (await query.AnyAsync()).Should().Be(expected, name); (await query.CountAsync() > 0).Should().Be(expected, $"{name}: the count agrees"); } (await Redb.TreeQuery(root.id).AnyAsync(n => n.Code == $"C05-{tag}")).Should().BeTrue("a predicate one node passes"); (await Redb.TreeQuery(root.id).AnyAsync(n => n.Code == $"none-{tag}")).Should().BeFalse("a predicate no node passes"); } [Fact] public async Task TreeFilters_Combined_AllApply_InAnyOrder() { // root -> a, b; a -> a1, a2; a2 -> a21. Leaves: a1, a21, b. var tag = Guid.NewGuid().ToString("N")[..8]; var nodes = new Dictionary>(); async Task Add(string name, string? parent) { var node = TestDataFactory.CreateTreeNode($"{name}-{tag}", $"{name}-{tag}"); node.id = parent == null ? await Redb.SaveAsync(node) : await Redb.CreateChildAsync(node, nodes[parent]); nodes[name] = node; return node.id; } var root = await Add("root", null); var a = await Add("a", "root"); var b = await Add("b", "root"); var a1 = await Add("a1", "a"); var a2 = await Add("a2", "a"); var a21 = await Add("a21", "a2"); async Task Ids(Func, IRedbQueryable> shape) => (await shape(Redb.TreeQuery(root)).ToListAsync()).Select(n => n.id).OrderBy(i => i).ToArray(); long[] Set(params long[] ids) => ids.OrderBy(i => i).ToArray(); // Each alone. (await Ids(q => q.WhereChildrenOf(a))).Should().Equal(Set(a1, a2), "children of a"); (await Ids(q => q.WhereLeaves())).Should().Equal(Set(a1, a21, b), "leaves of the subtree"); (await Ids(q => q.WhereDescendantsOf(a))).Should().Equal(Set(a1, a2, a21), "descendants of a"); // Together: every filter applies, whichever comes first. (await Ids(q => q.WhereChildrenOf(a).WhereLeaves())).Should().Equal(Set(a1), "children of a that are leaves"); (await Ids(q => q.WhereLeaves().WhereChildrenOf(a))).Should().Equal(Set(a1), "leaves that are children of a"); (await Ids(q => q.WhereDescendantsOf(a).WhereLeaves())).Should().Equal(Set(a1, a21), "descendants of a that are leaves"); (await Ids(q => q.WhereLeaves().WhereDescendantsOf(a))).Should().Equal(Set(a1, a21), "leaves below a"); (await Ids(q => q.WhereChildrenOf(a).WhereChildrenOf(b))).Should().BeEmpty("no node is a child of both"); (await Ids(q => q.WhereDescendantsOf(a2).WhereChildrenOf(a))).Should().BeEmpty("a21 is below a2 but not a child of a"); } [Fact] public async Task DistinctBy_WithFilterOrderAndPage_OneNodePerKey() { // DistinctBy over a subtree on a Props field, with a filter, an ordering by the key and a page. With the // planner on SQL Server reads it over the streams, SQLite over a pivot the nodes drive. var tag = Guid.NewGuid().ToString("N")[..8]; var root = TestDataFactory.CreateTreeNode($"dist-{tag}", $"DIST-{tag}"); root.id = await Redb.SaveAsync(root); var nodes = new List>(); for (var i = 0; i < 12; i++) { var node = TestDataFactory.CreateTreeNode($"dist-{tag}-{i:D2}", $"D{i:D2}-{tag}", 1000m * (i % 4 + 1)); node.id = await Redb.CreateChildAsync(node, i < 4 ? root : nodes[i % 4]); nodes.Add(node); } IRedbQueryable Q() => Redb.TreeQuery(root.id); var filtered = await Q().Where(n => n.Budget > 1000m).DistinctBy(n => n.Budget).ToListAsync(); filtered.Select(n => n.Props.Budget).Should().OnlyHaveUniqueItems().And.BeEquivalentTo(new[] { 2000m, 3000m, 4000m }); filtered.Should().AllSatisfy(n => nodes.Single(x => x.id == n.id).Props.Budget.Should().Be(n.Props.Budget)); (await Q().Where(n => n.Budget > 1000m).OrderByDescending(n => n.Budget).DistinctBy(n => n.Budget).ToListAsync()) .Select(n => n.Props.Budget).Should().Equal(4000m, 3000m, 2000m); (await Q().OrderBy(n => n.Budget).DistinctBy(n => n.Budget).Take(2).ToListAsync()) .Select(n => n.Props.Budget).Should().Equal(1000m, 2000m); (await Q().Where(n => n.Budget > 1000m).DistinctBy(n => n.Budget).CountAsync()).Should().Be(3); } /// Children of a fresh root: (name, code, budget) per child, in this order. private async Task> SeedChildrenAsync(string tag, params (string Name, string Code, decimal Budget)[] children) { var root = TestDataFactory.CreateTreeNode($"droot-{tag}", $"DROOT-{tag}"); root.id = await Redb.SaveAsync(root); foreach (var (name, code, budget) in children) await Redb.CreateChildAsync(TestDataFactory.CreateTreeNode($"{name}-{tag}", $"{code}-{tag}", budget), root); return root; } [Fact] public async Task Distinct_OverATree_OnePerPropsHash_CountsOrdersAndPages() { // Three children with the same props, two with other same props: two nodes. var tag = Guid.NewGuid().ToString("N")[..8]; var root = await SeedChildrenAsync(tag, ("same", "S", 1000m), ("same", "S", 1000m), ("same", "S", 1000m), ("other", "O", 2000m), ("other", "O", 2000m)); IRedbQueryable Q() => Redb.TreeQuery(root.id); (await Q().Distinct().ToListAsync()).Select(n => n.Props.Budget).Should().BeEquivalentTo(new[] { 1000m, 2000m }); (await Q().Distinct().CountAsync()).Should().Be(2); (await Q().Distinct().OrderBy(n => n.Budget).Skip(1).ToListAsync()).Select(n => n.Props.Budget).Should().Equal(2000m); } [Fact] public async Task DistinctRedb_OverATree_OnePerBaseFields_AndCounts() { // Children under two names (different budgets, so the props differ): two nodes. var tag = Guid.NewGuid().ToString("N")[..8]; var root = await SeedChildrenAsync(tag, ("a", "A1", 1000m), ("a", "A2", 2000m), ("a", "A3", 3000m), ("b", "B1", 4000m), ("b", "B2", 5000m)); IRedbQueryable Q() => Redb.TreeQuery(root.id); (await Q().DistinctRedb().ToListAsync()).Select(n => n.name).Should().BeEquivalentTo(new[] { $"a-{tag}", $"b-{tag}" }); (await Q().DistinctRedb().CountAsync()).Should().Be(2); } [Fact] public async Task DistinctByRedb_And_DistinctBy_OverATree_WithAnOrderingAndAPage() { var tag = Guid.NewGuid().ToString("N")[..8]; var root = await SeedChildrenAsync(tag, ("a", "A1", 1000m), ("a", "A2", 1000m), ("b", "B1", 2000m), ("b", "B2", 2000m), ("c", "C1", 3000m)); IRedbQueryable Q() => Redb.TreeQuery(root.id); // One node per name, in the order of the key, then the page. (await Q().OrderBy(n => n.Budget).DistinctByRedb(o => o.Name).Skip(1).Take(1).ToListAsync()) .Select(n => n.name).Should().Equal($"b-{tag}"); (await Q().DistinctByRedb(o => o.Name).CountAsync()).Should().Be(3); // One node per budget, skipping the first. (await Q().OrderBy(n => n.Budget).DistinctBy(n => n.Budget).Skip(1).ToListAsync()) .Select(n => n.Props.Budget).Should().Equal(2000m, 3000m); } [Fact] public async Task DistinctBy_OverATree_ThenAnyAllWindowGroupBy_CurrentBehaviour() { // What these combinations do today over a tree; the intended meaning is not defined yet (see BUGS_FOUND). // Budget 1000: the first child is "low", the second "high"; budget 2000: "high". var tag = Guid.NewGuid().ToString("N")[..8]; var root = await SeedChildrenAsync(tag, ("low", "L", 1000m), ("high", "H1", 1000m), ("high", "H2", 2000m)); IRedbQueryable Q() => Redb.TreeQuery(root.id); (await Q().DistinctBy(n => n.Budget).AnyAsync()).Should().BeTrue(); // Every key has a node named "high", though the kept node of budget 1000 is "low". (await Q().DistinctBy(n => n.Budget).AllAsync(n => n.Name.StartsWith("high"))).Should().BeTrue(); (await Q().DistinctBy(n => n.Budget).WithWindow(w => w.OrderByDesc(x => x.Budget)) .SelectAsync(x => new { x.Id, R = Win.RowNumber() })).Should().HaveCount(3); (await Q().DistinctBy(n => n.Budget).GroupBy(x => x.Budget) .SelectAsync(g => new { g.Key, N = Agg.Count(g) })).Sum(g => g.N).Should().Be(3); } [Fact] public async Task ParentChains_OfTreeListRootListAndLoadWithParents_ReachTheRoot_DeeperThan100Levels() { // ToTreeListAsync, ToRootListAsync and LoadWithParentsAsync read the ancestors of the objects in one statement. // A chain of 120 levels: SQL Server stops a recursive statement at 100 unless told otherwise. var tag = Guid.NewGuid().ToString("N")[..8]; var root = TestDataFactory.CreateTreeNode($"chain-{tag}", $"CHAIN-{tag}"); root.id = await Redb.SaveAsync(root); var chain = new List { root.id }; var parent = root; for (var i = 1; i <= 120; i++) { var node = TestDataFactory.CreateTreeNode($"chain-{tag}-{i:D3}", $"L{i:D3}-{tag}"); node.id = await Redb.CreateChildAsync(node, parent); chain.Add(node.id); parent = node; } List Up(ITreeRedbObject node) { var ids = new List(); for (var current = node; current != null; current = current.Parent) ids.Add(current.Id); return ids; } IEnumerable Expected(int level) => Enumerable.Range(0, level + 1).Select(l => chain[level - l]); var deep = (await Redb.LoadWithParentsAsync(new[] { chain[120], chain[60] })).ToDictionary(n => n.id); deep.Keys.Should().BeEquivalentTo(new[] { chain[120], chain[60] }); Up(deep[chain[120]]).Should().Equal(Expected(120), "the whole chain of 120 levels up to the root"); Up(deep[chain[60]]).Should().Equal(Expected(60)); var picked = await Redb.TreeQuery(root.id).Where(n => n.Code == $"L003-{tag}" || n.Code == $"L005-{tag}").ToTreeListAsync(); picked.Select(n => n.id).Should().BeEquivalentTo(new[] { chain[3], chain[5] }); foreach (var node in picked) Up(node).Should().Equal(Expected(chain.IndexOf(node.id))); var roots = await Redb.TreeQuery(root.id).Where(n => n.Code == $"L004-{tag}").ToRootListAsync(); roots.Select(r => r.Id).Should().Equal(root.id); } [Fact] public async Task CycleInParents_IsAnError_NotAHang() { var tag = Guid.NewGuid().ToString("N")[..8]; var a = TestDataFactory.CreateTreeNode($"cycle-a-{tag}", $"CA-{tag}"); a.id = await Redb.SaveAsync(a); var b = TestDataFactory.CreateTreeNode($"cycle-b-{tag}", $"CB-{tag}"); b.id = await Redb.CreateChildAsync(b, a); var c = TestDataFactory.CreateTreeNode($"cycle-c-{tag}", $"CC-{tag}"); c.id = await Redb.CreateChildAsync(c, b); // a -> b -> c -> a: written past the services, which refuse it. await Redb.Context.ExecuteAsync($"UPDATE _objects SET _id_parent = {c.id} WHERE _id = {a.id}"); try { var descendants = () => Redb.GetDescendantsAsync(a); (await descendants.Should().ThrowAsync()).Which.Message.Should().Contain("Cyclic"); var path = () => Redb.GetPathToRootAsync(b); (await path.Should().ThrowAsync()).Which.Message.Should().Contain("Cyclic"); var delete = () => Redb.DeleteSubtreeAsync(a); (await delete.Should().ThrowAsync()).Which.Message.Should().Contain("Cyclic"); } finally { await Redb.Context.ExecuteAsync($"UPDATE _objects SET _id_parent = NULL WHERE _id = {a.id}"); } (await Redb.DeleteSubtreeAsync(a)).Should().Be(3); } [Fact] public async Task MoveUnderOwnDescendant_IsRefused() { var tag = Guid.NewGuid().ToString("N")[..8]; var root = await SeedUnsortedTreeAsync(tag); var grandchild = (await Redb.GetDescendantsAsync(root)).Last(); var move = () => Redb.MoveObjectAsync(root, grandchild); (await move.Should().ThrowAsync()).Which.Message.Should().Contain("cyclic"); (await Redb.GetPathToRootAsync(grandchild)).First().id.Should().Be(root.id, "nothing moved"); } [Fact] public async Task Permissions_ARefusedBranchIsLeftOutWithItsSubtree() { var tag = Guid.NewGuid().ToString("N")[..8]; var user = await Redb.UserProvider.CreateUserAsync( new CreateUserRequest { Login = $"tree-perm-{tag}", Name = $"tree-perm-{tag}", Password = "tree-perm-password-1" }); var root = TestDataFactory.CreateTreeNode($"perm-{tag}", $"P-{tag}"); root.id = await Redb.SaveAsync(root); var allowed = TestDataFactory.CreateTreeNode($"perm-a-{tag}", $"PA-{tag}"); allowed.id = await Redb.CreateChildAsync(allowed, root); var allowedChild = TestDataFactory.CreateTreeNode($"perm-a1-{tag}", $"PA1-{tag}"); allowedChild.id = await Redb.CreateChildAsync(allowedChild, allowed); var refused = TestDataFactory.CreateTreeNode($"perm-b-{tag}", $"PB-{tag}"); refused.id = await Redb.CreateChildAsync(refused, root); await Redb.CreateChildAsync(TestDataFactory.CreateTreeNode($"perm-b1-{tag}", $"PB1-{tag}"), refused); // Reading granted on the root (inherited below it); the refused branch has a row of its own without reading. await Redb.GrantPermissionAsync(user, root, PermissionAction.Select); await Redb.GrantPermissionAsync(user, refused, PermissionAction.Delete); var previousCheck = Redb.Configuration.DefaultCheckPermissionsOnLoad; var previousUser = Redb.SecurityContext.CurrentUser; Redb.Configuration.DefaultCheckPermissionsOnLoad = true; Redb.SecurityContext.SetCurrentUser(user); try { (await Redb.GetDescendantsAsync(root)).Select(d => d.id) .Should().Equal(allowed.id, allowedChild.id); var tree = await Redb.LoadTreeAsync(root); tree.Children.Select(c => c.Id).Should().Equal(allowed.id); (await Redb.GetPolymorphicDescendantsAsync(root, user)).Select(d => d.Id) .Should().Equal(allowed.id, allowedChild.id); (await Redb.GetPathToRootAsync(allowedChild)).Select(p => p.id) .Should().Equal(root.id, allowed.id, allowedChild.id); } finally { Redb.SecurityContext.SetCurrentUser(previousUser); Redb.Configuration.DefaultCheckPermissionsOnLoad = previousCheck; } } } Path: redb/redb.Tests.Integration/Tests/Base/ProWindowTestsBase.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/ProWindowTestsBase.cs ---- using redb.Core; 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; /// /// Windows of the Pro providers: the shape that reads the shown fields after Take/Skip, and the SQL preview (the Free /// providers run windows through a SQL function and have no preview). /// public abstract class ProWindowTestsBase : WindowTestsBase { protected ProWindowTestsBase(IRedbService redb) : base(redb) { } [Fact] public async Task Window_SkipTake_ShownFieldsAreReadForTheRowsKept() { // The window is computed over the fields it needs; the fields only shown (FirstName, HomeAddress.City) are read // afterwards for the rows Skip/Take keep. Each row must carry its own fields, and the window values must be // those of the whole filtered set. Two departments of this test only, so parallel seeding changes no rank. var tag = Guid.NewGuid().ToString("N")[..8]; var (a, b) = ($"win-a-{tag}", $"win-b-{tag}"); await Redb.SaveAsync(Enumerable.Range(0, 24) .Select(i => TestDataFactory.CreateEmployee(i, firstName: $"W{tag}{i:D2}", salary: 40000m + (i % 7) * 1000m, department: i % 2 == 0 ? a : b, city: $"City{i % 5}")) .ToList()); var truth = await Redb.Query().Where(e => e.Department == a || e.Department == b).ToListAsync(); truth.Should().HaveCount(24); var byId = truth.ToDictionary(o => o.Id); var rows = await Redb.Query() .Where(e => e.Department == a || e.Department == b) .Skip(5).Take(10) .WithWindow(w => w.PartitionBy(e => e.Department).OrderByDesc(e => e.Salary)) .SelectAsync(e => new { e.Id, e.Props.FirstName, City = e.Props.HomeAddress!.City, e.Props.Department, Rank = Win.Rank(), Total = Win.Sum(e.Props.Salary) }); rows.Should().HaveCount(10); rows.Select(r => r.Id).Should().OnlyHaveUniqueItems(); foreach (var r in rows) { var t = byId[r.Id]; var department = truth.Where(o => o.Props.Department == t.Props.Department).Select(o => o.Props.Salary).ToList(); r.FirstName.Should().Be(t.Props.FirstName); r.City.Should().Be(t.Props.HomeAddress!.City); r.Department.Should().Be(t.Props.Department); r.Rank.Should().Be(1 + department.Count(s => s > t.Props.Salary)); r.Total.Should().Be(department.Where(s => s >= t.Props.Salary).Sum(), "a running sum within the department"); } } [Fact] public async Task Window_WithoutBaseFields_ReadsItsFieldsAlone_AndLeavesOutTheTrash() { // A window that reads no base field takes its rows from the fields alone: _objects is joined only when the // window reads one of its columns. The objects of the fields are those of the scheme, so a soft-deleted object // (moved to the trash, its values kept) stays out as before. var tag = Guid.NewGuid().ToString("N")[..8]; var department = $"win-t-{tag}"; var ids = await Redb.SaveAsync(Enumerable.Range(0, 6) .Select(i => TestDataFactory.CreateEmployee(i, firstName: $"T{tag}{i}", salary: 50000m + i * 1000m, department: department)) .ToList()); await Redb.SoftDeleteAsync(new[] { ids[5] }); var window = Redb.Query().Where(e => e.Department == department) .WithWindow(w => w.PartitionBy(e => e.Department).OrderByDesc(e => e.Salary)); var rows = await window.SelectAsync(e => new { e.Props.Salary, Rank = Win.RowNumber() }); rows.Select(r => r.Salary).Should().BeEquivalentTo(new[] { 50000m, 51000m, 52000m, 53000m, 54000m }, "the soft-deleted object is not in the window"); rows.Select(r => r.Rank).Should().BeEquivalentTo(new long[] { 1, 2, 3, 4, 5 }); (await window.ToSqlStringAsync(e => new { e.Props.Salary, Rank = Win.RowNumber() })) .Should().Contain("FROM pvt_cte p").And.NotContain("JOIN pvt_cte p"); (await window.ToSqlStringAsync(e => new { e.Id, e.Props.Salary, Rank = Win.RowNumber() })) .Should().Contain("JOIN pvt_cte p", "a base field of the window is read from _objects"); } [Fact] public async Task Window_SqlPreview_CarriesTheFilter() { // ToSqlStringAsync of a window after Where used to drop the filter: the preview is the SQL that runs. var sql = await Redb.Query() .Where(e => e.Salary > 70123m) .Take(20) .WithWindow(w => w.PartitionBy(e => e.Department).OrderByDesc(e => e.Salary)) .ToSqlStringAsync(e => new { e.Props.FirstName, Rank = Win.RowNumber() }); sql.Should().Contain("70123"); } } Path: redb/redb.Tests.Integration/Tests/Base/ProjectionTestsBase.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/ProjectionTestsBase.cs ---- using redb.Core; using redb.Core.Models.Entities; using redb.Core.Query.Aggregation; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// E2E-контракт серверных проекций `Query<T>().Select(...)` (ревью 2026-09-03, волна 1.1: /// до этого набора у Select не было НИ ОДНОГО интеграционного теста). Контракт: проекция обязана /// вернуть те же значения, что вернула бы полная загрузка с последующим вычислением лямбды в /// памяти, — независимо от того, урезал ли провайдер Props на сервере (PG) или грузил целиком и /// резал на клиенте (MSSQL/SQLite). Часть тестов написана red-before под известные дефекты ревью /// (S-2 OrderBy-null, S-3 Distinct+Count, S-5 частичный разбор лямбды, S-6 референс в пути, /// S-7 Agg внутри Select) и зеленеет по мере волн 2-3. /// public abstract class ProjectionTestsBase : IAsyncLifetime { protected readonly IRedbService Redb; protected ProjectionTestsBase(IRedbService redb) => Redb = redb; public async Task InitializeAsync() => await ResetAsync(); public async Task DisposeAsync() => await ResetAsync(); private async Task ResetAsync() => await Redb.Context.ExecuteAsync( "DELETE FROM _objects WHERE _id_scheme IN (SELECT _id FROM _schemes WHERE _name IN ('ProjectionProbe', 'ProjectionProbeChild'))"); private async Task SyncAsync() { await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); } private async Task SeedAsync(ProjectionProbeProps props, string name = "probe") => await Redb.SaveAsync(new RedbObject { name = name, Props = props }); // ============================================================ // === База: значения доезжают как при полной загрузке === // ============================================================ [Fact] public async Task SimpleFields_AnonymousType() { await SyncAsync(); await SeedAsync(new ProjectionProbeProps { S = "alpha", N = 7, D = 1.5m, Flag = true }); var rs = await Redb.Query() .Select(x => new { x.Props.S, x.Props.N, x.Props.D }) .ToListAsync(); rs.Should().ContainSingle(); rs[0].S.Should().Be("alpha"); rs[0].N.Should().Be(7); rs[0].D.Should().Be(1.5m); } [Fact] public async Task BaseField_Id_RidesAlongProps() { await SyncAsync(); var id = await SeedAsync(new ProjectionProbeProps { S = "with-id" }); var rs = await Redb.Query() .Select(x => new { x.Id, x.Props.S }) .ToListAsync(); rs.Should().ContainSingle(); rs[0].Id.Should().Be(id, "у каждой спроецированной строки должен остаться id её объекта"); rs[0].S.Should().Be("with-id"); } /// True where the provider reads only the projected props rows (Pro: ProLazyPropsLoader with the /// projected structure ids). Free providers may load whole and cut on the client. protected virtual bool ReadsOnlyProjectedRows => false; /// /// The projection of new { x.Id, x.Props.S } asks for the structure of S and nothing else, and the read it /// runs brings back only that row: the other fields of the objects it hands to the lambda stay at their defaults. /// A misread of the projected statement once cost a round of measurements (2026-11-24). /// [Fact] public async Task IdAndPropsField_ReadsOnlyTheProjectedStructure() { if (!ReadsOnlyProjectedRows) return; var scheme = await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); var sId = scheme.Structures.Single(s => s.Name == "S" && s.IdParent == null).Id; await SeedAsync(new ProjectionProbeProps { S = "only-s", N = 7, D = 1.5m, Flag = true, Tags = ["a"], Nested = new ProjectionProbeNested { City = "C", Zip = 3 } }); var projected = Redb.Query().Select(x => new { x.Id, x.Props.S }); (await projected.ToListAsync()).Should().ContainSingle().Which.S.Should().Be("only-s"); var asked = (HashSet?)projected.GetType().GetProperty("ProjectedStructureIds")!.GetValue(projected); asked.Should().BeEquivalentTo(new[] { sId }, "the projection asks for the structure of S only"); // The read the projection runs, on the same settings, with the objects it hands to the lambda kept. var paths = (List?)projected.GetType() .GetField("_projectedFieldPaths", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)! .GetValue(projected); var working = ((redb.Core.Query.RedbQueryable)Redb.Query()).CloneForProjection(); working.SetProjectedFieldPaths(paths); var read = await working.ToListWithProjectionAsync(asked, skipPropsLoading: true); var props = read.Should().ContainSingle().Which.GetPropsDirectly()!; props.S.Should().Be("only-s"); props.N.Should().Be(0, "N is not projected, so its row is not read"); props.D.Should().BeNull(); props.Flag.Should().BeFalse(); props.Tags.Should().BeNull(); props.Nested.Should().BeNull(); } [Fact] public async Task NestedClassField() { await SyncAsync(); await SeedAsync(new ProjectionProbeProps { S = "n", Nested = new ProjectionProbeNested { City = "Kazan", Zip = 420000 } }); var rs = await Redb.Query() .Select(x => new { City = x.Props.Nested!.City, x.Props.Nested!.Zip }) .ToListAsync(); rs.Should().ContainSingle(); rs[0].City.Should().Be("Kazan"); rs[0].Zip.Should().Be(420000); } [Fact] public async Task ArrayOfClass_InnerSelectToList() { await SyncAsync(); await SeedAsync(new ProjectionProbeProps { S = "arr", Items = [ new ProjectionProbeItem { Name = "a", Price = 10m }, new ProjectionProbeItem { Name = "b", Price = 20m }, ] }); var rs = await Redb.Query() .Select(x => new { Names = x.Props.Items!.Select(i => i.Name).ToList() }) .ToListAsync(); rs.Should().ContainSingle(); rs[0].Names.Should().Equal("a", "b"); } [Fact] public async Task StringArrayField() { await SyncAsync(); await SeedAsync(new ProjectionProbeProps { S = "tags", Tags = ["red", "green"] }); var rs = await Redb.Query() .Select(x => new { x.Props.Tags }) .ToListAsync(); rs.Should().ContainSingle(); rs[0].Tags.Should().Equal("red", "green"); } [Fact] public async Task ComputedMembers_BinaryAndConcat() { await SyncAsync(); await SeedAsync(new ProjectionProbeProps { S = "x", N = 41 }); var rs = await Redb.Query() .Select(x => new { Total = x.Props.N + 1, Label = x.Props.S + "!" }) .ToListAsync(); rs.Should().ContainSingle(); rs[0].Total.Should().Be(42); rs[0].Label.Should().Be("x!"); } [Fact] public async Task Conditional_And_Coalesce() { await SyncAsync(); await SeedAsync(new ProjectionProbeProps { S = "yes", N = 1, Flag = true, D = null }); var rs = await Redb.Query() .Select(x => new { K = x.Props.Flag ? x.Props.S : "no", Dd = x.Props.D ?? -1m, }) .ToListAsync(); rs.Should().ContainSingle(); rs[0].K.Should().Be("yes"); rs[0].Dd.Should().Be(-1m); } [Fact] public async Task Dto_MemberInit_PlainAssignments() { await SyncAsync(); await SeedAsync(new ProjectionProbeProps { S = "dto", N = 5 }); var rs = await Redb.Query() .Select(x => new ProjectionDto { A = x.Props.S, N = x.Props.N }) .ToListAsync(); rs.Should().ContainSingle(); rs[0].A.Should().Be("dto"); rs[0].N.Should().Be(5); } [Fact] public async Task WhereAfterSelect_FiltersProjectedRows() { await SyncAsync(); await SeedAsync(new ProjectionProbeProps { S = "keep", N = 10 }); await SeedAsync(new ProjectionProbeProps { S = "drop", N = 1 }); var rs = await Redb.Query() .Select(x => new { x.Props.S, x.Props.N }) .Where(r => r.N > 5) .ToListAsync(); rs.Should().ContainSingle(); rs[0].S.Should().Be("keep"); } [Fact] public async Task CountAsync_Plain_MatchesSource() { await SyncAsync(); await SeedAsync(new ProjectionProbeProps { S = "c1" }); await SeedAsync(new ProjectionProbeProps { S = "c2" }); var count = await Redb.Query() .Select(x => new { x.Props.S }) .CountAsync(); count.Should().Be(2); } [Fact] public async Task FirstOrDefaultAsync_ReturnsProjectedShape() { await SyncAsync(); await SeedAsync(new ProjectionProbeProps { S = "first", N = 3 }); var r = await Redb.Query() .Select(x => new { x.Props.S, x.Props.N }) .FirstOrDefaultAsync(); r.Should().NotBeNull(); r!.S.Should().Be("first"); } // ============================================================ // === Red-before дефектов ревью (зеленеют волнами 2-3) === // ============================================================ [Fact] public async Task TakeAfterWhereAfterSelect_PaginatesTheFilteredRows() { // S-4 (решение владельца 2026-09-04): Take после in-memory Where обязан резать // ОТФИЛЬТРОВАННЫЕ строки. Раньше Take уходил в SQL до фильтра - сервер отдавал первую // попавшуюся страницу, фильтр выкидывал из неё, и строки молча терялись. await SyncAsync(); for (var i = 1; i <= 30; i++) await SeedAsync(new ProjectionProbeProps { S = $"p{i}", N = i }); var rs = await Redb.Query() .Select(x => new { x.Props.N }) .Where(r => r.N > 10) .Take(5) .ToListAsync(); rs.Should().HaveCount(5, "кандидатов с N>10 двадцать - страница обязана быть полной"); rs.Should().OnlyContain(r => r.N > 10); } [Fact] public async Task SkipTake_AfterWhereAndOrderBy_PagesTheFilteredOrderedRows() { await SyncAsync(); for (var i = 1; i <= 30; i++) await SeedAsync(new ProjectionProbeProps { S = $"p{i}", N = i }); var rs = await Redb.Query() .Select(x => new { x.Props.N }) .Where(r => r.N > 10) .OrderBy(r => r.N) .Skip(5) .Take(5) .ToListAsync(); rs.Select(r => r.N).Should().Equal(new[] { 16, 17, 18, 19, 20 }, "вторая страница отфильтрованного и отсортированного набора"); } [Fact] public async Task TakeBeforeWhere_KeepsCallOrderSemantics() { // Пин порядка вызовов: Take ДО пост-Select Where режет источник (как в LINQ), // а Where потом фильтрует уже отрезанную страницу. await SyncAsync(); for (var i = 1; i <= 20; i++) await SeedAsync(new ProjectionProbeProps { S = $"p{i}", N = i }); var rs = await Redb.Query() .OrderBy(x => x.N) .Select(x => new { x.Props.N }) .Take(10) .Where(r => r.N > 5) .ToListAsync(); rs.Select(r => r.N).Should().Equal(6, 7, 8, 9, 10); } [Fact] public async Task WhereAfterSelect_OnNestedProjectedMember_Filters() { // S-4 шаг 2: предикат по спроецированному вложенному члену транслируется в источник. await SyncAsync(); await SeedAsync(new ProjectionProbeProps { S = "k", Nested = new ProjectionProbeNested { City = "Kazan" } }); await SeedAsync(new ProjectionProbeProps { S = "m", Nested = new ProjectionProbeNested { City = "Moscow" } }); var rs = await Redb.Query() .Select(x => new { x.Props.S, City = x.Props.Nested!.City }) .Where(r => r.City == "Kazan") .ToListAsync(); rs.Should().ContainSingle(); rs[0].S.Should().Be("k"); } [Fact] public async Task WhereAfterSelect_OnComputedMember_StillFiltersCorrectly() { // Вычисляемый член не транслируется - фильтр остаётся в памяти и обязан быть корректен. await SyncAsync(); for (var i = 1; i <= 20; i++) await SeedAsync(new ProjectionProbeProps { S = $"p{i}", N = i }); var rs = await Redb.Query() .Select(x => new { Total = x.Props.N + 1 }) .Where(r => r.Total > 11) .Take(5) .ToListAsync(); rs.Should().HaveCount(5); rs.Should().OnlyContain(r => r.Total > 11); } [Fact] public async Task WhereAfterSelect_MixedWithBaseFieldMember_StillFiltersCorrectly() { // Член из базового поля (x.Id) не транслируется - корректная фильтрация в памяти. await SyncAsync(); var id1 = await SeedAsync(new ProjectionProbeProps { S = "one", N = 1 }); await SeedAsync(new ProjectionProbeProps { S = "two", N = 2 }); var rs = await Redb.Query() .Select(x => new { x.Id, x.Props.S }) .Where(r => r.Id == id1) .ToListAsync(); rs.Should().ContainSingle(); rs[0].S.Should().Be("one"); } [Fact] public async Task OrderByAfterSelect_NullKey_DoesNotCrash() { // S-2: null-ключ подменялся new object() и Comparer валил запрос. await SyncAsync(); await SeedAsync(new ProjectionProbeProps { S = null, N = 1 }); await SeedAsync(new ProjectionProbeProps { S = "b", N = 2 }); var rs = await Redb.Query() .Select(x => new { x.Props.S }) .OrderBy(r => r.S) .ToListAsync(); rs.Should().HaveCount(2, "null-ключ - штатная сортировка, а не крушение"); rs[0].S.Should().BeNull("LINQ-контракт: null сортируется первым по возрастанию"); rs[1].S.Should().Be("b"); } [Fact] public async Task CountAsync_AfterDistinct_MatchesToList() { // S-3: Distinct применялся в памяти, а Count уходил в источник мимо дедупа. await SyncAsync(); await SeedAsync(new ProjectionProbeProps { S = "dup", N = 1 }); await SeedAsync(new ProjectionProbeProps { S = "dup", N = 2 }); await SeedAsync(new ProjectionProbeProps { S = "uniq", N = 3 }); var q = Redb.Query() .Select(x => new { x.Props.S }) .Distinct(); var list = await q.ToListAsync(); var count = await q.CountAsync(); list.Should().HaveCount(2); count.Should().Be(list.Count, "CountAsync обязан считать то же, что вернёт ToListAsync"); } [Fact] public async Task Dto_NestedMemberInit_IsNotSilentlyPartial() { // S-5: MemberMemberBinding (Sub = { X = ... }) не разбирался экстрактором путей - поле // молча не загружалось, и лямбда писала default. Контракт: либо путь извлечён, либо // полная загрузка; тихое обнуление запрещено. await SyncAsync(); await SeedAsync(new ProjectionProbeProps { S = "mm", N = 77 }); var rs = await Redb.Query() .Select(x => new ProjectionDto { A = x.Props.S, Sub = { X = x.Props.N } }) .ToListAsync(); rs.Should().ContainSingle(); rs[0].A.Should().Be("mm"); rs[0].Sub.X.Should().Be(77, "нераспознанный узел лямбды обязан откатывать на полную загрузку, а не молча обнулять поле"); } [Fact] public async Task Projection_ThroughReference_IsNotSilentlyNull() { // S-6: путь через референс (Child.Props.Label) давал мусорный сегмент "Props" - сервер // его не разрешал, lazy-загрузчик занулён, поле молча null. await SyncAsync(); var child = new RedbObject { name = "child", Props = new ProjectionProbeChildProps { Label = "child-label" } }; await Redb.SaveAsync(child); await SeedAsync(new ProjectionProbeProps { S = "parent", Child = child }); var rs = await Redb.Query() .Select(x => new { Label = x.Props.Child!.Props!.Label }) .ToListAsync(); rs.Should().ContainSingle(); rs[0].Label.Should().Be("child-label", "проекция через референс обязана либо работать, либо внятно отказывать - но не возвращать тихий null"); } [Fact] public async Task AggInsideSelect_RoutesToAggregatePath() { // S-7 (решение владельца 2026-09-03: маршрутизируем): пример из XML-доки Agg // `.Select(x => new { Total = Agg.Sum(...) })` кидал NotSupportedException в рантайме. await SyncAsync(); await SeedAsync(new ProjectionProbeProps { S = "a1", D = 10m }); await SeedAsync(new ProjectionProbeProps { S = "a2", D = 32m }); var rs = await Redb.Query() .Select(x => new { Total = Agg.Sum(x.Props.D) }) .ToListAsync(); rs.Should().ContainSingle("Select с агрегатами - одна строка агрегатов"); rs[0].Total.Should().Be(42m); } // ============================================================ // === A field next to something that needs every field === // ============================================================ // Found 2026-10-12 on a copy of a production database. A selector that named one field and, next // to it, used the object, its Props, or an expression the field walk did not enter, loaded that // one field only: the rest arrived as defaults, silently. Alone, each of these shapes fell back // to a full load by accident (no field recognised at all), which is why they went unnoticed. private static string Describe(RedbObject o) => $"{o.Props.S}:{o.Props.N}"; [Fact] public async Task WholeObject_NextToField_IsNotSilentlyPartial() { await SyncAsync(); await SeedAsync(new ProjectionProbeProps { S = "whole", N = 5 }); var rs = await Redb.Query() .Select(x => new { O = x, x.Props.S }) .ToListAsync(); rs.Should().ContainSingle(); rs[0].S.Should().Be("whole"); rs[0].O.Props.N.Should().Be(5, "the object handed on whole must carry every field"); } [Fact] public async Task WholeProps_NextToField_IsNotSilentlyPartial() { await SyncAsync(); await SeedAsync(new ProjectionProbeProps { S = "props", N = 6, Flag = true }); var rs = await Redb.Query() .Select(x => new { P = x.Props, x.Props.S }) .ToListAsync(); rs.Should().ContainSingle(); rs[0].P.N.Should().Be(6); rs[0].P.Flag.Should().BeTrue(); } [Fact] public async Task MethodOverObject_NextToField_IsNotSilentlyPartial() { await SyncAsync(); await SeedAsync(new ProjectionProbeProps { S = "call", N = 8 }); var rs = await Redb.Query() .Select(x => new { D = Describe(x), x.Props.S }) .ToListAsync(); rs.Should().ContainSingle(); rs[0].D.Should().Be("call:8", "a method that receives the object may read any field of it"); } [Fact] public async Task MemberOfCoalesce_NextToField_LoadsTheCoalescedField() { await SyncAsync(); await SeedAsync(new ProjectionProbeProps { S = "four", N = 9 }); var rs = await Redb.Query() .Select(x => new { x.Props.N, L = (x.Props.S ?? "").Length }) .ToListAsync(); rs.Should().ContainSingle(); rs[0].N.Should().Be(9); rs[0].L.Should().Be(4, "S is read inside the parentheses and has to be loaded"); } [Fact] public async Task MemberOfCallResult_NextToField_LoadsTheCalledField() { await SyncAsync(); await SeedAsync(new ProjectionProbeProps { S = " pad ", N = 10 }); var rs = await Redb.Query() .Select(x => new { x.Props.N, L = x.Props.S!.Trim().Length }) .ToListAsync(); rs.Should().ContainSingle(); rs[0].L.Should().Be(3, "S is the receiver of Trim() and has to be loaded"); } [Fact] public async Task NullGuardOfProps_KeepsTheFieldValue() { await SyncAsync(); await SeedAsync(new ProjectionProbeProps { S = "guarded" }); var rs = await Redb.Query() .Select(x => new { x.Id, S = x.Props != null ? x.Props.S : null }) .ToListAsync(); rs.Should().ContainSingle(); rs[0].S.Should().Be("guarded"); } [Fact] public async Task BaseFieldsOnly_ReturnsTheirValues() { await SyncAsync(); var id = await SeedAsync(new ProjectionProbeProps { S = "base", N = 1 }, name: "base-only"); var ids = await Redb.Query().Select(x => x.Id).ToListAsync(); var rows = await Redb.Query().Select(x => new { x.Id, x.Name }).ToListAsync(); ids.Should().Equal(id); rows.Should().ContainSingle(); rows[0].Id.Should().Be(id); rows[0].Name.Should().Be("base-only"); } [Fact] public async Task SourceQuery_RunAgainAfterProjection_ReturnsWholeObjects() { // The projection used to write its settings into the query it was built from; the same // query run again as a list then returned objects with the projected fields only. await SyncAsync(); await SeedAsync(new ProjectionProbeProps { S = "reuse", N = 11, Flag = true }); var query = Redb.Query(); (await query.Select(x => x.Props.S).ToListAsync()).Should().Equal("reuse"); (await query.Select(x => x.Id).ToListAsync()).Should().ContainSingle(); var objects = await query.ToListAsync(); objects.Should().ContainSingle(); objects[0].Props.S.Should().Be("reuse"); objects[0].Props.N.Should().Be(11, "a projection run earlier over the same query must not strip its objects"); objects[0].Props.Flag.Should().BeTrue(); } // ============================================================ // === Ordering after Select: the source sorts, Select only shapes === // ============================================================ [Fact] public async Task OrderByAfterSelect_ThenTakeSkip_PagesInOrder() { // Select(...).OrderBy(...).Take(...) runs as OrderBy(...).Take(...).Select(...): the source sorts and // cuts the page, the projection shapes only the page. await SyncAsync(); foreach (var n in new[] { 7, 3, 9, 1, 5, 8, 2, 6, 4 }) await SeedAsync(new ProjectionProbeProps { S = $"p{n}", N = n }); var top = await Redb.Query() .Select(x => new { x.Props.N, x.Props.S }) .OrderByDescending(r => r.N) .Take(3) .ToListAsync(); top.Select(r => r.N).Should().Equal(9, 8, 7); var second = await Redb.Query() .Select(x => new { x.Props.N }) .OrderBy(r => r.N) .Skip(3) .Take(3) .ToListAsync(); second.Select(r => r.N).Should().Equal(4, 5, 6); } [Fact] public async Task ThenByAfterSelect_AddsAKey() { await SyncAsync(); await SeedAsync(new ProjectionProbeProps { S = "b", N = 1 }); await SeedAsync(new ProjectionProbeProps { S = "c", N = 2 }); await SeedAsync(new ProjectionProbeProps { S = "a", N = 1 }); var asc = await Redb.Query() .Select(x => new { x.Props.N, x.Props.S }) .OrderBy(r => r.N) .ThenBy(r => r.S) .ToListAsync(); asc.Select(r => $"{r.N}{r.S}").Should().Equal("1a", "1b", "2c"); var desc = await Redb.Query() .Select(x => new { x.Props.N, x.Props.S }) .OrderBy(r => r.N) .ThenByDescending(r => r.S) .Take(2) .ToListAsync(); desc.Select(r => $"{r.N}{r.S}").Should().Equal("1b", "1a"); } [Fact] public async Task OrderByAfterSelect_ObjectFieldAndNestedMember() { await SyncAsync(); var ids = new List(); foreach (var city in new[] { "Omsk", "Kazan", "Perm" }) ids.Add(await SeedAsync(new ProjectionProbeProps { S = city, Nested = new ProjectionProbeNested { City = city } })); var byId = await Redb.Query() .Select(x => new { x.Id, x.Props.S }) .OrderByDescending(r => r.Id) .Take(2) .ToListAsync(); byId.Select(r => r.Id).Should().Equal(ids.OrderByDescending(i => i).Take(2)); var byCity = await Redb.Query() .Select(x => new { City = x.Props.Nested!.City }) .OrderBy(r => r.City) .Take(2) .ToListAsync(); byCity.Select(r => r.City).Should().Equal("Kazan", "Omsk"); } [Fact] public async Task OrderByAfterSelect_ComputedKey_SortsInMemory() { // A key computed over Props members is not sent to the source; it sorts in memory, as before. await SyncAsync(); foreach (var n in new[] { 4, 1, 3, 2 }) await SeedAsync(new ProjectionProbeProps { S = $"p{n}", N = n }); var rs = await Redb.Query() .Select(x => new { Twice = x.Props.N * 2 }) .OrderByDescending(r => r.Twice) .Take(2) .ToListAsync(); rs.Select(r => r.Twice).Should().Equal(8, 6); } [Fact] public async Task ThenByAfterSelect_WithoutOrderBy_Throws() { await SyncAsync(); var act = () => Redb.Query() .Select(x => new { x.Props.N }) .ThenBy(r => r.N); act.Should().Throw().WithMessage("*OrderBy*"); } } Path: redb/redb.Tests.Integration/Tests/Base/PropertyRenameTestsBase.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/PropertyRenameTestsBase.cs ---- using redb.Core; using redb.Core.Exceptions; using redb.Core.Models.Entities; using redb.Core.Utils; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// [RedbRename] on properties: the sync renames the stored structure in place (same id, same values), a second /// sync does nothing, both names stored is an error, and a class older than the rename stops at its sync instead of /// adding the old name again. Every name-derived signature of the scheme is checked after the rename: the scheme hash, /// the cached scheme, the structure tree, the metadata cache table, and queries through it (the Pro field resolver on /// the Pro fixtures). /// public abstract class PropertyRenameTestsBase : IAsyncLifetime { protected readonly IRedbService Redb; protected PropertyRenameTestsBase(IRedbService redb) => Redb = redb; private static readonly string[] Schemes = [ typeof(RenameBasicV1).FullName!, typeof(RenameChainV1).FullName!, typeof(RenameJumpV1).FullName!, typeof(RenameBothV1).FullName!, typeof(RenameClashProps).FullName!, typeof(RenameReuseV1).FullName!, typeof(RenameTypeV1).FullName!, typeof(RenameHashV1).FullName!, typeof(RenameSwapV1).FullName!, typeof(RenameSwapOneStep).FullName!, ]; public async Task InitializeAsync() => await ResetAsync(); public async Task DisposeAsync() => await ResetAsync(); private async Task ResetAsync() { foreach (var name in Schemes) { await Redb.Context.ExecuteAsync( $"DELETE FROM _objects WHERE _id_scheme IN (SELECT _id FROM _schemes WHERE _name = '{name}')"); await Redb.Context.ExecuteAsync( $"DELETE FROM _structures WHERE _id_scheme IN (SELECT _id FROM _schemes WHERE _name = '{name}')"); await Redb.Context.ExecuteAsync($"DELETE FROM _schemes WHERE _name = '{name}'"); } Redb.Cache.Clear(); } private Task StructureIdAsync(string scheme, string name) => Redb.Context.ExecuteScalarAsync( $"SELECT _id FROM _structures WHERE _name = '{name}' AND _id_scheme = (SELECT _id FROM _schemes WHERE _name = '{scheme}')"); private Task RenamedFromAsync(long structureId) => Redb.Context.ExecuteScalarAsync($"SELECT _renamed_from FROM _structures WHERE _id = {structureId}"); /// /// The database as an intermediate class version left it after its rename: a second class claiming the same /// explicit scheme name would be a name conflict in one test assembly, so that sync is reproduced by SQL. /// private async Task StageRenameAsync(long structureId, string name, string renamedFrom) { await Redb.Context.ExecuteAsync( $"UPDATE _structures SET _name = '{name}', _renamed_from = '{renamedFrom}' WHERE _id = {structureId}"); Redb.Cache.Clear(); } private Task StructureCountAsync(string scheme) => Redb.Context.ExecuteScalarAsync( $"SELECT COUNT(*) FROM _structures WHERE _id_scheme = (SELECT _id FROM _schemes WHERE _name = '{scheme}')"); [Fact] public async Task Rename_KeepsStructuresAndValues_RootAndNested() { var scheme = typeof(RenameBasicV1).FullName!; await Redb.SyncSchemeAsync(); var obj = new RedbObject { name = "rename-basic", Props = new RenameBasicV1 { Title = "h1", Count = 7, Address = new RenameAddressV1 { City = "Paris", Street = "Rue" } }, }; obj.id = await Redb.SaveAsync(obj); var titleId = await StructureIdAsync(scheme, "Title"); var cityId = await StructureIdAsync(scheme, "City"); var structureCount = await StructureCountAsync(scheme); // Caches warmed under the old names: a query through every name-keyed path. (await Redb.Query().Where(x => x.Title == "h1" && x.Address.City == "Paris").CountAsync()).Should().Be(1); await Redb.SyncSchemeAsync(); (await StructureIdAsync(scheme, "Heading")).Should().Be(titleId, "the rename keeps the structure"); (await StructureIdAsync(scheme, "Town")).Should().Be(cityId, "a nested property is renamed the same way"); (await StructureIdAsync(scheme, "Title")).Should().BeNull(); (await StructureIdAsync(scheme, "City")).Should().BeNull(); (await StructureCountAsync(scheme)).Should().Be(structureCount, "nothing is added or deleted"); (await RenamedFromAsync(titleId!.Value)).Should().Be("[\"Title\"]"); (await RenamedFromAsync(cityId!.Value)).Should().Be("[\"City\"]"); var loaded = await Redb.LoadAsync(obj.id); loaded!.Props.Heading.Should().Be("h1"); loaded.Props.Address.Town.Should().Be("Paris"); loaded.Props.Address.Street.Should().Be("Rue"); loaded.Props.Count.Should().Be(7); (await Redb.Query().Where(x => x.Heading == "h1").CountAsync()).Should().Be(1); (await Redb.Query().Where(x => x.Address.Town == "Paris").CountAsync()).Should().Be(1); } [Fact] public async Task Rename_RecomputesOrInvalidatesEveryNameDerivedSignature() { var scheme = typeof(RenameBasicV1).FullName!; // SyncSchemeAsync returns the scheme as read back from _schemes after the sync: its hash is the stored one. var before = await Redb.SyncSchemeAsync(); var hashBefore = before.StructureHash; // Every cache filled under the old names first. (await Redb.GetSchemeByTypeAsync())!.Structures.Should().Contain(s => s.Name == "Title"); (await Redb.GetStructureTreeAsync(before.Id)).Should().Contain(n => n.Structure.Name == "Title"); var titleId = (await StructureIdAsync(scheme, "Title"))!.Value; var after = await Redb.SyncSchemeAsync(); after.Id.Should().Be(before.Id); var hashAfter = after.StructureHash; hashAfter.Should().NotBeNull(); hashAfter.Should().NotBe(hashBefore!.Value, "the scheme hash covers the names and is recomputed"); hashAfter.Should().Be(SchemeHashCalculator.ComputeSchemeStructureHash(after.Structures.Cast().ToList()), "the stored hash is the hash of the renamed structures"); var cached = await Redb.GetSchemeByTypeAsync(); cached!.StructureHash.Should().Be(hashAfter, "the cached scheme is replaced"); cached.Structures.Should().Contain(s => s.Id == titleId && s.Name == "Heading"); cached.Structures.Should().NotContain(s => s.Name == "Title" || s.Name == "City"); var tree = await Redb.GetStructureTreeAsync(after.Id); tree.Should().Contain(n => n.Structure.Id == titleId && n.Structure.Name == "Heading", "the tree cache is dropped"); tree.Single(n => n.Structure.Name == "Address").Children.Should().Contain(n => n.Structure.Name == "Town"); (await Redb.Context.ExecuteScalarAsync( $"SELECT _name FROM _scheme_metadata_cache WHERE _structure_id = {titleId}")) .Should().Be("Heading", "the metadata cache table is rebuilt"); (await Redb.Context.ExecuteScalarAsync( $"SELECT COUNT(*) FROM _scheme_metadata_cache WHERE _scheme_id = {after.Id} AND _name IN ('Title', 'City')")) .Should().Be(0); // A second sync is a no-op: the same hash, the same rows. (await Redb.SyncSchemeAsync()).StructureHash.Should().Be(hashAfter); (await RenamedFromAsync(titleId)).Should().Be("[\"Title\"]"); } [Fact] public async Task OldClass_AfterRename_StopsWithoutChanges() { var scheme = typeof(RenameBasicV1).FullName!; await Redb.SyncSchemeAsync(); var obj = new RedbObject { name = "rename-old-class", Props = new RenameBasicV1 { Title = "kept", Address = new RenameAddressV1 { City = "Rome" } }, }; obj.id = await Redb.SaveAsync(obj); await Redb.SyncSchemeAsync(); var structureCount = await StructureCountAsync(scheme); Redb.Cache.Clear(); var act = () => Redb.SyncSchemeAsync(); var error = (await act.Should().ThrowAsync()).Which; error.Name.Should().Be("RenameBasicV1.Title"); error.StoredNames.Should().Equal("Heading"); (await StructureIdAsync(scheme, "Title")).Should().BeNull("the old name is not added again"); (await StructureCountAsync(scheme)).Should().Be(structureCount, "nothing is deleted"); (await Redb.LoadAsync(obj.id))!.Props.Heading.Should().Be("kept"); } [Fact] public async Task OldClass_NestedRenameOnly_Stops() { var scheme = typeof(RenameBasicV1).FullName!; await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); // Only the nested rename is undone in the database: the root level matches the old class again. var headingId = (await StructureIdAsync(scheme, "Heading"))!.Value; await Redb.Context.ExecuteAsync($"UPDATE _structures SET _name = 'Title', _renamed_from = NULL WHERE _id = {headingId}"); Redb.Cache.Clear(); var act = () => Redb.SyncSchemeAsync(); var error = (await act.Should().ThrowAsync()).Which; error.Name.Should().Be("RenameAddressV1.City"); (await StructureIdAsync(scheme, "Town")).Should().NotBeNull(); } [Fact] public async Task Chain_StepByStep_KeepsEveryPreviousName() { var scheme = typeof(RenameChainV1).FullName!; await Redb.SyncSchemeAsync(); var obj = new RedbObject { name = "rename-chain", Props = new RenameChainV1 { Title = "c" } }; obj.id = await Redb.SaveAsync(obj); var id = (await StructureIdAsync(scheme, "Title"))!.Value; await StageRenameAsync(id, "Heading", "[\"Title\"]"); await Redb.SyncSchemeAsync(); (await StructureIdAsync(scheme, "Caption")).Should().Be(id); (await RenamedFromAsync(id)).Should().Be("[\"Title\",\"Heading\"]"); (await Redb.LoadAsync(obj.id))!.Props.Caption.Should().Be("c"); // The first class is two renames behind and still stops. Redb.Cache.Clear(); await FluentActions.Invoking(() => Redb.SyncSchemeAsync()) .Should().ThrowAsync(); (await StructureIdAsync(scheme, "Caption")).Should().Be(id); } [Fact] public async Task Chain_DatabaseThatMissedAVersion_IsRenamedToo() { var scheme = typeof(RenameJumpV1).FullName!; await Redb.SyncSchemeAsync(); var obj = new RedbObject { name = "rename-jump", Props = new RenameJumpV1 { Title = "j" } }; obj.id = await Redb.SaveAsync(obj); var id = (await StructureIdAsync(scheme, "Title"))!.Value; await Redb.SyncSchemeAsync(); (await StructureIdAsync(scheme, "Caption")).Should().Be(id); (await RenamedFromAsync(id)).Should().Be("[\"Title\"]"); (await Redb.LoadAsync(obj.id))!.Props.Caption.Should().Be("j"); } [Fact] public async Task BothNamesStored_IsAnError_AndChangesNothing() { var scheme = typeof(RenameBothV1).FullName!; await Redb.SyncSchemeAsync(); var titleId = (await StructureIdAsync(scheme, "Title"))!.Value; var headingId = (await StructureIdAsync(scheme, "Heading"))!.Value; var act = () => Redb.SyncSchemeAsync(); var error = (await act.Should().ThrowAsync()).Which; error.Name.Should().Be("RenameBothV2.Heading"); error.StoredNames.Should().Equal("Title"); (await StructureIdAsync(scheme, "Title")).Should().Be(titleId); (await StructureIdAsync(scheme, "Heading")).Should().Be(headingId); } [Fact] public async Task PreviousName_CarriedAgain_BeforeTheRenameIsApplied_IsADeclarationError() { // The database stores Title and not Heading: the stored Title could belong to the renamed Heading or to the // new Title. var scheme = typeof(RenameReuseV1).FullName!; await Redb.SyncSchemeAsync(); var id = (await StructureIdAsync(scheme, "Title"))!.Value; var structureCount = await StructureCountAsync(scheme); var act = () => Redb.SyncSchemeAsync(); (await act.Should().ThrowAsync()).Which.Message.Should().Contain("[RedbRename(\"Title\")]"); (await StructureIdAsync(scheme, "Title")).Should().Be(id); (await StructureCountAsync(scheme)).Should().Be(structureCount, "nothing is written"); } [Fact] public async Task PreviousName_CarriedAgain_InANewDatabase_CreatesBoth() { // A database created with the class: neither name is stored, both properties are new; the next sync is a no-op. var scheme = typeof(RenameClashProps).FullName!; var first = await Redb.SyncSchemeAsync(); var headingId = (await StructureIdAsync(scheme, "Heading"))!.Value; var titleId = (await StructureIdAsync(scheme, "Title"))!.Value; Redb.Cache.Clear(); (await Redb.SyncSchemeAsync()).StructureHash.Should().Be(first.StructureHash); (await StructureIdAsync(scheme, "Heading")).Should().Be(headingId); (await StructureIdAsync(scheme, "Title")).Should().Be(titleId); (await RenamedFromAsync(headingId)).Should().BeNull("a database created with the renamed class has no history"); } [Fact] public async Task FreedName_TakenByANewProperty_IsAllowed() { var scheme = typeof(RenameReuseV1).FullName!; await Redb.SyncSchemeAsync(); var id = (await StructureIdAsync(scheme, "Title"))!.Value; await StageRenameAsync(id, "Heading", "[\"Title\"]"); await Redb.SyncSchemeAsync(); (await StructureIdAsync(scheme, "Heading")).Should().Be(id); (await StructureIdAsync(scheme, "Title")).Should().NotBeNull().And.NotBe(id, "the freed name is a new property"); // The next sync is a no-op. Redb.Cache.Clear(); await Redb.SyncSchemeAsync(); (await StructureIdAsync(scheme, "Heading")).Should().Be(id); (await RenamedFromAsync(id)).Should().Be("[\"Title\"]"); // The class of the first version still stops: it lacks the renamed property. Redb.Cache.Clear(); await FluentActions.Invoking(() => Redb.SyncSchemeAsync()) .Should().ThrowAsync(); } [Fact] public async Task Rename_KeepsEveryStoredHash_RootAndNested() { // Root: Title -> Aaron moves the property before Alpha in name order. Nested: City -> Town moves it after // Street. The first name of the chain keeps both where they sorted, so no stored hash moves. await Redb.SyncSchemeAsync(); var flat = new RedbObject { name = "rename-hash-root", Props = new RenameHashV1 { Alpha = "a", Title = "t", Zulu = "z" }, }; flat.id = await Redb.SaveAsync(flat); await Redb.SyncSchemeAsync(); var nested = new RedbObject { name = "rename-hash-nested", Props = new RenameBasicV1 { Title = "h", Count = 3, Address = new RenameAddressV1 { City = "Oslo", Street = "Gate" } }, }; nested.id = await Redb.SaveAsync(nested); var flatHash = (await Redb.LoadAsync(flat.id))!.Hash; var nestedHash = (await Redb.LoadAsync(nested.id))!.Hash; var addressHash = RedbHash.ComputeForProps(nested.Props.Address); flatHash.Should().NotBeNull(); nestedHash.Should().NotBeNull(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); Redb.Cache.Clear(); var flatAfter = (await Redb.LoadAsync(flat.id))!; flatAfter.Props.Aaron.Should().Be("t"); flatAfter.Hash.Should().Be(flatHash); RedbHash.ComputeFor(flatAfter).Should().Be(flatHash, "the renamed class computes the hash that is stored"); var nestedAfter = (await Redb.LoadAsync(nested.id))!; nestedAfter.Props.Address.Town.Should().Be("Oslo"); RedbHash.ComputeFor(nestedAfter).Should().Be(nestedHash); RedbHash.ComputeForProps(nestedAfter.Props.Address).Should().Be(addressHash, "the content hash of the nested class (base row, unique keys) does not move either"); // An unchanged save keeps the stored hash. await Redb.SaveAsync(flatAfter); (await Redb.LoadAsync(flat.id))!.Hash.Should().Be(flatHash); } [Fact] public async Task Swap_ThroughATemporaryName_KeepsTheHashes_AndSavesTheValuesSwappedBack() { // Left and Right swap names through Tmp, one deployment per rename; the first two are staged by SQL, the class // of the third (RenameSwapV3) renames Tmp to Right. Ordered by the current names, the swapped class would hash // the swapped-back values exactly as the stored row, and a save that compares hashes would skip them. var scheme = typeof(RenameSwapV1).FullName!; await Redb.SyncSchemeAsync(); var obj = new RedbObject { name = "rename-swap", Props = new RenameSwapV1 { Left = "x", Right = "y" } }; obj.id = await Redb.SaveAsync(obj); var storedHash = (await Redb.LoadAsync(obj.id))!.Hash; var leftId = (await StructureIdAsync(scheme, "Left"))!.Value; var rightId = (await StructureIdAsync(scheme, "Right"))!.Value; await StageRenameAsync(leftId, "Tmp", "[\"Left\"]"); await StageRenameAsync(rightId, "Left", "[\"Right\"]"); await Redb.SyncSchemeAsync(); (await StructureIdAsync(scheme, "Right")).Should().Be(leftId); (await StructureIdAsync(scheme, "Left")).Should().Be(rightId); (await RenamedFromAsync(leftId)).Should().Be("[\"Left\",\"Tmp\"]"); (await RenamedFromAsync(rightId)).Should().Be("[\"Right\"]"); Redb.Cache.Clear(); var loaded = (await Redb.LoadAsync(obj.id))!; loaded.Props.Right.Should().Be("x"); loaded.Props.Left.Should().Be("y"); loaded.Hash.Should().Be(storedHash); RedbHash.ComputeFor(loaded).Should().Be(storedHash, "no stored hash moves across the swap"); loaded.Props.Right = "y"; loaded.Props.Left = "x"; RedbHash.ComputeFor(loaded)!.Value.Should().NotBe(storedHash!.Value, "the swapped-back values are a change"); await Redb.SaveAsync(loaded); Redb.Cache.Clear(); var reloaded = (await Redb.LoadAsync(obj.id))!; reloaded.Props.Right.Should().Be("y"); reloaded.Props.Left.Should().Be("x"); } [Fact] public async Task Swap_TwoRenamesInOneDeployment_IsRefusedByTheReuseRule() { // Only Left to Tmp is applied; the class of the last step arrives next, asking Right to Left and Tmp to Right // at once. The database stores Right and not Left: the stored Right could be the renamed one or the other. var scheme = typeof(RenameSwapV1).FullName!; await Redb.SyncSchemeAsync(); var leftId = (await StructureIdAsync(scheme, "Left"))!.Value; var rightId = (await StructureIdAsync(scheme, "Right"))!.Value; await StageRenameAsync(leftId, "Tmp", "[\"Left\"]"); var act = () => Redb.SyncSchemeAsync(); (await act.Should().ThrowAsync()).Which.Message .Should().Contain("the database stores 'Right' but not 'Left'"); (await StructureIdAsync(scheme, "Tmp")).Should().Be(leftId); (await StructureIdAsync(scheme, "Right")).Should().Be(rightId); } [Fact] public async Task Swap_InOneStep_IsADeclarationError_InANewDatabase() { var act = () => Redb.SyncSchemeAsync(); (await act.Should().ThrowAsync()).Which.Message .Should().Contain("swaps the two names in one step").And.Contain("temporary name"); (await StructureCountAsync(typeof(RenameSwapOneStep).FullName!)).Should().Be(0); } [Fact] public async Task Swap_InOneStep_IsADeclarationError_WithAHistory() { // The database already holds the swapped state with its history: the class is refused all the same, from the // declaration alone. var scheme = typeof(RenameSwapV1).FullName!; await Redb.SyncSchemeAsync(); var leftId = (await StructureIdAsync(scheme, "Left"))!.Value; var rightId = (await StructureIdAsync(scheme, "Right"))!.Value; await StageRenameAsync(leftId, "SwapTmp", "[\"Left\"]"); await StageRenameAsync(rightId, "Left", "[\"Right\"]"); await StageRenameAsync(leftId, "Right", "[\"Left\"]"); await Redb.Context.ExecuteAsync( $"UPDATE _schemes SET _name = '{typeof(RenameSwapOneStep).FullName}' WHERE _name = '{scheme}'"); Redb.Cache.Clear(); var act = () => Redb.SyncSchemeAsync(); (await act.Should().ThrowAsync()).Which.Message .Should().Contain("swaps the two names in one step"); (await StructureIdAsync(typeof(RenameSwapOneStep).FullName!, "Right")).Should().Be(leftId); (await StructureIdAsync(typeof(RenameSwapOneStep).FullName!, "Left")).Should().Be(rightId); } [Fact] public async Task History_WithAnotherFirstName_StopsWithoutChanges() { var scheme = typeof(RenameBasicV1).FullName!; await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); var headingId = (await StructureIdAsync(scheme, "Heading"))!.Value; // The history starts with a name the class does not declare first. await Redb.Context.ExecuteAsync($"UPDATE _structures SET _renamed_from = '[\"Caption\",\"Title\"]' WHERE _id = {headingId}"); Redb.Cache.Clear(); var act = () => Redb.SyncSchemeAsync(); var error = (await act.Should().ThrowAsync()).Which; error.Name.Should().Be("RenameBasicV2.Heading"); error.StoredNames.Should().Equal("Caption", "Title"); error.Message.Should().Contain("[RedbRename(\"Caption\")]"); (await StructureIdAsync(scheme, "Heading")).Should().Be(headingId); } [Fact] public async Task History_WithoutTheAttribute_StopsWithoutChanges() { // A renamed property whose class dropped [RedbRename]: its hashes would be computed in another order. var scheme = typeof(RenameTypeV1).FullName!; await Redb.SyncSchemeAsync(); var id = (await StructureIdAsync(scheme, "Count"))!.Value; await Redb.Context.ExecuteAsync($"UPDATE _structures SET _renamed_from = '[\"Amount\"]' WHERE _id = {id}"); Redb.Cache.Clear(); var act = () => Redb.SyncSchemeAsync(); var error = (await act.Should().ThrowAsync()).Which; error.Name.Should().Be("RenameTypeV1.Count"); error.Message.Should().Contain("declares none"); (await StructureIdAsync(scheme, "Count")).Should().Be(id); } [Fact] public async Task Chain_FirstRenameOfADatabaseCreatedMidChain_RecordsTheChainFromTheFirstName() { // The database was created by the class of the middle version (Heading): it has no history. Renaming it to // Caption records the chain from its first name, the name the hash canon sorts by. var scheme = typeof(RenameChainV1).FullName!; await Redb.SyncSchemeAsync(); var id = (await StructureIdAsync(scheme, "Title"))!.Value; await Redb.Context.ExecuteAsync($"UPDATE _structures SET _name = 'Heading' WHERE _id = {id}"); Redb.Cache.Clear(); await Redb.SyncSchemeAsync(); (await StructureIdAsync(scheme, "Caption")).Should().Be(id); (await RenamedFromAsync(id)).Should().Be("[\"Title\",\"Heading\"]"); } [Fact] public async Task RenameAndTypeChange_RenamesFirst_ThenMigratesTheType() { var scheme = typeof(RenameTypeV1).FullName!; await Redb.SyncSchemeAsync(); var obj = new RedbObject { name = "rename-type", Props = new RenameTypeV1 { Count = 42 } }; obj.id = await Redb.SaveAsync(obj); var id = (await StructureIdAsync(scheme, "Count"))!.Value; await Redb.SyncSchemeAsync(); (await StructureIdAsync(scheme, "Total")).Should().Be(id); (await Redb.LoadAsync(obj.id))!.Props.Total.Should().Be(42); } } Path: redb/redb.Tests.Integration/Tests/Base/PropsCacheHeaderTestsBase.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/PropsCacheHeaderTestsBase.cs ---- using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Core; using redb.Core.Extensions; using redb.Core.Models.Configuration; using redb.Core.Models.Entities; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// Cluster review of the props cache (2026-09-11). _hash used to cover Props only, while /// the header - name, note, value_*, value_unique, parent, owner, dates - was written on every /// save and never hashed: a save on another node could change the header without moving the /// hash, and the point load, answering from the cache, handed out a stale header with a valid /// hash. Now _hash covers the header too (full-object-hash plan), and the partial /// UPDATE _objects paths that bypass the save (tree move, trash) reset it. /// /// "Another node" here is a second ServiceProvider with its own cache domain on the same /// database - a real second process as far as the cache is concerned. Every test builds its own /// hosts: the shared fixtures run with the cache off. /// public abstract class PropsCacheHeaderTestsBase { /// /// Registers the provider on the options builder (Free or Pro, see ). /// Called once per node; a suite that prepares a database file must do so once per test, /// not per node - both nodes share one database. /// protected abstract void UseProvider(RedbOptionsBuilder options); protected virtual void Register(IServiceCollection services, Action configure) => services.AddRedb(configure); private ServiceProvider Build(string node) { var services = new ServiceCollection(); services.AddLogging(b => b.SetMinimumLevel(LogLevel.Warning)); Register(services, options => { UseProvider(options); options.Configure(c => { c.EnablePropsCache = true; c.SkipHashValidationOnCacheCheck = false; // One cache domain per node AND per suite: the Free and Pro suites of one database // run in parallel on the same connection string, and the hit counters are exact. c.CacheDomain = $"header-probe-{GetType().Name}-{node}"; }); }); return services.BuildServiceProvider(); } private static async Task BootAsync(ServiceProvider sp) { var redb = sp.GetRequiredService(); await redb.InitializeAsync(ensureCreated: true); await redb.SyncSchemeAsync(); await redb.InitializeTypeRegistryAsync(); ((RedbServiceBase)redb).PropsCache.Instance.Should().NotBeNull("the props cache must be active, or this test proves nothing"); return redb; } /// Saves a keyed object on node A and loads it once through the cache, so the next load is a hit. private static async Task SeedCachedAsync(IRedbService nodeA, string tag) { var id = await nodeA.SaveAsync(new RedbObject { name = "before", note = "note-before", ValueUnique = $"HP-{tag}-{Guid.NewGuid():N}", Props = new HeaderProbeProps { Title = "title" } }); // The save caches the very instance it wrote; evict, so the first load goes to the // database through the caching path and the next one is a validated hit. ((RedbServiceBase)nodeA).PropsCache.Instance!.Clear(); (await nodeA.LoadAsync(id, depth: 1))!.name.Should().Be("before"); return id; } /// Node B changes the HEADER only, through the library; the Props stay as they are. private static async Task HeaderChangedOnNodeBAsync(IRedbService nodeB, long id) { var theirs = (await nodeB.LoadAsync(id, depth: 1))!; theirs.name = "after"; theirs.note = "note-after"; theirs.ValueUnique = $"HP-after-{Guid.NewGuid():N}"; await nodeB.SaveAsync(theirs); return theirs.ValueUnique; } private static void AssertFreshHeader(RedbObject? served, string expectedKey) { served.Should().NotBeNull(); served!.name.Should().Be("after", "a header change on another node moves _hash, so the cached copy must not be served"); served.note.Should().Be("note-after"); served.ValueUnique.Should().Be(expectedKey, "the object key is header state and must be as fresh as the name"); served.Props.Title.Should().Be("title"); } [Fact] public async Task HeaderChange_OnAnotherNode_IsSeenByThePointLoad() { await using var spA = Build("a"); await using var spB = Build("b"); var nodeA = await BootAsync(spA); var nodeB = await BootAsync(spB); var id = await SeedCachedAsync(nodeA, "async"); var newKey = await HeaderChangedOnNodeBAsync(nodeB, id); AssertFreshHeader(await nodeA.LoadAsync(id, depth: 1), newKey); } [Fact] public async Task HeaderChange_OnAnotherNode_IsSeenByTheSyncPointLoad() { // The thread-pool-free twin (RedbListItem.Object's road) has its own hit branch. await using var spA = Build("a"); await using var spB = Build("b"); var nodeA = await BootAsync(spA); var nodeB = await BootAsync(spB); var id = await SeedCachedAsync(nodeA, "sync"); var newKey = await HeaderChangedOnNodeBAsync(nodeB, id); AssertFreshHeader(nodeA.Load(id, depth: 1), newKey); } [Fact] public async Task UnchangedObject_IsServedFromTheCache() { // The other side of the contract: the header is covered by the hash, so an untouched // object still costs one narrow probe and no reload. await using var spA = Build("a"); var nodeA = await BootAsync(spA); var id = await SeedCachedAsync(nodeA, "hit"); var cache = ((RedbServiceBase)nodeA).PropsCache; var first = await nodeA.LoadAsync(id, depth: 1); var hitsBefore = cache.GetStats().HitCount; var again = await nodeA.LoadAsync(id, depth: 1); cache.GetStats().HitCount.Should().Be(hitsBefore + 1, "nothing changed - the load must be a validated hit"); again.Should().BeSameAs(first, "a hit serves the cached instance whole"); } [Fact] public async Task Move_OnAnotherNode_IsSeenByThePointLoad() { // A tree move is a partial UPDATE of the row outside the save path: it must reset _hash, // or a cached copy would keep answering with the old parent. await using var spA = Build("a"); await using var spB = Build("b"); var nodeA = await BootAsync(spA); var nodeB = await BootAsync(spB); var oldParent = await nodeA.SaveAsync(new RedbObject { name = "old-parent", Props = new HeaderProbeProps { Title = "p1" } }); var newParent = await nodeA.SaveAsync(new RedbObject { name = "new-parent", Props = new HeaderProbeProps { Title = "p2" } }); var childId = await nodeA.SaveAsync(new RedbObject { name = "child", parent_id = oldParent, Props = new HeaderProbeProps { Title = "c" } }); ((RedbServiceBase)nodeA).PropsCache.Instance!.Clear(); (await nodeA.LoadAsync(childId, depth: 1))!.parent_id.Should().Be(oldParent); var theirs = (await nodeB.LoadAsync(childId, depth: 1))!; await nodeB.MoveObjectAsync(theirs, new RedbObject { id = newParent }); (await nodeA.LoadAsync(childId, depth: 1))!.parent_id.Should().Be(newParent, "a move on another node resets the hash, so the cached copy with the old parent must not be served"); } [Fact] public async Task TreeLoads_CarryTheObjectKey() { // The row-to-object mappers and tree conversions had not learned value_unique (found by // the header pins on the way). await using var spA = Build("a"); var redb = await BootAsync(spA); var rootKey = $"HP-root-{Guid.NewGuid():N}"; var childKey = $"HP-child-{Guid.NewGuid():N}"; var rootId = await redb.SaveAsync(new RedbObject { name = "root", ValueUnique = rootKey, Props = new HeaderProbeProps { Title = "root" } }); await redb.SaveAsync(new RedbObject { name = "child", parent_id = rootId, ValueUnique = childKey, Props = new HeaderProbeProps { Title = "child" } }); var root = (await redb.LoadAsync(rootId, depth: 1))!; var typed = await redb.LoadTreeAsync(root, maxDepth: 2); typed.ValueUnique.Should().Be(rootKey, "the typed tree root is converted from the loaded object and must keep its key"); typed.Children.Single().ValueUnique.Should().Be(childKey, "typed children are mapped from rows and must keep their key"); var poly = await redb.LoadPolymorphicTreeAsync(root, maxDepth: 2); poly.ValueUnique.Should().Be(rootKey, "the polymorphic root goes through the dynamic mapper and must keep its key"); poly.Children.Single().ValueUnique.Should().Be(childKey); } } Path: redb/redb.Tests.Integration/Tests/Base/PropsCacheSkipValidationTestsBase.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/PropsCacheSkipValidationTestsBase.cs ---- using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Core; using redb.Core.Extensions; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using redb.Tests.Integration.Helpers; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// The props cache under SkipHashValidationOnCacheCheck: a /// standalone application that trusts its own writes. Every write of the process must still reach the cache, and a load /// by a list of ids must use the cache in both modes with one query for the whole batch - it is the road of the list-item /// preload and of LoadLinkedObjectsAsync. /// public abstract class PropsCacheSkipValidationTestsBase { private readonly SqlRecorder _recorder = new(); protected abstract void UseProvider(RedbOptionsBuilder options); protected virtual void Register(IServiceCollection services, Action configure) => services.AddRedb(configure); private ServiceProvider Build(bool skipHashValidation) { var services = new ServiceCollection(); services.AddLogging(b => b.SetMinimumLevel(LogLevel.Warning)); Register(services, options => { UseProvider(options); options.Configure(c => { c.EnablePropsCache = true; c.SkipHashValidationOnCacheCheck = skipHashValidation; // A props cache lives per domain for the process: one domain per suite and per mode. c.CacheDomain = $"props-cache-skip-{GetType().Name}-{(skipHashValidation ? "skip" : "validate")}"; }); }); RecordingRedbContext.Decorate(services, _recorder); return services.BuildServiceProvider(); } private static string NewTag() => Guid.NewGuid().ToString("N")[..8]; private static async Task BootAsync(IRedbService redb) { await redb.InitializeAsync(ensureCreated: true); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.InitializeTypeRegistryAsync(); } [Fact] public async Task MovedObject_LoadsWithItsNewParent_WhenHashValidationIsSkipped() { await using var sp = Build(skipHashValidation: true); await using var scope = sp.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); await BootAsync(redb); var tag = NewTag(); var parentA = new RedbObject { name = $"skip-parent-a-{tag}", Props = new SimpleProps { Title = "a" } }; parentA.id = await redb.SaveAsync(parentA); var parentB = new RedbObject { name = $"skip-parent-b-{tag}", Props = new SimpleProps { Title = "b" } }; parentB.id = await redb.SaveAsync(parentB); // A plain object under a parent: what CreateChildAsync writes, saved as RedbObject so that the stored hash // is the one the loaded object recomputes (a TreeRedbObject stores a different hash - see the plan, §11). var child = new RedbObject { name = $"skip-child-{tag}", parent_id = parentA.id, Props = new SimpleProps { Title = "child" } }; child.id = await redb.SaveAsync(child); var before = (await redb.LoadAsync(child.id))!; before.parent_id.Should().Be(parentA.id, "precondition: the child hangs under its first parent"); (await redb.LoadAsync(child.id)).Should().BeSameAs(before, "precondition: the second load is a cache hit - the scenario is about a cached object"); await redb.MoveObjectAsync(child, parentB); var after = (await redb.LoadAsync(child.id))!; after.parent_id.Should().Be(parentB.id, "a move bypasses the save path: the database drops the object's hash, and the cached copy must go with it - " + "without hash validation a load never asks the database"); } /// /// An object saved as - every CreateChildAsync, every tree node - stored a /// header-only hash: the save recognised the exact generic type RedbObject<> and nothing derived from it. /// The loaded RedbObject<T> hashes header and Props, so the cache never served such objects. /// [Theory] [InlineData("SaveAsync")] [InlineData("CreateChildAsync")] public async Task ObjectSavedAsATreeObject_IsServedFromTheCache(string road) { await using var sp = Build(skipHashValidation: false); await using var scope = sp.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); await BootAsync(redb); var tag = NewTag(); var node = new TreeRedbObject { name = $"tree-{road}-{tag}", Props = new TreeNodeProps { Name = "n", Code = "N", Budget = 1000000m } }; if (road == "SaveAsync") { node.id = await redb.SaveAsync(node); } else { var parent = new RedbObject { name = $"tree-parent-{tag}", Props = new SimpleProps { Title = "p" } }; parent.id = await redb.SaveAsync(parent); node.id = await redb.CreateChildAsync(node, parent); } var first = (await redb.LoadAsync(node.id))!; first.hash.Should().Be(first.ComputeHash(), "the hash the save stored is the one the loaded object recomputes - otherwise every cache probe of the object is a miss"); var second = (await redb.LoadAsync(node.id))!; second.Should().BeSameAs(first, "the second load of an unchanged object is a cache hit"); } [Theory] [InlineData(false)] [InlineData(true)] public async Task BatchLoadOfCachedObjects_IssuesOneQuery_AndServesTheCachedInstances(bool skipHashValidation) { await using var sp = Build(skipHashValidation); await using var scope = sp.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); await BootAsync(redb); var tag = NewTag(); var ids = new long[5]; for (var i = 0; i < ids.Length; i++) ids[i] = await redb.SaveAsync(new RedbObject { name = $"skip-batch-{tag}-{i}", Props = new SimpleProps { Title = $"batch-{i}" } }); // Warm the cache the way any single load does. var warmed = new Dictionary(); foreach (var id in ids) warmed[id] = (await redb.LoadAsync(id))!; _recorder.Start(); var loaded = await redb.LoadAsync(ids); var commands = _recorder.Stop(); loaded.Should().HaveCount(ids.Length); loaded.Should().OnlyContain(o => ReferenceEquals(o, warmed[o.Id]), "every object of the batch is in the cache: the load serves the cached instances instead of materializing again"); commands.Should().HaveCount(1, "one query resolves the hashes of the whole batch (the polymorphic load needs the schemes anyway); the cache answers the rest"); } } Path: redb/redb.Tests.Integration/Tests/Base/PropsCacheTransactionKeepTestsBase.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/PropsCacheTransactionKeepTestsBase.cs ---- using System.Transactions; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Core; using redb.Core.Exceptions; using redb.Core.Extensions; using redb.Core.Models.Entities; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// A shared instance inside a transaction (owner decision 2026-09-17, replacing the rule of 2026-09-15). While the /// transaction has written nothing, what its connection reads is committed state, so a shared instance keeps the lazy /// reference it loads - the writer's edit of root.Props.Next.Props followed by SaveAsync(root.Props.Next) /// is saved, whether the root was loaded before the transaction or served from the cache inside it - and forgets it /// if the transaction rolls back. Once the transaction has written, what it reads may be its own uncommitted work: /// the shared instance keeps nothing of it, and saving that stub is refused loudly. /// public abstract class PropsCacheTransactionKeepTestsBase { protected abstract void UseProvider(RedbOptionsBuilder options); protected virtual void Register(IServiceCollection services, Action configure) => services.AddRedb(configure); private ServiceProvider Build(string domain) { var services = new ServiceCollection(); services.AddLogging(b => b.SetMinimumLevel(LogLevel.Warning)); Register(services, options => { UseProvider(options); options.Configure(c => { c.EnablePropsCache = true; c.CacheDomain = $"props-cache-keep-{GetType().Name}-{domain}"; // The objects behind list items load on first touch, not with the list: the list fact reads item.Object // inside the transaction. c.PreloadListItemLinkedObjects = false; }); }); return services.BuildServiceProvider(); } private static string NewTag() => Guid.NewGuid().ToString("N")[..8]; private static async Task BootAsync(IRedbService redb) { await redb.InitializeAsync(ensureCreated: true); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.InitializeTypeRegistryAsync(); } /// Seeds and loads the root once, so the root the test gets is the cached, shared instance. private static async Task<(long RootId, long NextId)> SeedSharedChainAsync(IRedbService redb, string tag) { var nextId = await redb.SaveAsync(new RedbObject { name = $"keep-next-{tag}", Props = new LazyNodeProps { Label = "v1" } }); var rootId = await redb.SaveAsync(new RedbObject { name = $"keep-root-{tag}", Props = new LazyNodeProps { Label = "root", Next = new RedbObject { id = nextId } } }); // The save does not cache a graph holding a hand-made reference ({ id = nextId }, no header); the load does, // with the reference as a stub that carries its header. await redb.LoadAsync(rootId, depth: 1); return (rootId, nextId); } private static async Task> LoadSharedRootAsync(IRedbService redb, long rootId) { var root = (await redb.LoadAsync(rootId, depth: 1))!; root.Props.Next!.IsPropsLoaded.Should().BeFalse("precondition: at depth 1 the reference is a stub"); (await redb.LoadAsync(rootId, depth: 1)).Should().BeSameAs(root, "precondition: the root is served from the cache - a shared instance"); return root; } private static async Task LabelInAFreshScopeAsync(ServiceProvider sp, long id) { await using var scope = sp.CreateAsyncScope(); var reloaded = await scope.ServiceProvider.GetRequiredService().LoadAsync(id); return reloaded!.Props.Label; } [Fact] public async Task AnEditOfALazyReference_OfAnObjectLoadedBeforeTheTransaction_IsSaved() { await using var sp = Build("before"); await using var scope = sp.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); await BootAsync(redb); var (rootId, nextId) = await SeedSharedChainAsync(redb, NewTag()); var root = await LoadSharedRootAsync(redb, rootId); await redb.Context.ExecuteAtomicAsync(async () => { root.Props.Next!.Props.Label = "v2"; await redb.SaveAsync(root.Props.Next); }); (await LabelInAFreshScopeAsync(sp, nextId)).Should().Be("v2", "the transaction had written nothing when the reference loaded: what it read is committed state, kept on the instance"); } [Fact] public async Task AnEditOfALazyReference_OfACachedObject_InsideACleanTransaction_IsSaved() { await using var sp = Build("clean"); await using var scope = sp.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); await BootAsync(redb); var (rootId, nextId) = await SeedSharedChainAsync(redb, NewTag()); await redb.Context.ExecuteAtomicAsync(async () => { var root = await LoadSharedRootAsync(redb, rootId); root.Props.Next!.Props.Label = "v2"; await redb.SaveAsync(root.Props.Next); }); (await LabelInAFreshScopeAsync(sp, nextId)).Should().Be("v2"); } [Fact] public async Task AnEditOfALazyReference_OfACachedObject_InsideACleanAmbientTransaction_IsSaved() { await using var sp = Build("clean-ambient"); await using var scope = sp.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); await BootAsync(redb); var (rootId, nextId) = await SeedSharedChainAsync(redb, NewTag()); using (var tx = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) { var root = await LoadSharedRootAsync(redb, rootId); root.Props.Next!.Props.Label = "v2"; await redb.SaveAsync(root.Props.Next); tx.Complete(); } (await LabelInAFreshScopeAsync(sp, nextId)).Should().Be("v2"); } /// /// The boundary of the rule: after the transaction has written, what its connection reads may be its own /// uncommitted work, so the shared instance keeps nothing - and saving the stub is refused, never a fresh reload. /// [Fact] public async Task AnEditOfALazyReference_AfterAWriteInTheTransaction_IsRefusedAtSave() { await using var sp = Build("dirty"); await using var scope = sp.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); await BootAsync(redb); var (rootId, _) = await SeedSharedChainAsync(redb, NewTag()); await redb.Context.ExecuteAtomicAsync(async () => { await redb.SaveAsync(new RedbObject { name = $"keep-write-{NewTag()}", Props = new SimpleProps { Title = "written" } }); var root = await LoadSharedRootAsync(redb, rootId); root.Props.Next!.Props.Label = "v2"; root.Props.Next.IsPropsLoaded.Should().BeFalse("a shared stub keeps nothing a writing transaction reads"); var act = async () => await redb.SaveAsync(root.Props.Next); await act.Should().ThrowAsync(); }); } [Fact] public async Task ALazyLoadKeptInsideARolledBackTransaction_IsForgotten() { await using var sp = Build("rollback"); await using var scope = sp.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); await BootAsync(redb); var (rootId, _) = await SeedSharedChainAsync(redb, NewTag()); var root = await LoadSharedRootAsync(redb, rootId); var act = async () => await redb.Context.ExecuteAtomicAsync(async () => { root.Props.Next!.Props.Label.Should().Be("v1"); root.Props.Next.IsPropsLoaded.Should().BeTrue("inside a clean transaction the shared stub keeps what it loaded"); await Task.Yield(); throw new InvalidOperationException("boom"); }); await act.Should().ThrowAsync().WithMessage("boom"); root.Props.Next!.IsPropsLoaded.Should().BeFalse("what a rolled-back transaction loaded is forgotten"); root.Props.Next.Props.Label.Should().Be("v1", "the next read loads again"); } [Fact] public async Task AnEditOfAListItemObject_OfACachedList_InsideATransaction_IsSaved() { await using var sp = Build("list"); await using var scope = sp.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); await BootAsync(redb); var tag = NewTag(); var objectId = await redb.SaveAsync(new RedbObject { name = $"keep-item-{tag}", Props = new SimpleProps { Title = "v1" } }); var list = await redb.ListProvider.SaveListAsync(RedbList.Create($"keep-list-{tag}", "keep")); await redb.ListProvider.SaveListItemAsync(new RedbListItem { IdList = list.Id, Value = "linked", IdObject = objectId }); // Cached - and so shared - before the transaction. var items = await redb.ListProvider.GetListItemsAsync(list.Id); (await redb.ListProvider.GetListItemsAsync(list.Id)).Should().BeSameAs(items, "precondition: the list is served from the cache"); await redb.Context.ExecuteAtomicAsync(async () => { var item = items.Single(); ((RedbObject)item.Object!).Props.Title = "v2"; await redb.SaveAsync((RedbObject)item.Object!); }); await using var reader = sp.CreateAsyncScope(); var reloaded = await reader.ServiceProvider.GetRequiredService().LoadAsync(objectId); reloaded!.Props.Title.Should().Be("v2", "item.Object read twice inside a clean transaction is one instance"); } } Path: redb/redb.Tests.Integration/Tests/Base/PropsCacheTransactionTestsBase.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/PropsCacheTransactionTestsBase.cs ---- using System.Transactions; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Core; using redb.Core.Exceptions; using redb.Core.Extensions; using redb.Core.Models.Entities; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// The props cache and the list cache publish committed state only (review after 4.0.0, findings 1-2). A cache Set /// marked the graph shared at once, and a shared instance does not keep what one transaction saw (owner decision /// 2026-09-15) - so inside a transaction the writer's own loaded object never kept its lazy references either: /// root.Props.Next.Props.Label = ...; SaveAsync(root.Props.Next) saved a fresh reload and the edit was lost, and /// every read of item.Object was a query. Now a Set inside a transaction waits for its commit: until then the /// instance is the writer's own, and a rolled-back transaction leaves nothing in the cache. /// public abstract class PropsCacheTransactionTestsBase { private readonly SqlRecorder _recorder = new(); protected abstract void UseProvider(RedbOptionsBuilder options); protected virtual void Register(IServiceCollection services, Action configure) => services.AddRedb(configure); private ServiceProvider Build(string domain, bool skipHashValidation = false) { var services = new ServiceCollection(); services.AddLogging(b => b.SetMinimumLevel(LogLevel.Warning)); Register(services, options => { UseProvider(options); options.Configure(c => { c.EnablePropsCache = true; c.SkipHashValidationOnCacheCheck = skipHashValidation; c.CacheDomain = $"props-cache-tx-{GetType().Name}-{domain}"; }); }); RecordingRedbContext.Decorate(services, _recorder); return services.BuildServiceProvider(); } private static string NewTag() => Guid.NewGuid().ToString("N")[..8]; private static async Task BootAsync(IRedbService redb) { await redb.InitializeAsync(ensureCreated: true); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.InitializeTypeRegistryAsync(); } /// /// Seeds in a cache domain of its own: the objects reach the domain under test only through the loads of the test - the /// scenario is the writer's own load, not an instance served from the cache. /// private async Task<(long RootId, long NextId)> SeedChainInAnotherDomainAsync(string domain) { await using var seeder = Build($"{domain}-seed"); await using var scope = seeder.CreateAsyncScope(); var writer = scope.ServiceProvider.GetRequiredService(); await BootAsync(writer); return await SeedChainAsync(writer, NewTag()); } private static async Task<(long RootId, long NextId)> SeedChainAsync(IRedbService redb, string tag) { var nextId = await redb.SaveAsync(new RedbObject { name = $"cachetx-next-{tag}", Props = new LazyNodeProps { Label = "v1" } }); var rootId = await redb.SaveAsync(new RedbObject { name = $"cachetx-root-{tag}", Props = new LazyNodeProps { Label = "root", Next = new RedbObject { id = nextId } } }); return (rootId, nextId); } private static async Task EditNextAsync(IRedbService redb, long rootId, long nextId) { var root = (await redb.LoadAsync(rootId, depth: 1))!; root.Props.Next!.IsPropsLoaded.Should().BeFalse("precondition: at depth 1 the reference is a stub"); root.Props.Next.id.Should().Be(nextId, "precondition: the stub names the referenced object"); root.Props.Next._lazyLoader.Should().NotBeNull("precondition: the stub carries the loader of its database"); root.Props.Next.Props.Label = "v2"; await redb.SaveAsync(root.Props.Next); } private static async Task LabelInAFreshScopeAsync(ServiceProvider sp, long id) { await using var scope = sp.CreateAsyncScope(); var reloaded = await scope.ServiceProvider.GetRequiredService().LoadAsync(id); return reloaded!.Props.Label; } /// /// The instance a save caches is the caller's own graph, hand-made references included: a reference written as /// new RedbObject<T> { id = x } carried no loader, so a load served from the cache returned that very /// stub and its Props came back null - no query, no exception. The load path installs the loaders before /// the cache Set; the save path must too. /// [Fact] public async Task ASavedObjectServedFromTheCache_LoadsItsHandMadeReferences() { await using var sp = Build("saved"); await using var scope = sp.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); await BootAsync(redb); var (rootId, _) = await SeedChainAsync(redb, NewTag()); var served = (await redb.LoadAsync(rootId, depth: 1))!; served.Props.Next!._lazyLoader.Should().NotBeNull("a cached graph's stubs load on the reader's scope"); served.Props.Next.Props.Should().NotBeNull("the reference loads on first touch"); served.Props.Next.Props.Label.Should().Be("v1"); } [Fact] public async Task AnEditOfALazyReference_InsideAnExplicitTransaction_IsSaved() { await using var sp = Build("explicit"); await using var scope = sp.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); await BootAsync(redb); var (rootId, nextId) = await SeedChainInAnotherDomainAsync("explicit"); await redb.Context.ExecuteAtomicAsync(() => EditNextAsync(redb, rootId, nextId)); (await LabelInAFreshScopeAsync(sp, nextId)).Should().Be("v2", "the edit was made on the instance the save read: the object a writer loaded is not shared before its " + "transaction commits"); } [Fact] public async Task AnEditOfALazyReference_InsideAnAmbientTransaction_IsSaved() { await using var sp = Build("ambient"); await using var scope = sp.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); await BootAsync(redb); var (rootId, nextId) = await SeedChainInAnotherDomainAsync("ambient"); using (var tx = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) { await EditNextAsync(redb, rootId, nextId); tx.Complete(); } (await LabelInAFreshScopeAsync(sp, nextId)).Should().Be("v2"); } // A root served from the cache, edited through its stub inside a transaction: see PropsCacheTransactionKeepTestsBase - // kept while the transaction has written nothing, refused at save once it has (owner decision 2026-09-17). [Fact] public async Task ALoadInsideARolledBackTransaction_LeavesNoCacheEntry() { // Seeded in one cache domain, exercised in another: the object reaches the second cache only through the load // inside the transaction, if at all. long id; await using (var seeder = Build("rollback-seed", skipHashValidation: true)) await using (var seedScope = seeder.CreateAsyncScope()) { var writer = seedScope.ServiceProvider.GetRequiredService(); await BootAsync(writer); id = await writer.SaveAsync(new RedbObject { name = $"cachetx-rollback-{NewTag()}", Props = new SimpleProps { Title = "seed" } }); } await using var sp = Build("rollback", skipHashValidation: true); await using var scope = sp.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); await BootAsync(redb); var act = async () => await redb.Context.ExecuteAtomicAsync(async () => { await redb.LoadAsync(id); throw new InvalidOperationException("boom"); }); await act.Should().ThrowAsync(); _recorder.Start(); await redb.LoadAsync(id); var commands = _recorder.Stop(); commands.Should().NotBeEmpty( "nothing of a rolled-back transaction reaches the cache, so the next load reads the database - without hash " + "validation a cache hit would have read nothing"); } [Fact] public async Task AnEditOfAListItemObject_InsideATransaction_IsSaved() { await using var sp = Build("list"); await using var scope = sp.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); await BootAsync(redb); var tag = NewTag(); var objectId = await redb.SaveAsync(new RedbObject { name = $"cachetx-item-{tag}", Props = new SimpleProps { Title = "v1" } }); var list = await redb.ListProvider.SaveListAsync(RedbList.Create($"cachetx-list-{tag}", "cachetx")); await redb.ListProvider.SaveListItemAsync(new RedbListItem { IdList = list.Id, Value = "linked", IdObject = objectId }); await redb.Context.ExecuteAtomicAsync(async () => { var item = (await redb.ListProvider.GetListItemsAsync(list.Id)).Single(); ((RedbObject)item.Object!).Props.Title = "v2"; await redb.SaveAsync((RedbObject)item.Object!); }); await using var reader = sp.CreateAsyncScope(); var reloaded = await reader.ServiceProvider.GetRequiredService().LoadAsync(objectId); reloaded!.Props.Title.Should().Be("v2", "item.Object read twice inside a transaction is one instance: the items a reader loaded are not shared " + "before the transaction commits"); } } Path: redb/redb.Tests.Integration/Tests/Base/PropsDepthBoundaryTestsBase.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/PropsDepthBoundaryTestsBase.cs ---- using redb.Core; using redb.Core.Models.Entities; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// The props depth boundary of the Pro loader. With WithPropsDepth(1) every reference of the page comes back as /// a stub: the referenced object's base fields, no props, a loader for the first access. The loader read the values of /// the referenced objects (and their list items and the types) before its depth check and then dropped them, so a page /// of stubs paid for a page of loaded references. A reference at the boundary costs the read of its base fields only. /// public abstract class PropsDepthBoundaryTestsBase { protected readonly IRedbService Redb; protected PropsDepthBoundaryTestsBase(IRedbService redb) => Redb = redb; private async Task SaveNodeAsync(string label, long? nextId) => await Redb.SaveAsync(new RedbObject { name = label, Props = new LazyNodeProps { Label = label, Next = nextId is { } id ? new RedbObject { id = id } : null } }); private Task>> PageAsync(long id, int? propsDepth) { var query = Redb.Query().WhereRedb(o => o.Id == id); return (propsDepth is { } depth ? query.WithPropsDepth(depth) : query).ToListAsync(); } [Fact] public async Task AtDepthOne_ReferenceIsAStub_AndItsValuesAreNotRead() { await Redb.SyncSchemeAsync(); var tag = Guid.NewGuid().ToString("N")[..8]; var leafId = await SaveNodeAsync($"depth-leaf-{tag}", null); var withReference = await SaveNodeAsync($"depth-with-{tag}", leafId); var withoutReference = await SaveNodeAsync($"depth-without-{tag}", null); // Once each first: the scheme and type caches are filled before anything is counted. await PageAsync(withReference, 1); await PageAsync(withoutReference, 1); List>? page = null; var withCommands = await Helpers.CommandCounter.CountWithoutScalarsAsync(async () => page = await PageAsync(withReference, 1)); var withoutCommands = await Helpers.CommandCounter.CountWithoutScalarsAsync(() => PageAsync(withoutReference, 1)); var stub = page!.Single().Props.Next; stub.Should().NotBeNull("the reference is handed out at the boundary"); stub!.IsPropsLoaded.Should().BeFalse("props depth 1 leaves the reference a stub"); stub.GetPropsDirectly().Should().BeNull("a stub carries no props"); stub.id.Should().Be(leafId); stub.name.Should().Be($"depth-leaf-{tag}", "the stub carries the base fields of the referenced object"); (withCommands - withoutCommands).Should().Be(1, "a reference at the boundary costs the read of its base fields, not of its values, list items and types"); stub.Props!.Label.Should().Be($"depth-leaf-{tag}", "the stub still loads its props on first access"); } [Fact] public async Task AtDefaultDepth_ReferenceIsLoaded() { await Redb.SyncSchemeAsync(); var tag = Guid.NewGuid().ToString("N")[..8]; var leafId = await SaveNodeAsync($"depth-leaf-{tag}", null); var withReference = await SaveNodeAsync($"depth-with-{tag}", leafId); var reference = (await PageAsync(withReference, null)).Single().Props.Next; reference.Should().NotBeNull(); reference!.IsPropsLoaded.Should().BeTrue("below the boundary the referenced object is materialised"); reference.GetPropsDirectly()!.Label.Should().Be($"depth-leaf-{tag}"); } } Path: redb/redb.Tests.Integration/Tests/Base/PvtAuditTestsBase.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/PvtAuditTestsBase.cs ---- using redb.Core; using redb.Core.Models.Entities; using redb.Core.Query; using redb.Tests.Integration.Helpers; using redb.Tests.Integration.Models; using System.Text.RegularExpressions; namespace redb.Tests.Integration.Tests.Base; /// /// Audit suite for the PVT-vs-Pro parity matrix of the free and Pro query paths. /// /// Runs against both PostgresFixture (Free) and PostgresProFixture (Pro), /// so any regression on either side surfaces immediately. /// /// Skip-fact tests document known gaps that must be flipped to active when fixed. /// public abstract class PvtAuditTestsBase { protected readonly IRedbService Redb; protected readonly bool IsPro; protected PvtAuditTestsBase(IRedbService redb, bool isPro) { Redb = redb; IsPro = isPro; } // ──────────────────────────────────────────────────────────────────── // §2.x #2.1 — ListItem accessors // ──────────────────────────────────────────────────────────────────── private async Task<(List Ids, RedbListItem Active, RedbListItem Blocked)> SeedPersonsWithStatusAsync(string listName) { var existing = await Redb.ListProvider.GetListByNameAsync(listName); if (existing != null) { var oldItems = await Redb.ListProvider.GetListItemsAsync(existing.Id); if (oldItems.Count > 0) await Redb.Context.Bulk.BulkDeleteValuesByListItemIdsAsync(oldItems.Select(i => i.Id).ToList()); await Redb.ListProvider.DeleteListAsync(existing.Id); } var list = RedbList.Create(listName, listName); list = await Redb.ListProvider.SaveListAsync(list); var statuses = await Redb.ListProvider.AddItemsAsync(list, ["Active", "Blocked"]); var active = statuses.First(s => s.Value == "Active"); var blocked = statuses.First(s => s.Value == "Blocked"); var persons = Enumerable.Range(0, 6).Select(i => new RedbObject { name = $"AuditPerson_{i}", Props = new PersonProps { Name = $"Person{i}", Age = 20 + i, Email = $"p{i}@audit.test", Status = i % 2 == 0 ? active : blocked } }).ToList(); var ids = await Redb.SaveAsync(persons); for (int i = 0; i < persons.Count; i++) persons[i].id = ids[i]; return (ids, active, blocked); } [Fact] public async Task ListItem_StatusValue_FiltersByDisplayText() { var (_, _, _) = await SeedPersonsWithStatusAsync("AuditStatuses_ValueAccessor"); var results = await Redb.Query() .Where(p => p.Status!.Value == "Active") .ToListAsync(); results.Should().NotBeEmpty(); results.Should().AllSatisfy(r => r.Props.Status!.Value.Should().Be("Active")); } [Fact] public async Task ListItem_StatusId_FiltersByItemId() { var (_, active, _) = await SeedPersonsWithStatusAsync("AuditStatuses_IdAccessor"); var results = await Redb.Query() .Where(p => p.Status!.Id == active.Id) .ToListAsync(); results.Should().NotBeEmpty(); results.Should().AllSatisfy(r => r.Props.Status!.Id.Should().Be(active.Id)); } [Fact] public async Task ListItem_RolesAnyValue_FiltersByDisplayText() { var existing = await Redb.ListProvider.GetListByNameAsync("AuditRoles"); if (existing != null) { var oldItems = await Redb.ListProvider.GetListItemsAsync(existing.Id); if (oldItems.Count > 0) await Redb.Context.Bulk.BulkDeleteValuesByListItemIdsAsync(oldItems.Select(i => i.Id).ToList()); await Redb.ListProvider.DeleteListAsync(existing.Id); } var rolesList = RedbList.Create("AuditRoles", "AuditRoles"); rolesList = await Redb.ListProvider.SaveListAsync(rolesList); var roles = await Redb.ListProvider.AddItemsAsync(rolesList, ["Admin", "User", "Viewer"]); var adminItem = roles.First(r => r.Value == "Admin"); var userItem = roles.First(r => r.Value == "User"); var rolePersons = Enumerable.Range(0, 4).Select(i => new RedbObject { name = $"AuditRolePerson_{i}", Props = new PersonProps { Name = $"P{i}", Age = 30, Email = $"r{i}@audit.test", Roles = i % 2 == 0 ? [adminItem, userItem] : [userItem] } }).ToList(); await Redb.SaveAsync(rolePersons); var results = await Redb.Query() .Where(p => p.Roles!.Any(r => r.Value == "Admin")) .ToListAsync(); results.Should().NotBeEmpty(); results.Should().AllSatisfy(r => r.Props.Roles!.Any(x => x.Value == "Admin").Should().BeTrue()); } /// /// Direct e => e.Status == redbListItem must be rewritten by /// FacetFilterBuilder into a .Id-keyed facet (the field stores /// _listitem bigint, never display text). Verifies the C# provider /// already emits the correct ID-based payload — no PVT-side string lookup /// is needed. /// [Fact] public async Task ListItem_DirectInstanceComparison_RoutesThroughId() { var (_, active, _) = await SeedPersonsWithStatusAsync("AuditStatuses_DirectInstance"); var results = await Redb.Query() .Where(p => p.Status == active) .ToListAsync(); results.Should().NotBeEmpty(); results.Should().AllSatisfy(r => r.Props.Status!.Id.Should().Be(active.Id)); } // ──────────────────────────────────────────────────────────────────── // §3 H1 — Take(0) must return empty, not throw (CHANGELOG 2026-05-22) // ──────────────────────────────────────────────────────────────────── [Fact] public async Task Take_Zero_ReturnsEmpty_WithoutThrowing() { await TestDataFactory.SeedEmployees(Redb, 10); var results = await Redb.Query() .OrderBy(e => e.LastName) .Take(0) .ToListAsync(); results.Should().BeEmpty(); } [Fact] public async Task Take_Zero_ReturnsEmpty_OnTreeQuery() { await TestDataFactory.SeedEmployees(Redb, 6); var results = await Redb.TreeQuery() .OrderBy(e => e.LastName) .Take(0) .ToListAsync(); results.Should().BeEmpty(); } [Fact] public void Take_Negative_StillThrows() { var act = () => Redb.Query().Take(-1); act.Should().Throw(); } // ──────────────────────────────────────────────────────────────────── // §1 #2 / §3 #8 — DistinctBy on tree query (DISTINCT ON parity) // ──────────────────────────────────────────────────────────────────── [Fact] public async Task DistinctBy_DedupsByKey() { await TestDataFactory.SeedEmployees(Redb, 20); var distinct = await Redb.Query() .DistinctBy(e => e.Department) .ToListAsync(); var rawCount = await Redb.Query().CountAsync(); distinct.Select(r => r.Props.Department).Distinct().Count() .Should().Be(distinct.Count, "DistinctBy must yield one row per Department"); distinct.Count.Should().BeLessThanOrEqualTo(rawCount); } // ──────────────────────────────────────────────────────────────────── // §2.x #2.2 — Dict Tuple Key (ValueTuple keys serialized via RedbKeySerializer // to Base64-JSON; parser and storage share the same encoding, so query path // matches storage path 1:1). // ──────────────────────────────────────────────────────────────────── [Fact] public async Task DictTupleKey_PerformanceReviews_FiltersByCompositeKey() { // Seeder writes PerformanceReviews[(2024, "Q1")] = "Excellent" when i % 3 == 0, // otherwise "Good". With 12 employees that yields exactly 4 "Excellent" rows. await TestDataFactory.SeedEmployees(Redb, 12); var results = await Redb.Query() .Where(e => e.PerformanceReviews![ValueTuple.Create(2024, "Q1")] == "Excellent") .ToListAsync(); results.Should().NotBeEmpty(); results.Should().AllSatisfy(r => r.Props.PerformanceReviews![(2024, "Q1")].Should().Be("Excellent")); } // ──────────────────────────────────────────────────────────────────── // §2.x #2.3 — Object reference fields (RedbObject property). // Covers null-check semantics (most common real-world use). Nested-field // JOIN (e.g. e.CurrentProject.ProjectId > 0) requires cross-scheme JOIN // infrastructure in PVT and remains a deferred probe below. // ──────────────────────────────────────────────────────────────────── private async Task<(int WithProject, int WithoutProject, string Department)> SeedEmployeesWithProjectsAsync(string department) { const int total = 6; const int withProject = 4; // Phase 1: batch-save all projects to get their ids. var projects = Enumerable.Range(0, withProject).Select(i => new RedbObject { name = $"{department}_Project_{i:D2}", Props = new ProjectMetricsProps { ProjectId = 1000 + i, TasksCompleted = 5 + i, TasksTotal = 10 + i, Budget = 50_000d + i * 1000, TeamSize = 3 + i, Technologies = ["dotnet", "postgres"] } }).ToList(); var projectIds = await Redb.SaveAsync(projects); for (int i = 0; i < projects.Count; i++) projects[i].id = projectIds[i]; // Phase 2: build employees, wire their CurrentProject reference, batch-save. var employees = Enumerable.Range(0, total).Select(i => { var emp = TestDataFactory.CreateEmployee(i, department: department); if (i < withProject) emp.Props.CurrentProject = projects[i]; return emp; }).ToList(); await Redb.SaveAsync(employees); return (withProject, total - withProject, department); } [Fact] public async Task ObjectRef_CurrentProject_NotNull_Filters() { var (withProject, _, dept) = await SeedEmployeesWithProjectsAsync("AuditObjRefNotNull"); var results = await Redb.Query() .Where(e => e.Department == dept && e.CurrentProject != null) .ToListAsync(); results.Should().HaveCount(withProject); results.Should().AllSatisfy(r => r.Props.CurrentProject.Should().NotBeNull()); } [Fact] public async Task ObjectRef_CurrentProject_IsNull_Filters() { var (_, withoutProject, dept) = await SeedEmployeesWithProjectsAsync("AuditObjRefIsNull"); var results = await Redb.Query() .Where(e => e.Department == dept && e.CurrentProject == null) .ToListAsync(); results.Should().HaveCount(withoutProject); results.Should().AllSatisfy(r => r.Props.CurrentProject.Should().BeNull()); } [Fact(Skip = "Audit probe §2.3 (deferred) — nested-field through _id_object_ref " + "(e.CurrentProject!.Props.ProjectId > X) is NOT supported in either tier: " + "Free throws `pvt_resolve_field_path: nested segment \"Props\" not found`, " + "Pro throws `SchemeFieldResolver: Failed to resolve Props fields`. " + "Requires cross-scheme JOIN infrastructure in PVT and SchemeFieldResolver in Pro.")] public async Task ObjectRef_CurrentProject_NestedField_Filters() { var (_, _, dept) = await SeedEmployeesWithProjectsAsync("RefNested_" + Guid.NewGuid().ToString("N").Substring(0, 6)); var results = await Redb.Query() .Where(e => e.Department == dept && e.CurrentProject!.Props.ProjectId > 1001) .ToListAsync(); results.Should().HaveCount(2); } // ──────────────────────────────────────────────────────────────────── // §2.x #2.4 — Sql.Function whitelist. // The free PVT parser already routes Sql.Function("NAME", args) through // CustomFunctionExpression → FacetFilterBuilder → JSON {"$name": [...]}. // pvt_build_scalar_expr accepts only the hardcoded set of $-keys and raises // for anything else — so the whitelist is enforced by construction. // ──────────────────────────────────────────────────────────────────── [Fact] public async Task SqlFunction_Coalesce_Filters() { await TestDataFactory.SeedEmployees(Redb, 10); // Salary = 50000 + i*5000, so COALESCE(Salary, 0) > 80000 matches i in {7,8,9} → 3 rows. var results = await Redb.Query() .Where(e => Sql.Function("COALESCE", e.Salary, 0m) > 80000m) .ToListAsync(); results.Should().NotBeEmpty(); results.Should().AllSatisfy(r => r.Props.Salary.Should().BeGreaterThan(80000m)); } [Fact] public async Task SqlFunction_UnknownName_ThrowsWhitelistViolation() { await TestDataFactory.SeedEmployees(Redb, 3); var act = async () => await Redb.Query() .Where(e => Sql.Function("definitely_not_a_known_function_xyz", e.Age) > 0) .ToListAsync(); // Unknown $-keys hit the ELSE-branch of pvt_build_scalar_expr and trigger // RAISE EXCEPTION (Pro path throws its own NotSupportedException up front). await act.Should().ThrowAsync( "Sql.Function with non-whitelisted name must be rejected (no silent fallback)"); } // ──────────────────────────────────────────────────────────────────── // §1.x Phase 2.A — Coalesce operator (??) // Shared parser (BaseFilterExpressionParser) now emits CoalesceExpression // for ExpressionType.Coalesce. Free → {"$coalesce":[…]} (PVT 17_pvt_expr.sql), // Pro → COALESCE(a, b, …). Right-associative `a ?? b ?? c` is flattened // to a single n-ary node. // ──────────────────────────────────────────────────────────────────── [Fact] public async Task Coalesce_NullableDouble_FallsBackToConstant() { await TestDataFactory.SeedEmployees(Redb, 10); // (Rating ?? 0.0) > 3.5 // Pollution-resistant: assert every returned row satisfies the predicate // and that at least one row is returned (seeded data guarantees matches). var results = await Redb.Query() .Where(e => (e.Rating ?? 0.0) > 3.5) .ToListAsync(); results.Should().NotBeEmpty(); results.Should().AllSatisfy(r => (r.Props.Rating ?? 0.0).Should().BeGreaterThan(3.5)); // Cross-check: at least one row in the *full* dataset must violate the // predicate; otherwise the filter is trivially "always true" and we'd be // unable to distinguish a working filter from a no-op. var totalCount = await Redb.Query().CountAsync(); var failingCount = await Redb.Query() .Where(e => (e.Rating ?? 0.0) <= 3.5) .CountAsync(); failingCount.Should().BeGreaterThan(0, "the dataset must contain at least one row that fails the predicate, " + "otherwise this test cannot detect a no-op WHERE clause"); results.Count.Should().BeLessThan(totalCount); } [Fact] public async Task Coalesce_Chained_FlattensToNAry() { await TestDataFactory.SeedEmployees(Redb, 10); // EmployeeCode is null for i%3==0 (≈ 1/3 of rows). FirstName is always set. // (EmployeeCode ?? FirstName).Length > 100 is always false on seeded data // (FirstName lengths are short), so a working filter returns zero rows. // If the filter were a no-op we'd get the full dataset back. var results = await Redb.Query() .Where(e => (e.EmployeeCode ?? e.FirstName).Length > 100) .ToListAsync(); var totalCount = await Redb.Query().CountAsync(); totalCount.Should().BeGreaterThan(0); results.Should().BeEmpty( "predicate is universally false on seeded data — a non-empty result " + "indicates the chained `??` was not compiled into the WHERE clause"); } // ──────────────────────────────────────────────────────────────────── // §1.y Phase 2.B — Conditional ternary (?:) // Shared parser emits ConditionalValueExpression for C# ?:. // Free → {"$if":[cond, then, else]} (PVT 17_pvt_expr.sql), // Pro → (CASE WHEN cond THEN ifTrue ELSE ifFalse END). // ──────────────────────────────────────────────────────────────────── [Fact] public async Task Ternary_PropertyVsConstant_Filters() { await TestDataFactory.SeedEmployees(Redb, 12); // (e.IsRemote ? 1 : 0) == 1 → selects only remote employees. var results = await Redb.Query() .Where(e => (e.IsRemote ? 1 : 0) == 1) .ToListAsync(); var totalCount = await Redb.Query().CountAsync(); var nonRemoteCount = await Redb.Query() .Where(e => !e.IsRemote) .CountAsync(); nonRemoteCount.Should().BeGreaterThan(0, "the dataset must contain at least one non-remote row to prove the " + "ternary actually narrowed the result set"); results.Should().NotBeEmpty(); results.Should().AllSatisfy(r => r.Props.IsRemote.Should().BeTrue()); results.Count.Should().BeLessThan(totalCount); } [Fact] public async Task Ternary_NestedScalarBranches_Filters() { await TestDataFactory.SeedEmployees(Redb, 12); // (e.IsRemote ? e.Salary : e.Salary * 2m) > 200000m // For remote rows the bare Salary is compared to 200k; for non-remote // rows the doubled Salary is compared. Seeded salaries are well below // 200k so the bare-Salary branch never matches, while the doubled- // Salary branch matches a subset of non-remote rows — proving the // CASE branch selector follows the test column. var results = await Redb.Query() .Where(e => (e.IsRemote ? e.Salary : e.Salary * 2m) > 200000m) .ToListAsync(); var totalCount = await Redb.Query().CountAsync(); totalCount.Should().BeGreaterThan(0); results.Should().AllSatisfy(r => { var effective = r.Props.IsRemote ? r.Props.Salary : r.Props.Salary * 2m; effective.Should().BeGreaterThan(200000m); }); results.Count.Should().BeLessThan(totalCount); } // ──────────────────────────────────────────────────────────────────── // §1.z Phase 2.C — Multi-arg string functions // (Substring / Replace / IndexOf / PadLeft). // Shared parser emits MultiArgFunctionCallExpression; parser also // applies index translation (Substring start+1, IndexOf POSITION-1) // so SQL output matches C# semantics on both tiers. // Free → {"$substring":[...]}, {"$replace":[...]}, {"$indexof":[...]}, // {"$padleft":[...]}, {"$padright":[...]} (17_pvt_expr.sql). // Pro → SUBSTRING / REPLACE / POSITION / LPAD / RPAD. // ──────────────────────────────────────────────────────────────────── [Fact] public async Task StringFns_SubstringAndIndexOf_FiltersByEmployeeCode() { await TestDataFactory.SeedEmployees(Redb, 15); // EmployeeCode is null for index%3==0 (~1/3 of rows). The remaining // codes look like "EMP-0001", so Substring(0,3)=="EMP" and the // dash sits at position 3 (0-based) — IndexOf("-")==3. var query = Redb.Query(); var totalCount = await query.CountAsync(); var hits = await query .Where(e => e.EmployeeCode!.Substring(0, 3) == "EMP" && e.EmployeeCode!.IndexOf("-") == 3) .ToListAsync(); hits.Should().NotBeEmpty(); hits.Should().AllSatisfy(r => { r.Props.EmployeeCode.Should().NotBeNull(); r.Props.EmployeeCode!.Substring(0, 3).Should().Be("EMP"); r.Props.EmployeeCode!.IndexOf("-").Should().Be(3); }); hits.Count.Should().BeLessThan(totalCount, "rows with null EmployeeCode must be dropped by the props JOIN"); } [Fact] public async Task StringFns_ReplaceAndPadLeft_FiltersByLastName() { await TestDataFactory.SeedEmployees(Redb, 12); // LastName values are "Last000".."Last011" (7 chars). PadLeft(10) pads // with 3 spaces on the left -> " Last000". PG `LPAD(s, n)` truncates // when s is longer than n (C# PadLeft does not), so width MUST exceed // input length to keep C# and PG semantics aligned. // Replace("Last", "ZZZ") composes a second multi-arg call into the // same predicate. var query = Redb.Query(); var hits = await query .Where(e => e.LastName.PadLeft(10) == " Last000" && e.LastName.Replace("Last", "ZZZ") == "ZZZ000") .ToListAsync(); hits.Should().NotBeEmpty(); hits.Should().AllSatisfy(r => r.Props.LastName.Should().Be("Last000")); } [Fact] public async Task StringFns_PadLeft_DoesNotTruncate_LikeCSharp() { // Contract test for Phase 2.C.1: when the requested width is SMALLER // than the input string, C# PadLeft is a no-op (returns the original // string unchanged). Native PG LPAD/RPAD truncate in that case, so // both Free PVT ($padleft) and Pro emitter wrap the requested width // in GREATEST(length(s), n). Without that wrap this filter would // match zero rows because LPAD('Last000', 5) = 'Last0' != 'Last000'. await TestDataFactory.SeedEmployees(Redb, 5); var hits = await Redb.Query() .Where(e => e.LastName.PadLeft(5) == "Last000") .ToListAsync(); hits.Should().NotBeEmpty( "PG LPAD must not truncate when target width < input length"); hits.Should().AllSatisfy(r => r.Props.LastName.Should().Be("Last000")); } // ──────────────────────────────────────────────────────────────────── // §1.aa Phase 2.D — Math methods (Sqrt/Sign/Exp/Log/Log10/Pow + Round 2-arg) // Free → {"$sqrt":[…]} / {"$power":[…]} etc. (17_pvt_expr.sql), // Pro → SQRT()/POWER()/LN()/LOG(base,value) native PG. // ──────────────────────────────────────────────────────────────────── [Fact] public async Task MathFns_SqrtAndExp_FiltersByRating() { // Single-arg path: PropertyFunction.Sqrt, .Exp via FunctionCallExpression. // Rating values for 20 employees follow `i % 4 == 0 ? null : 3.0 + (i % 5) * 0.5`, // so the only Rating that satisfies BOTH (Sqrt(r) > 2 -> r > 4) AND // (Exp(r) > 100 -> r > ln(100) ≈ 4.605) is r = 5.0. // r = 5.0 happens at i % 5 == 4, excluding i % 4 == 0 → i ∈ {9, 14, 19}. await TestDataFactory.SeedEmployees(Redb, 20); var hits = await Redb.Query() .Where(e => e.Rating!.Value > 0 && Math.Sqrt(e.Rating!.Value) > 2.0 && Math.Exp(e.Rating!.Value) > 100.0) .ToListAsync(); hits.Should().NotBeEmpty(); hits.Should().AllSatisfy(r => { r.Props.Rating.Should().NotBeNull(); r.Props.Rating!.Value.Should().BeGreaterThan(4.605, "Exp(r) > 100 implies r > ln(100)"); }); } [Fact] public async Task MathFns_PowAndLog_FiltersByRating() { // Multi-arg path: PropertyFunction.Pow ($power) and .Log (1-arg natural log $ln). // Pow(r, 2) > 20 -> r > sqrt(20) ≈ 4.472. // Log(r) > 1.5 -> r > exp(1.5) ≈ 4.482. // Both reduce to r ∈ {4.5, 5.0} in the seeded distribution. await TestDataFactory.SeedEmployees(Redb, 20); var hits = await Redb.Query() .Where(e => e.Rating!.Value > 0 && Math.Pow(e.Rating!.Value, 2.0) > 20.0 && Math.Log(e.Rating!.Value) > 1.5) .ToListAsync(); hits.Should().NotBeEmpty(); hits.Should().AllSatisfy(r => { r.Props.Rating.Should().NotBeNull(); r.Props.Rating!.Value.Should().BeGreaterThan(4.48, "Log(r) > 1.5 implies r > exp(1.5)"); }); } // ──────────────────────────────────────────────────────────────────── // §1.ab Phase 2.E — DateTime methods (AddX, DayOfWeek, DayOfYear) // Free → {"$dateadd":["unit",date,n]} / {"$dayofyear":[date]} (17_pvt_expr.sql), // Pro → (date + n * INTERVAL '1 unit') / EXTRACT(DOY FROM date) native PG. // HireDate is seeded as `new DateTime(2020,1,1,…UTC).AddMonths(index)` // (TestDataFactory.cs:59) so dates for 20 employees span 2020-01 … 2021-08. // ──────────────────────────────────────────────────────────────────── [Fact] public async Task DateFns_AddYears_FiltersByHireDate() { // AddYears via MultiArgFunctionCallExpression → $dateadd / INTERVAL '1 year'. // HireDate.AddYears(10) >= 2031-01-01 ⇒ HireDate >= 2021-01-01 ⇒ index >= 12. await TestDataFactory.SeedEmployees(Redb, 20); var threshold = new DateTime(2031, 1, 1, 0, 0, 0, DateTimeKind.Utc); var hits = await Redb.Query() .Where(e => e.HireDate.AddYears(10) >= threshold) .ToListAsync(); hits.Should().NotBeEmpty( "HireDate seeded for >=12 months past 2020-01 satisfies the +10y threshold"); hits.Should().AllSatisfy(r => r.Props.HireDate.AddYears(10).Should().BeOnOrAfter(threshold)); } [Fact] public async Task DateFns_DayOfYearAndAddMonths_FiltersByHireDate() { // DayOfYear via FunctionCallExpression ($dayofyear / EXTRACT(DOY FROM ...)). // AddMonths via MultiArgFunctionCallExpression ($dateadd / INTERVAL '1 month'). // Seeded HireDates fall on the 1st-of-month so DOY=1 picks January rows only. await TestDataFactory.SeedEmployees(Redb, 20); var hits = await Redb.Query() .Where(e => e.HireDate.DayOfYear == 1 && e.HireDate.AddMonths(12).Year >= 2022) .ToListAsync(); hits.Should().NotBeEmpty(); hits.Should().AllSatisfy(r => { r.Props.HireDate.DayOfYear.Should().Be(1); r.Props.HireDate.AddMonths(12).Year.Should().BeGreaterThanOrEqualTo(2022); }); } // ───────────────────────────────────────────────────────────────── // §1.ac Phase 2.F — Regex methods (IsMatch / Replace) // Free → {"$expr":{"$regex":[...]}} / {"$regexreplace":[...,"g"]} (17_pvt_expr.sql) // Pro → PG '~' / '~*' / REGEXP_REPLACE(... , 'g') // LastName seeded as "Last000".."Last019"; FirstName as "Employee000".."Employee019". // ───────────────────────────────────────────────────────────────── [Fact] public async Task RegexFns_IsMatch_FiltersByLastName() { // Regex.IsMatch routes through ComparisonExpression with RegexMatch operator. // Pattern '^Last00[0-2]$' matches exactly Last000/Last001/Last002 → 3 rows. await TestDataFactory.SeedEmployees(Redb, 20); var pattern = "^Last00[0-2]$"; var hits = await Redb.Query() .Where(e => Regex.IsMatch(e.LastName, pattern)) .ToListAsync(); hits.Should().NotBeEmpty(); hits.Should().AllSatisfy(r => Regex.IsMatch(r.Props.LastName, pattern).Should().BeTrue()); } [Fact] public async Task RegexFns_Replace_FiltersByTransformedFirstName() { // Regex.Replace routes through MultiArgFunctionCallExpression(RegexReplace). // Strip digits from FirstName and compare against the literal stem 'Employee'. // All 20 seeded employees have FirstName like 'Employee00X', so all match. await TestDataFactory.SeedEmployees(Redb, 20); var hits = await Redb.Query() .Where(e => Regex.Replace(e.FirstName, "[0-9]+", "") == "Employee") .ToListAsync(); hits.Should().NotBeEmpty(); hits.Should().AllSatisfy(r => Regex.Replace(r.Props.FirstName, "[0-9]+", "").Should().Be("Employee")); } // ──────────────────────────────────────────────────────────────────── // §2 #7 — Property functions (lock at LINQ level) // ──────────────────────────────────────────────────────────────────── [Fact] public async Task PropertyFunction_StringLength_Filters() { await TestDataFactory.SeedEmployees(Redb, 15); var results = await Redb.Query() .Where(e => e.LastName.Length > 6) .Take(20) .ToListAsync(); results.Should().AllSatisfy(r => r.Props.LastName.Length.Should().BeGreaterThan(6)); } [Fact] public async Task PropertyFunction_ArrayCount_Filters() { await TestDataFactory.SeedEmployees(Redb, 15); var results = await Redb.Query() .Where(e => e.Skills!.Length >= 3) .Take(20) .ToListAsync(); results.Should().NotBeEmpty(); results.Should().AllSatisfy(r => r.Props.Skills!.Length.Should().BeGreaterThanOrEqualTo(3)); } [Fact] public async Task PropertyFunction_DictContainsKey_Filters() { await TestDataFactory.SeedEmployees(Redb, 10); var results = await Redb.Query() .Where(e => e.PhoneDirectory!.ContainsKey("desk")) .Take(20) .ToListAsync(); results.Should().NotBeEmpty(); results.Should().AllSatisfy(r => r.Props.PhoneDirectory!.Should().ContainKey("desk")); } } Path: redb/redb.Tests.Integration/Tests/Base/PvtPrefilterEquivalenceTestsBase.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/PvtPrefilterEquivalenceTestsBase.cs ---- using redb.Core; using redb.Core.Query; using redb.Core.Query.Aggregation; using redb.Tests.Integration.Helpers; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// Differential tests for the PVT prefilter (RedbServiceConfiguration.EnablePvtPrefilter). /// /// The prefilter narrows the object set BEFORE the pivot aggregate runs. It is built as a superset: /// it may let extra objects through, it may never lose one, and the authoritative filter stays above /// GROUP BY. So for every query the result must be identical with the prefilter on and off. /// /// Each test runs the same query twice against the same rows, flipping the flag in between, and /// compares the two answers. A divergence is a prefilter bug, never a reason to relax the assertion. /// The row form is destructive by nature: rows failing its predicate never reach the aggregate, so a /// pivot column left uncovered collapses to NULL and its object silently disappears. Catching exactly /// that is what this suite is for, which is why several cases deliberately put a field in ORDER BY or /// DISTINCT BY that the filter never mentions. /// /// Every ordered query ends with ThenByRedb(o => o.Id) before Take. The seed data repeats across /// tests in a collection, so Age, Salary and HireDate all carry ties, and a Take over a partial /// order returns an arbitrary slice that differs run to run. Without the tiebreak the assertions /// compare noise: MSSql alone produced five such false failures in one full run. /// public abstract class PvtPrefilterEquivalenceTestsBase { protected readonly IRedbService Redb; private bool _seeded; protected PvtPrefilterEquivalenceTestsBase(IRedbService redb) => Redb = redb; /// /// A page the leading form takes (a condition on the sort field that rejects NULL) ordered then by the object id /// (ThenByRedb). The streams branch of the form sorts by the id as well and must carry that column: on PostgreSQL and /// SQLite it did not, and the page failed with "column pvt._id does not exist". Pages with and without Skip, ascending /// and descending, must equal the ones with the prefilter off. /// [Fact] public async Task LeadingForm_ThenByObjectId_SameAnswers() { await SeedAsync(); var restore = Redb.Configuration.EnablePvtPrefilter; try { IRedbQueryable BySalary() => Redb.Query() .Where(e => e.Salary > 0m).OrderBy(e => e.Salary).ThenByRedb(o => o.Id); IRedbQueryable ByAgeDesc() => Redb.Query() .Where(e => e.Age >= 20).OrderByDescending(e => e.Age).ThenByRedb(o => o.Id); async Task AnswersAsync() => string.Join("; ", new[] { string.Join(",", (await BySalary().Take(10).ToListAsync()).Select(r => r.Id)), string.Join(",", (await BySalary().Skip(7).Take(10).ToListAsync()).Select(r => r.Id)), string.Join(",", (await ByAgeDesc().Take(10).ToListAsync()).Select(r => r.Id)), string.Join(",", (await ByAgeDesc().Skip(25).Take(10).ToListAsync()).Select(r => r.Id)), }); Redb.UpdateConfiguration(c => c.EnablePvtPrefilter = true); var on = await AnswersAsync(); Redb.UpdateConfiguration(c => c.EnablePvtPrefilter = false); var off = await AnswersAsync(); on.Should().Be(off, "the leading form changes the plan, not the page"); } finally { Redb.UpdateConfiguration(c => c.EnablePvtPrefilter = restore); } } /// /// A page with no filter, sorted descending by a field a quarter of the objects lack (Rating), is led by the index /// of values of that field: the objects without a value come last. Pages inside the values, one that crosses into /// the objects without a value and one past every object (the walk does not fill them, the other branch answers), /// with ThenBy and without; without a tiebreak only the sequence of sort values is compared. /// [Fact] public async Task LeadingForm_UnfilteredDescending_SameAnswers() { await SeedAsync(); var restore = Redb.Configuration.EnablePvtPrefilter; try { IRedbQueryable ByRating() => Redb.Query() .OrderByDescending(e => e.Rating).ThenByRedb(o => o.Id); IRedbQueryable ByRatingThenAge() => Redb.Query() .OrderByDescending(e => e.Rating).ThenBy(e => e.Age).ThenByRedb(o => o.Id); IRedbQueryable BySalary() => Redb.Query() .OrderByDescending(e => e.Salary); async Task AnswersAsync() { var rated = await Redb.Query().Where(e => e.Rating != null).CountAsync(); var total = await Redb.Query().CountAsync(); return string.Join("; ", new[] { string.Join(",", (await ByRating().Take(10).ToListAsync()).Select(r => r.Id)), string.Join(",", (await ByRating().Skip(7).Take(10).ToListAsync()).Select(r => r.Id)), string.Join(",", (await ByRating().Skip(rated - 4).Take(10).ToListAsync()).Select(r => r.Id)), string.Join(",", (await ByRating().Skip(total + 5).Take(10).ToListAsync()).Select(r => r.Id)), string.Join(",", (await ByRatingThenAge().Skip(3).Take(10).ToListAsync()).Select(r => r.Id)), string.Join(",", (await ByRatingThenAge().Skip(rated - 2).Take(5).ToListAsync()).Select(r => r.Id)), string.Join(",", (await BySalary().Take(10).ToListAsync()).Select(r => r.Props.Salary)), string.Join(",", (await BySalary().Skip(12).Take(10).ToListAsync()).Select(r => r.Props.Salary)), }); } Redb.UpdateConfiguration(c => c.EnablePvtPrefilter = true); var on = await AnswersAsync(); Redb.UpdateConfiguration(c => c.EnablePvtPrefilter = false); var off = await AnswersAsync(); on.Should().Be(off, "the walk of the index changes the plan, not the page"); } finally { Redb.UpdateConfiguration(c => c.EnablePvtPrefilter = restore); } } private async Task SeedAsync() { if (_seeded) return; await TestDataFactory.SeedEmployees(Redb, 40); _seeded = true; } /// /// Runs the same delegate twice, prefilter off then on, and restores the previous setting. /// private async Task<(T Off, T On)> BothAsync(Func> run) { var restore = Redb.Configuration.EnablePvtPrefilter; try { Redb.UpdateConfiguration(c => c.EnablePvtPrefilter = false); var off = await run(); Redb.UpdateConfiguration(c => c.EnablePvtPrefilter = true); var on = await run(); return (off, on); } finally { Redb.UpdateConfiguration(c => c.EnablePvtPrefilter = restore); } } private async Task AssertSameAsync(Func> build, string because) { await SeedAsync(); var (off, on) = await BothAsync(async () => { var rows = await build().ToListAsync(); return rows.Select(r => r.id).ToList(); }); on.Should().Equal(off, because); } // ────────────────────────────────────────────────────────────────── // The flag must actually reach the query provider // ────────────────────────────────────────────────────────────────── /// /// Guards the whole suite against a false green. If the configuration object the service exposes /// were a different instance from the one the query provider reads, every test below would compare /// two identical runs and pass without testing anything. /// [Fact] public async Task Flag_ChangesGeneratedSql() { await SeedAsync(); var (off, on) = await BothAsync(() => Redb.Query() .Where(e => e.Position.Contains("Developer") || e.Department.Contains("Engineering")) .ToSqlStringAsync()); on.Should().NotBe(off, "an OR over two selective string fields is the canonical shape the prefilter handles; " + "identical SQL means EnablePvtPrefilter never reached the query provider"); } /// /// The planner writes its decision into the SQL preview as comments. Refusals are the interesting /// half: before this existed, finding out why a production query got no prefilter meant patching /// the API to log the configuration flag and waiting for a deploy. /// /// The comments live in GetSqlPreviewAsync only. They must never reach the executed /// statement: a comment that varies per query is a distinct plan-cache key in both PostgreSQL and /// SQL Server, which would trade a diagnostic for a cache that never hits. /// [Fact] public async Task PlannerTrace_ExplainsTheDecision() { await SeedAsync(); var restore = Redb.Configuration.EnablePvtPrefilter; try { Redb.UpdateConfiguration(c => c.EnablePvtPrefilter = true); // The prefilter lives in the aggregate form. A plain OrderByRedb(o => o.Id) now goes inside // the streams form, so the ordering is an expression over Id, which still keeps the query // on the aggregate form; the order is the same. var applied = await Redb.Query() .Where(e => e.Position.Contains("Developer") || e.Department.Contains("Engineering")) .OrderByRedb(o => o.Id + 0) .Take(100) .ToSqlStringAsync(); applied.Should().Contain("-- PVT prefilter:", "the planner decision belongs in the preview, next to the parameter block"); applied.Should().Contain("branch:", "an applied plan lists the branches it emitted"); // Age enters the pivot through ORDER BY, so no branch can cover it and the row form would // null its column out. The trace has to name that, not just stay silent. // // Deliberately ordered by a Props field rather than filtered by one: since every conjunct // became a branch, a second FILTER field is covered like the first and no longer declines. var declined = await Redb.Query() .Where(e => e.Position.Contains("Developer")) .OrderBy(e => e.Age) .ThenByRedb(o => o.Id + 0) .Take(100) .ToSqlStringAsync(); declined.Should().Contain("PivotNotCovered", "a refusal must say which guard stopped it"); declined.Should().Contain("Age", "and which pivot column was left uncovered"); } finally { Redb.UpdateConfiguration(c => c.EnablePvtPrefilter = restore); } } /// /// "a || b || c" parses as OrElse(OrElse(a, b), c). The planner read only the direct operands of /// the outer OR, met the inner OR as an unknown leaf and declined the whole disjunction with /// NoAnalyzableLeaf, although each leaf was expressible. Two leaves got the prefilter, three /// did not. The ordering is an expression over Id for the reason given in PlannerTrace_ExplainsTheDecision. /// [Fact] public async Task Or_ThreeLeaves_GetsOneBranchEach() { await SeedAsync(); IRedbQueryable Build() => Redb.Query() .WhereRedb(o => o.Id > 0) .Where(e => e.Position.Contains("Developer") || e.Department.Contains("Engineering") || e.LastName.Contains("son")) .OrderByRedb(o => o.Id + 0) .Take(100); var (_, sql) = await BothAsync(() => Build().ToSqlStringAsync()); sql.Should().Contain("-- PVT prefilter: Row form, 3 branch(es)", "every leaf of a nested OR is reachable, so each becomes a branch"); var (off, on) = await BothAsync(async () => (await Build().ToListAsync()).Select(r => r.id).ToList()); on.Should().Equal(off, "the prefilter is a superset and must not change the answer"); } // ────────────────────────────────────────────────────────────────── // Shapes the planner accepts // ────────────────────────────────────────────────────────────────── [Fact] public Task Or_TwoStringFields_SameResults() => AssertSameAsync( () => Redb.Query() .Where(e => e.Position.Contains("Developer") || e.Department.Contains("Engineering")) .OrderBy(e => e.Age).ThenBy(e => e.Salary).ThenByRedb(o => o.Id).Take(100), "an OR over two covered structures is the shape the row form is built for"); [Fact] public Task Or_SameFieldTwice_SameResults() => AssertSameAsync( () => Redb.Query() .Where(e => e.Department == "Engineering" || e.Department == "Marketing") .OrderBy(e => e.Salary).ThenByRedb(o => o.Id).Take(100), "both branches sit on one structure, which merges into a single covered branch"); [Fact] public Task Or_ThreeFieldsMixedTypes_SameResults() => AssertSameAsync( () => Redb.Query() .Where(e => e.Position.Contains("Senior") || e.Age > 40 || e.Salary > 150000m) .OrderBy(e => e.Age).ThenByRedb(o => o.Id).Take(100), "branches over different storage columns must all render correctly"); [Fact] public Task Range_SingleNumericField_SameResults() => AssertSameAsync( () => Redb.Query() .Where(e => e.Salary >= 60000m && e.Salary < 120000m) .OrderBy(e => e.Salary).ThenByRedb(o => o.Id).Take(100), "two half-lines on one structure merge into one selective range"); [Fact] public Task Range_DateTimeField_SameResults() => AssertSameAsync( () => Redb.Query() .Where(e => e.HireDate >= new DateTime(2020, 6, 1, 0, 0, 0, DateTimeKind.Utc) && e.HireDate < new DateTime(2021, 6, 1, 0, 0, 0, DateTimeKind.Utc)) .OrderBy(e => e.HireDate).ThenByRedb(o => o.Id).Take(100), "date ranges are the case the partial index on the datetime column exists for"); [Fact] public Task Equality_SingleStringField_SameResults() => AssertSameAsync( () => Redb.Query() .Where(e => e.Department == "Engineering") .OrderBy(e => e.Age).ThenByRedb(o => o.Id).Take(100), "a single leaf behaves like a one-branch disjunction"); [Fact] public Task StartsWith_SingleStringField_SameResults() => AssertSameAsync( () => Redb.Query() .Where(e => e.Position.StartsWith("Senior")) .OrderBy(e => e.Salary).ThenByRedb(o => o.Id).Take(100), "StartsWith renders as a LIKE with a trailing wildcard only"); // ────────────────────────────────────────────────────────────────── // Pivot columns the filter never mentions — the destructive case // ────────────────────────────────────────────────────────────────── [Fact] public Task Or_OrderByUnfilteredField_SameResults() => AssertSameAsync( () => Redb.Query() .Where(e => e.Position.Contains("Developer") || e.Department.Contains("Engineering")) .OrderBy(e => e.HireDate).ThenBy(e => e.Salary).ThenByRedb(o => o.Id).Take(100), "HireDate enters the pivot through ORDER BY; if the prefilter dropped its rows the column " + "would collapse to NULL and the ordering would change"); [Fact] public Task Or_DistinctByUnfilteredField_SameResults() => AssertSameAsync( () => Redb.Query() .Where(e => e.Position.Contains("Developer") || e.Department.Contains("Engineering")) .DistinctBy(e => e.Department) .OrderBy(e => e.Department).ThenByRedb(o => o.Id).Take(100), "DISTINCT BY adds a pivot column the filter never names"); [Fact] public Task Range_OrderByOtherField_SameResults() => AssertSameAsync( () => Redb.Query() .Where(e => e.Salary >= 60000m && e.Salary < 120000m) .OrderBy(e => e.Position).ThenBy(e => e.Salary).ThenByRedb(o => o.Id).Take(100), "a covered filter plus an uncovered ordering column is where coverage must refuse the prefilter"); // ────────────────────────────────────────────────────────────────── // Membership in a constant set // ────────────────────────────────────────────────────────────────── [Fact] public Task In_OnStringField_SameResults() => AssertSameAsync( () => { var wanted = new[] { "Engineering", "Marketing", "Sales" }; return Redb.Query() .Where(e => wanted.Contains(e.Department)) .OrderBy(e => e.Age).ThenByRedb(o => o.Id).Take(100); }, "membership is the most selective shape after equality and must reach the value scan"); [Fact] public Task In_OnNumericField_SameResults() => AssertSameAsync( () => { var wanted = new[] { 26, 30, 34, 41 }; return Redb.Query() .Where(e => wanted.Contains(e.Age)) .OrderBy(e => e.Salary).ThenByRedb(o => o.Id).Take(100); }, "the numeric column has its own partial index, so the branch should be index-served"); /// /// The shape production tripped over: an empty set. It is legitimately empty, but a branch /// rendered from it would be a contradiction, and inside a disjunction it would quietly take the /// other branches with it. The planner declines instead, and the answer must still be right. /// [Fact] public Task In_EmptySet_SameResults() => AssertSameAsync( () => { var wanted = Array.Empty(); return Redb.Query() .Where(e => wanted.Contains(e.Department)) .OrderByRedb(o => o.Id).Take(100); }, "an empty set matches nothing and must do so with the prefilter on as well as off"); /// /// Three conditions, because `a && b && c` parses as a tree rather than as one node with /// three operands. Before the planner flattened nested conjunctions the middle node was not a /// leaf, the third condition was lost, and coverage then refused the whole plan. /// [Fact] public Task And_ThreeFields_SameResults() => AssertSameAsync( () => Redb.Query() .Where(e => e.Department == "Engineering" && e.Age > 25 && e.Salary > 60000m) .OrderByRedb(o => o.Id).Take(100), "every conjunct becomes a branch, and a conjunct nested by the parser must not be lost"); // ────────────────────────────────────────────────────────────────── // Shapes the planner must refuse // ────────────────────────────────────────────────────────────────── [Fact] public Task And_AcrossDifferentFields_SameResults() => AssertSameAsync( () => Redb.Query() .Where(e => e.Position.Contains("Developer") && e.Department.Contains("Engineering")) .OrderBy(e => e.Age).ThenByRedb(o => o.Id).Take(100), "a row belongs to one structure, so a cross-field conjunction is not expressible at row level"); /// /// The shape that loses objects rather than merely reordering them. A nested disjunction under a /// conjunction would give the planner a multi-branch candidate whose sibling conjunct reads a /// column the prefilter has already nulled out: an employee whose Position matches and whose /// Department matches the outer term but not the inner one loses its Department row, so the /// surviving filter reads NULL and drops the employee outright. /// [Fact] public Task NestedOr_UnderAnd_OnCoveredStructure_SameResults() => AssertSameAsync( () => Redb.Query() .Where(e => (e.Position.Contains("Developer") || e.Department.Contains("Engineering")) && e.Department.Contains("a")) .OrderByRedb(o => o.Id).Take(100), "the sibling conjunct reads Department, which a Position-only match would have nulled out"); /// /// Same trap without any ordering or distinct to hide behind: nothing outside the filter reads the /// pivot here, so only the conjunction itself can expose the nulled column. /// [Fact] public Task NestedOr_UnderAnd_NoOrdering_SameResults() => AssertSameAsync( () => Redb.Query() .Where(e => (e.Position.Contains("Senior") || e.Department.Contains("Engineering")) && e.Position.Contains("e")) .OrderByRedb(o => o.Id).Take(100), "the sibling conjunct reads Position, which a Department-only match would have nulled out"); /// /// A pure disjunction with nothing reading the pivot outside the filter. This is the shape the /// prefilter exists for and the one guard 2 must keep allowing, so a regression that disables the /// prefilter wholesale would still pass here while Flag_ChangesGeneratedSql catches it. /// [Fact] public Task Or_NoPropsOrdering_SameResults() => AssertSameAsync( () => Redb.Query() .Where(e => e.Position.Contains("Developer") || e.Department.Contains("Engineering")) .OrderByRedb(o => o.Id).Take(100), "ordering by the object id keeps every pivot column readable by the filter alone"); [Fact] public Task NullCheck_WithOr_SameResults() => AssertSameAsync( () => Redb.Query() .Where(e => e.EmployeeCode == null || e.Department.Contains("Engineering")) .OrderBy(e => e.Age).ThenByRedb(o => o.Id).Take(100), "a null check needs absent and present-but-not-matching to stay distinct, which dropping rows blurs"); [Fact] public Task ArrayContains_WithOr_SameResults() => AssertSameAsync( () => Redb.Query() .Where(e => e.Skills!.Contains("C#") || e.Department.Contains("Marketing")) .OrderBy(e => e.Age).ThenByRedb(o => o.Id).Take(100), "array membership is not a row predicate; the planner must give up on the whole disjunction"); // An OR of several Contains over one array is one read of its elements with the values in a list (SQL Server folds // it); the answers stay those of the other form. [Fact] public Task ArrayContains_OrOfSeveral_SameResults() => AssertSameAsync( () => Redb.Query() .Where(e => e.Skills != null && (e.Skills.Contains("C#") || e.Skills.Contains("Python") || e.Skills.Contains("SQL"))) .OrderBy(e => e.Age).ThenByRedb(o => o.Id).Take(100), "the OR of the memberships is the membership of any of the values"); [Fact] public Task ArrayContains_OrOfSeveral_WithAnotherCondition_SameResults() => AssertSameAsync( () => Redb.Query() .Where(e => e.Skills!.Contains("C#") || e.Department.Contains("Marketing") || e.Skills!.Contains("Python")) .OrderBy(e => e.Age).ThenByRedb(o => o.Id).Take(100), "the memberships fold, the other condition stays beside them"); [Fact] public Task ArrayContains_NotOfAnOr_SameResults() => AssertSameAsync( () => Redb.Query() .Where(e => !(e.Skills!.Contains("C#") || e.Skills!.Contains("Python"))) .OrderBy(e => e.Age).ThenByRedb(o => o.Id).Take(100), "the negation of the folded membership is the negation of the OR"); // A Contains as the narrow condition drives the objects from the element rows (PostgreSQL), each object once: the // answers of pages, counts and sums stay those of the form over every object. [Fact] public Task ArrayContains_Drives_Page_SameResults() => AssertSameAsync( () => Redb.Query() .Where(e => e.Skills!.Contains("Azure")) .OrderByRedb(o => o.Id).Take(100), "the objects read off the element rows are those that hold the value, each once"); [Fact] public Task ArrayContains_TwoOfOneArray_Drive_SameResults() => AssertSameAsync( () => Redb.Query() .Where(e => e.Skills!.Contains("C#") && e.Skills!.Contains("SQL")) .OrderByRedb(o => o.Id).Take(100), "both values are held in two element rows of one object; one row equal to both would lose it"); [Fact] public async Task ArrayContains_Drives_CountAndSum_SameResults() { await SeedAsync(); var (off, on) = await BothAsync(async () => { var count = await Redb.Query().Where(e => e.Skills!.Contains("Azure")).CountAsync(); var withAge = await Redb.Query().Where(e => e.Skills!.Contains("Azure") && e.Age >= 30).CountAsync(); var sum = await Redb.Query().Where(e => e.Skills!.Contains("Azure")).SumAsync(e => e.Age); return (count, withAge, sum); }); on.Should().Be(off, "each object once in the count and in the sum"); on.count.Should().BeGreaterThan(0, "the seed holds Azure in every fifth skill set"); } [Fact] public Task NestedObjectField_WithOr_SameResults() => AssertSameAsync( () => Redb.Query() .Where(e => e.HomeAddress!.City == "New York" || e.Department.Contains("Marketing")) .OrderBy(e => e.Age).ThenByRedb(o => o.Id).Take(100), "nested fields reach the pivot through their own aliases"); [Fact] public Task Dictionary_WithOr_SameResults() => AssertSameAsync( () => Redb.Query() .Where(e => e.PhoneDirectory!.ContainsKey("desk") || e.Department.Contains("Marketing")) .OrderBy(e => e.Age).ThenByRedb(o => o.Id).Take(100), "dictionary access is not a row predicate either"); [Fact] public Task BaseFieldFilter_WithOr_SameResults() => AssertSameAsync( () => Redb.Query() .Where(e => e.Position.Contains("Developer") || e.Department.Contains("Engineering")) .WhereRedb(o => o.Id > 0) .OrderBy(e => e.Age).ThenByRedb(o => o.Id).Take(100), "a filter on the object itself lands beside the pivot and must not collide with it"); // ────────────────────────────────────────────────────────────────── // Paths other than ToListAsync // ────────────────────────────────────────────────────────────────── [Fact] public async Task Count_WithOr_SameResults() { await SeedAsync(); var (off, on) = await BothAsync(() => Redb.Query() .Where(e => e.Position.Contains("Developer") || e.Department.Contains("Engineering")) .CountAsync()); on.Should().Be(off, "counting goes through its own SQL builder"); } [Fact] public async Task Tree_WithOr_SameResults() { var root = TestDataFactory.CreateTreeNode("PrefilterRoot", "PF-ROOT", 1_000_000m); root.id = await Redb.SaveAsync(root); for (var i = 0; i < 6; i++) { var child = TestDataFactory.CreateTreeNode( i % 2 == 0 ? $"Engineering {i}" : $"Marketing {i}", $"PF-{i}", 100_000m + i * 10_000m); child.id = await Redb.CreateChildAsync(child, root); var grand = TestDataFactory.CreateTreeNode($"Team {i}", $"PF-{i}-T", 10_000m + i); await Redb.CreateChildAsync(grand, child); } var rootObj = await Redb.LoadAsync(root.id); var (off, on) = await BothAsync(async () => { var rows = await Redb.TreeQuery(rootObj) .Where(n => n.Name.Contains("Engineering") || n.Code.Contains("PF-1")) .OrderBy(n => n.Budget) .ToListAsync(); return rows.Select(r => r.id).ToList(); }); on.Should().Equal(off, "the tree provider builds its own pivot over the recursive CTE"); } /// /// The delete path is the one caller whose only scheme filter lives inside the pivot CTE, so it is /// where a wrongly narrowed pivot would destroy data rather than merely hide it. Each run works on /// its own freshly saved batch, so the two are independent and directly comparable. /// [Fact] public async Task Delete_WithOr_DeletesTheSameRows() { async Task<(int Deleted, int Survived)> RunAsync(string marker) { var batch = Enumerable.Range(0, 12) .Select(i => TestDataFactory.CreateEmployee( i, department: i % 2 == 0 ? marker : marker + "-keep")) .ToList(); var ids = await Redb.SaveAsync(batch); var idSet = ids.ToHashSet(); var deleted = await Redb.Query() .Where(e => e.Department == marker) .WhereRedb(o => idSet.Contains(o.Id)) .DeleteAsync(); var survivors = await Redb.Query() .WhereRedb(o => idSet.Contains(o.Id)) .Take(100) .ToListAsync(); return (deleted, survivors.Count); } var (off, on) = await BothAsync(() => RunAsync(Guid.NewGuid().ToString("N")[..8])); on.Should().Be(off, "DeleteAsync keeps its own scheme check; the prefilter must not widen it"); } /// /// An entry of a dictionary addressed by its key (PhoneDirectory["desk"]) is one row per object: the streams join /// it by the key instead of grouping every row of the dictionary in the scheme (E060, 100 000 employees, a page of /// 100: 270-300 ms -> 90-100 ms). Asserted on the SQL; the answers must not change. /// [Fact] public async Task DictionaryEntryByKey_ReadByStreams_SameAnswers() { await TestDataFactory.SeedEmployees(Redb, 40); // An employee without the dictionary has no key in it: both forms must count it under !ContainsKey. var withoutDirectory = TestDataFactory.CreateEmployee(9201); withoutDirectory.Props.PhoneDirectory = null; await Redb.SaveAsync(withoutDirectory); var restore = Redb.Configuration.EnablePvtPrefilter; try { IRedbQueryable HasDesk() => Redb.Query() .Where(e => e.PhoneDirectory!.ContainsKey("desk")) .OrderByRedb(o => o.Id).Take(10); IRedbQueryable DeskIs() => Redb.Query() .Where(e => e.PhoneDirectory!["desk"] == "555-1003"); Redb.UpdateConfiguration(c => c.EnablePvtPrefilter = true); (await HasDesk().ToSqlStringAsync()).Should().Contain("-- PVT form: Streams,", "a dictionary entry by its key maps to one row per object"); async Task<(List Page, int Count, int Missing)> AnswersAsync() => ( (await HasDesk().ToListAsync()).Select(o => o.Id).ToList(), await DeskIs().CountAsync(), await Redb.Query().Where(e => !e.PhoneDirectory!.ContainsKey("absent-key")).CountAsync()); var on = await AnswersAsync(); Redb.UpdateConfiguration(c => c.EnablePvtPrefilter = false); var off = await AnswersAsync(); on.Page.Should().Equal(off.Page); on.Page.Should().NotBeEmpty(); on.Count.Should().Be(off.Count); on.Missing.Should().Be(off.Missing); on.Missing.Should().Be(await Redb.Query().CountAsync(), "no employee has the key absent-key"); } finally { Redb.UpdateConfiguration(c => c.EnablePvtPrefilter = restore); } } /// /// SQL Server and SQLite: MIN and MAX without any condition take the first entry of the index of values of each field in /// its order, the trash subtracted; a batch with SUM or AVG, a filter or WhereRedb keeps the streams form. The employees /// holding the highest salary and the lowest age are moved to the trash, so the first entries of those indexes belong to /// trashed objects. Answers must equal the ones with the prefilter off for a decimal, an integer, a nullable double, a /// date, a nested-class field, base fields with COUNT(*), and an empty scheme. /// protected async Task UnfilteredExtremes_FirstEntryOfTheIndex_SameAnswersAsync() { await TestDataFactory.SeedEmployees(Redb, 30); var restore = Redb.Configuration.EnablePvtPrefilter; try { Redb.UpdateConfiguration(c => c.EnablePvtPrefilter = false); IRedbQueryable All() => Redb.Query(); var richest = (await All().OrderByDescending(e => e.Salary).ThenByRedb(o => o.Id).Take(1).ToListAsync()).Single().Id; var youngest = (await All().OrderBy(e => e.Age).ThenByRedb(o => o.Id).Take(1).ToListAsync()).Single().Id; await Redb.SoftDeleteAsync(new[] { richest, youngest }); await Redb.SyncSchemeAsync(); Redb.UpdateConfiguration(c => c.EnablePvtPrefilter = true); const string firstEntry = "ORDER BY v._numeric DESC"; (await All().ToAggregateSqlStringAsync(x => new { Mn = Agg.Min(x.Props.Salary), Mx = Agg.Max(x.Props.Salary), C = Agg.Count() })) .Should().Contain(firstEntry, "no condition: the extreme is the first entry of the index"); (await All().ToAggregateSqlStringAsync(x => new { Mx = Agg.Max(x.Props.Salary), S = Agg.Sum(x.Props.Age) })) .Should().NotContain(firstEntry, "a SUM in the batch keeps the streams form"); (await All().Where(e => e.Age > 0).ToAggregateSqlStringAsync(x => new { Mx = Agg.Max(x.Props.Salary) })) .Should().NotContain(firstEntry, "a filter keeps the streams form"); (await All().WhereRedb(o => o.Id > 0).ToAggregateSqlStringAsync(x => new { Mx = Agg.Max(x.Props.Salary) })) .Should().NotContain(firstEntry, "WhereRedb keeps the streams form"); async Task AnswersAsync() => System.Text.Json.JsonSerializer.Serialize(new object[] { await All().AggregateAsync(x => new { Mn = Agg.Min(x.Props.Salary), Mx = Agg.Max(x.Props.Salary), C = Agg.Count() }), await All().AggregateAsync(x => new { Mn = Agg.Min(x.Props.Age), Mx = Agg.Max(x.Props.Age) }), // Rating is a double, null on every fourth employee. await All().AggregateAsync(x => new { Mn = Agg.Min(x.Props.Rating), Mx = Agg.Max(x.Props.Rating) }), await All().AggregateAsync(x => new { Mn = Agg.Min(x.Props.HireDate), Mx = Agg.Max(x.Props.HireDate) }), await All().AggregateAsync(x => new { Low = Agg.Min(x.Props.HomeAddress!.Building!.Floor), Top = Agg.Max(x.Props.HomeAddress!.Building!.Floor) }), await All().AggregateAsync(x => new { FirstId = Agg.Min(x.Id), LastId = Agg.Max(x.Id), C = Agg.Count(), Mx = Agg.Max(x.Props.Salary) }), await All().AggregateAsync(x => new { Mx = Agg.Max(x.Props.Salary), S = Agg.Sum(x.Props.Age) }), await Redb.Query().AggregateAsync(x => new { MnN = Agg.Min(x.Props.Number), MxA = Agg.Max(x.Props.Amount), MnR = Agg.Min(x.Props.Ratio), C = Agg.Count() }), }); var on = await AnswersAsync(); Redb.UpdateConfiguration(c => c.EnablePvtPrefilter = false); var off = await AnswersAsync(); on.Should().Be(off, "reading the first entry of the index changes the plan, not the answer"); } finally { Redb.UpdateConfiguration(c => c.EnablePvtPrefilter = restore); } } /// /// SQL Server and SQLite: AllAsync over the whole scheme with a predicate on one plain field first looks for a /// counterexample among the first 1 000 objects, then compares the objects of the scheme with the values of the field /// that satisfy the predicate. 1 100 objects of a scheme of their own put the counterexamples past the probe, so the /// counts decide: another name at the end, an object without a note, the same objects moved to the trash. A Where or a /// WhereRedb before AllAsync, a number field and an IN list are compared too. Every answer must equal the one with the /// prefilter off. /// protected async Task AllWithoutFilter_ProbeThenCounts_SameAnswersAsync() { var objects = Enumerable.Range(0, 1100).Select(i => (redb.Core.Models.Contracts.IRedbObject) new redb.Core.Models.Entities.RedbObject { name = $"all-text-{i}", // The last object holds another name; the one before it has no note. Props = new AllTextProbeProps { Name = i == 1099 ? "b" : "a", Note = i == 1098 ? null : "n" } }).ToList(); var ids = await Redb.AddNewObjectsAsync(objects); await TestDataFactory.SeedEmployees(Redb, 20); var restore = Redb.Configuration.EnablePvtPrefilter; try { IRedbQueryable Q() => Redb.Query(); IRedbQueryable E() => Redb.Query(); async Task AnswersAsync() => string.Join(",", await Q().AllAsync(p => p.Name == "a"), await Q().AllAsync(p => p.Name != "zzz"), await Q().AllAsync(p => p.Name.StartsWith("a")), await Q().AllAsync(p => p.Note != null), await Q().AllAsync(p => p.Note == "n"), await Q().AllAsync(p => new[] { "a", "b" }.Contains(p.Name)), await Q().Where(p => p.Note == "n").AllAsync(p => p.Name == "a"), await Q().WhereRedb(o => o.Id < ids[1099]).AllAsync(p => p.Name == "a"), await E().AllAsync(e => e.Age >= 0), await E().AllAsync(e => e.Salary > 1_000_000m), await E().AllAsync(e => e.Rating != null), // Every other narrowing a query carries keeps its own answer: DistinctBy compares keys, not objects. await Q().DistinctBy(p => p.Note).AllAsync(p => p.Name == "a"), await Q().Distinct().AllAsync(p => p.Name == "a"), await Q().Take(5).AllAsync(p => p.Name == "a"), await Q().Skip(1090).AllAsync(p => p.Name == "a"), await Q().WhereInRedb(o => o.Id, ids.Take(10)).AllAsync(p => p.Name == "a")); Redb.UpdateConfiguration(c => c.EnablePvtPrefilter = true); var on = await AnswersAsync(); Redb.UpdateConfiguration(c => c.EnablePvtPrefilter = false); var off = await AnswersAsync(); on.Should().Be(off, "the probe and the counts change the plan, not the answer"); on.Should().StartWith("False,True,False,False,False,True,False,True", "one late other name, one object without a note; Where keeps the object with another name"); // The objects past the probe moved to the trash: their values stay until the purge and must not count. await Redb.SoftDeleteAsync(new[] { ids[1098], ids[1099] }); Redb.UpdateConfiguration(c => c.EnablePvtPrefilter = true); var trashedOn = await AnswersAsync(); Redb.UpdateConfiguration(c => c.EnablePvtPrefilter = false); var trashedOff = await AnswersAsync(); trashedOn.Should().Be(trashedOff, "the trash is subtracted from the values counted"); trashedOn.Should().StartWith("True,True,True,True,True,True,True,True", "the objects left all hold the name and the note"); } finally { Redb.UpdateConfiguration(c => c.EnablePvtPrefilter = restore); } } } Path: redb/redb.Tests.Integration/Tests/Base/PvtPrefilterListItemTestsBase.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/PvtPrefilterListItemTestsBase.cs ---- using redb.Core; using redb.Core.Models.Entities; using redb.Core.Query; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// Differential tests for the PVT prefilter over ListItem fields. /// /// Kept apart from because these need a list and its /// items, which the Employee fixture does not have. /// /// A ListItem field is the one place where a single structure carries several accessors, and they do /// not behave alike. Status.Id lives in the row's own _listitem column, so it is a plain /// row predicate. Status.Value and Status.Alias live in _list_items and need a /// join, which no row predicate can express. The planner has to take the first and refuse the other /// two, and it has to do so while all three share a structure id. /// /// This was found in production: a filter over `ShippingPoint.Id` got no prefilter at all, first /// because every ListItem accessor was refused wholesale, then because membership in a set was not /// an expressible leaf. /// public abstract class PvtPrefilterListItemTestsBase { protected readonly IRedbService Redb; protected PvtPrefilterListItemTestsBase(IRedbService redb) => Redb = redb; /// Six persons over three statuses, so every subset below is non-trivial. private async Task> SeedAsync(string listName) { var existing = await Redb.ListProvider.GetListByNameAsync(listName); if (existing != null) { var oldItems = await Redb.ListProvider.GetListItemsAsync(existing.Id); if (oldItems.Count > 0) await Redb.Context.Bulk.BulkDeleteValuesByListItemIdsAsync(oldItems.Select(i => i.Id).ToList()); await Redb.ListProvider.DeleteListAsync(existing.Id); } var list = await Redb.ListProvider.SaveListAsync(RedbList.Create(listName, listName)); var items = await Redb.ListProvider.AddItemsAsync(list, ["Active", "Blocked", "Archived"]); var persons = Enumerable.Range(0, 9).Select(i => new RedbObject { name = $"{listName}_{i}", Props = new PersonProps { Name = $"Person{i}", Age = 20 + i, Email = $"p{i}@prefilter.test", Status = items[i % items.Count] } }).ToList(); await Redb.SaveAsync(persons); return items; } private async Task<(T Off, T On)> BothAsync(Func> run) { var restore = Redb.Configuration.EnablePvtPrefilter; try { Redb.UpdateConfiguration(c => c.EnablePvtPrefilter = false); var off = await run(); Redb.UpdateConfiguration(c => c.EnablePvtPrefilter = true); var on = await run(); return (off, on); } finally { Redb.UpdateConfiguration(c => c.EnablePvtPrefilter = restore); } } private async Task AssertSameAsync(Func> build, string because) { var (off, on) = await BothAsync(async () => { var rows = await build().ToListAsync(); return rows.Select(r => r.id).ToList(); }); on.Should().Equal(off, because); } [Fact] public async Task ListItemId_Equality_SameResults() { var items = await SeedAsync("PrefilterStatuses_Equality"); var active = items.First(i => i.Value == "Active"); await AssertSameAsync( () => Redb.Query() .Where(p => p.Status!.Id == active.Id) .OrderByRedb(o => o.Id).Take(100), "Status.Id is stored in the row's own _listitem column and is a plain row predicate"); } [Fact] public async Task ListItemId_In_SameResults() { var items = await SeedAsync("PrefilterStatuses_In"); var wanted = items.Where(i => i.Value != "Archived").Select(i => i.Id).ToArray(); await AssertSameAsync( () => Redb.Query() .Where(p => wanted.Contains(p.Status!.Id)) .OrderByRedb(o => o.Id).Take(100), "membership over a ListItem id is the production shape that had no prefilter at all"); } /// /// Both accessors sit on one structure, and only one of them may become a branch. If the refused /// one ever leaked in, its predicate would be spliced onto the wrong column: a string pattern /// against a bigint. /// [Fact] public async Task ListItemId_WithValueAccessor_SameResults() { var items = await SeedAsync("PrefilterStatuses_Mixed"); var active = items.First(i => i.Value == "Active"); await AssertSameAsync( () => Redb.Query() .Where(p => p.Status!.Id == active.Id && p.Status!.Value == "Active") .OrderByRedb(o => o.Id).Take(100), "Status.Value needs a join to _list_items, so it must stay out of the row predicate " + "while Status.Id goes in, and the answer must not change either way"); } [Fact] public async Task ListItemValue_SameResults() { await SeedAsync("PrefilterStatuses_Value"); await AssertSameAsync( () => Redb.Query() .Where(p => p.Status!.Value == "Active") .OrderByRedb(o => o.Id).Take(100), "the display text lives in _list_items, which no row predicate can reach"); } /// /// The production query in full: membership over a ListItem id next to an ordinary field. Both /// halves are expressible, so both become branches; before that, the planner kept only the more /// selective one and then refused the plan because the other column was left uncovered. /// [Fact] public async Task ListItemId_In_WithSecondField_SameResults() { var items = await SeedAsync("PrefilterStatuses_TwoFields"); var wanted = items.Where(i => i.Value != "Archived").Select(i => i.Id).ToArray(); await AssertSameAsync( () => Redb.Query() .Where(p => wanted.Contains(p.Status!.Id) && p.Age > 21) .OrderByRedb(o => o.Id).Take(100), "every conjunct becomes a branch, so the ListItem column is covered and the plan stands"); } } Path: redb/redb.Tests.Integration/Tests/Base/QueryOrderTestsBase.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/QueryOrderTestsBase.cs ---- using redb.Core; using redb.Core.Models.Entities; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// A query returns its objects in the order asked for, in a list and in a tree. The objects are saved so that the order /// asked for is the reverse of the id order, which is the order a plain scan returns. Free on SQL Server read a tree /// page by joining the objects to the ordered ids without carrying the order. /// public abstract class QueryOrderTestsBase { protected readonly IRedbService Redb; protected QueryOrderTestsBase(IRedbService redb) => Redb = redb; private async Task<(string Tag, long Root)> SeedAsync() { await Redb.SyncSchemeAsync(); var tag = "ord-" + Guid.NewGuid().ToString("N")[..8]; var root = new TreeRedbObject { name = $"{tag}-root", Props = new SimpleProps { Title = $"{tag}-root", Price = 1000 } }; root.id = await Redb.SaveAsync(root); for (var i = 1; i <= 8; i++) { // Saved with a falling price: the later the id, the lower the price. var child = new TreeRedbObject { name = $"{tag}-{i}", Props = new SimpleProps { Title = tag, Count = i, Price = 100 - i } }; await Redb.CreateChildAsync(child, root); } return (tag, root.id); } [Fact] public async Task Tree_OrderByWithTake_KeepsTheOrder() { var (tag, root) = await SeedAsync(); var nodes = await Redb.TreeQuery(root).Where(p => p.Title == tag).OrderBy(p => p.Price).Take(6).ToListAsync(); nodes.Select(o => o.Props.Count).Should().Equal(8, 7, 6, 5, 4, 3); } /// /// Without Take there is no paging. Free on SQL Server dropped ORDER BY then (T-SQL keeps an ORDER BY inside a /// derived table only with OFFSET), and the objects came back in the order of the plan. /// [Fact] public async Task List_OrderByWithoutTake_KeepsTheOrder() { var (tag, _) = await SeedAsync(); var asc = await Redb.Query().Where(p => p.Title == tag).OrderBy(p => p.Price).ToListAsync(); var desc = await Redb.Query().Where(p => p.Title == tag).OrderByDescending(p => p.Count).ToListAsync(); asc.Select(o => o.Props.Count).Should().Equal(8, 7, 6, 5, 4, 3, 2, 1); desc.Select(o => o.Props.Count).Should().Equal(8, 7, 6, 5, 4, 3, 2, 1); } [Fact] public async Task Tree_OrderByWithoutTake_KeepsTheOrder() { var (tag, root) = await SeedAsync(); var nodes = await Redb.TreeQuery(root).Where(p => p.Title == tag).OrderBy(p => p.Price).ToListAsync(); nodes.Select(o => o.Props.Count).Should().Equal(8, 7, 6, 5, 4, 3, 2, 1); } } Path: redb/redb.Tests.Integration/Tests/Base/QueryPlannerBlockTestsBase.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/QueryPlannerBlockTestsBase.cs ---- using Microsoft.Extensions.DependencyInjection; using redb.Core; using redb.Core.Models.Entities; using redb.Core.Query; using redb.Tests.Integration.Helpers; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// The query planner switched for a block of code (redb.WithQueryPlanner(bool)), Pro only. The configuration is /// one object per process; the block changes the calling flow only, nests, restores on dispose, and leaves concurrent /// flows alone. The form is told by the SQL: the aggregate pivot folds the value rows with GROUP BY, the streams form of /// a filter, a sort and a page has none. Runs in both planner modes of the suite: the block wins over either. /// public abstract class QueryPlannerBlockTestsBase { protected readonly IRedbService Redb; private readonly IServiceProvider _services; protected QueryPlannerBlockTestsBase(IRedbService redb, IServiceProvider services) { Redb = redb; _services = services; } private async Task SeedAsync() { await Redb.SyncSchemeAsync(); var tag = "pvb-" + Guid.NewGuid().ToString("N")[..8]; for (var i = 1; i <= 6; i++) { var employee = TestDataFactory.CreateEmployee(i, firstName: $"{tag}-{i}", department: tag, salary: 1000m * i); employee.Props.Age = 20 + i; await Redb.SaveAsync(employee); } return tag; } private static IRedbQueryable Page(IRedbService redb, string tag) => redb.Query().Where(e => e.Department == tag && e.Age >= 22).OrderBy(e => e.Salary).Take(3); private static bool IsAggregatePivot(string sql) => sql.Contains("GROUP BY", StringComparison.OrdinalIgnoreCase); [Fact] public async Task Block_SwitchesTheFormForTheCallingFlow_AndTheAnswerStaysTheSame() { var tag = await SeedAsync(); string sqlOff, sqlOn; List idsOff, idsOn; using (Redb.WithQueryPlanner(false)) { QueryPlannerScope.BlockValue.Should().BeFalse(); sqlOff = await Page(Redb, tag).ToSqlStringAsync(); idsOff = (await Page(Redb, tag).ToListAsync()).Select(o => o.id).ToList(); } using (Redb.WithQueryPlanner(true)) { sqlOn = await Page(Redb, tag).ToSqlStringAsync(); idsOn = (await Page(Redb, tag).ToListAsync()).Select(o => o.id).ToList(); } IsAggregatePivot(sqlOff).Should().BeTrue("with the planner off the query is read through the aggregate pivot:\n" + sqlOff); IsAggregatePivot(sqlOn).Should().BeFalse("with the planner on this page is read through the streams form:\n" + sqlOn); idsOn.Should().HaveCount(3).And.Equal(idsOff, "the form changes, the answer does not"); QueryPlannerScope.BlockValue.Should().BeNull("both blocks are disposed"); } [Fact] public async Task Blocks_Nest_AndDisposingRestoresTheOuterValue() { var tag = await SeedAsync(); using (Redb.WithQueryPlanner(false)) { using (Redb.WithQueryPlanner(true)) IsAggregatePivot(await Page(Redb, tag).ToSqlStringAsync()).Should().BeFalse("the inner block turns the planner on"); IsAggregatePivot(await Page(Redb, tag).ToSqlStringAsync()).Should().BeTrue("the outer block is in effect again"); } } [Fact] public async Task Block_DoesNotReachAConcurrentFlow() { var tag = await SeedAsync(); using var bothInside = new Barrier(2); async Task InBlock(bool enabled) { using var scope = _services.CreateScope(); var redb = scope.ServiceProvider.GetRequiredService(); using (redb.WithQueryPlanner(enabled)) { bothInside.SignalAndWait(); // both blocks are open at the same time return await Page(redb, tag).ToSqlStringAsync(); } } var off = Task.Run(() => InBlock(false)); var on = Task.Run(() => InBlock(true)); await Task.WhenAll(off, on); IsAggregatePivot(await off).Should().BeTrue("the flow that switched the planner off reads the pivot"); IsAggregatePivot(await on).Should().BeFalse("the concurrent flow that switched it on is not affected"); } [Fact] public async Task OutsideAnyBlock_TheConfigurationDecides() { var tag = await SeedAsync(); QueryPlannerScope.BlockValue.Should().BeNull(); var configured = QueryPlannerScope.IsEnabled(Redb.Configuration); IsAggregatePivot(await Page(Redb, tag).ToSqlStringAsync()).Should().Be(!configured, $"EnablePvtPrefilter is {configured} for this suite and no block is open"); } [Fact] public async Task TheBlockInEffectWhereTheQueryRuns_Decides() { var tag = await SeedAsync(); // Composed inside a block, run after it: the value at the run counts. IRedbQueryable composed; using (Redb.WithQueryPlanner(false)) composed = Page(Redb, tag); using (Redb.WithQueryPlanner(true)) IsAggregatePivot(await composed.ToSqlStringAsync()).Should().BeFalse("it runs inside the block that turns the planner on"); // Started inside a block, awaited after it: the call keeps the block it was made in. Task started; using (Redb.WithQueryPlanner(false)) started = Page(Redb, tag).ToSqlStringAsync(); IsAggregatePivot(await started).Should().BeTrue("the call was made inside the block that turns the planner off"); } } Path: redb/redb.Tests.Integration/Tests/Base/QueryRowsAsJsonTestsBase.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/QueryRowsAsJsonTestsBase.cs ---- using System.Text.Json; using redb.Core; using redb.Tests.Integration.Helpers; namespace redb.Tests.Integration.Tests.Base; /// /// IRedbContext.QueryRowsAsJsonAsync on every provider: each row an object keyed by column name, numbers as numbers, /// text as text, NULL kept as null, a parameter bound, "[]" for no rows, and one command (one telemetry span) per call. /// public abstract class QueryRowsAsJsonTestsBase { protected readonly IRedbService Redb; protected QueryRowsAsJsonTestsBase(IRedbService redb) => Redb = redb; private const string TwoRows = "SELECT $1 AS label, 7 AS n, 2.5 AS d, CAST(NULL AS INT) AS empty " + "UNION ALL SELECT 'b', 8, 3.5, CAST(NULL AS INT)"; [Fact] public async Task Rows_AreObjectsKeyedByColumn_WithNullsKept() { var json = await Redb.Context.QueryRowsAsJsonAsync(TwoRows, new object[] { "a" }); using var doc = JsonDocument.Parse(json); var rows = doc.RootElement.EnumerateArray().OrderBy(r => r.GetProperty("label").GetString()).ToList(); rows.Should().HaveCount(2); rows[0].GetProperty("label").GetString().Should().Be("a", "the parameter is bound"); rows[0].GetProperty("n").GetInt32().Should().Be(7); rows[0].GetProperty("d").GetDecimal().Should().Be(2.5m); rows[0].GetProperty("empty").ValueKind.Should().Be(JsonValueKind.Null, "a NULL column is kept, as null"); rows[1].GetProperty("label").GetString().Should().Be("b"); rows[1].GetProperty("n").GetInt32().Should().Be(8); rows[1].GetProperty("d").GetDecimal().Should().Be(3.5m); } [Fact] public async Task NoRows_IsAnEmptyArray() => (await Redb.Context.QueryRowsAsJsonAsync("SELECT 1 AS n WHERE 1 = 0", Array.Empty())).Should().Be("[]"); [Fact] public async Task OneCall_IsOneCommand() => (await CommandCounter.CountAsync(() => Redb.Context.QueryRowsAsJsonAsync(TwoRows, new object[] { "a" }))) .Should().Be(1); } Path: redb/redb.Tests.Integration/Tests/Base/RareRangePagesTestsBase.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/RareRangePagesTestsBase.cs ---- using redb.Core; using redb.Core.Models.Entities; using redb.Core.Query; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// A page sorted by one field under an open range on another: on SQL Server the range is counted first and drives the /// page at or below a cap, the statement without the count runs above it. Every side of the cap must give the answer /// computed from the loaded objects, with the planner off and on: a number and a date range, sorted by a number and a /// date, ascending (objects without the sort value first) and descending, with Skip. /// public abstract class RareRangePagesTestsBase { private const int Objects = 3000; private static readonly SemaphoreSlim SeedLock = new(1, 1); private static readonly DateTime Start = new(2025, 1, 1, 0, 0, 0, DateTimeKind.Utc); protected readonly IRedbService Redb; protected RareRangePagesTestsBase(IRedbService redb) => Redb = redb; private async Task>> SeedAsync() { await SeedLock.WaitAsync(); try { var all = await Redb.Query().ToListAsync(); if (all.Count == Objects) return all; if (all.Count > 0) await Redb.DeleteAsync(all.Select(o => o.Id).ToList()); var objects = Enumerable.Range(0, Objects).Select(i => new RedbObject { name = $"rare-range-{i:0000}", Props = new RareRangeProps { // A permutation of 0..2999, absent on every 37th object. Score = i % 37 == 0 ? null : (i * 7919L) % Objects, Salary = i % 41 == 0 ? null : 1000m + (i * 131L) % 5000, When = i % 43 == 0 ? null : Start.AddMinutes((i * 211L) % Objects) } }).ToList(); for (var i = 0; i < objects.Count; i += 1000) await Redb.SaveAsync(objects.Skip(i).Take(1000).ToList()); all = await Redb.Query().ToListAsync(); all.Should().HaveCount(Objects); return all; } finally { SeedLock.Release(); } } private async Task EachFormAsync(Func check) { var restore = Redb.Configuration.EnablePvtPrefilter; try { foreach (var on in new[] { false, true }) { Redb.UpdateConfiguration(c => c.EnablePvtPrefilter = on); await check(on ? "planner on" : "planner off"); } } finally { Redb.UpdateConfiguration(c => c.EnablePvtPrefilter = restore); } } private static List Page(IEnumerable> all, Func keep, Func key, bool descending, int skip) { // The first object holds none of the three values: no row at all, no Props, and no range keeps it. var kept = all.Where(o => o.Props != null && keep(o.Props)); var ordered = descending ? kept.OrderByDescending(o => key(o.Props)) : kept.OrderBy(o => key(o.Props)); return ordered.ThenBy(o => o.Id).Skip(skip).Take(20).Select(o => o.Id).ToList(); } [Theory] [InlineData(12, false, 0)] [InlineData(12, true, 0)] [InlineData(900, false, 10)] [InlineData(900, true, 0)] [InlineData(1500, false, 0)] [InlineData(1500, true, 10)] [InlineData(2900, false, 10)] [InlineData(2900, true, 0)] public async Task NumberRange_SortedByNumber(long below, bool descending, int skip) { var all = await SeedAsync(); var withSortCondition = Page(all, p => p.Salary > 0 && p.Score < below, p => p.Salary, descending, skip); var rangeAlone = Page(all, p => p.Score < below, p => p.Salary, descending, skip); await EachFormAsync(async form => { var q = Redb.Query().Where(p => p.Salary > 0m && p.Score < below); var page = await (descending ? q.OrderByDescending(p => p.Salary) : q.OrderBy(p => p.Salary)).ThenByRedb(o => o.Id) .Skip(skip).Take(20).ToListAsync(); page.Select(o => o.Id).Should().Equal(withSortCondition, $"Salary > 0 and Score < {below}, {form}"); var alone = Redb.Query().Where(p => p.Score < below); var alonePage = await (descending ? alone.OrderByDescending(p => p.Salary) : alone.OrderBy(p => p.Salary)).ThenByRedb(o => o.Id) .Skip(skip).Take(20).ToListAsync(); alonePage.Select(o => o.Id).Should().Equal(rangeAlone, $"Score < {below} alone, objects without Salary where the order puts them, {form}"); var noTiebreak = await (descending ? alone.OrderByDescending(p => p.Salary) : alone.OrderBy(p => p.Salary)) .Skip(skip).Take(20).ToListAsync(); noTiebreak.Should().HaveCount(rangeAlone.Count, $"Score < {below}, no tiebreak, {form}"); }); } [Theory] [InlineData(12, false)] [InlineData(12, true)] [InlineData(2900, false)] [InlineData(2900, true)] public async Task NumberRange_SortedByDate(long below, bool descending) { var all = await SeedAsync(); var expected = Page(all, p => p.Score < below, p => p.When, descending, 0); await EachFormAsync(async form => { var q = Redb.Query().Where(p => p.Score < below); var page = await (descending ? q.OrderByDescending(p => p.When) : q.OrderBy(p => p.When)).ThenByRedb(o => o.Id) .Take(20).ToListAsync(); page.Select(o => o.Id).Should().Equal(expected, $"Score < {below} by When, {form}"); }); } [Theory] [InlineData(12, false)] [InlineData(12, true)] [InlineData(2900, false)] [InlineData(2900, true)] public async Task DateRange_SortedByNumber(int minutes, bool descending) { var all = await SeedAsync(); var before = Start.AddMinutes(minutes); var expected = Page(all, p => p.When < before, p => p.Salary, descending, 0); await EachFormAsync(async form => { var q = Redb.Query().Where(p => p.When < before); var page = await (descending ? q.OrderByDescending(p => p.Salary) : q.OrderBy(p => p.Salary)).ThenByRedb(o => o.Id) .Take(20).ToListAsync(); page.Select(o => o.Id).Should().Equal(expected, $"When before {minutes} minutes by Salary, {form}"); }); } [Fact] public async Task ThePreviewRunsNothing_AndShowsTheBatch() { await SeedAsync(); var sql = await Redb.Query().Where(p => p.Score < 12).OrderBy(p => p.Salary).Take(20).ToSqlStringAsync(); sql.Should().NotBeNullOrWhiteSpace(); var commands = await Helpers.CommandCounter.CountAsync(async () => await Redb.Query().Where(p => p.Score < 12).OrderBy(p => p.Salary).Take(20).ToSqlStringAsync()); commands.Should().Be(0, "a preview builds the statement, it runs nothing"); } } Path: redb/redb.Tests.Integration/Tests/Base/ReaderConnectionTestsBase.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/ReaderConnectionTestsBase.cs ---- using System.Transactions; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Core; using redb.Core.Data; using redb.Core.Extensions; using redb.Core.Models.Configuration; using redb.Core.Models.Entities; using redb.Core.Providers; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// A data object owns no connection. A /// lazy load - , the Props of a reference stub - runs on the live redb scope of whoever /// reads it. The old model opened a fresh scope and pooled connection per read for every list item without a loader of /// its own (all Pro and Free materialization) and for every reference inside a cached object. /// /// The detector is the context a load's SQL ran on: the reader's own context, and no context created meanwhile. Seeding /// and "a scope that ended" run in async helper methods: whatever they resolve never stays current for the test body. /// /// public abstract class ReaderConnectionTestsBase { private readonly SqlRecorder _recorder = new(); /// 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); /// A scalar command that holds the connection for a couple of seconds on this database. protected abstract string SlowScalarSql { get; } private ServiceProvider Build(Action configure, string domainSuffix = "") { var services = new ServiceCollection(); services.AddLogging(b => b.SetMinimumLevel(LogLevel.Warning)); Register(services, options => { UseProvider(options); options.Configure(c => { c.EnablePropsCache = false; c.SkipHashValidationOnCacheCheck = false; configure(c); // One domain per suite (the Free and Pro suites of one database run in parallel) and per cache setting: // a props cache is kept per domain for the process, so a test with the cache on would leave it to the next. c.CacheDomain = $"reader-connection-{GetType().Name}-{(c.EnablePropsCache ? "cache" : "nocache")}{domainSuffix}"; }); }); RecordingRedbContext.Decorate(services, _recorder); return services.BuildServiceProvider(); } private static string NewTag() => Guid.NewGuid().ToString("N")[..8]; private static async Task BootAsync(IRedbService redb) { await redb.InitializeAsync(ensureCreated: true); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.InitializeTypeRegistryAsync(); } private sealed record ItemSeed(long RootId, long LinkedObjectId); /// A root whose list item is linked to an object. private static async Task SeedLinkedItemAsync(ServiceProvider sp) { await using var scope = sp.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); await BootAsync(redb); var tag = NewTag(); var linkedObjectId = await redb.SaveAsync(new RedbObject { name = $"reader-linked-{tag}", Props = new SimpleProps { Title = "linked" } }); var list = await redb.ListProvider.SaveListAsync(RedbList.Create($"reader-{tag}", "reader")); var linked = await redb.ListProvider.SaveListItemAsync(new RedbListItem { IdList = list.Id, Value = "linked", IdObject = linkedObjectId }); var rootId = await redb.SaveAsync(new RedbObject { name = $"reader-root-{tag}", Props = new CtProbeProps { Label = "root", Status = linked } }); return new ItemSeed(rootId, linkedObjectId); } /// root → mid → leaf; the props cache is cleared, so the next load goes to the database. private static async Task SeedChainAsync(ServiceProvider sp, string tag) { await using var scope = sp.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); await BootAsync(redb); var leafId = await redb.SaveAsync(new RedbObject { name = $"reader-leaf-{tag}", Props = new LazyNodeProps { Label = $"leaf-{tag}" } }); var midId = await redb.SaveAsync(new RedbObject { name = $"reader-mid-{tag}", Props = new LazyNodeProps { Label = $"mid-{tag}", Next = new RedbObject { id = leafId } } }); var rootId = await redb.SaveAsync(new RedbObject { name = $"reader-root-{tag}", Props = new LazyNodeProps { Label = $"root-{tag}", Next = new RedbObject { id = midId } } }); ((RedbServiceBase)redb).PropsCache.Instance?.Clear(); return rootId; } /// A scope loads the root at depth 1 - caching it when the props cache is on - and ends. private static async Task> LoadRootInAScopeThatEndsAsync(ServiceProvider sp, long rootId) { await using var scope = sp.CreateAsyncScope(); var root = (await scope.ServiceProvider.GetRequiredService().LoadAsync(rootId, depth: 1))!; root.Props.Next!.IsPropsLoaded.Should().BeFalse("precondition: the reference is a stub"); return root; } private static async Task ItemFromAScopeThatEndsAsync(ServiceProvider sp, ItemSeed seed) { await using var scope = sp.CreateAsyncScope(); var root = await scope.ServiceProvider.GetRequiredService().LoadAsync(seed.RootId, depth: 10); return root!.Props.Status!; } private void AssertOnTheReadersContext(string path, IReadOnlyList commands, IRedbContext reader) { _recorder.ContextsCreated.Should().Be(0, $"{path}: a lazy load uses the reader's scope and opens no scope of its own"); commands.Should().NotBeEmpty($"{path}: the load ran its SQL"); commands.Should().OnlyContain(c => ReferenceEquals(c.Context, reader), $"{path}: every command of the load ran on the reader's context - its one connection"); } private static void AssertLinkedItem(RedbListItem? item, long linkedObjectId) { item.Should().NotBeNull("precondition: the list item is materialized"); item!.IdObject.Should().Be(linkedObjectId, "precondition: the item carries its object link"); item.IsObjectLoaded.Should().BeFalse("precondition: the object is still lazy"); } [Fact] public async Task ListItemFromALoad_ObjectLoadsOnTheReadersContext() { await using var sp = Build(_ => { }); var seed = await SeedLinkedItemAsync(sp); await using var scope = sp.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); var reader = scope.ServiceProvider.GetRequiredService(); var root = (await redb.LoadAsync(seed.RootId, depth: 10))!; AssertLinkedItem(root.Props.Status, seed.LinkedObjectId); _recorder.Start(); var linked = root.Props.Status!.Object; var commands = _recorder.Stop(); linked.Should().NotBeNull(); linked!.Id.Should().Be(seed.LinkedObjectId); AssertOnTheReadersContext("item from LoadAsync", commands, reader); } [Fact] public async Task ListItemFromAQuery_ObjectLoadsOnTheReadersContext() { await using var sp = Build(_ => { }); var seed = await SeedLinkedItemAsync(sp); await using var scope = sp.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); var reader = scope.ServiceProvider.GetRequiredService(); var rows = await redb.Query().WhereRedb(o => o.Id == seed.RootId).ToListAsync(); var item = rows.Should().ContainSingle().Subject.Props.Status; AssertLinkedItem(item, seed.LinkedObjectId); _recorder.Start(); var linked = await item!.GetObjectAsync(); var commands = _recorder.Stop(); linked.Should().NotBeNull(); linked!.Id.Should().Be(seed.LinkedObjectId); AssertOnTheReadersContext("item from a query", commands, reader); } [Fact] public async Task CachedObjectInAnotherScope_ReferenceLoadsOnTheReadersContext() { await using var sp = Build(c => c.EnablePropsCache = true); var tag = NewTag(); var rootId = await SeedChainAsync(sp, tag); var cached = await LoadRootInAScopeThatEndsAsync(sp, rootId); await using var scope = sp.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); var reader = scope.ServiceProvider.GetRequiredService(); var served = (await redb.LoadAsync(rootId, depth: 1))!; served.Should().BeSameAs(cached, "precondition: the cache serves the shared instance"); var stub = served.Props.Next!; stub.IsPropsLoaded.Should().BeFalse("precondition: the reference is a stub"); _recorder.Start(); var label = stub.Props.Label; var commands = _recorder.Stop(); label.Should().Be($"mid-{tag}"); AssertOnTheReadersContext("reference inside a cached object", commands, reader); } [Fact] public async Task ListItemRead_WithoutALiveScope_Refuses() { await using var sp = Build(_ => { }); var seed = await SeedLinkedItemAsync(sp); var item = await ItemFromAScopeThatEndsAsync(sp, seed); AssertLinkedItem(item, seed.LinkedObjectId); _recorder.Start(); Action read = () => _ = item.Object; read.Should().Throw().WithMessage("*BeginAccess*", "no live redb scope reads here: a clear refusal naming the explicit ways, not a hidden scope and connection"); _recorder.Stop(); _recorder.ContextsCreated.Should().Be(0); } [Fact] public async Task ReferenceRead_WithoutALiveScope_Refuses() { await using var sp = Build(_ => { }); var rootId = await SeedChainAsync(sp, NewTag()); var root = await LoadRootInAScopeThatEndsAsync(sp, rootId); var stub = root.Props.Next!; _recorder.Start(); Action read = () => _ = stub.Props; read.Should().Throw().WithMessage("*BeginAccess*", "no live redb scope reads here: a clear refusal naming the explicit ways, not a hidden scope and connection"); _recorder.Stop(); _recorder.ContextsCreated.Should().Be(0); } [Fact] public async Task CachedReferenceInsideATransaction_SeesTheTransaction_AndIsNotMemoized() { await using var sp = Build(c => c.EnablePropsCache = true); var tag = NewTag(); var rootId = await SeedChainAsync(sp, tag); var cached = await LoadRootInAScopeThatEndsAsync(sp, rootId); var midId = cached.Props.Next!.id; using (new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) { await using var scope = sp.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); var mid = (await redb.LoadAsync(midId, depth: 1))!; mid.Props.Label = $"uncommitted-{tag}"; await redb.SaveAsync(mid); var served = (await redb.LoadAsync(rootId, depth: 1))!; served.Should().BeSameAs(cached, "precondition: the cache serves the shared instance"); var stub = served.Props.Next!; stub.Props.Label.Should().Be($"uncommitted-{tag}", "the load runs on the reader's connection, inside the reader's transaction"); stub.IsPropsLoaded.Should().BeFalse( "a shared instance does not keep what one transaction saw - the write may roll back"); // not completed: the write rolls back } await using (var after = sp.CreateAsyncScope()) { var redb = after.ServiceProvider.GetRequiredService(); var served = (await redb.LoadAsync(rootId, depth: 1))!; served.Props.Next!.Props.Label.Should().Be($"mid-{tag}", "the shared instance never kept the rolled-back write"); } } [Fact] public async Task InjectedListProvider_IsTheServicesOwn() { await using var sp = Build(_ => { }); await using var scope = sp.CreateAsyncScope(); scope.ServiceProvider.GetRequiredService().Should().BeSameAs( scope.ServiceProvider.GetRequiredService().ListProvider, "one list provider per scope - a second instance in the same scope behaves differently"); } // === New API of the model: BeginAccess, the FreshScope option, the explicit batch === /// Runs on a thread that carries none of the caller's execution context. private static void RunInAnotherExecutionContext(Action action) { Exception? failure = null; Thread thread; using (ExecutionContext.SuppressFlow()) { thread = new Thread(() => { try { action(); } catch (Exception ex) { failure = ex; } }); thread.Start(); } thread.Join(); if (failure != null) throw new InvalidOperationException("the action failed on the other thread", failure); } [Fact] public async Task ItemReadWhereItsScopeIsNotCurrent_LoadsOnTheScopeThatMaterializedIt() { await using var sp = Build(_ => { }); var seed = await SeedLinkedItemAsync(sp); await using var scope = sp.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); var origin = scope.ServiceProvider.GetRequiredService(); var item = (await redb.LoadAsync(seed.RootId, depth: 10))!.Props.Status!; AssertLinkedItem(item, seed.LinkedObjectId); // A test fixture, a service kept in a field, a UI event handler: the scope that materialized the item lives, but // is not current where the item is read (owner decision 2026-09-15: then the origin answers, while it lives). _recorder.Start(); Core.Models.Contracts.IRedbObject? linked = null; RunInAnotherExecutionContext(() => linked = item.Object); var commands = _recorder.Stop(); linked.Should().NotBeNull(); linked!.Id.Should().Be(seed.LinkedObjectId); AssertOnTheReadersContext("item read where its scope is not current", commands, origin); } [Fact] public async Task SharedObjectReadWhereNoScopeIsCurrent_Refuses_AndLoadsOnTheScope_InsideBeginAccess() { await using var sp = Build(c => c.EnablePropsCache = true); var tag = NewTag(); var rootId = await SeedChainAsync(sp, tag); await using var scope = sp.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); var reader = scope.ServiceProvider.GetRequiredService(); // The load caches the root: from here on it is shared by every scope, not bound to this one. var stub = (await redb.LoadAsync(rootId, depth: 1))!.Props.Next!; stub.IsPropsLoaded.Should().BeFalse("precondition: the reference is a stub"); Exception? refused = null; RunInAnotherExecutionContext(() => { try { _ = stub.Props; } catch (Exception ex) { refused = ex; } }); refused.Should().BeOfType( "a shared instance loads on the reader's scope only - it is never bound to the scope that cached it"); stub.IsPropsLoaded.Should().BeFalse(); _recorder.Start(); string? label = null; RunInAnotherExecutionContext(() => { using (redb.BeginAccess()) label = stub.Props.Label; }); var commands = _recorder.Stop(); label.Should().Be($"mid-{tag}"); AssertOnTheReadersContext("shared instance inside BeginAccess", commands, reader); } [Fact] public async Task ListItemRead_WithoutALiveScope_LoadsInAFreshScope_WhenConfigured() { await using var sp = Build(c => c.LazyLoadWithoutScope = LazyLoadWithoutScopeMode.FreshScope); var seed = await SeedLinkedItemAsync(sp); var item = await ItemFromAScopeThatEndsAsync(sp, seed); AssertLinkedItem(item, seed.LinkedObjectId); _recorder.Start(); var linked = item.Object; _recorder.Stop(); linked.Should().NotBeNull(); linked!.Id.Should().Be(seed.LinkedObjectId); _recorder.ContextsCreated.Should().Be(1, "the option opens exactly one scope for the load"); } [Fact] public async Task LoadLinkedObjectsAsync_LoadsTheItemsOnTheServicesContext() { await using var sp = Build(c => c.PreloadListItemLinkedObjects = false); long listId; long[] objectIds; await using (var seedScope = sp.CreateAsyncScope()) { var seeder = seedScope.ServiceProvider.GetRequiredService(); await BootAsync(seeder); var tag = NewTag(); objectIds = new long[3]; for (var i = 0; i < objectIds.Length; i++) objectIds[i] = await seeder.SaveAsync(new RedbObject { name = $"reader-batch-{tag}-{i}", Props = new SimpleProps { Title = $"batch-{i}" } }); var list = await seeder.ListProvider.SaveListAsync(RedbList.Create($"reader-batch-{tag}", "reader-batch")); listId = list.Id; foreach (var objectId in objectIds) await seeder.ListProvider.SaveListItemAsync(new RedbListItem { IdList = list.Id, Value = $"item-{objectId}", IdObject = objectId }); } await using var scope = sp.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); var reader = scope.ServiceProvider.GetRequiredService(); var items = await redb.ListProvider.GetListItemsAsync(listId); items.Should().HaveCount(objectIds.Length).And.OnlyContain(i => !i.IsObjectLoaded, "precondition: the preload is off"); _recorder.Start(); var loaded = await redb.LoadLinkedObjectsAsync(items); var commands = _recorder.Stop(); loaded.Keys.Should().BeEquivalentTo(objectIds); items.Should().OnlyContain(i => i.IsObjectLoaded && i.Object != null && i.Object.Id == i.IdObject); AssertOnTheReadersContext("LoadLinkedObjectsAsync", commands, reader); } // === The rest of the §4.1 matrix: what a shared instance loads, parallel reads, two databases, every road === private static async Task ListItemFromAScopeThatEndsAsync(ServiceProvider sp, long listId) { await using var scope = sp.CreateAsyncScope(); var items = await scope.ServiceProvider.GetRequiredService().ListProvider.GetListItemsAsync(listId); return items.Should().ContainSingle().Subject; } /// A list of items, each linked to an object of its own. private static async Task SeedListOfLinkedObjectsAsync(ServiceProvider sp, int count, string label) { await using var scope = sp.CreateAsyncScope(); var seeder = scope.ServiceProvider.GetRequiredService(); await BootAsync(seeder); var tag = NewTag(); var list = await seeder.ListProvider.SaveListAsync(RedbList.Create($"reader-{label}-{tag}", $"reader-{label}")); for (var i = 0; i < count; i++) { var objectId = await seeder.SaveAsync(new RedbObject { name = $"reader-{label}-{tag}-{i}", Props = new SimpleProps { Title = $"{label}-{i}" } }); await seeder.ListProvider.SaveListItemAsync(new RedbListItem { IdList = list.Id, Value = $"item-{i}", IdObject = objectId }); } return list.Id; } [Theory] [InlineData(false)] [InlineData(true)] public async Task SharedObject_WhatItLoaded_IsShared_NotBoundToTheReadersScope(bool explicitAsyncLoad) { await using var sp = Build(c => c.EnablePropsCache = true); var tag = NewTag(); var rootId = await SeedChainAsync(sp, tag); var cached = await LoadRootInAScopeThatEndsAsync(sp, rootId); await using var scope = sp.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); var served = (await redb.LoadAsync(rootId, depth: 1))!; served.Should().BeSameAs(cached, "precondition: the cache serves the shared instance"); var mid = served.Props.Next!; if (explicitAsyncLoad) await mid.LoadPropsAsync(); else _ = mid.Props; mid.IsPropsLoaded.Should().BeTrue("outside a transaction a shared instance keeps what it loaded"); var leaf = mid.Props.Next!; leaf.IsPropsLoaded.Should().BeFalse("precondition: a lazy load reaches depth 1, the next reference is a stub"); Exception? refused = null; RunInAnotherExecutionContext(() => { try { _ = leaf.Props; } catch (Exception ex) { refused = ex; } }); refused.Should().BeOfType( "a graph hung on a shared instance is shared too: it loads on the reader's scope only, never on the scope " + "that happened to load it"); } [Fact] public async Task SharedObject_LoadPropsAsyncInsideATransaction_IsNotMemoized() { await using var sp = Build(c => c.EnablePropsCache = true); var tag = NewTag(); var rootId = await SeedChainAsync(sp, tag); var cached = await LoadRootInAScopeThatEndsAsync(sp, rootId); var midId = cached.Props.Next!.id; using (new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) { await using var scope = sp.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); var mid = (await redb.LoadAsync(midId, depth: 1))!; mid.Props.Label = $"uncommitted-{tag}"; await redb.SaveAsync(mid); var served = (await redb.LoadAsync(rootId, depth: 1))!; served.Should().BeSameAs(cached, "precondition: the cache serves the shared instance"); var stub = served.Props.Next!; await stub.LoadPropsAsync(); stub.IsPropsLoaded.Should().BeFalse( "a shared instance does not keep what one transaction saw - the write may roll back"); stub.Props.Label.Should().Be($"uncommitted-{tag}", "the reader still sees its own transaction"); // not completed: the write rolls back } await using (var after = sp.CreateAsyncScope()) { var redb = after.ServiceProvider.GetRequiredService(); var served = (await redb.LoadAsync(rootId, depth: 1))!; served.Props.Next!.Props.Label.Should().Be($"mid-{tag}", "the shared instance never kept the rolled-back write"); } } [Fact] public async Task CachedListItemInsideATransaction_SeesTheTransaction_AndIsNotMemoized() { await using var sp = Build(c => c.PreloadListItemLinkedObjects = false); var tag = NewTag(); var listId = await SeedListOfLinkedObjectsAsync(sp, 1, $"cached-item-{tag}"); var cachedItem = await ListItemFromAScopeThatEndsAsync(sp, listId); var objectId = cachedItem.IdObject!.Value; using (new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) { await using var scope = sp.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); var obj = (await redb.LoadAsync(objectId))!; obj.Props.Title = $"uncommitted-{tag}"; await redb.SaveAsync(obj); var item = (await redb.ListProvider.GetListItemsAsync(listId)).Should().ContainSingle().Subject; item.Should().BeSameAs(cachedItem, "precondition: the list cache serves the shared item"); item.IsObjectLoaded.Should().BeFalse("precondition: the preload is off"); ((RedbObject)item.Object!).Props.Title.Should().Be($"uncommitted-{tag}", "the load runs on the reader's connection, inside the reader's transaction"); item.IsObjectLoaded.Should().BeFalse( "a shared item does not keep what one transaction saw - the write may roll back"); // not completed: the write rolls back } await using (var after = sp.CreateAsyncScope()) { var redb = after.ServiceProvider.GetRequiredService(); var item = (await redb.ListProvider.GetListItemsAsync(listId)).Should().ContainSingle().Subject; ((RedbObject)item.Object!).Props.Title.Should().NotBe($"uncommitted-{tag}", "the shared item never kept the rolled-back write"); } } [Fact] public async Task CachedListItem_TheObjectItLoaded_IsShared_NotBoundToTheReadersScope() { await using var sp = Build(c => c.PreloadListItemLinkedObjects = false); var seed = await SeedLinkedItemAsync(sp); var tag = NewTag(); long listId; await using (var seedScope = sp.CreateAsyncScope()) { var seeder = seedScope.ServiceProvider.GetRequiredService(); var list = await seeder.ListProvider.SaveListAsync(RedbList.Create($"reader-shared-graph-{tag}", "reader-shared-graph")); listId = list.Id; await seeder.ListProvider.SaveListItemAsync(new RedbListItem { IdList = list.Id, Value = "root", IdObject = seed.RootId }); } var cachedItem = await ListItemFromAScopeThatEndsAsync(sp, listId); await using var scope = sp.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); var item = (await redb.ListProvider.GetListItemsAsync(listId)).Should().ContainSingle().Subject; item.Should().BeSameAs(cachedItem, "precondition: the list cache serves the shared item"); var root = (RedbObject)item.Object!; item.IsObjectLoaded.Should().BeTrue("outside a transaction a shared item keeps what it loaded"); var nested = root.Props.Status; AssertLinkedItem(nested, seed.LinkedObjectId); Exception? refused = null; RunInAnotherExecutionContext(() => { try { _ = nested!.Object; } catch (Exception ex) { refused = ex; } }); refused.Should().BeOfType( "the object a shared item keeps is shared too: its items load on the reader's scope only, never on the scope " + "that happened to load it"); } [Fact] public async Task ParallelReadsInOneScope_AreRefused() { await using var sp = Build(_ => { }); var seed = await SeedLinkedItemAsync(sp); await using var scope = sp.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); var item = (await redb.LoadAsync(seed.RootId, depth: 10))!.Props.Status!; AssertLinkedItem(item, seed.LinkedObjectId); _recorder.Start(); var slow = Task.Run(() => redb.Context.ExecuteScalarAsync(SlowScalarSql)); var deadline = DateTime.UtcNow.AddSeconds(10); while (!_recorder.Peek().Any(c => c.Sql == SlowScalarSql) && DateTime.UtcNow < deadline) await Task.Delay(20); // The recorder notes a command just before the connection takes it. await Task.Delay(300); Action read = () => _ = item.Object; read.Should().Throw().WithMessage("*concurrently*", "one scope is one connection: a second read while a command runs is refused, not given a connection of its own"); await slow; _recorder.Stop(); _recorder.ContextsCreated.Should().Be(0); item.IsObjectLoaded.Should().BeFalse("a refusal loads nothing and keeps nothing"); } [Fact] public async Task TwoDatabasesInOneFlow_AnItemLoadsOnItsOwn_AndAnItemOfNoDatabaseIsRefused() { await using var spA = Build(_ => { }, "-a"); await using var spB = Build(_ => { }, "-b"); var seed = await SeedLinkedItemAsync(spA); await using var scopeA = spA.CreateAsyncScope(); var redbA = scopeA.ServiceProvider.GetRequiredService(); var contextA = scopeA.ServiceProvider.GetRequiredService(); var item = (await redbA.LoadAsync(seed.RootId, depth: 10))!.Props.Status!; AssertLinkedItem(item, seed.LinkedObjectId); // A scope of the second database becomes current, nearer than the first. await using var scopeB = spB.CreateAsyncScope(); scopeB.ServiceProvider.GetRequiredService().Should().NotBeNull(); _recorder.Start(); var linked = item.Object; var commands = _recorder.Stop(); linked.Should().NotBeNull(); linked!.Id.Should().Be(seed.LinkedObjectId); AssertOnTheReadersContext("an item of the first database while the second is nearer", commands, contextA); var unknown = new RedbListItem { IdObject = seed.LinkedObjectId }; Action read = () => _ = unknown.Object; read.Should().Throw().WithMessage("*two databases*", "an item built in user code carries no database: with two current it is never read from a guessed one"); } [Fact] public async Task LoadLinkedObjectsAsync_CommandsDoNotGrowWithTheItems() { await using var sp = Build(c => c.PreloadListItemLinkedObjects = false); var warmUp = await SeedListOfLinkedObjectsAsync(sp, 2, "batch-warm"); var two = await SeedListOfLinkedObjectsAsync(sp, 2, "batch-two"); var six = await SeedListOfLinkedObjectsAsync(sp, 6, "batch-six"); await using var scope = sp.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); async Task CommandsToLoad(long listId) { var items = await redb.ListProvider.GetListItemsAsync(listId); items.Should().OnlyContain(i => !i.IsObjectLoaded, "precondition: the preload is off"); _recorder.Start(); var loaded = await redb.LoadLinkedObjectsAsync(items); var commands = _recorder.Stop(); loaded.Should().HaveCount(items.Count()); return commands.Count; } await CommandsToLoad(warmUp); var forTwo = await CommandsToLoad(two); var forSix = await CommandsToLoad(six); forSix.Should().Be(forTwo, "one batch for the whole list: the commands do not grow with the number of items"); } [Fact] public async Task ListItemFromASyncLoad_ObjectLoadsOnTheReadersContext() { await using var sp = Build(_ => { }); var seed = await SeedLinkedItemAsync(sp); await using var scope = sp.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); var reader = scope.ServiceProvider.GetRequiredService(); var root = redb.Load(seed.RootId, depth: 10)!; AssertLinkedItem(root.Props.Status, seed.LinkedObjectId); _recorder.Start(); var linked = root.Props.Status!.Object; var commands = _recorder.Stop(); linked.Should().NotBeNull(); linked!.Id.Should().Be(seed.LinkedObjectId); AssertOnTheReadersContext("item from a sync Load", commands, reader); } [Fact] public async Task ListItemFromABatchLoad_ObjectLoadsOnTheReadersContext() { await using var sp = Build(_ => { }); var seed = await SeedLinkedItemAsync(sp); await using var scope = sp.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); var reader = scope.ServiceProvider.GetRequiredService(); var loaded = await redb.LoadAsync(new[] { seed.RootId }, depth: 10); var root = loaded.Should().ContainSingle().Which.Should().BeOfType>().Subject; AssertLinkedItem(root.Props.Status, seed.LinkedObjectId); _recorder.Start(); var linked = await root.Props.Status!.GetObjectAsync(); var commands = _recorder.Stop(); linked.Should().NotBeNull(); linked!.Id.Should().Be(seed.LinkedObjectId); AssertOnTheReadersContext("item from a batch load", commands, reader); } [Fact] public async Task ListItemFromATree_ObjectLoadsOnTheReadersContext() { await using var sp = Build(_ => { }); var seed = await SeedLinkedItemAsync(sp); long parentId; await using (var seedScope = sp.CreateAsyncScope()) { var seeder = seedScope.ServiceProvider.GetRequiredService(); var status = (await seeder.LoadAsync(seed.RootId, depth: 10))!.Props.Status!; var parent = new RedbObject { name = $"reader-tree-parent-{NewTag()}", Props = new CtProbeProps { Label = "parent" } }; parent.id = await seeder.SaveAsync(parent); parentId = parent.id; await seeder.CreateChildAsync(new TreeRedbObject { name = "reader-tree-child", Props = new CtProbeProps { Label = "child", Status = status } }, parent); } await using var scope = sp.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); var reader = scope.ServiceProvider.GetRequiredService(); var parentObj = (await redb.LoadAsync(parentId, depth: 1))!; var child = (await redb.GetChildrenAsync(parentObj)).Should().ContainSingle().Subject; AssertLinkedItem(child.Props.Status, seed.LinkedObjectId); _recorder.Start(); var linked = await child.Props.Status!.GetObjectAsync(); var commands = _recorder.Stop(); linked.Should().NotBeNull(); linked!.Id.Should().Be(seed.LinkedObjectId); AssertOnTheReadersContext("item from a tree", commands, reader); } } Path: redb/redb.Tests.Integration/Tests/Base/RecordingRedbContext.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/RecordingRedbContext.cs ---- using System.Collections.Concurrent; using System.Data; using Microsoft.Extensions.DependencyInjection; using redb.Core.Data; namespace redb.Tests.Integration.Tests.Base; /// /// One command seen by : its SQL text, the thread it was issued on and the context /// instance (one scope, one connection) it ran on. /// public sealed record RecordedCommand(string Sql, int ThreadId, IRedbContext Context); /// /// Commands that went through a between and , /// and how many contexts - scopes with a connection of their own - were created meanwhile. /// public sealed class SqlRecorder { private readonly ConcurrentQueue _commands = new(); private volatile bool _armed; private int _contextsCreated; /// Contexts created since . public int ContextsCreated => Volatile.Read(ref _contextsCreated); public void Start() { _commands.Clear(); Interlocked.Exchange(ref _contextsCreated, 0); _armed = true; } public IReadOnlyList Stop() { _armed = false; return _commands.ToArray(); } /// The commands recorded so far; recording goes on. public IReadOnlyList Peek() => _commands.ToArray(); /// /// Runs before a QueryAsync command is forwarded, with its SQL text, armed or not: a test does something to the /// database between two statements of one operation (a delete between the read of the objects and of their values). /// public Func? BeforeQuery { get; set; } /// Runs after a QueryAsync command returned, with its SQL text, armed or not (see ). public Func? AfterQuery { get; set; } internal void Note(IRedbContext context, string sql) { if (_armed) _commands.Enqueue(new RecordedCommand(sql, Environment.CurrentManagedThreadId, context)); } internal void NoteCreated() { if (_armed) Interlocked.Increment(ref _contextsCreated); } } /// /// Test decorator over the provider's : records the SQL text of every command that goes /// through the context, then forwards it. It tells WHICH road a load took - the Free in-database JSON builder or the Pro /// C# materializer - and ON WHICH context, without depending on the database having that function: on SQLite the Free /// native extension is process-wide static state that another suite may or may not have loaded. /// /// Every SQL-bearing member is implemented here, the synchronous ones included: their interface defaults forward to /// and would bypass the record. A new SQL member of must be /// added here too. /// /// public sealed class RecordingRedbContext : IRedbContext { private readonly IRedbContext _inner; private readonly SqlRecorder _recorder; public RecordingRedbContext(IRedbContext inner, SqlRecorder recorder) { _inner = inner; _recorder = recorder; } /// Wraps the last registration - the one every service resolves. public static void Decorate(IServiceCollection services, SqlRecorder recorder) { var descriptor = services.LastOrDefault(d => d.ServiceType == typeof(IRedbContext)) ?? throw new InvalidOperationException("No IRedbContext registration to decorate"); var factory = descriptor.ImplementationFactory ?? throw new InvalidOperationException($"IRedbContext is expected to be registered by a factory: {descriptor}"); services.Remove(descriptor); services.Add(new ServiceDescriptor(typeof(IRedbContext), sp => { recorder.NoteCreated(); return new RecordingRedbContext((IRedbContext)factory(sp), recorder); }, descriptor.Lifetime)); } private string Note(string sql) { _recorder.Note(this, sql); return sql; } public bool IsDisposed => _inner.IsDisposed; public IRedbConnection Db => _inner.Db; public IKeyGenerator Keys => _inner.Keys; public IBulkOperations Bulk => _inner.Bulk; public async Task> QueryAsync(string sql, params object[] parameters) where T : new() { if (_recorder.BeforeQuery is { } before) await before(sql); var rows = await _inner.QueryAsync(Note(sql), parameters); if (_recorder.AfterQuery is { } after) await after(sql); return rows; } public async Task> QueryAsync(string sql, object[] parameters, CancellationToken cancellationToken) where T : new() { if (_recorder.BeforeQuery is { } before) await before(sql); var rows = await _inner.QueryAsync(Note(sql), parameters, cancellationToken); if (_recorder.AfterQuery is { } after) await after(sql); return rows; } public Task QueryFirstOrDefaultAsync(string sql, params object[] parameters) where T : class, new() => _inner.QueryFirstOrDefaultAsync(Note(sql), parameters); public Task QueryFirstOrDefaultAsync(string sql, object[] parameters, CancellationToken cancellationToken) where T : class, new() => _inner.QueryFirstOrDefaultAsync(Note(sql), parameters, cancellationToken); public Task ExecuteScalarAsync(string sql, params object[] parameters) => _inner.ExecuteScalarAsync(Note(sql), parameters); public Task ExecuteScalarAsync(string sql, object[] parameters, CancellationToken cancellationToken) => _inner.ExecuteScalarAsync(Note(sql), parameters, cancellationToken); public T? QueryFirstOrDefault(string sql, params object[] parameters) where T : class, new() => _inner.QueryFirstOrDefault(Note(sql), parameters); public T? ExecuteScalar(string sql, params object[] parameters) => _inner.ExecuteScalar(Note(sql), parameters); public string? ExecuteJson(string sql, params object[] parameters) => _inner.ExecuteJson(Note(sql), parameters); public List Query(string sql, params object[] parameters) where T : new() => _inner.Query(Note(sql), parameters); public int Execute(string sql, params object[] parameters) => _inner.Execute(Note(sql), parameters); public Task> QueryScalarListAsync(string sql, params object[] parameters) => _inner.QueryScalarListAsync(Note(sql), parameters); public Task> QueryScalarListAsync(string sql, object[] parameters, CancellationToken cancellationToken) => _inner.QueryScalarListAsync(Note(sql), parameters, cancellationToken); public Task ExecuteAsync(string sql, params object[] parameters) => _inner.ExecuteAsync(Note(sql), parameters); public Task ExecuteAsync(string sql, object[] parameters, CancellationToken cancellationToken) => _inner.ExecuteAsync(Note(sql), parameters, cancellationToken); public Task ExecuteJsonAsync(string sql, params object[] parameters) => _inner.ExecuteJsonAsync(Note(sql), parameters); public Task ExecuteJsonAsync(string sql, object[] parameters, CancellationToken cancellationToken) => _inner.ExecuteJsonAsync(Note(sql), parameters, cancellationToken); public Task> ExecuteJsonListAsync(string sql, params object[] parameters) => _inner.ExecuteJsonListAsync(Note(sql), parameters); public Task> ExecuteJsonListAsync(string sql, object[] parameters, CancellationToken cancellationToken) => _inner.ExecuteJsonListAsync(Note(sql), parameters, cancellationToken); public Task QueryRowsAsJsonAsync(string sql, object[] parameters, CancellationToken cancellationToken = default) => _inner.QueryRowsAsJsonAsync(Note(sql), parameters, cancellationToken); public IRedbTransaction? CurrentTransaction => _inner.CurrentTransaction; public bool IsInTransaction => _inner.IsInTransaction; public Task BeginTransactionAsync(IsolationLevel? isolationLevel = null, CancellationToken cancellationToken = default) => _inner.BeginTransactionAsync(isolationLevel, cancellationToken); public Task ExecuteAtomicAsync(Func operations, CancellationToken cancellationToken = default) => _inner.ExecuteAtomicAsync(operations, cancellationToken); public Task ExecuteAtomicAsync(IsolationLevel isolationLevel, Func operations, CancellationToken cancellationToken = default) => _inner.ExecuteAtomicAsync(isolationLevel, operations, cancellationToken); public Task ExecuteAtomicAsync(Func> operations, CancellationToken cancellationToken = default) => _inner.ExecuteAtomicAsync(operations, cancellationToken); public Task ExecuteAtomicAsync(IsolationLevel isolationLevel, Func> operations, CancellationToken cancellationToken = default) => _inner.ExecuteAtomicAsync(isolationLevel, operations, cancellationToken); public Task NextObjectIdAsync(CancellationToken cancellationToken = default) => _inner.NextObjectIdAsync(cancellationToken); public Task NextValueIdAsync(CancellationToken cancellationToken = default) => _inner.NextValueIdAsync(cancellationToken); public Task NextObjectIdBatchAsync(int count, CancellationToken cancellationToken = default) => _inner.NextObjectIdBatchAsync(count, cancellationToken); public Task NextValueIdBatchAsync(int count, CancellationToken cancellationToken = default) => _inner.NextValueIdBatchAsync(count, cancellationToken); public ValueTask DisposeAsync() => _inner.DisposeAsync(); public void Dispose() => _inner.Dispose(); } Path: redb/redb.Tests.Integration/Tests/Base/RedundantArrayGuardTestsBase.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/RedundantArrayGuardTestsBase.cs ---- using System.Linq.Expressions; using redb.Core; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using redb.Core.Query; using redb.Tests.Integration.Helpers; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// x.Skills != null && x.Skills.Contains(v): the Pro parser drops the null guard, which an element test of the /// same AND chain already implies, so the statement is the one of the test alone. The objects found and their count stay /// those of the guarded condition, over arrays with elements, an empty array and no array, on the flat and the tree /// query. The shapes are those of the examples E168 (Contains), E169 (Contains OR Contains), E170 (Contains AND Contains) /// and E171 (a scalar AND Contains), and Any with a predicate over an array of classes. /// public abstract class RedundantArrayGuardTestsBase { protected readonly IRedbService Redb; protected RedundantArrayGuardTestsBase(IRedbService redb) => Redb = redb; // Seven objects: elements in five of them, an empty array and no array. private static readonly string[]?[] SkillSets = [["C#", "SQL"], ["C#"], ["Python"], ["C#", "Python"], ["SQL"], [], null]; private sealed record Seeded(long RootId, List Ids, List Props); private async Task SeedAsync() { await Redb.SyncSchemeAsync(); var tag = "rag-" + Guid.NewGuid().ToString("N")[..8]; var root = new TreeRedbObject { name = $"{tag}-root", Props = TestDataFactory.CreateEmployee(0, department: $"{tag}-root").Props }; root.id = await Redb.SaveAsync(root); var ids = new List(); var props = new List(); for (var i = 0; i < SkillSets.Length; i++) { var p = TestDataFactory.CreateEmployee(i + 1, firstName: $"{tag}-{i}", department: tag).Props; p.Age = 27 + i; p.Skills = SkillSets[i]; ids.Add(await Redb.CreateChildAsync(new TreeRedbObject { name = $"{tag}-{i}", Props = p }, root)); props.Add(p); } return new Seeded(root.id, ids, props); } private IRedbQueryable Employees(Seeded s, bool tree) { if (tree) return Redb.TreeQuery(s.RootId).WhereRedb(o => o.Id != s.RootId); var idSet = s.Ids.ToHashSet(); return Redb.Query().WhereRedb(o => idSet.Contains(o.Id)); } private static long[] Expected(Seeded s, Func rule) => s.Ids.Where((_, i) => rule(s.Props[i])).OrderBy(id => id).ToArray(); private async Task ShouldFind(Seeded s, bool tree, Expression> filter, long[] expected) { var found = (await Employees(s, tree).Where(filter).ToListAsync()).Select(o => o.id).OrderBy(id => id).ToArray(); found.Should().Equal(expected); (await Employees(s, tree).Where(filter).CountAsync()).Should().Be(expected.Length); } public static TheoryData FlatAndTree => new() { false, true }; [Theory] [MemberData(nameof(FlatAndTree))] public async Task Contains_E168(bool tree) { var s = await SeedAsync(); await ShouldFind(s, tree, e => e.Skills != null && e.Skills.Contains("C#"), Expected(s, p => p.Skills != null && p.Skills.Contains("C#"))); } [Theory] [MemberData(nameof(FlatAndTree))] public async Task ContainsOrContains_E169(bool tree) { var s = await SeedAsync(); await ShouldFind(s, tree, e => e.Skills != null && (e.Skills.Contains("C#") || e.Skills.Contains("Python")), Expected(s, p => p.Skills != null && (p.Skills.Contains("C#") || p.Skills.Contains("Python")))); } [Theory] [MemberData(nameof(FlatAndTree))] public async Task ContainsAndContains_E170(bool tree) { var s = await SeedAsync(); await ShouldFind(s, tree, e => e.Skills != null && e.Skills.Contains("C#") && e.Skills.Contains("SQL"), Expected(s, p => p.Skills != null && p.Skills.Contains("C#") && p.Skills.Contains("SQL"))); } [Theory] [MemberData(nameof(FlatAndTree))] public async Task ScalarAndContains_E171(bool tree) { var s = await SeedAsync(); await ShouldFind(s, tree, e => e.Age > 28 && e.Skills != null && e.Skills.Contains("C#"), Expected(s, p => p.Age > 28 && p.Skills != null && p.Skills.Contains("C#"))); } [Fact] public async Task GuardedStatement_IsTheStatementOfTheTestAlone() { await Redb.SyncSchemeAsync(); async Task Same(Expression> guarded, Expression> alone) { var a = await Redb.Query().Where(guarded).Take(100).ToSqlStringAsync(); var b = await Redb.Query().Where(alone).Take(100).ToSqlStringAsync(); a.Should().Be(b); } await Same(e => e.Skills != null && e.Skills.Contains("C#"), e => e.Skills!.Contains("C#")); await Same(e => e.Skills != null && (e.Skills.Contains("C#") || e.Skills.Contains("Python")), e => e.Skills!.Contains("C#") || e.Skills!.Contains("Python")); await Same(e => e.Age > 30 && e.Skills != null && e.Skills.Contains("C#"), e => e.Age > 30 && e.Skills!.Contains("C#")); } [Fact] public async Task AnyOverAnArrayOfClasses_WithTheGuard() { await Redb.SyncSchemeAsync(); var tag = "rag-" + Guid.NewGuid().ToString("N")[..8]; List rows = [ new() { Tag = tag, Number = 1, Lines = [new() { Kind = "a", Qty = 1 }, new() { Kind = "b", Qty = 2 }] }, new() { Tag = tag, Number = 2, Lines = [new() { Kind = "b", Qty = 3 }] }, new() { Tag = tag, Number = 3, Lines = [] }, new() { Tag = tag, Number = 4 }, ]; await Redb.SaveAsync(rows.Select(p => (IRedbObject)new RedbObject { name = $"{tag}-{p.Number}", Props = p }).ToList()); var query = Redb.Query().Where(p => p.Tag == tag).Where(p => p.Lines != null && p.Lines.Any(l => l.Kind == "a")); (await query.ToListAsync()).Select(o => o.Props.Number).Should().Equal(1); (await query.CountAsync()).Should().Be(1); } } 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); } } Path: redb/redb.Tests.Integration/Tests/Base/ReferenceStubTestsBase.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/ReferenceStubTestsBase.cs ---- using redb.Core; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// The contract for a RedbObject<T> reference at the depth boundary of get_object_json: /// it is a stub — the referenced object's base fields (id, scheme_id, hash, …) /// with no properties — and never null. Identical on the three Free JSON builders. /// /// /// Before V4 the builders disagreed: PostgreSQL and the SQLite extension emitted the stub, MSSQL /// emitted null (a @max_depth > 0 guard in front of the recursive call). The same /// employee loaded with the same depth had a project on two providers and none on the third. /// /// /// /// The stub is also what lazy references are built on (LAZY_REFERENCES_PLAN §2): it carries the id /// to load by and the hash to look the cache up with. So this is a contract test, not a regression /// test — it pins the shape every later piece relies on. /// /// public abstract class ReferenceStubTestsBase : IAsyncLifetime { protected readonly IRedbService Redb; // The database is shared with whole-scheme tests: every object a test saves is deleted after it, // the employees first, then the projects they reference. private readonly List _employees = new(); private readonly List _projects = new(); protected ReferenceStubTestsBase(IRedbService redb) => Redb = redb; public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() { if (_employees.Count > 0) await Redb.DeleteAsync(_employees); if (_projects.Count > 0) await Redb.DeleteAsync(_projects); } // A complete employee, so that a whole-scheme aggregate never meets a zero salary or an empty department. private static EmployeeProps StubEmployee(string firstName, string lastName, long projectId) => new() { FirstName = firstName, LastName = lastName, Age = 30, Position = "dev", Salary = 1000m, Department = "Stub", HireDate = new DateTime(2020, 1, 1, 0, 0, 0, DateTimeKind.Utc), CurrentProject = new RedbObject { id = projectId } }; private async Task<(long employeeId, long projectId)> SaveEmployeeWithProjectAsync(string tag) { var project = new RedbObject { name = $"stub-project-{tag}", Props = new ProjectMetricsProps { ProjectId = 7, TasksTotal = 10, TasksCompleted = 3 } }; var projectId = await Redb.SaveAsync(project); _projects.Add(projectId); var employee = new RedbObject { name = $"stub-employee-{tag}", Props = StubEmployee("Stub", tag, projectId) }; var employeeId = await Redb.SaveAsync(employee); _employees.Add(employeeId); return (employeeId, projectId); } /// /// Depth 1: the root has its properties, the reference under it sits exactly at the boundary. /// [Fact] public async Task AtDepthBoundary_ReferenceIsAStub_NotNull() { var (employeeId, projectId) = await SaveEmployeeWithProjectAsync("boundary"); var loaded = await Redb.LoadAsync(employeeId, depth: 1); loaded.Should().NotBeNull(); loaded!.Props.Should().NotBeNull("the root is never a stub"); var stub = loaded.Props.CurrentProject; stub.Should().NotBeNull("a reference at the depth boundary is a stub, never null — on every provider"); stub!.id.Should().Be(projectId); stub.scheme_id.Should().BeGreaterThan(0, "the stub carries the scheme to materialise by"); stub.hash.Should().NotBeNull("the stub carries the hash the props cache is keyed by"); stub.GetPropsDirectly().Should().BeNull("a stub has no properties, that is what makes it a stub"); } /// Depth 2: the same reference is a full object. The boundary is the only thing that differs. [Fact] public async Task BelowDepthBoundary_ReferenceIsMaterialised() { var (employeeId, projectId) = await SaveEmployeeWithProjectAsync("full"); var loaded = await Redb.LoadAsync(employeeId, depth: 2); var reference = loaded!.Props.CurrentProject; reference.Should().NotBeNull(); reference!.id.Should().Be(projectId); reference.Props.Should().NotBeNull(); reference.Props.TasksTotal.Should().Be(10); } /// /// The stub's hash equals the referenced object's stored hash. LAZY §4.1 hangs on this: the /// parent's hash will use it instead of walking into the reference. /// [Fact] public async Task StubHash_EqualsStoredHashOfReferencedObject() { var (employeeId, projectId) = await SaveEmployeeWithProjectAsync("hash"); var stub = (await Redb.LoadAsync(employeeId, depth: 1))!.Props.CurrentProject!; var full = await Redb.LoadAsync(projectId, depth: 1); stub.hash.Should().Be(full!.hash); } /// /// Saving a parent whose reference is by id only must write the reference and leave the /// referenced object alone. Before the fix the stub was collected as an object to save and the /// parent's save rewrote the project as an empty object: values deleted, name reset to /// Object_<id>, hash cleared — silently, on every provider. /// [Fact] public async Task SavingParent_WithReferenceById_LeavesReferencedObjectIntact() { var (_, projectId) = await SaveEmployeeWithProjectAsync("intact"); var project = await Redb.LoadAsync(projectId, depth: 1); project.Should().NotBeNull(); project!.name.Should().Be("stub-project-intact"); project.hash.Should().NotBeNull(); project.Props.TasksTotal.Should().Be(10); project.Props.TasksCompleted.Should().Be(3); } /// /// The batch save shares the collector with the single save; same contract. Two parents name the /// same project: the reference is not deduplicated away, each parent gets its own reference row. /// [Fact] public async Task SavingParents_InBatch_WithReferenceById_LeavesReferencedObjectIntact() { var project = new RedbObject { name = "stub-project-batch", Props = new ProjectMetricsProps { ProjectId = 8, TasksTotal = 20, TasksCompleted = 5 } }; var projectId = await Redb.SaveAsync(project); _projects.Add(projectId); var employees = Enumerable.Range(0, 2).Select(i => new RedbObject { name = $"stub-employee-batch-{i}", Props = StubEmployee("Batch", i.ToString(), projectId) }).Cast().ToList(); var ids = await Redb.SaveAsync(employees); _employees.AddRange(ids); ids.Should().HaveCount(2); var loaded = await Redb.LoadAsync(projectId, depth: 1); loaded!.name.Should().Be("stub-project-batch"); loaded.Props.TasksTotal.Should().Be(20); foreach (var id in ids) (await Redb.LoadAsync(id, depth: 1))!.Props.CurrentProject!.id.Should().Be(projectId); } } Path: redb/redb.Tests.Integration/Tests/Base/RegexQueryTestsBase.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/RegexQueryTestsBase.cs ---- using System.Text.RegularExpressions; using redb.Core; using redb.Tests.Integration.Helpers; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// Regex.IsMatch and Regex.Replace in a LINQ filter run in the database. A filter the provider drops would return /// every employee, so each test asserts that only matching rows came back. /// LastName is seeded as "Last000".."Last019". /// public abstract class RegexQueryTestsBase { protected readonly IRedbService Redb; protected RegexQueryTestsBase(IRedbService redb) => Redb = redb; [Fact] public async Task IsMatch_FiltersInTheDatabase() { await TestDataFactory.SeedEmployees(Redb, 20); const string pattern = "^Last00[0-2]$"; var hits = await Redb.Query() .Where(e => Regex.IsMatch(e.LastName, pattern)) .ToListAsync(); hits.Should().NotBeEmpty(); hits.Should().OnlyContain(r => Regex.IsMatch(r.Props.LastName, pattern)); } [Fact] public async Task IsMatchIgnoringCase_FiltersInTheDatabase() { await TestDataFactory.SeedEmployees(Redb, 20); const string pattern = "^last00[0-2]$"; var hits = await Redb.Query() .Where(e => Regex.IsMatch(e.LastName, pattern, RegexOptions.IgnoreCase)) .ToListAsync(); hits.Should().NotBeEmpty(); hits.Should().OnlyContain(r => Regex.IsMatch(r.Props.LastName, pattern, RegexOptions.IgnoreCase)); } [Fact] public async Task Replace_FiltersInTheDatabase() { await TestDataFactory.SeedEmployees(Redb, 20); // Only "Last001" becomes "X1". var hits = await Redb.Query() .Where(e => Regex.Replace(e.LastName, "^Last00", "X") == "X1") .ToListAsync(); hits.Should().NotBeEmpty(); hits.Should().OnlyContain(r => r.Props.LastName == "Last001"); } } Path: redb/redb.Tests.Integration/Tests/Base/RolledBackSaveIdsTestsBase.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/RolledBackSaveIdsTestsBase.cs ---- using Microsoft.Extensions.DependencyInjection; using redb.Core; using redb.Core.Attributes; using redb.Core.Data; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; namespace redb.Tests.Integration.Tests.Base; [RedbScheme("RolledBackSaveProbe")] public class RolledBackSaveProps { public string Text { get; set; } = ""; public string[] Tags { get; set; } = Array.Empty(); public List Items { get; set; } = new(); public RedbObject? Leaf { get; set; } } public class RolledBackSaveItem { public string Label { get; set; } = ""; public int Weight { get; set; } } [RedbScheme("RolledBackSaveLeaf")] public class RolledBackSaveLeafProps { public string Note { get; set; } = ""; } /// A scheme no other test syncs: the scheme-cache case drops and recreates it. [RedbScheme("RolledBackSaveFreshScheme")] public class RolledBackSaveFreshProps { public string Text { get; set; } = ""; public int Number { get; set; } } /// /// A save inside a transaction that rolls back. On SQLite the ids of such a save came from the caller's transaction /// (the key cache empty, the single writer's lock held by the caller) and went back with it, while the saved objects /// kept them: the next save got the same ids, and saving the first object again overwrote the second one's row /// (since 4.0.0). The ids of a rolled-back save now go back to 0 on the objects, and the generator never hands out an /// id twice. A rolled-back scheme sync leaves nothing in the scheme caches either. /// Every case starves the shared key cache after BEGIN, so the ids come from inside the transaction; the /// precondition is asserted, a case that took its ids elsewhere fails rather than passes. /// public abstract class RolledBackSaveIdsTestsBase : IAsyncLifetime { private readonly IServiceProvider _services; private readonly string _tag = "rbids-" + Guid.NewGuid().ToString("N")[..10] + "-"; protected RolledBackSaveIdsTestsBase(IServiceProvider services) => _services = services; /// The top of the id sequence, read inside the caller's transaction; null where ids never roll back. protected abstract string? SequenceTopSql { get; } public async Task InitializeAsync() { await using var scope = _services.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); } public async Task DisposeAsync() { await using var scope = _services.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); await redb.Context.ExecuteAsync($"DELETE FROM _objects WHERE _name LIKE '{_tag}%'"); } private RedbObject NewGraph(string who) => new() { name = _tag + who, Props = new RolledBackSaveProps { Text = "written by " + who, Tags = new[] { who + "-t1", who + "-t2", who + "-t3" }, Items = new List { new() { Label = who + "-i1", Weight = 1 }, new() { Label = who + "-i2", Weight = 2 }, }, Leaf = new RedbObject { name = _tag + who + "-leaf", Props = new RolledBackSaveLeafProps { Note = "leaf of " + who }, }, }, }; /// Empties the shared key cache inside an open transaction and returns the sequence top it sees. private async Task StarveKeysAsync(IRedbService redb) { RedbKeyGeneratorBase.ClearAllCaches(); return SequenceTopSql == null ? null : await redb.Context.ExecuteScalarAsync(SequenceTopSql); } private static void AssertTakenInsideTransaction(long? top, long id, string what) { if (top is { } t) Assert.True(id > t, $"precondition: the id of {what} ({id}) comes from inside the transaction (sequence top {t})"); } private async Task AssertGraphAsync(IRedbService redb, long id, string who) { var loaded = await redb.LoadAsync(id); Assert.NotNull(loaded); Assert.Equal(_tag + who, loaded!.name); Assert.Equal("written by " + who, loaded.Props.Text); Assert.Equal(new[] { who + "-t1", who + "-t2", who + "-t3" }, loaded.Props.Tags); Assert.Equal(new[] { who + "-i1", who + "-i2" }, loaded.Props.Items.Select(i => i.Label).ToArray()); Assert.Equal(new[] { 1, 2 }, loaded.Props.Items.Select(i => i.Weight).ToArray()); Assert.NotNull(loaded.Props.Leaf); Assert.Equal("leaf of " + who, loaded.Props.Leaf!.Props.Note); } private async Task CountOwnObjectsAsync(IRedbService redb) => await redb.Context.ExecuteScalarAsync($"SELECT COUNT(*) FROM _objects WHERE _name LIKE '{_tag}%'"); [Fact] public async Task RolledBackSave_ThenAnotherSave_ThenTheFirstAgain_KeepsBothObjects() { await using var scope = _services.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); var a = NewGraph("A"); await using (var tx = await redb.Context.BeginTransactionAsync()) { var top = await StarveKeysAsync(redb); await redb.SaveAsync(a); AssertTakenInsideTransaction(top, a.Id, "A"); await tx.RollbackAsync(); } var (aIdAfterRollback, leafIdAfterRollback) = (a.Id, a.Props.Leaf!.Id); var b = NewGraph("B"); var bId = await redb.SaveAsync(b); var aId = await redb.SaveAsync(a); await AssertGraphAsync(redb, bId, "B"); await AssertGraphAsync(redb, aId, "A"); Assert.NotEqual(aId, bId); Assert.Equal(4, await CountOwnObjectsAsync(redb)); Assert.Equal((0L, 0L), (aIdAfterRollback, leafIdAfterRollback)); } [Fact] public async Task RolledBackSave_ValueRows_EverySaveInItsOwnStarvedTransaction_KeepsBothObjects() { // The same sequence with every save inside a transaction whose ids come from the transaction itself: the // value rows of the second save and of the retry take their ids there too. await using var scope = _services.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); async Task SaveStarvedAsync(RedbObject obj, bool commit) { await using var tx = await redb.Context.BeginTransactionAsync(); await StarveKeysAsync(redb); var id = await redb.SaveAsync(obj); if (commit) await tx.CommitAsync(); else await tx.RollbackAsync(); return id; } var a = NewGraph("A"); await SaveStarvedAsync(a, commit: false); var b = NewGraph("B"); var bId = await SaveStarvedAsync(b, commit: true); var aId = await SaveStarvedAsync(a, commit: true); await AssertGraphAsync(redb, bId, "B"); await AssertGraphAsync(redb, aId, "A"); Assert.NotEqual(aId, bId); Assert.Equal(4, await CountOwnObjectsAsync(redb)); var valueIds = await redb.Context.ExecuteScalarAsync( $"SELECT COUNT(*) FROM _values v JOIN _objects o ON o._id = v._id_object WHERE o._name LIKE '{_tag}%'"); var distinctValueIds = await redb.Context.ExecuteScalarAsync( $"SELECT COUNT(DISTINCT v._id) FROM _values v JOIN _objects o ON o._id = v._id_object WHERE o._name LIKE '{_tag}%'"); Assert.Equal(valueIds, distinctValueIds); } /// Recognized as a deadlock by (the type name and SqlState 40P01). private sealed class PostgresException : Exception { public PostgresException() : base("simulated deadlock") { } public string SqlState => "40P01"; } [Fact] public async Task RetryHelper_FirstAttemptRolledBack_AnotherSaveBetween_KeepsBothObjects() { await using var scope = _services.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); var a = NewGraph("A"); long cId = 0; var attempt = 0; var aId = await DeadlockRetryHelper.ExecuteWithRetryAsync(async () => { attempt++; if (attempt == 2) { // Another unit of work saves between the attempts, from its own scope. await using var other = _services.CreateAsyncScope(); cId = await other.ServiceProvider.GetRequiredService().SaveAsync(NewGraph("C")); } await using var tx = await redb.Context.BeginTransactionAsync(); var top = attempt == 1 ? await StarveKeysAsync(redb) : null; var id = await redb.SaveAsync(a); if (attempt == 1) { AssertTakenInsideTransaction(top, id, "A"); throw new PostgresException(); } await tx.CommitAsync(); return id; }, baseDelayMs: 1); Assert.Equal(2, attempt); await AssertGraphAsync(redb, cId, "C"); await AssertGraphAsync(redb, aId, "A"); Assert.NotEqual(aId, cId); Assert.Equal(4, await CountOwnObjectsAsync(redb)); } [Fact] public async Task ExistingObject_InARolledBackSave_KeepsItsId_NewNestedObjectGoesBackToZero() { await using var scope = _services.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); var e = NewGraph("E"); var eId = await redb.SaveAsync(e); var oldLeafId = e.Props.Leaf!.Id; e.Props.Text = "changed inside"; e.Props.Leaf = new RedbObject { name = _tag + "E-leaf2", Props = new RolledBackSaveLeafProps { Note = "second leaf" }, }; await using (var tx = await redb.Context.BeginTransactionAsync()) { var top = await StarveKeysAsync(redb); await redb.SaveAsync(e); AssertTakenInsideTransaction(top, e.Props.Leaf.Id, "the new leaf"); await tx.RollbackAsync(); } var (eIdAfterRollback, leafIdAfterRollback) = (e.Id, e.Props.Leaf.Id); var rolledBackLeaf = e.Props.Leaf; var b = NewGraph("B"); var bId = await redb.SaveAsync(b); e.Props.Text = "written by E"; e.Props.Leaf = new RedbObject { name = _tag + "E-leaf3", Props = new RolledBackSaveLeafProps { Note = "leaf of E" }, }; await redb.SaveAsync(e); // The leaf of the rolled-back save, saved on its own now: a row of its own, not B's or B's leaf's. var leafId = await redb.SaveAsync(rolledBackLeaf); await AssertGraphAsync(redb, bId, "B"); await AssertGraphAsync(redb, eId, "E"); Assert.Equal("second leaf", (await redb.LoadAsync(leafId))!.Props.Note); Assert.NotEqual(0L, oldLeafId); Assert.Equal((eId, 0L), (eIdAfterRollback, leafIdAfterRollback)); } [Fact] public async Task IdKeptFromARolledBackTransaction_SavedLater_IsNeverHandedOutAgain() { // An id the application took itself inside a transaction that rolled back, stored later with that id: the row // stands above the sequence. The ids handed out after it (another process does not know the in-memory mark, // which the fresh cache domain stands for here), and the trash container of a delete, must skip it. await using var scope = _services.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); long held; await using (var tx = await redb.Context.BeginTransactionAsync()) { var top = await StarveKeysAsync(redb); held = (await redb.Context.NextObjectIdBatchAsync(1))[0]; AssertTakenInsideTransaction(top, held, "the explicit id"); await tx.RollbackAsync(); } // The bulk insert keeps preset ids (SaveAsync would switch an unknown id to a new one). var kept = NewGraph("K"); kept.Props.Leaf = null; kept.Id = held; await redb.AddNewObjectsAsync(new IRedbObject[] { kept }); Assert.Equal(held, kept.Id); // Another process: its first range comes from the stored sequence, not from this process's mark. if (SequenceTopSql != null) await redb.Context.ExecuteAsync($"UPDATE sqlite_sequence SET seq = {held - 1} WHERE name = '_global_identity' AND seq >= {held}"); var victim = NewGraph("V"); var victimId = await redb.SaveAsync(victim); Assert.True(await redb.DeleteAsync(victimId)); RedbKeyGeneratorBase.ClearAllCaches(); var b = NewGraph("B"); var bId = await redb.SaveAsync(b); var keptBack = await redb.LoadAsync(held); Assert.Equal((_tag + "K", "written by K"), (keptBack!.name, keptBack.Props.Text)); await AssertGraphAsync(redb, bId, "B"); Assert.NotEqual(held, bId); } [Fact] public async Task SchemeCreatedInARolledBackTransaction_IsCreatedAgainOnTheNextSave() { await using var scope = _services.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); await DropFreshSchemeAsync(redb); var first = new RedbObject { name = _tag + "fresh-1", Props = new RolledBackSaveFreshProps { Text = "first", Number = 1 }, }; await using (var tx = await redb.Context.BeginTransactionAsync()) { await StarveKeysAsync(redb); await redb.SaveAsync(first); await tx.RollbackAsync(); } Assert.Equal(0L, await redb.Context.ExecuteScalarAsync( "SELECT COUNT(*) FROM _schemes WHERE _name = 'RolledBackSaveFreshScheme'")); var second = new RedbObject { name = _tag + "fresh-2", Props = new RolledBackSaveFreshProps { Text = "second", Number = 2 }, }; var secondId = await redb.SaveAsync(second); var firstId = await redb.SaveAsync(first); var loadedSecond = await redb.LoadAsync(secondId); var loadedFirst = await redb.LoadAsync(firstId); Assert.Equal(("second", 2), (loadedSecond!.Props.Text, loadedSecond.Props.Number)); Assert.Equal(("first", 1), (loadedFirst!.Props.Text, loadedFirst.Props.Number)); var found = await redb.Query().Where(p => p.Number == 2).ToListAsync(); Assert.Contains(found, o => o.Id == secondId); } // Dropped at the start, before this process cached the scheme (no other test uses it), so a rerun on the same // database starts without it too. private static async Task DropFreshSchemeAsync(IRedbService redb) { const string scheme = "(SELECT _id FROM _schemes WHERE _name = 'RolledBackSaveFreshScheme')"; await redb.Context.ExecuteAsync($"DELETE FROM _objects WHERE _id_scheme IN {scheme}"); await redb.Context.ExecuteAsync($"DELETE FROM _scheme_metadata_cache WHERE _scheme_id IN {scheme}"); await redb.Context.ExecuteAsync($"DELETE FROM _structures WHERE _id_scheme IN {scheme}"); await redb.Context.ExecuteAsync("DELETE FROM _schemes WHERE _name = 'RolledBackSaveFreshScheme'"); } [Fact] public async Task StarvedCache_ParallelSavesWithRollbacks_EveryCommittedObjectKeepsItsData() { // The shape of the failures seen under load: the key cache starved, writers in parallel, some transactions // rolled back and their objects saved again. const int workers = 4; const int iterations = 40; var committed = new System.Collections.Concurrent.ConcurrentBag<(long Id, string Who)>(); async Task WorkAsync(int worker) { await using var scope = _services.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); var rolledBack = new List<(RedbObject Obj, string Who)>(); async Task SaveAsync(RedbObject obj, string who, bool rollback) { await using var tx = await redb.Context.BeginTransactionAsync(); await StarveKeysAsync(redb); await redb.SaveAsync(obj); if (rollback) { await tx.RollbackAsync(); rolledBack.Add((obj, who)); } else { await tx.CommitAsync(); committed.Add((obj.Id, who)); } } for (var i = 0; i < iterations; i++) { var who = $"w{worker}-{i}"; await SaveAsync(NewGraph(who), who, rollback: (i + worker) % 3 == 0); // The retries come later, after this worker's and the other workers' saves took ids: every third // iteration retries the oldest rolled-back object, the rest wait for the end. if (i % 3 == 2 && rolledBack.Count > 0) { var (obj, w) = rolledBack[0]; rolledBack.RemoveAt(0); await SaveAsync(obj, w, rollback: false); } } while (rolledBack.Count > 0) { var (obj, w) = rolledBack[0]; rolledBack.RemoveAt(0); await SaveAsync(obj, w, rollback: false); } } await Task.WhenAll(Enumerable.Range(0, workers).Select(WorkAsync)); await using var check = _services.CreateAsyncScope(); var reader = check.ServiceProvider.GetRequiredService(); var lost = new List(); foreach (var (id, who) in committed) { var loaded = await reader.LoadAsync(id); if (loaded?.name != _tag + who || loaded.Props.Text != "written by " + who) lost.Add($"{who} (id {id}) loads as '{loaded?.name}'"); } Assert.True(lost.Count == 0, $"{lost.Count} of {committed.Count} saved objects lost their data: {string.Join("; ", lost.Take(10))}"); foreach (var (id, who) in committed) await AssertGraphAsync(reader, id, who); Assert.Equal(workers * iterations, committed.Select(c => c.Id).Distinct().Count()); Assert.Equal(workers * iterations * 2, await CountOwnObjectsAsync(reader)); } } Path: redb/redb.Tests.Integration/Tests/Base/RootDuplicatesScenario.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/RootDuplicatesScenario.cs ---- using Microsoft.Extensions.Logging; using redb.Core; using redb.Core.Data; using redb.Core.Models.Entities; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// A database written before the schema lock: root fields of one scheme twice (RootStructureKey). Planted by hand on /// the probe scheme, with the unique key of root structures dropped: an empty duplicate of a scalar, an empty duplicate /// of a nested class with its child, and a duplicate of Count holding a value of an object next to the original's. /// public sealed class RootDuplicatesScenario { public long TitleDuplicate { get; private set; } public long PartDuplicate { get; private set; } public long PartDuplicateChild { get; private set; } public long CountDuplicate { get; private set; } public long ObjectId { get; private set; } private const string SchemeName = "schema_lock_sync_probe"; public static async Task PlantAsync(IRedbService redb, IRedbContext context) { var scenario = new RootDuplicatesScenario(); await context.ExecuteAsync($"DROP INDEX IF EXISTS \"{RootStructureKey.IndexName}\""); await redb.SyncSchemeAsync(); scenario.ObjectId = await redb.SaveAsync(new RedbObject { name = "root-duplicates", Props = new SchemaLockSyncProbeProps { Title = "t", Count = 5, Part = new SchemaLockSyncProbePart { City = "c" } } }); var scheme = await context.ExecuteScalarAsync($"SELECT _id FROM _schemes WHERE _name = '{SchemeName}'"); // Ids well above anything the sequence handed out in these test databases. var next = 9_000_000_000L + await context.ExecuteScalarAsync("SELECT CAST(COUNT(*) AS BIGINT) FROM _structures") * 10; async Task CopyAsync(string name, long? parentOfOriginal, long? newParent) { var id = next++; var originalParent = parentOfOriginal == null ? "_id_parent IS NULL" : $"_id_parent = {parentOfOriginal}"; await context.ExecuteAsync( "INSERT INTO _structures (_id, _id_parent, _id_scheme, _id_type, _name, _order, _collection_type, _key_type, _allow_not_null) " + $"SELECT {id}, {(newParent?.ToString() ?? "NULL")}, _id_scheme, _id_type, _name, _order, _collection_type, _key_type, _allow_not_null " + $"FROM _structures WHERE _id_scheme = {scheme} AND _name = '{name}' AND {originalParent}"); return id; } scenario.TitleDuplicate = await CopyAsync("Title", null, null); scenario.PartDuplicate = await CopyAsync("Part", null, null); var part = await context.ExecuteScalarAsync( $"SELECT _id FROM _structures WHERE _id_scheme = {scheme} AND _name = 'Part' AND _id_parent IS NULL AND _id <> {scenario.PartDuplicate}"); scenario.PartDuplicateChild = await CopyAsync("City", part, scenario.PartDuplicate); scenario.CountDuplicate = await CopyAsync("Count", null, null); var count = await context.ExecuteScalarAsync( $"SELECT _id FROM _structures WHERE _id_scheme = {scheme} AND _name = 'Count' AND _id_parent IS NULL AND _id <> {scenario.CountDuplicate}"); await context.ExecuteAsync( "INSERT INTO _values (_id, _id_structure, _id_object, _Long) " + $"SELECT {next++}, {scenario.CountDuplicate}, _id_object, _Long FROM _values WHERE _id_structure = {count} AND _id_object = {scenario.ObjectId}"); return scenario; } /// One more copy of a root field of the probe scheme, empty. public async Task CopyRootAsync(IRedbContext context, string name) { var id = 9_100_000_000L + await context.ExecuteScalarAsync("SELECT CAST(COUNT(*) AS BIGINT) FROM _structures"); await context.ExecuteAsync( "INSERT INTO _structures (_id, _id_parent, _id_scheme, _id_type, _name, _order, _collection_type, _key_type, _allow_not_null) " + $"SELECT {id}, NULL, s._id_scheme, s._id_type, s._name, s._order, s._collection_type, s._key_type, s._allow_not_null " + $"FROM _structures s JOIN _schemes sc ON sc._id = s._id_scheme " + $"WHERE sc._name = '{SchemeName}' AND s._name = '{name}' AND s._id_parent IS NULL AND s._id = " + $"(SELECT MIN(x._id) FROM _structures x WHERE x._id_scheme = s._id_scheme AND x._name = '{name}' AND x._id_parent IS NULL)"); return id; } public static async Task StructureExistsAsync(IRedbContext context, long id) => await context.ExecuteScalarAsync($"SELECT CAST(COUNT(*) AS BIGINT) FROM _structures WHERE _id = {id}") == 1; /// /// After a start over the planted database: Count, the one field whose copies both hold values, is listed by /// SchemaProblems with both ids and logged as an error once. /// public void ShouldReportCountOnly(IRedbService started, CollectingLoggerProvider logs) { var problem = started.SchemaProblems.Should().ContainSingle().Which; problem.Kind.Should().Be(redb.Core.Models.RedbSchemaProblemKind.DuplicateRootStructure); problem.SchemeName.Should().Be(SchemeName); problem.Field.Should().Be("Count"); problem.StructureIds.Should().Contain(CountDuplicate).And.HaveCount(2); logs.Errors.Should().ContainSingle(e => e.Contains("'Count'") && e.Contains("Duplicate root structures")); } /// The hand fix of UPGRADING.md: the duplicate with the value goes, its value with it. public Task ResolveByHandAsync(IRedbContext context) => context.ExecuteAsync($"DELETE FROM _structures WHERE _id = {CountDuplicate}"); } /// Keeps the warnings a service logs, for the tests that expect one. public sealed class CollectingLoggerProvider : ILoggerProvider { public List Warnings { get; } = []; public List Errors { get; } = []; public ILogger CreateLogger(string categoryName) => new Logger(this); public void Dispose() { } private sealed class Logger(CollectingLoggerProvider owner) : ILogger { public IDisposable? BeginScope(TState state) where TState : notnull => null; public bool IsEnabled(LogLevel logLevel) => logLevel >= LogLevel.Warning; public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter) { if (logLevel < LogLevel.Warning) return; lock (owner) (logLevel >= LogLevel.Error ? owner.Errors : owner.Warnings).Add(formatter(state, exception)); } } } Path: redb/redb.Tests.Integration/Tests/Base/RowHolders.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/RowHolders.cs ---- using Microsoft.Data.SqlClient; using Microsoft.Extensions.Configuration; using Npgsql; namespace redb.Tests.Integration.Tests.Base; /// Row-lock holders for : a session of its own per provider. internal static class RowHolders { private static string Cs(string name) => new ConfigurationBuilder().SetBasePath(AppContext.BaseDirectory).AddJsonFile("appsettings.json").Build().GetConnectionString(name)!; /// SQL Server: UPDLOCK on the row; the waiter is found in sys.dm_exec_requests by its blocking session. public static async Task SqlServerAsync(long objectId) { var cs = new SqlConnectionStringBuilder(Cs("MSSql")) { Pooling = false }.ConnectionString; var conn = new SqlConnection(cs); await conn.OpenAsync(); var tx = (SqlTransaction)await conn.BeginTransactionAsync(); await using (var hold = new SqlCommand("SELECT _id FROM _objects WITH (UPDLOCK, ROWLOCK) WHERE _id = @id", conn, tx)) { hold.Parameters.AddWithValue("@id", objectId); await hold.ExecuteScalarAsync(); } int spid; await using (var me = new SqlCommand("SELECT @@SPID", conn, tx)) spid = Convert.ToInt32(await me.ExecuteScalarAsync()); return new Holder( async timeout => { await using var probe = new SqlConnection(cs); await probe.OpenAsync(); await using var cmd = new SqlCommand("SELECT COUNT(*) FROM sys.dm_exec_requests WHERE blocking_session_id = @spid", probe); cmd.Parameters.AddWithValue("@spid", spid); return await PollAsync(async () => Convert.ToInt32(await cmd.ExecuteScalarAsync()) > 0, timeout); }, async sql => { await using (var run = new SqlCommand(sql, conn, tx)) await run.ExecuteNonQueryAsync(); await tx.CommitAsync(); }, async () => { await tx.DisposeAsync(); await conn.DisposeAsync(); }); } /// PostgreSQL: SELECT ... FOR UPDATE; the waiter is found through pg_blocking_pids. public static async Task PostgresAsync(long objectId) { var cs = new NpgsqlConnectionStringBuilder(Cs("Postgres")) { Pooling = false }.ConnectionString; var conn = new NpgsqlConnection(cs); await conn.OpenAsync(); var tx = await conn.BeginTransactionAsync(); await using (var hold = new NpgsqlCommand("SELECT _id FROM _objects WHERE _id = $1 FOR UPDATE", conn, tx)) { hold.Parameters.AddWithValue(objectId); await hold.ExecuteScalarAsync(); } int pid; await using (var me = new NpgsqlCommand("SELECT pg_backend_pid()", conn, tx)) pid = Convert.ToInt32(await me.ExecuteScalarAsync()); return new Holder( async timeout => { await using var probe = new NpgsqlConnection(cs); await probe.OpenAsync(); await using var cmd = new NpgsqlCommand("SELECT count(*) FROM pg_stat_activity WHERE $1 = ANY(pg_blocking_pids(pid))", probe); cmd.Parameters.AddWithValue(pid); return await PollAsync(async () => Convert.ToInt64(await cmd.ExecuteScalarAsync()) > 0, timeout); }, async sql => { await using (var run = new NpgsqlCommand(sql, conn, tx)) await run.ExecuteNonQueryAsync(); await tx.CommitAsync(); }, async () => { await tx.DisposeAsync(); await conn.DisposeAsync(); }); } private static async Task PollAsync(Func> condition, TimeSpan timeout) { var until = DateTime.UtcNow + timeout; while (DateTime.UtcNow < until) { if (await condition()) return true; await Task.Delay(50); } return false; } private sealed class Holder(Func> wait, Func commit, Func dispose) : ConcurrentDeleteCountTestsBase.IRowHolder { public async Task WaitUntilSomeoneWaitsAsync(TimeSpan timeout) { if (!await wait(timeout)) throw new TimeoutException("precondition: the delete never waited on the held row lock"); } public Task ExecuteAndCommitAsync(string sql) => commit(sql); public async ValueTask DisposeAsync() => await dispose(); } } Path: redb/redb.Tests.Integration/Tests/Base/RowMapperKindsTestsBase.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/RowMapperKindsTestsBase.cs ---- using System.Text.Json.Serialization; using redb.Core; namespace redb.Tests.Integration.Tests.Base; /// /// The row mapper of each provider (QueryAsync<T> of redb.Context) over a type with a property of every kind: the /// column names it accepts (the property name in any case, its snake_case name, JsonPropertyName, a leading /// underscore), a column no property takes (ignored), NULL into a nullable property, and the conversions it makes /// (a wider integer into a narrower one, numeric and double into decimal, the database's boolean, guid, timestamp /// and binary types). The mapper now binds the columns once per result set and sets the properties through compiled /// setters; what it reads must not change. /// public abstract class RowMapperKindsTestsBase { protected readonly IRedbService Redb; protected RowMapperKindsTestsBase(IRedbService redb) => Redb = redb; /// /// One row: _id 1 (bigint), count 7 (bigint), maybe_long NULL, amount 12.50 (numeric), from_double 1.5 (double), /// ratio 0.25 (double), flag true, key_value 6f1d0c3e-2b4a-4c8e-9a51-3d2f7e8b9c01, when_at 2026-01-02 03:04:05 UTC, /// day NULL, bytes 0x0102, NAME 'abc', display_name 'shown', first_seen 2026-03-04 00:00:00 UTC, zzz 'x'. /// protected abstract string KindsSql { get; } /// One row: kind 2 (an integer column into an enum property). protected abstract string EnumSql { get; } public enum MapperKind { None = 0, First = 1, Second = 2 } public class MapperKindsRow { public long Id { get; set; } public int Count { get; set; } public long? MaybeLong { get; set; } public decimal Amount { get; set; } public decimal FromDouble { get; set; } public double Ratio { get; set; } public bool Flag { get; set; } public Guid KeyValue { get; set; } public DateTimeOffset WhenAt { get; set; } public DateTime? Day { get; set; } public byte[]? Bytes { get; set; } public string? Name { get; set; } [JsonPropertyName("display_name")] public string? Shown { get; set; } public DateTime FirstSeen { get; set; } } public class MapperEnumRow { public MapperKind Kind { get; set; } } [Fact] public async Task EveryKind_IsReadAsBefore() { var rows = await Redb.Context.QueryAsync(KindsSql); rows.Should().HaveCount(1); var row = rows[0]; row.Id.Should().Be(1); row.Count.Should().Be(7); row.MaybeLong.Should().BeNull(); row.Amount.Should().Be(12.50m); row.FromDouble.Should().Be(1.5m); row.Ratio.Should().Be(0.25); row.Flag.Should().BeTrue(); row.KeyValue.Should().Be(Guid.Parse("6f1d0c3e-2b4a-4c8e-9a51-3d2f7e8b9c01")); row.WhenAt.Should().BeCloseTo(new DateTimeOffset(2026, 1, 2, 3, 4, 5, TimeSpan.Zero), TimeSpan.FromMilliseconds(1)); row.WhenAt.Offset.Should().Be(TimeSpan.Zero); row.Day.Should().BeNull(); row.Bytes.Should().Equal(1, 2); row.Name.Should().Be("abc", "a column name in other case reaches the property"); row.Shown.Should().Be("shown", "JsonPropertyName names the column"); row.FirstSeen.Should().BeCloseTo(new DateTime(2026, 3, 4, 0, 0, 0, DateTimeKind.Utc), TimeSpan.FromMilliseconds(1)); } [Fact] public async Task ManyRows_EachRowItsOwnValues() { // The columns are bound on the first row and reused: every row must still get its own values. var rows = await Redb.Context.QueryAsync( $"SELECT * FROM ({KindsSql}) a UNION ALL SELECT * FROM ({KindsSql.Replace("'abc'", "'def'")}) b"); rows.Select(r => r.Name).Should().BeEquivalentTo(new[] { "abc", "def" }); } /// An integer column into an enum property, as the provider read it before. protected virtual async Task AssertEnumAsync() { var rows = await Redb.Context.QueryAsync(EnumSql); rows.Single().Kind.Should().Be(MapperKind.Second); } [Fact] public Task IntegerIntoEnum_AsBefore() => AssertEnumAsync(); } Path: redb/redb.Tests.Integration/Tests/Base/SaveGraphHashTestsBase.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/SaveGraphHashTestsBase.cs ---- using redb.Core; using redb.Core.Models.Entities; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// A save of a graph that is not a tree (review after 4.0.0, finding 3). The parent's hash carries "id:hash" of every /// reference, so a reference must be hashed before its parents. The collector is pre-order and collects a target shared /// by two parents once, under the first; hashing in reverse collection order put the second parent before the target, /// and its stored hash carried the target's stale hash for ever - a props-cache miss on every load. The same collector /// never deduplicated a new object: one instance referenced twice was collected, given an id and inserted twice. /// public abstract class SaveGraphHashTestsBase { protected readonly IRedbService Redb; protected SaveGraphHashTestsBase(IRedbService redb) => Redb = redb; private static string NewTag() => Guid.NewGuid().ToString("N")[..8]; private static RedbObject Node(string name, string title, RedbObject? left = null, RedbObject? right = null) => new() { name = name, Props = new GraphNodeProps { Title = title, Left = left, Right = right } }; [Fact] public async Task TwoNewParents_SharingAnEditedTarget_StoreTheHashTheLoadRecomputes() { await Redb.SyncSchemeAsync(); var tag = NewTag(); var targetId = await Redb.SaveAsync(Node($"graph-target-{tag}", "v1")); var target = (await Redb.LoadAsync(targetId))!; // Edited: its stored hash is stale, the save recomputes it - and every parent must hash it after that. target.Props.Title = "v2"; var left = Node($"graph-left-{tag}", "left", left: target); var right = Node($"graph-right-{tag}", "right", left: target); await Redb.SaveAsync(Node($"graph-root-{tag}", "root", left: left, right: right)); foreach (var id in new[] { left.id, right.id }) { var loaded = (await Redb.LoadAsync(id))!; loaded.hash.Should().Be(loaded.ComputeHash(), $"the stored hash of '{loaded.name}' must be the hash the loaded object recomputes - the props cache and " + "the ChangeTracking shortcut compare exactly these two"); } } [Fact] public async Task ANewObject_ReferencedByTwoParents_IsSavedOnce() { await Redb.SyncSchemeAsync(); var tag = NewTag(); var shared = Node($"graph-shared-{tag}", "shared"); var a = Node($"graph-a-{tag}", "a", left: shared); var b = Node($"graph-b-{tag}", "b", left: shared); await Redb.SaveAsync(Node($"graph-root2-{tag}", "root", left: a, right: b)); var rows = await Redb.Context.ExecuteScalarAsync( $"SELECT COUNT(*) FROM _objects WHERE _name = 'graph-shared-{tag}'"); rows.Should().Be(1, "one instance is one object, however many parents reference it"); var loadedA = (await Redb.LoadAsync(a.id))!; var loadedB = (await Redb.LoadAsync(b.id))!; loadedA.Props.Left!.id.Should().Be(loadedB.Props.Left!.id, "both parents reference the one saved object"); } } Path: redb/redb.Tests.Integration/Tests/Base/SaveInterceptorTestsBase.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/SaveInterceptorTestsBase.cs ---- using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Core; using redb.Core.Extensions; using redb.Core.Interception; using redb.Core.Models.Configuration; using redb.Core.Models.Entities; using redb.Tests.Integration.Helpers; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// Save-pipeline interceptors (discussion #12, items 3-4), EF-shaped by the owner's decision: /// an exception from Saving cancels the save (nothing reaches the database), an exception from /// Saved propagates but the data IS committed, and under ChangeTracking the Saved context carries /// the value-level diff. Each test builds its own ServiceProvider - interceptors are a DI /// concern, and the shared fixtures must not see them. /// public abstract class SaveInterceptorTestsBase { /// appsettings connection-string name: Postgres / MSSql / Sqlite. protected abstract string ConnectionStringName { get; } /// Provider registration (Free: options.UseX; Pro subclasses use the Pro overload). protected abstract void UseProvider(RedbOptionsBuilder options, string connectionString); /// services.AddRedb for Free, services.AddRedbPro for Pro subclasses. protected virtual void AddRedbServices(IServiceCollection services, Action configure) => services.AddRedb(configure); /// Pro subclasses run ChangeTracking - the Changes feed exists only there. protected virtual PropsSaveStrategy Strategy => PropsSaveStrategy.DeleteInsert; private static async Task CleanupNameAsync(IRedbService redb, string name) => await redb.Context.ExecuteAsync($"DELETE FROM _objects WHERE _name = '{name}'"); private ServiceProvider Build(RecordingInterceptor recorder, bool propsCache = false) { var cs = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build() .GetConnectionString(ConnectionStringName)!; var services = new ServiceCollection(); services.AddLogging(b => b.SetMinimumLevel(LogLevel.Warning)); services.AddSingleton(recorder); AddRedbServices(services, options => { UseProvider(options, cs); options.Configure(c => { c.PropsSaveStrategy = Strategy; c.EnablePropsCache = propsCache; c.CacheDomain = propsCache ? $"save-interceptor-cache-{Guid.NewGuid():N}" : "save-interceptor"; }); }); return services.BuildServiceProvider(); } [Fact] public async Task SavingAndSaved_SeeTheSave_InOrder() { var recorder = new RecordingInterceptor(); await using var sp = Build(recorder); var redb = sp.GetRequiredService(); await redb.SyncSchemeAsync(); await CleanupNameAsync(redb, "interceptor-probe"); var obj = TestDataFactory.CreateSimple("interceptor-probe", 5m); var id = await redb.SaveAsync(obj); recorder.SavingContexts.Should().HaveCount(1); recorder.SavedContexts.Should().HaveCount(1); recorder.Order.Should().Equal("saving", "saved"); var saving = recorder.SavingContexts[0]; saving.RootObjects.Should().ContainSingle().Which.Name.Should().Be("interceptor-probe"); saving.AllObjects.Should().NotBeEmpty(); saving.Strategy.Should().Be(Strategy); var saved = recorder.SavedContexts[0]; saved.SavedIds.Should().Equal(id); saving.NewObjects.Should().ContainSingle("the object arrived without an id - this save creates it"); saved.NewObjectIds.Should().Contain(id, "Saved reports the freshly assigned id"); } [Fact] public async Task ThrowInSaving_CancelsTheSave() { var recorder = new RecordingInterceptor { ThrowInSaving = true }; await using var sp = Build(recorder); var redb = sp.GetRequiredService(); await redb.SyncSchemeAsync(); await CleanupNameAsync(redb, "interceptor-cancelled"); var obj = TestDataFactory.CreateSimple("interceptor-cancelled", 5m); var act = async () => await redb.SaveAsync(obj); await act.Should().ThrowAsync().WithMessage("*saving-veto*"); recorder.SavedContexts.Should().BeEmpty("a cancelled save must not report success"); var count = await redb.Context.ExecuteScalarAsync( "SELECT COUNT(*) FROM _objects WHERE _name = 'interceptor-cancelled'"); count.Should().Be(0, "Saving runs before the transaction opens - nothing may reach the database"); } [Fact] public async Task ThrowInSaved_Propagates_ButTheDataIsCommitted() { var recorder = new RecordingInterceptor { ThrowInSaved = true }; await using var sp = Build(recorder); var redb = sp.GetRequiredService(); await redb.SyncSchemeAsync(); await CleanupNameAsync(redb, "interceptor-saved-throw"); var obj = TestDataFactory.CreateSimple("interceptor-saved-throw", 5m); var act = async () => await redb.SaveAsync(obj); await act.Should().ThrowAsync().WithMessage("*saved-veto*", "EF-style: the Saved exception reaches the caller"); var count = await redb.Context.ExecuteScalarAsync( "SELECT COUNT(*) FROM _objects WHERE _name = 'interceptor-saved-throw'"); count.Should().Be(1, "Saved runs after the commit - the data stays saved"); } [Fact] public async Task ChangesFeed_MatchesTheStrategy() { var recorder = new RecordingInterceptor(); await using var sp = Build(recorder); var redb = sp.GetRequiredService(); await redb.SyncSchemeAsync(); await CleanupNameAsync(redb, "interceptor-diff"); var obj = TestDataFactory.CreateSimple("interceptor-diff", 5m); obj.id = await redb.SaveAsync(obj); var loaded = await redb.LoadAsync(obj.id, depth: 1); loaded!.Props.Title = "interceptor-diff-changed"; await redb.SaveAsync(loaded); var saved = recorder.SavedContexts[^1]; saved.NewObjectIds.Should().BeEmpty("the second save updates an existing object, creates nothing"); if (Strategy == PropsSaveStrategy.ChangeTracking) { saved.Changes.Should().NotBeNull("ChangeTracking computes a diff - the feed hands it over"); saved.Changes!.Should().Contain(c => c.Type == RedbValueChangeType.Update && c.PropertyPath == "Title" && c.NewValue != null && c.NewValue.String == "interceptor-diff-changed", "the edited value must appear as an Update at the model-level path, carrying the new content"); } else { saved.Changes.Should().BeNull("DeleteInsert rewrites everything and diffs nothing"); } } [Fact] public async Task DeletingAndDeleted_SeeTheDelete_AndVetoWorks() { // Happy path + both veto semantics for the delete hooks (owner decision: deletes are // intercepted too). Deleting cancels; Deleted propagates but the row is gone. var recorder = new RecordingInterceptor(); await using var sp = Build(recorder); var redb = sp.GetRequiredService(); await redb.SyncSchemeAsync(); await CleanupNameAsync(redb, "interceptor-delete"); var obj = TestDataFactory.CreateSimple("interceptor-delete", 5m); obj.id = await redb.SaveAsync(obj); (await redb.DeleteAsync(obj)).Should().BeTrue(); recorder.DeletingContexts.Should().ContainSingle().Which.ObjectIds.Should().Equal(obj.id); recorder.DeletedContexts.Should().ContainSingle().Which.DeletedCount.Should().BeGreaterThan(0); recorder.DeletingContexts[0].KnownObjects.Should().ContainSingle("delete-by-object hands the instance over"); } [Fact] public async Task ThrowInDeleting_CancelsTheDelete() { var recorder = new RecordingInterceptor { ThrowInDeleting = true }; await using var sp = Build(recorder); var redb = sp.GetRequiredService(); await redb.SyncSchemeAsync(); await CleanupNameAsync(redb, "interceptor-delete-veto"); var obj = TestDataFactory.CreateSimple("interceptor-delete-veto", 5m); obj.id = await redb.SaveAsync(obj); var act = async () => await redb.DeleteAsync(obj.id); await act.Should().ThrowAsync().WithMessage("*deleting-veto*"); var count = await redb.Context.ExecuteScalarAsync( $"SELECT COUNT(*) FROM _objects WHERE _id = {obj.id}"); count.Should().Be(1, "Deleting runs before the SQL - the object must survive the veto"); recorder.DeletedContexts.Should().BeEmpty(); } [Fact] public async Task ThrowInDeleted_Propagates_ButTheRowIsGone() { var recorder = new RecordingInterceptor { ThrowInDeleted = true }; await using var sp = Build(recorder); var redb = sp.GetRequiredService(); await redb.SyncSchemeAsync(); await CleanupNameAsync(redb, "interceptor-deleted-throw"); var obj = TestDataFactory.CreateSimple("interceptor-deleted-throw", 5m); obj.id = await redb.SaveAsync(obj); var act = async () => await redb.DeleteAsync(obj.id); await act.Should().ThrowAsync().WithMessage("*deleted-veto*"); var count = await redb.Context.ExecuteScalarAsync( $"SELECT COUNT(*) FROM _objects WHERE _id = {obj.id}"); count.Should().Be(0, "Deleted runs after the SQL - the row is gone whatever the interceptor throws"); } /// A root, two children, a grandchild under the first child: four objects, ids in walk order. private static async Task SeedSubtreeAsync(IRedbService redb, string name) { await redb.SyncSchemeAsync(); await CleanupNameAsync(redb, name); var root = new TreeRedbObject { name = name, Props = new SimpleProps { Title = name } }; root.id = await redb.SaveAsync(root); var a = new TreeRedbObject { name = name, Props = new SimpleProps { Title = name, Count = 1 } }; a.id = await redb.CreateChildAsync(a, root); var b = new TreeRedbObject { name = name, Props = new SimpleProps { Title = name, Count = 2 } }; b.id = await redb.CreateChildAsync(b, root); var g = new TreeRedbObject { name = name, Props = new SimpleProps { Title = name, Count = 3 } }; g.id = await redb.CreateChildAsync(g, a); return [root.id, a.id, b.id, g.id]; } /// /// DeleteSubtreeAsync runs the delete interceptors as DeleteAsync does: one DeletingAsync before and one DeletedAsync /// after, with the whole subtree it collected and the count of what it deleted. It used to run none. /// [Fact] public async Task DeleteSubtree_FiresDeletingAndDeleted_WithTheWholeSubtree() { var recorder = new RecordingInterceptor(); await using var sp = Build(recorder); var redb = sp.GetRequiredService(); var ids = await SeedSubtreeAsync(redb, "interceptor-subtree"); recorder.Order.Clear(); var deleted = await redb.DeleteSubtreeAsync(new RedbObject { id = ids[0] }); deleted.Should().Be(4); recorder.Order.Should().Equal("deleting", "deleted"); recorder.DeletingContexts.Should().ContainSingle().Which.ObjectIds.Should().BeEquivalentTo(ids); var done = recorder.DeletedContexts.Should().ContainSingle().Subject; done.ObjectIds.Should().BeEquivalentTo(ids); done.DeletedCount.Should().Be(4); } [Fact] public async Task ThrowInDeleting_CancelsTheSubtreeDelete() { var recorder = new RecordingInterceptor { ThrowInDeleting = true }; await using var sp = Build(recorder); var redb = sp.GetRequiredService(); var ids = await SeedSubtreeAsync(redb, "interceptor-subtree-veto"); var act = async () => await redb.DeleteSubtreeAsync(new RedbObject { id = ids[0] }); await act.Should().ThrowAsync().WithMessage("*deleting-veto*"); var count = await redb.Context.ExecuteScalarAsync( "SELECT COUNT(*) FROM _objects WHERE _name = 'interceptor-subtree-veto'"); count.Should().Be(4, "Deleting runs before the SQL - the subtree must survive the veto"); recorder.DeletedContexts.Should().BeEmpty(); } /// DeleteSubtreeAsync removes every object it deleted from the Props cache, as DeleteAsync does. [Fact] public async Task DeleteSubtree_RemovesTheSubtreeFromThePropsCache() { var recorder = new RecordingInterceptor(); await using var sp = Build(recorder, propsCache: true); var redb = sp.GetRequiredService(); await redb.InitializeAsync(ensureCreated: true); // creates the Props cache of the domain var ids = await SeedSubtreeAsync(redb, "interceptor-subtree-cache"); var cache = ((RedbServiceBase)redb).PropsCache; foreach (var id in ids) cache.Set((await redb.LoadAsync(id))!); cache.GetWithoutHashValidation(ids[3]).Should().NotBeNull("precondition: the grandchild is cached"); await redb.DeleteSubtreeAsync(new RedbObject { id = ids[0] }); foreach (var id in ids) cache.GetWithoutHashValidation(id).Should().BeNull("object {0} was deleted", id); } [Fact] public async Task RegistrySubscription_InALiveScope_RunsAfterDi_AndStopsOnDispose() { // A module subscribes after the service exists (its scope is open, the DI interceptors fixed): the very next // save reaches it after the DI one; once disposed, nothing reaches it, while the DI interceptor goes on. var journal = new List(); var fromDi = new RecordingInterceptor { Tag = "di", Journal = journal }; await using var sp = Build(fromDi); var redb = sp.GetRequiredService(); await redb.SyncSchemeAsync(); await CleanupNameAsync(redb, "interceptor-registry"); var module = new RecordingInterceptor { Tag = "module", Journal = journal }; var subscription = sp.GetRequiredService().Add(module); var obj = TestDataFactory.CreateSimple("interceptor-registry", 5m); obj.id = await redb.SaveAsync(obj); journal.Should().Equal("di:saving", "module:saving", "di:saved", "module:saved"); module.SavedContexts.Should().ContainSingle().Which.SavedIds.Should().Equal(obj.id); subscription.Dispose(); journal.Clear(); obj.Props.Title = "interceptor-registry-2"; await redb.SaveAsync(obj); await redb.DeleteAsync(obj.id); journal.Should().Equal("di:saving", "di:saved", "di:deleting", "di:deleted"); module.SavedContexts.Should().HaveCount(1, "a disposed subscription is not called again"); } [Fact] public async Task RegistrySubscription_SeesDeletes_AndItsVetoCancelsAnySave() { var recorderFromDi = new RecordingInterceptor(); await using var sp = Build(recorderFromDi); var redb = sp.GetRequiredService(); await redb.SyncSchemeAsync(); await CleanupNameAsync(redb, "interceptor-registry-delete"); await CleanupNameAsync(redb, "interceptor-registry-veto"); var registry = sp.GetRequiredService(); var obj = TestDataFactory.CreateSimple("interceptor-registry-delete", 5m); obj.id = await redb.SaveAsync(obj); var module = new RecordingInterceptor(); using (registry.Add(module)) (await redb.DeleteAsync(obj)).Should().BeTrue(); module.DeletingContexts.Should().ContainSingle().Which.ObjectIds.Should().Equal(obj.id); module.DeletedContexts.Should().ContainSingle(); var veto = new RecordingInterceptor { ThrowInSaving = true }; using (registry.Add(veto)) { var act = async () => await redb.SaveAsync(TestDataFactory.CreateSimple("interceptor-registry-veto", 5m)); await act.Should().ThrowAsync().WithMessage("*saving-veto*"); } var count = await redb.Context.ExecuteScalarAsync( "SELECT COUNT(*) FROM _objects WHERE _name = 'interceptor-registry-veto'"); count.Should().Be(0, "a registry interceptor vetoes like a DI one: nothing reaches the database"); } [Fact] public async Task RegistrySubscription_MadeDuringASave_WaitsForTheNextOne() { // One snapshot per operation: an interceptor subscribed while a save runs must not get a Saved without its // Saving. The next save sees it from the start. var registry = default(IRedbSaveInterceptorRegistry); var late = new RecordingInterceptor { Tag = "late" }; IDisposable? lateSubscription = null; var fromDi = new RecordingInterceptor { OnSaving = () => lateSubscription ??= registry!.Add(late), }; await using var sp = Build(fromDi); registry = sp.GetRequiredService(); var redb = sp.GetRequiredService(); await redb.SyncSchemeAsync(); await CleanupNameAsync(redb, "interceptor-registry-late"); var obj = TestDataFactory.CreateSimple("interceptor-registry-late", 5m); obj.id = await redb.SaveAsync(obj); late.SavingContexts.Should().BeEmpty(); late.SavedContexts.Should().BeEmpty("the save had started without it"); obj.Props.Title = "interceptor-registry-late-2"; await redb.SaveAsync(obj); late.Order.Should().Equal("saving", "saved"); lateSubscription!.Dispose(); } private sealed class RecordingInterceptor : IRedbSaveInterceptor { /// Prefix of the entries this recorder writes into . public string Tag { get; init; } = ""; /// A journal shared with other recorders, to see their relative order. public List? Journal { get; init; } /// Runs inside SavingAsync, before the recording. public Action? OnSaving { get; init; } public List SavingContexts { get; } = new(); public List SavedContexts { get; } = new(); public List DeletingContexts { get; } = new(); public List DeletedContexts { get; } = new(); public List Order { get; } = new(); public bool ThrowInSaving { get; init; } public bool ThrowInSaved { get; init; } public bool ThrowInDeleting { get; init; } public bool ThrowInDeleted { get; init; } private void Record(string hook) { Order.Add(hook); Journal?.Add($"{Tag}:{hook}"); } public Task SavingAsync(RedbSavingContext context, CancellationToken cancellationToken = default) { OnSaving?.Invoke(); SavingContexts.Add(context); Record("saving"); if (ThrowInSaving) throw new InvalidOperationException("saving-veto"); return Task.CompletedTask; } public Task SavedAsync(RedbSavedContext context, CancellationToken cancellationToken = default) { SavedContexts.Add(context); Record("saved"); if (ThrowInSaved) throw new InvalidOperationException("saved-veto"); return Task.CompletedTask; } public Task DeletingAsync(RedbDeletingContext context, CancellationToken cancellationToken = default) { DeletingContexts.Add(context); Record("deleting"); if (ThrowInDeleting) throw new InvalidOperationException("deleting-veto"); return Task.CompletedTask; } public Task DeletedAsync(RedbDeletedContext context, CancellationToken cancellationToken = default) { DeletedContexts.Add(context); Record("deleted"); if (ThrowInDeleted) throw new InvalidOperationException("deleted-veto"); return Task.CompletedTask; } } } Path: redb/redb.Tests.Integration/Tests/Base/SaveLockScopeTestsBase.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/SaveLockScopeTestsBase.cs ---- using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Core; using redb.Core.Extensions; using redb.Core.Models.Entities; using redb.Core.Query; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// A save locks the rows of the objects that existed before it (ObjectStorage_LockObjectsForUpdate) and nothing else. /// The ids of the objects it creates are given out before the write, and the save used to lock them too: rows that do /// not exist yet, and on SQL Server a lock statement that then read the rows of concurrent writers and deadlocked /// writers of disjoint objects. The statements are seen through the test context. /// public abstract class SaveLockScopeTestsBase { private readonly SqlRecorder _recorder = new(); protected abstract void UseProvider(RedbOptionsBuilder options); protected virtual void Register(IServiceCollection services, Action configure) => services.AddRedb(configure); private ServiceProvider Build() { var services = new ServiceCollection(); services.AddLogging(b => b.SetMinimumLevel(LogLevel.Warning)); Register(services, options => { UseProvider(options); options.Configure(c => c.CacheDomain = $"save-lock-{GetType().Name}-{Guid.NewGuid():N}"); }); RecordingRedbContext.Decorate(services, _recorder); return services.BuildServiceProvider(); } private async Task<(ServiceProvider Host, IRedbService Redb, string LockSql)> StartAsync() { var host = Build(); var redb = host.GetRequiredService(); await redb.InitializeAsync(ensureCreated: true); await redb.SyncSchemeAsync(); return (host, redb, host.GetRequiredService().ObjectStorage_LockObjectsForUpdate()); } private static RedbObject NewRow(string tag) => new() { name = tag, Props = new ConcurrentWriterRowProps { Tag = tag, Key = tag, Payload = "p", WrittenAt = DateTimeOffset.UtcNow } }; private int LockStatements(IReadOnlyList commands, string lockSql) => commands.Count(c => c.Sql == lockSql); [Fact] public async Task NewObject_TopLevelSave_TakesNoLock() { var (host, redb, lockSql) = await StartAsync(); await using var _ = host; _recorder.Start(); var id = await redb.SaveAsync(NewRow($"lock-new-{Guid.NewGuid():N}")); var commands = _recorder.Stop(); id.Should().BePositive(); LockStatements(commands, lockSql).Should().Be(0, "an object this save creates has no row to lock yet"); } [Fact] public async Task NewObject_SaveInsideExecuteAtomic_TakesNoLock() { var (host, redb, lockSql) = await StartAsync(); await using var _ = host; _recorder.Start(); await redb.Context.ExecuteAtomicAsync(() => redb.SaveAsync(NewRow($"lock-atomic-{Guid.NewGuid():N}"))); var commands = _recorder.Stop(); LockStatements(commands, lockSql).Should().Be(0, "inside a transaction too, a new object has no row to lock"); } [Fact] public async Task ExistingObject_Resave_LocksItsRow() { var (host, redb, lockSql) = await StartAsync(); await using var _ = host; var tag = $"lock-old-{Guid.NewGuid():N}"; var id = await redb.SaveAsync(NewRow(tag)); var loaded = (await redb.LoadAsync(id))!; loaded.Props.Payload = "changed"; _recorder.Start(); await redb.SaveAsync(loaded); var commands = _recorder.Stop(); LockStatements(commands, lockSql).Should().Be(1, "an existing object's row is locked before it is rewritten"); } } Path: redb/redb.Tests.Integration/Tests/Base/SchemaInitTestsBase.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/SchemaInitTestsBase.cs ---- using Microsoft.Extensions.DependencyInjection; using redb.Core; using redb.Core.Models.Entities; using redb.Export.Services; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// redb init () on PostgreSQL and SQL Server: into an empty database it creates the /// schema with the module this build requires; a database that already holds the redb schema is refused before anything /// runs. Run over an existing database, the SQL Server script dropped every foreign key and the id sequence before its /// first CREATE TABLE failed, and the database went on without them. Scratch databases of their own, dropped afterwards. /// public abstract class SchemaInitTestsBase { /// postgres or mssql. protected abstract string ProviderName { get; } /// The module version this build requires. protected abstract string RequiredVersion { get; } /// A new empty database of this run; the subclass drops it afterwards. protected abstract Task NewDatabaseAsync(string suffix); /// A redb service over with a cache domain of its own. protected abstract ServiceProvider Build(string cs); /// The first column of the first row as text. protected abstract Task ScalarAsync(string cs, string sql); /// The sequences, the foreign keys, the triggers with their state, the module version. protected abstract Task> CatalogAsync(string cs); [Fact] public async Task Init_IntoAnEmptyDatabase_CreatesTheSchemaWithTheRequiredModule() { var cs = await NewDatabaseAsync("init"); await SchemaInitService.InitializeAsync(ProviderName, cs); (await CatalogAsync(cs)).Should().Contain($"module {RequiredVersion}"); await using var provider = Build(cs); await provider.GetRequiredService().InitializeAsync(typeof(ExportService).Assembly); } [Fact] public async Task ASecondInit_IsRefused_AndTouchesNothing() { var cs = await NewDatabaseAsync("again"); await SchemaInitService.InitializeAsync(ProviderName, cs); await using (var provider = Build(cs)) { var redb = provider.GetRequiredService(); await redb.InitializeAsync(typeof(ExportService).Assembly); await redb.SyncSchemeAsync(); await redb.SaveAsync(new RedbObject { name = "kept", Props = new SimpleProps { Title = "k" } }); } var before = await StateAsync(cs); before.Should().Contain(l => l.StartsWith("fk ", StringComparison.Ordinal), "precondition: init created the foreign keys"); before.Should().Contain(l => l.StartsWith("sequence ", StringComparison.Ordinal), "precondition: init created the id sequence"); var initAgain = async () => await SchemaInitService.InitializeAsync(ProviderName, cs); (await initAgain.Should().ThrowAsync()).Which.Message .Should().Contain("already holds the redb schema").And.Contain("has changed nothing") .And.Contain($"redb schema --upgrade --provider {ProviderName}"); (await StateAsync(cs)).Should().Equal(before); } private async Task> StateAsync(string cs) { var lines = await CatalogAsync(cs); foreach (var table in new[] { "_schemes", "_structures", "_objects", "_values", "_users", "_roles" }) lines.Add($"{table}={await ScalarAsync(cs, $"SELECT COUNT(*) FROM {table}")}"); return lines; } } Path: redb/redb.Tests.Integration/Tests/Base/SchemaMissingTestsBase.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/SchemaMissingTestsBase.cs ---- using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Core; using redb.Core.Exceptions; using redb.Core.Extensions; namespace redb.Tests.Integration.Tests.Base; /// /// InitializeAsync() without ensureCreated: true on a database that has no redb /// schema. Creation is opt-in by design (owner, 2026-09-12: the application role usually may not /// run DDL, and an unexpected empty database is more often a wrong connection string than a /// fresh installation) - but the failure used to be a raw driver error from the first start-up /// query, saying nothing about ensureCreated. Pinned: the situation is named by /// with the way out in the message, and the way out works. /// Each suite provides a throwaway empty database on its own server. /// public abstract class SchemaMissingTestsBase { /// Creates an empty database (no redb schema) and returns its connection string. protected abstract Task CreateEmptyDatabaseAsync(); /// Drops the database created by . protected abstract Task DropDatabaseAsync(string connectionString); protected abstract void UseProvider(RedbOptionsBuilder options, string connectionString); protected static string ConnString(string name) => new ConfigurationBuilder() .SetBasePath(AppContext.BaseDirectory) .AddJsonFile("appsettings.json") .Build() .GetConnectionString(name)!; private ServiceProvider Build(string connectionString) { var services = new ServiceCollection(); services.AddLogging(b => b.SetMinimumLevel(LogLevel.Warning)); services.AddRedb(options => { UseProvider(options, connectionString); options.Configure(c => { c.EnablePropsCache = false; c.CacheDomain = $"schema-missing-{GetType().Name}"; }); }); return services.BuildServiceProvider(); } [Fact] public async Task InitializeWithoutEnsureCreated_OnAnEmptyDatabase_NamesTheSituation() { var cs = await CreateEmptyDatabaseAsync(); try { await using (var sp = Build(cs)) { var redb = sp.GetRequiredService(); var act = async () => await redb.InitializeAsync(); var thrown = await act.Should().ThrowAsync( "an empty database must be named as such, not surface a raw driver error from the first start-up query"); thrown.Which.Message.Should().Contain("ensureCreated: true", "the message must say how to get out of it"); } // The way out the message names works on the very same database. await using (var sp = Build(cs)) { var redb = sp.GetRequiredService(); await redb.InitializeAsync(ensureCreated: true); } } finally { await DropDatabaseAsync(cs); } } } Path: redb/redb.Tests.Integration/Tests/Base/SchemaUpgradeTestsBase.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/SchemaUpgradeTestsBase.cs ---- using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Core; using redb.Core.Data; using redb.Core.Exceptions; using redb.Core.Extensions; using redb.Core.Models.Entities; using redb.Tests.Integration.Fixtures; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// Start-up against a database whose SQL module is behind this build — the situation every existing /// installation is in on the first start after an upgrade — under the three policies that matter: /// /// /// the connected role owns the schema: the module is applied automatically (the behaviour /// every 3.x installation relies on); /// the connected role may read and write but not change the schema — the DBA revoked owner /// rights after installing: start-up must stop with /// naming the script, not with a driver error; /// AutoApplyDatabaseUpgrades = false: start-up stops with the same exception without /// trying, whatever the rights. /// /// /// /// No shared fixture can model this — the shared test database is upgraded by the first fixture that /// touches it. Each provider subclass therefore owns a database of its own (redb_upgrade_<run>), /// created from the schema script, and a restricted login of its own, both named with the suffix of the run /// (). They live for the class and are dropped by their exact names after it; the tests reset /// the module version themselves. /// /// public abstract class SchemaUpgradeTestsBase : IAsyncLifetime, IClassFixture { protected SchemaUpgradeTestsBase(SchemaUpgradeCleanup cleanup) { RunSuffix = cleanup.Suffix; cleanup.Register(DropOwnedServerObjectsAsync); } /// The suffix of this run in the names of the class's databases and login or role. protected string RunSuffix { get; } /// /// Drops the databases and the login or role this class owns on the test server. Runs once, after the last test of /// the class, also when tests failed: the suites run on shared servers. /// protected abstract Task DropOwnedServerObjectsAsync(); /// Connection string of an owner/admin login to the upgrade database. protected abstract string OwnerConnectionString { get; } /// Connection string of a login that may read and write but not change the schema. protected abstract string RestrictedConnectionString { get; } /// Provider registration for AddRedb. protected abstract void UseProvider(RedbOptionsBuilder options, string connectionString); /// /// Creates the database (if absent) and the restricted login. Runs once per test class /// instance; idempotent. The schema itself is created by the first owner start-up below. /// protected abstract Task PrepareDatabaseAndLoginAsync(); /// /// Grants the restricted login DML on every table and EXECUTE on every function — after the /// schema exists, which is why this is a second step. Idempotent. /// protected abstract Task GrantRestrictedAsync(); /// Rewrites the module version function in the database to return the given string. protected abstract Task SetDeployedModuleVersionAsync(string version); /// Reads the module version the database currently reports. protected abstract Task ReadDeployedModuleVersionAsync(); /// /// Rewrites the module compatibility function to return the given value; null drops the function, as a module of /// a version before it has none. /// protected abstract Task SetDeployedModuleCompatAsync(string? compat); /// Drops and re-creates a SEPARATE, completely empty database for the fresh-install test. protected abstract Task RecreateFreshDatabaseAsync(); /// Owner connection string pointing at that fresh-install database. protected abstract string FreshDatabaseConnectionString { get; } private string? _requiredVersion; public async Task InitializeAsync() { await PrepareDatabaseAndLoginAsync(); // Learn what this build requires by starting once as owner: after that the database is // current and the tests below roll it back deliberately. await using var sp = Build(OwnerConnectionString, autoApply: true); var redb = sp.GetRequiredService(); await redb.InitializeAsync(ensureCreated: true); _requiredVersion = await ReadDeployedModuleVersionAsync(); _requiredVersion.Should().NotBeNullOrWhiteSpace(); await GrantRestrictedAsync(); } public Task DisposeAsync() => Task.CompletedTask; /// /// Registration entry point. Pro subclasses swap in AddRedbPro: the upgrade contract is /// the tier's, not the provider's, and Pro tiers used to opt out of the module deployment /// altogether - which left every existing database without the V4 columns. /// protected virtual void AddRedbServices(IServiceCollection services, Action configure) => services.AddRedb(configure); protected ServiceProvider Build(string connectionString, bool autoApply, string cacheDomain = "schema-upgrade", ILoggerProvider? logs = null) { var services = new ServiceCollection(); services.AddLogging(b => { b.SetMinimumLevel(LogLevel.Warning); if (logs != null) b.AddProvider(logs); }); AddRedbServices(services, options => { UseProvider(options, connectionString); options.Configure(c => { c.AutoApplyDatabaseUpgrades = autoApply; c.EnablePropsCache = false; // Own cache domain: this process also holds services on the shared test database. c.CacheDomain = cacheDomain; }); }); return services.BuildServiceProvider(); } /// /// Starts services at once against one database, each with a cache domain of its own, /// as the nodes of a cluster are separate processes. Returns the failures. /// private async Task> StartTogetherAsync(string connectionString, int nodes, bool ensureCreated) { var providers = Enumerable.Range(0, nodes) .Select(i => Build(connectionString, autoApply: true, cacheDomain: $"schema-upgrade-node{i}-{Guid.NewGuid():N}")) .ToList(); try { var starts = providers.Select(sp => Task.Run(async () => { try { await sp.GetRequiredService().InitializeAsync(ensureCreated); return null; } catch (Exception ex) { return ex; } })); return (await Task.WhenAll(starts)).Where(e => e != null).Select(e => e!).ToList(); } finally { foreach (var sp in providers) await sp.DisposeAsync(); } } [Fact] public async Task Owner_OutdatedModule_NodesStartingTogether_AllStart() { // FOREIGN-BUGS 7 of the AS4 stand: the panel and the worker of a Tsak cluster both met a database one module // behind, both applied the bundle, and the second died on "index already exists". The schema lock makes them // take turns; the one that waited finds the module deployed. for (var round = 0; round < 5; round++) { await SetDeployedModuleVersionAsync("0.0.0-test"); var failures = await StartTogetherAsync(OwnerConnectionString, nodes: 4, ensureCreated: false); failures.Should().BeEmpty($"every node starts (round {round})"); (await ReadDeployedModuleVersionAsync()).Should().Be(_requiredVersion); } } [Fact] public async Task FreshDatabase_NodesCreatingTheSchemaTogether_AllStart() { // Nodes starting together against an empty database: one creates the schema, the others find it created. // The scheme synchronization that follows runs under the same lock, so they do not insert the same schemes. for (var round = 0; round < 3; round++) { await RecreateFreshDatabaseAsync(); var failures = await StartTogetherAsync(FreshDatabaseConnectionString, nodes: 3, ensureCreated: true); failures.Should().BeEmpty($"every node starts (round {round})"); } } [Fact] public async Task RestrictedRole_DeployedDatabase_StartsWithoutSchemaWork() { // A database in step: tables there, module current, schemes synced by the owner in InitializeAsync above. A // role that may not change the schema starts, since nothing is left to change and no lock is taken. await using var sp = Build(RestrictedConnectionString, autoApply: true, cacheDomain: $"restricted-{Guid.NewGuid():N}"); await sp.GetRequiredService().InitializeAsync(ensureCreated: true); } [Fact] public async Task RestrictedRole_DeployedDatabase_SavesLoadsUpdatesAndDeletes() { // The application of a DBA-deployed database: it may read, write and execute, and nothing else. It starts with // schema changes turned off and does its whole data work: a new scheme, new objects (one and a list, flat and // under a parent), a load, a query, an update, a delete. No grant beyond the ones of GrantRestrictedAsync. await using var sp = Build(RestrictedConnectionString, autoApply: false, cacheDomain: $"restricted-data-{Guid.NewGuid():N}"); var redb = sp.GetRequiredService(); await redb.InitializeAsync(ensureCreated: true); await redb.SyncSchemeAsync(); var tag = "restricted-" + Guid.NewGuid().ToString("N")[..8]; var root = new TreeRedbObject { name = tag, Props = new SimpleProps { Title = tag, Count = 1 } }; root.id = await redb.SaveAsync(root); var childId = await redb.CreateChildAsync( new TreeRedbObject { name = tag + "-child", Props = new SimpleProps { Title = tag, Count = 2 } }, root); var listIds = await redb.SaveAsync(Enumerable.Range(3, 3) .Select(i => new RedbObject { name = $"{tag}-{i}", Props = new SimpleProps { Title = tag, Count = i } }) .ToList()); (await redb.Query().Where(p => p.Title == tag).CountAsync()).Should().Be(5); var loaded = (await redb.LoadAsync(childId))!; loaded.Props.Count.Should().Be(2); loaded.Props.Count = 20; await redb.SaveAsync(loaded); (await redb.LoadAsync(childId))!.Props.Count.Should().Be(20); (await redb.DeleteAsync(listIds)).Should().Be(3); (await redb.Query().Where(p => p.Title == tag).CountAsync()).Should().Be(2); } [Fact] public async Task Save_WithAReferenceToAMissingObject_IsRefusedByTheDatabase() { // The database keeps the references whole on every provider: an id that names no object is refused by the // foreign key, and nothing of the save stays behind. A bulk load that skipped the keys stored such a row on // SQL Server and gave the reference back as null. await using var sp = Build(OwnerConnectionString, autoApply: true, cacheDomain: $"dangling-ref-{Guid.NewGuid():N}"); var redb = sp.GetRequiredService(); await redb.InitializeAsync(ensureCreated: true); await redb.SyncSchemeAsync(); var name = "dangling-ref-" + Guid.NewGuid().ToString("N")[..8]; var act = () => redb.SaveAsync(new RedbObject { name = name, Props = new LazyNodeProps { Label = "a", Next = new RedbObject { id = MissingObjectId } } }); (await act.Should().ThrowAsync()).Which.ToString().Should().ContainEquivalentOf("foreign key"); (await redb.Query().WhereRedb(o => o.Name == name).CountAsync()).Should().Be(0, "the refused save leaves no object"); } [Fact] public async Task Save_UnderAMissingParent_IsRefusedByTheDatabase() { await using var sp = Build(OwnerConnectionString, autoApply: true, cacheDomain: $"dangling-parent-{Guid.NewGuid():N}"); var redb = sp.GetRequiredService(); await redb.InitializeAsync(ensureCreated: true); await redb.SyncSchemeAsync(); var name = "dangling-parent-" + Guid.NewGuid().ToString("N")[..8]; var act = () => redb.SaveAsync(new RedbObject { name = name, parent_id = MissingObjectId, Props = new SimpleProps { Title = name, Count = 1 } }); (await act.Should().ThrowAsync()).Which.ToString().Should().ContainEquivalentOf("foreign key"); (await redb.Query().WhereRedb(o => o.Name == name).CountAsync()).Should().Be(0, "the refused save leaves no object"); } /// An id no object of a test database has. private const long MissingObjectId = 987_654_321_987; [Fact] public async Task Scheme_NodesSyncingItTogether_AllSucceed() { // Runtime scheme sync (outside InitializeAsync): the workers of a Tsak cluster load modules sharing a Props // class, or a module version adding a field reaches every node at once. The sync that has to write takes the // schema lock; the nodes that waited find the scheme in step. var providers = Enumerable.Range(0, 4) .Select(i => Build(OwnerConnectionString, autoApply: true, cacheDomain: $"scheme-sync-node{i}-{Guid.NewGuid():N}")) .ToList(); try { var nodes = new List(); foreach (var sp in providers) { var redb = sp.GetRequiredService(); await redb.InitializeAsync(ensureCreated: true); nodes.Add(redb); } var failures = await SchemeSyncRace.RunAsync(nodes, providers[0].GetRequiredService(), rounds: 8); failures.Should().BeEmpty(); } finally { foreach (var sp in providers) await sp.DisposeAsync(); } } [Fact] public async Task FreshDatabase_InitializesFromScratch_AndRoundTrips() { // BR-5: the generated init ran the 28th migration's cache resync before the 29th file had // created the function - a TRULY fresh database died with 42883 mid-init, while every // lived-in database (these suites' databases included: they persist between runs) kept the // previous version of the function and never noticed. This is the fresh-install test that // was missing: an empty database, the full init, a working round trip. await RecreateFreshDatabaseAsync(); await using var sp = Build(FreshDatabaseConnectionString, autoApply: true); var redb = sp.GetRequiredService(); await redb.InitializeAsync(ensureCreated: true); await redb.SyncSchemeAsync(); var id = await redb.SaveAsync(new redb.Core.Models.Entities.RedbObject { name = "fresh-install", Props = new redb.Tests.Integration.Models.SimpleProps { Title = "fresh", Count = 1 } }); (await redb.LoadAsync(id, depth: 1))! .Props.Title.Should().Be("fresh"); } [Fact] public async Task Owner_OutdatedModule_IsUpgradedAutomatically() { await SetDeployedModuleVersionAsync("0.0.0-test"); await using var sp = Build(OwnerConnectionString, autoApply: true); await sp.GetRequiredService().InitializeAsync(ensureCreated: true); (await ReadDeployedModuleVersionAsync()).Should().Be(_requiredVersion, "an owner start-up must bring the module to the version the build requires"); } /// /// A database whose _types say String for TimeOnly and TimeSpan (created before they moved to Ticks in _Long) says /// Long after the module upgrade, in _types and in the metadata cache, so it writes their Ticks. Stored values are /// not converted; the module only changes the type rows. /// [Fact] public async Task Owner_OutdatedModule_SetsLongForTimeOnlyAndTimeSpan() { const string ids = "(-9223372036854775685, -9223372036854775684)"; await using (var sp = Build(OwnerConnectionString, autoApply: true)) { var ctx = sp.GetRequiredService(); await ctx.ExecuteAsync($"UPDATE _types SET _db_type = 'String' WHERE _id IN {ids}"); await ctx.ExecuteAsync($"UPDATE _scheme_metadata_cache SET db_type = 'String' WHERE _type_id IN {ids}"); } await SetDeployedModuleVersionAsync("0.0.0-test"); await using (var sp = Build(OwnerConnectionString, autoApply: true)) { await sp.GetRequiredService().InitializeAsync(ensureCreated: true); var ctx = sp.GetRequiredService(); (await ctx.ExecuteScalarAsync($"SELECT COUNT(*) FROM _types WHERE _id IN {ids} AND _db_type = 'Long'")) .Should().Be(2, "the module upgrade sets Long for TimeOnly and TimeSpan"); (await ctx.ExecuteScalarAsync($"SELECT COUNT(*) FROM _scheme_metadata_cache WHERE _type_id IN {ids} AND db_type <> 'Long'")) .Should().Be(0, "and the copy in the metadata cache"); } } [Fact] public async Task RestrictedRole_OutdatedModule_StopsWithSchemaOutdated_NotDriverError() { await SetDeployedModuleVersionAsync("0.0.0-test"); try { await using var sp = Build(RestrictedConnectionString, autoApply: true); var act = async () => await sp.GetRequiredService().InitializeAsync(ensureCreated: true); var ex = (await act.Should().ThrowAsync()).Which; ex.DeployedVersion.Should().Be("0.0.0-test"); ex.RequiredVersion.Should().Be(_requiredVersion); ex.Cause.Should().NotBeNull("the privilege error is kept as the cause"); ex.Message.Should().Contain("GetUpgradeScript"); (await ReadDeployedModuleVersionAsync()).Should().Be("0.0.0-test", "nothing may have been changed by a role that is not allowed to change it"); } finally { await RepairAsync(); } } [Fact] public async Task AutoApplyDisabled_OutdatedModule_StopsWithoutTrying() { await SetDeployedModuleVersionAsync("0.0.0-test"); try { await using var sp = Build(OwnerConnectionString, autoApply: false); var act = async () => await sp.GetRequiredService().InitializeAsync(ensureCreated: true); var ex = (await act.Should().ThrowAsync()).Which; ex.Cause.Should().BeNull("with automatic upgrades disabled nothing is attempted, so there is no cause"); (await ReadDeployedModuleVersionAsync()).Should().Be("0.0.0-test", "the owner role could have upgraded, but was told not to"); } finally { await RepairAsync(); } } /// /// Drops every column and index the V4 "0. Schema upgrades" block adds - _values._unique, /// _structures._unique/_unique_version/_lazy, _scheme_metadata_cache._unique/_unique_version/_lazy, /// _objects._value_unique and the two partial unique indexes - as a pre-V4 database looks. /// protected abstract Task DropV4UpgradeDdlAsync(); /// Whether all of the above exist again (eight columns, two indexes). protected abstract Task V4UpgradeDdlExistsAsync(); [Fact] public async Task DroppedUpgradeColumn_IsRestored_ByNormalStart() { // A database created before the column existed: no column, and a module version behind the // build - exactly what every existing installation is after a package upgrade. The bundle's // "0. Schema upgrades" block must put the column and its index back before anything else runs. await DropV4UpgradeDdlAsync(); await SetDeployedModuleVersionAsync("0.0.0-test"); await using var sp = Build(OwnerConnectionString, autoApply: true); await sp.GetRequiredService().InitializeAsync(ensureCreated: true); (await V4UpgradeDdlExistsAsync()).Should().BeTrue( "the schema-upgrades block of the bundle restores every V4 column and index on existing databases"); (await ReadDeployedModuleVersionAsync()).Should().Be(_requiredVersion); } [Fact] public async Task UpgradeScript_IsTheBundle_AndAppliedByOwnerRepairsTheDatabase() { await SetDeployedModuleVersionAsync("0.0.0-test"); await using var sp = Build(OwnerConnectionString, autoApply: false); var redb = sp.GetRequiredService(); var script = redb.GetUpgradeScript(); script.Should().NotBeNullOrWhiteSpace("providers with a versioned module export their upgrade script"); script!.Should().Contain("pvt_module_version", "the script ends by stamping the version"); // What the DBA does with the exported text. var ctx = sp.GetRequiredService(); await ApplyScriptAsOwnerAsync(ctx, script); (await ReadDeployedModuleVersionAsync()).Should().Be(_requiredVersion); } /// Applies a script the way the provider's start-up does (MSSQL splits by GO). protected abstract Task ApplyScriptAsOwnerAsync(IRedbContext ownerContext, string script); private async Task RepairAsync() { await using var sp = Build(OwnerConnectionString, autoApply: true); await sp.GetRequiredService().InitializeAsync(ensureCreated: true); } // ===== A module newer than the package: never put back ===== /// A version above any real one, new per test: the warning is written once per process and version. private static string NewerVersion() => $"99.0.{Random.Shared.Next(1, 1_000_000)}"; /// After a newer-module test: the module marked old again, so a start puts the package's module back. private async Task RepairFromNewerAsync() { await SetDeployedModuleVersionAsync("0.0.0-test"); await RepairAsync(); } [Fact] public async Task NewerModule_ThatServesThisPackage_IsLeftInPlace_AndTheStartGoesOn() { var newer = NewerVersion(); await SetDeployedModuleCompatAsync($"{_requiredVersion}|9.9.0"); await SetDeployedModuleVersionAsync(newer); try { var logs = new CapturingLoggerProvider(); await using (var sp = Build(OwnerConnectionString, autoApply: true, cacheDomain: $"newer-{Guid.NewGuid():N}", logs: logs)) await sp.GetRequiredService().InitializeAsync(ensureCreated: true); (await ReadDeployedModuleVersionAsync()).Should().Be(newer, "a package never puts its older module over a newer one"); logs.Warnings.Should().ContainSingle(w => w.Contains(newer) && w.Contains("left as it is")); // The same with automatic upgrades off: a newer module that serves the package is no reason to stop. await using (var sp = Build(OwnerConnectionString, autoApply: false, cacheDomain: $"newer-{Guid.NewGuid():N}")) await sp.GetRequiredService().InitializeAsync(ensureCreated: true); (await ReadDeployedModuleVersionAsync()).Should().Be(newer); } finally { await RepairFromNewerAsync(); } } [Fact] public async Task NewerModule_ThatNoLongerServesThisPackage_StopsTheStart_AndChangesNothing() { var newer = NewerVersion(); await SetDeployedModuleCompatAsync($"{newer}|9.9.0"); await SetDeployedModuleVersionAsync(newer); try { await using var sp = Build(OwnerConnectionString, autoApply: true, cacheDomain: $"newer-{Guid.NewGuid():N}"); var act = async () => await sp.GetRequiredService().InitializeAsync(ensureCreated: true); var ex = (await act.Should().ThrowAsync()).Which; ex.DeployedVersion.Should().Be(newer); ex.PackageVersion.Should().Be(_requiredVersion); ex.RequiredPackageVersion.Should().Be("9.9.0"); ex.Message.Should().Contain("from 9.9.0 on").And.Contain("Upgrade the redb packages") .And.Contain("the database was left unchanged"); (await ReadDeployedModuleVersionAsync()).Should().Be(newer); } finally { await RepairFromNewerAsync(); } } [Fact] public async Task NewerModule_WithoutTheCompatibilityFunction_StopsTheStart_AndChangesNothing() { var newer = NewerVersion(); await SetDeployedModuleCompatAsync(null); await SetDeployedModuleVersionAsync(newer); try { await using var sp = Build(OwnerConnectionString, autoApply: true, cacheDomain: $"newer-{Guid.NewGuid():N}"); var act = async () => await sp.GetRequiredService().InitializeAsync(ensureCreated: true); var ex = (await act.Should().ThrowAsync()).Which; ex.RequiredPackageVersion.Should().BeNull("the module states nothing, and no version is guessed"); ex.Message.Should().Contain("does not state which packages it serves"); (await ReadDeployedModuleVersionAsync()).Should().Be(newer); } finally { await RepairFromNewerAsync(); } } /// After a script the guard refused: drops what the refusal may have left on pooled connections. protected virtual Task AfterRefusedScriptAsync() => Task.CompletedTask; /// /// What a second run must not change: the foreign keys, the identity sequence, the triggers, the routines and the /// rows of the core tables, as one comparable string. /// protected abstract Task ReadSchemaFingerprintAsync(); /// /// Runs a script the way a person does: sqlcmd and SSMS go on to the next batch after an error, psql without /// ON_ERROR_STOP to the next statement. Returns the error messages. /// protected abstract Task> RunScriptByHandAsync(string script); private const string AlreadyDeployed = "already holds the redb schema"; [Fact] public async Task CreationScript_RunAgainOnADeployedDatabase_StopsAtTheGuard_AndChangesNothing() { await using var sp = Build(OwnerConnectionString, autoApply: false, cacheDomain: $"recreate-{Guid.NewGuid():N}"); var redb = sp.GetRequiredService(); var script = redb.GetSchemaScript(); var before = await ReadSchemaFingerprintAsync(); // The way the services run it: the service's own ExecuteSchemaScriptAsync, on the service's context. var execute = typeof(RedbServiceBase).GetMethod("ExecuteSchemaScriptAsync", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!; var act = async () => await (Task)execute.Invoke(redb, [script])!; (await act.Should().ThrowAsync()).Which.Message.Should().Contain(AlreadyDeployed); (await ReadSchemaFingerprintAsync()).Should().Be(before, "the script used to drop every foreign key and the identity sequence before it failed"); // The service goes on working on its own context, with no pool cleared by the test: on SQL Server the guard's // NOEXEC stayed on the session the context holds, and every later query answered nothing. (await sp.GetRequiredService().ExecuteScalarAsync("SELECT COUNT(*) FROM _users")) .Should().BeGreaterThan(0, "the context runs commands again after the refused script"); // The way a person runs it. var errors = await RunScriptByHandAsync(script); errors.Should().Contain(e => e.Contains(AlreadyDeployed)); await AfterRefusedScriptAsync(); (await ReadSchemaFingerprintAsync()).Should().Be(before, "the guard stops the batches after it too"); } [Fact] public async Task UpgradeScript_RunByHandOverANewerModule_IsRefused_AndChangesNothing() { // The script of this package is the "older" one here: the database carries a forged newer module. Start-up // never applies the script then; a DBA running it by hand must be stopped by the script itself before its // first change. The V4 columns are dropped first: the script's opening block would put them back. var newer = NewerVersion(); await DropV4UpgradeDdlAsync(); await SetDeployedModuleCompatAsync($"{newer}|9.9.0"); await SetDeployedModuleVersionAsync(newer); try { await using var sp = Build(OwnerConnectionString, autoApply: false, cacheDomain: $"newer-{Guid.NewGuid():N}"); var script = sp.GetRequiredService().GetUpgradeScript(); script.Should().NotBeNullOrWhiteSpace(); var act = async () => await ApplyScriptAsOwnerAsync(sp.GetRequiredService(), script!); (await act.Should().ThrowAsync()).Which.Message.Should().Contain( $"carries the redb module {newer}, newer than {_requiredVersion} of this package, and it needs redb " + "packages from 9.9.0 on. Upgrade the redb packages of this application; the database was left unchanged."); await AfterRefusedScriptAsync(); (await ReadDeployedModuleVersionAsync()).Should().Be(newer, "the script stopped before it dropped the module"); (await V4UpgradeDdlExistsAsync()).Should().BeFalse("the script stopped before its first change"); } finally { await RepairFromNewerAsync(); } } } Path: redb/redb.Tests.Integration/Tests/Base/SchemeLoadValidationTestsBase.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/SchemeLoadValidationTestsBase.cs ---- using redb.Core; using redb.Core.Exceptions; using redb.Core.Models.Entities; using redb.Tests.Integration.Helpers; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// S1 — LoadAsync<TProps> verifies that the loaded object's scheme matches TProps, /// so an object loaded under the wrong type never yields garbage or poisons the cache. /// /// The reaction to a mismatch is configurable via ThrowOnSchemeMismatch: by default /// LoadAsync returns null (so a soft-deleted object, scheme -10, reads as null — what /// soft-delete callers expect); with the flag set it throws. /// /// public abstract class SchemeLoadValidationTestsBase { protected readonly IRedbService Redb; protected SchemeLoadValidationTestsBase(IRedbService redb) => Redb = redb; private async Task SaveSimpleAsync() { var obj = TestDataFactory.CreateSimple("S1-probe", 10m); return await Redb.SaveAsync(obj); } /// Runs with ThrowOnSchemeMismatch forced on, then restores it. private async Task WithStrictMismatchAsync(Func body) { var previous = Redb.Configuration.ThrowOnSchemeMismatch; Redb.Configuration.ThrowOnSchemeMismatch = true; try { await body(); } finally { Redb.Configuration.ThrowOnSchemeMismatch = previous; } } [Fact] public async Task LoadAsync_WrongType_ReturnsNull_ByDefault() { var id = await SaveSimpleAsync(); var loaded = await Redb.LoadAsync(id); loaded.Should().BeNull("default behaviour is a soft null, not an exception"); } [Fact] public async Task LoadAsync_WrongType_Throws_WhenStrict() { var id = await SaveSimpleAsync(); await WithStrictMismatchAsync(async () => { var act = async () => await Redb.LoadAsync(id); var ex = await act.Should().ThrowAsync(); ex.Which.ObjectId.Should().Be(id); ex.Which.RequestedType.Should().Be(typeof(EmployeeProps)); }); } [Fact] public async Task LoadAsync_CorrectType_Works() { var id = await SaveSimpleAsync(); var loaded = await Redb.LoadAsync(id); loaded.Should().NotBeNull(); loaded!.Props.Title.Should().Be("S1-probe"); } [Fact] public async Task LoadAsync_WrongType_DoesNotPoisonCache() { var id = await SaveSimpleAsync(); // Wrong-type load must be rejected BEFORE anything is cached... var bad = await Redb.LoadAsync(id); bad.Should().BeNull(); // ...so the correct-type load still returns clean data (no garbage lingering in the cache). var good = await Redb.LoadAsync(id); good.Should().NotBeNull(); good!.Props.Title.Should().Be("S1-probe"); } [Fact] public async Task LoadAsync_SoftDeletedObject_ReadsAsNull() { var id = await SaveSimpleAsync(); // SoftDeleteAsync (not the hard DeleteAsync) moves the object under a trash container and sets // its _id_scheme to -10 (@@__deleted). Loading it typed must not return it as a live SimpleProps — // -10 never matches a real scheme, so by default the guard returns null (what soft-delete expects). var mark = await Redb.SoftDeleteAsync(new[] { id }); mark.MarkedCount.Should().BeGreaterThan(0); var loaded = await Redb.LoadAsync(id); loaded.Should().BeNull(); } [Fact] public async Task LoadAsync_SoftDeletedObject_Throws_WhenStrict() { var id = await SaveSimpleAsync(); var mark = await Redb.SoftDeleteAsync(new[] { id }); mark.MarkedCount.Should().BeGreaterThan(0); await WithStrictMismatchAsync(async () => { var act = async () => await Redb.LoadAsync(id); await act.Should().ThrowAsync(); }); } } Path: redb/redb.Tests.Integration/Tests/Base/SchemeNamingTestsBase.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/SchemeNamingTestsBase.cs ---- using redb.Core; using redb.Core.Exceptions; using redb.Core.Models.Entities; using redb.Core.Utils; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// Scenarios A–U for explicit scheme names ([RedbScheme(Name = "...")]), scheme alias /// synchronisation, and the multi-node scheme creation race. /// /// Every test drops the schemes it touches first, so the suite is repeatable and order-independent — /// which matters because Free and Pro fixtures share a database on every provider. /// /// public abstract class SchemeNamingTestsBase { protected readonly IRedbService Redb; protected SchemeNamingTestsBase(IRedbService redb) => Redb = redb; // ============================================================ // === helpers === // ============================================================ /// Removes schemes by name (structures first — they are FK-bound) and clears the cache. private async Task DropSchemesAsync(params string[] names) { foreach (var name in names) { await Redb.Context.ExecuteAsync( $"DELETE FROM _structures WHERE _id_scheme IN (SELECT _id FROM _schemes WHERE _name = '{name}')"); await Redb.Context.ExecuteAsync($"DELETE FROM _schemes WHERE _name = '{name}'"); } // Raw SQL is invisible to the metadata cache; without this a later lookup would answer from a // scheme that no longer exists. Redb.Cache.Clear(); } private Task SchemeIdAsync(string name) => Redb.Context.ExecuteScalarAsync($"SELECT _id FROM _schemes WHERE _name = '{name}'"); private Task SchemeAliasAsync(string name) => Redb.Context.ExecuteScalarAsync($"SELECT _alias FROM _schemes WHERE _name = '{name}'"); private Task SchemeNameSpaceAsync(string name) => Redb.Context.ExecuteScalarAsync($"SELECT _name_space FROM _schemes WHERE _name = '{name}'"); /// Creates a scheme row directly, bypassing the library — the "other node" in race tests. private async Task InsertSchemeRawAsync(string name, long type = RedbTypeIds.Class, string? nameSpace = null) { var id = await Redb.Context.NextObjectIdAsync(); var nsColumn = nameSpace != null ? ", _name_space" : ""; var nsValue = nameSpace != null ? $", '{nameSpace}'" : ""; await Redb.Context.ExecuteAsync( $"INSERT INTO _schemes (_id, _name, _type{nsColumn}) VALUES ({id}, '{name}', {type}{nsValue})"); Redb.Cache.Clear(); return id; } private static string FullNameOf() => typeof(T).FullName!; // ============================================================ // === A, B — no explicit name: legacy behaviour is untouched === // ============================================================ [Fact] public async Task A_NoExplicitName_SchemeLivesByFullName() { var fullName = FullNameOf(); await DropSchemesAsync(fullName, nameof(NamingByTypeProps)); var scheme = await Redb.EnsureSchemeFromTypeAsync(); scheme.Name.Should().Be(fullName); (await SchemeIdAsync(fullName)).Should().NotBeNull(); (await SchemeIdAsync(nameof(NamingByTypeProps))).Should().BeNull(); } [Fact] public async Task B_NoExplicitName_MigratesFromShortName() { var fullName = FullNameOf(); var shortName = nameof(NamingByTypeProps); await DropSchemesAsync(fullName, shortName); var legacyId = await InsertSchemeRawAsync(shortName); var scheme = await Redb.EnsureSchemeFromTypeAsync(); scheme.Name.Should().Be(fullName); scheme.Id.Should().Be(legacyId, "renaming must preserve the id so objects stay attached"); (await SchemeIdAsync(shortName)).Should().BeNull(); (await SchemeNameSpaceAsync(fullName)).Should().Be(typeof(NamingByTypeProps).Namespace, "К7: adoption via the short name stamps the owner namespace"); } // ============================================================ // === C, D, E — the three-step chain === // ============================================================ [Fact] public async Task C_ExplicitName_CreatedOnCleanDatabase() { await DropSchemesAsync("naming.pinned", FullNameOf(), nameof(NamingPinnedProps)); var scheme = await Redb.EnsureSchemeFromTypeAsync(); scheme.Name.Should().Be("naming.pinned"); (await SchemeIdAsync(FullNameOf())).Should().BeNull("FullName must not be used at all"); } [Fact] public async Task D_ExplicitName_RenamesSchemeFoundByFullName() { var fullName = FullNameOf(); await DropSchemesAsync("naming.pinned", fullName, nameof(NamingPinnedProps)); var originalId = await InsertSchemeRawAsync(fullName); var scheme = await Redb.EnsureSchemeFromTypeAsync(); scheme.Name.Should().Be("naming.pinned"); scheme.Id.Should().Be(originalId, "the rename is an UPDATE of _name, not a new scheme"); (await SchemeIdAsync(fullName)).Should().BeNull(); } [Fact] public async Task E_ExplicitName_RenamesSchemeFoundByShortName() { var shortName = nameof(NamingPinnedProps); await DropSchemesAsync("naming.pinned", FullNameOf(), shortName); var originalId = await InsertSchemeRawAsync(shortName); var scheme = await Redb.EnsureSchemeFromTypeAsync(); scheme.Name.Should().Be("naming.pinned"); scheme.Id.Should().Be(originalId, "the third link of the chain must not orphan pre-FullName databases"); (await SchemeIdAsync(shortName)).Should().BeNull(); } // ============================================================ // === F, G, H — failing loudly === // ============================================================ [Fact] public async Task F_SplitBrain_TargetAndPreviousNameBothExist_Throws() { var fullName = FullNameOf(); await DropSchemesAsync("naming.split", fullName, nameof(NamingSplitProps)); // The rename already happened, and then an older binary re-created the old scheme. await InsertSchemeRawAsync("naming.split"); await InsertSchemeRawAsync(fullName); var act = async () => await Redb.EnsureSchemeFromTypeAsync(); await act.Should().ThrowAsync(); // Both rows survive: the operator has to merge them, the library must not pick one silently. (await SchemeIdAsync("naming.split")).Should().NotBeNull(); (await SchemeIdAsync(fullName)).Should().NotBeNull(); await DropSchemesAsync("naming.split", fullName); } // Scenarios G (two types claiming one name) and H (invalid explicit name) are NOT integration // tests: they would require a type with a bad or duplicate name to exist in this assembly, and // InitializeAsync auto-syncs every [RedbScheme] type it can see and rethrows — so such a type // breaks fixture start-up for every other test here. That is the intended product behaviour. // The rules themselves are covered by Tests/Unit/SchemeNameValidatorTests. // ============================================================ // === I, J — the database-level backstop === // ============================================================ [Theory] // Character-set rule — a single GLOB/LIKE test in every dialect. [InlineData("Raw Invalid Name")] [InlineData("Именование сырьём")] // Structural rules. [InlineData("raw..double")] [InlineData("raw.trailing.")] [InlineData("9raw")] // Reserved-word rule. This is the one that forced a recursive CTE in SQLite and STRING_SPLIT in // MSSql — it is the only case that actually splits the name into parts, so without it the // per-part machinery would never run and could be broken without anyone noticing. [InlineData("raw.class")] [InlineData("raw+static")] public async Task I_RawInsertOfInvalidName_RejectedByTrigger(string invalid) { await DropSchemesAsync(invalid); var act = async () => await InsertSchemeRawAsync(invalid); await act.Should().ThrowAsync("the trigger is the backstop for writes that bypass the library"); (await SchemeIdAsync(invalid)).Should().BeNull(); } [Fact] public async Task J_SystemPrefixedName_BypassesValidation() { const string systemName = "@@naming_probe"; await DropSchemesAsync(systemName); var id = await InsertSchemeRawAsync(systemName); id.Should().BeGreaterThan(0); (await SchemeIdAsync(systemName)).Should().Be(id); await DropSchemesAsync(systemName); } // ============================================================ // === K, L — caches and RTTI survive the rename === // ============================================================ [Fact] public async Task K_AfterRename_LookupsUseTheNewNameOnly() { var fullName = FullNameOf(); await DropSchemesAsync("naming.pinned", fullName, nameof(NamingPinnedProps)); await InsertSchemeRawAsync(fullName); var scheme = await Redb.EnsureSchemeFromTypeAsync(); (await Redb.GetSchemeByNameAsync("naming.pinned"))!.Id.Should().Be(scheme.Id); (await Redb.GetSchemeByNameAsync(fullName)).Should().BeNull("the old name must not resolve to a stale scheme"); (await Redb.GetSchemeByTypeAsync())!.Id.Should().Be(scheme.Id); Redb.GetSchemeNameForType().Should().Be("naming.pinned"); } [Fact] public async Task L_AfterRename_ObjectsRoundTrip() { await DropSchemesAsync("naming.pinned", FullNameOf(), nameof(NamingPinnedProps)); await Redb.SyncSchemeAsync(); var obj = new RedbObject { name = "naming-roundtrip", Props = new NamingPinnedProps { Title = "after rename" } }; obj.id = await Redb.SaveAsync(obj); var loaded = await Redb.LoadAsync(obj.id); loaded.Should().NotBeNull(); loaded!.Props.Title.Should().Be("after rename"); } // ============================================================ // === M, N — name plus alias, and idempotency === // ============================================================ [Fact] public async Task M_ExplicitNameAndAlias_BothPersisted() { await DropSchemesAsync("naming.with_alias", FullNameOf(), nameof(NamingWithAliasProps)); var scheme = await Redb.EnsureSchemeFromTypeAsync(); scheme.Name.Should().Be("naming.with_alias"); (await SchemeAliasAsync("naming.with_alias")).Should().Be("Именование: имя и алиас"); } [Fact] public async Task N_RepeatedSync_IsIdempotent() { await DropSchemesAsync("naming.pinned", FullNameOf(), nameof(NamingPinnedProps)); var first = await Redb.EnsureSchemeFromTypeAsync(); var second = await Redb.EnsureSchemeFromTypeAsync(); var third = await Redb.EnsureSchemeFromTypeAsync(); second.Id.Should().Be(first.Id); third.Id.Should().Be(first.Id); second.Name.Should().Be("naming.pinned"); } // ============================================================ // === O, P, R — the alias follows the attribute === // ============================================================ [Fact] public async Task O_AliasChangedInDatabase_IsRestoredFromAttribute() { var fullName = FullNameOf(); await DropSchemesAsync(fullName, nameof(NamingAliasProps)); var scheme = await Redb.EnsureSchemeFromTypeAsync(); (await SchemeAliasAsync(fullName)).Should().Be("Именование: алиас исходный"); // R: someone edits the alias by hand. await Redb.Context.ExecuteAsync($"UPDATE _schemes SET _alias = 'правка руками' WHERE _id = {scheme.Id}"); Redb.Cache.Clear(); await Redb.EnsureSchemeFromTypeAsync(); (await SchemeAliasAsync(fullName)).Should().Be("Именование: алиас исходный", "the attribute is the source of truth, exactly as it already is for structure aliases"); } [Fact] public async Task P_TypeWithoutAlias_ResetsAliasToNull() { await DropSchemesAsync("naming.pinned", FullNameOf(), nameof(NamingPinnedProps)); var scheme = await Redb.EnsureSchemeFromTypeAsync(); await Redb.Context.ExecuteAsync($"UPDATE _schemes SET _alias = 'лишний алиас' WHERE _id = {scheme.Id}"); Redb.Cache.Clear(); await Redb.EnsureSchemeFromTypeAsync(); (await SchemeAliasAsync("naming.pinned")).Should().BeNull( "a type that declares no alias must clear the column, not leave a ghost"); } [Fact] public async Task Q_AliasStableAcrossRepeatedSyncs() { var fullName = FullNameOf(); await DropSchemesAsync(fullName, nameof(NamingAliasProps)); await Redb.EnsureSchemeFromTypeAsync(); await Redb.EnsureSchemeFromTypeAsync(); await Redb.EnsureSchemeFromTypeAsync(); (await SchemeAliasAsync(fullName)).Should().Be("Именование: алиас исходный"); } // ============================================================ // === S, T, U — the multi-node creation race === // ============================================================ [Fact] public async Task S_LosingTheCreationRace_AdoptsTheWinnersScheme() { await DropSchemesAsync("naming.race", FullNameOf(), nameof(NamingRaceProps)); // Another node got there first: the row exists, and our lookups have already missed it. var winnerId = await InsertSchemeRawAsync("naming.race"); var scheme = await Redb.EnsureSchemeFromTypeAsync(); scheme.Id.Should().Be(winnerId, "the loser must adopt the existing scheme, not fail on UNIQUE(_name)"); (await Redb.Context.ExecuteScalarAsync( "SELECT COUNT(*) FROM _schemes WHERE _name = 'naming.race'")).Should().Be(1); } [Fact] public async Task T_LosingTheCreationRace_InsideTransaction_TransactionStillCommits() { await DropSchemesAsync("naming.race", FullNameOf(), nameof(NamingRaceProps)); var winnerId = await InsertSchemeRawAsync("naming.race"); // The point of the test: on PostgreSQL a raised unique violation would poison the transaction // and every following statement would fail with 25P02. Suppressing the conflict in SQL instead // of catching it is what keeps this commit possible. long adoptedId = 0; var act = async () => await Redb.Context.ExecuteAtomicAsync(async () => { var scheme = await Redb.EnsureSchemeFromTypeAsync(); adoptedId = scheme.Id; }); await act.Should().NotThrowAsync(); adoptedId.Should().Be(winnerId); } [Fact] public async Task U_ObjectSchemePath_HasTheSameProtection() { const string objectSchemeName = "naming_object_race"; await DropSchemesAsync(objectSchemeName); var winnerId = await InsertSchemeRawAsync(objectSchemeName, RedbTypeIds.Object); var scheme = await Redb.EnsureObjectSchemeAsync(objectSchemeName); scheme.Id.Should().Be(winnerId, "the untyped path must not be a second door into the same bug"); (await Redb.Context.ExecuteScalarAsync( $"SELECT COUNT(*) FROM _schemes WHERE _name = '{objectSchemeName}'")).Should().Be(1); await DropSchemesAsync(objectSchemeName); } // ============================================================ // === V, W, X — namespace as the ownership mark (V4, К7) === // ============================================================ [Fact] public async Task V_NameSpace_WrittenOnCreate_AndRestoredFromCode() { var fullName = FullNameOf(); await DropSchemesAsync(fullName, nameof(NamingByTypeProps)); await Redb.EnsureSchemeFromTypeAsync(); (await SchemeNameSpaceAsync(fullName)).Should().Be(typeof(NamingByTypeProps).Namespace); // A cleared owner (a pre-namespace database, or a deliberate hand-off) is re-stamped. await Redb.Context.ExecuteAsync($"UPDATE _schemes SET _name_space = NULL WHERE _name = '{fullName}'"); Redb.Cache.Clear(); await Redb.EnsureSchemeFromTypeAsync(); (await SchemeNameSpaceAsync(fullName)).Should().Be(typeof(NamingByTypeProps).Namespace); // A different owner is never overwritten, on any path: a scheme has one owner (К7, owner // decision 2026-09-01) - the typed stop names the way out instead. await Redb.Context.ExecuteAsync($"UPDATE _schemes SET _name_space = 'Hacked.Ns' WHERE _name = '{fullName}'"); Redb.Cache.Clear(); var act = async () => await Redb.EnsureSchemeFromTypeAsync(); var ex = (await act.Should().ThrowAsync()).Which; ex.SchemeNameSpace.Should().Be("Hacked.Ns"); ex.Message.Should().Contain("_name_space", "the message tells the operator what to do"); (await SchemeNameSpaceAsync(fullName)).Should().Be("Hacked.Ns", "the row is left as it is"); } [Fact] public async Task W_ShortNameAdoption_MatchingNamespace_Renames() { var fullName = FullNameOf(); var shortName = nameof(NamingByTypeProps); await DropSchemesAsync(fullName, shortName); var legacyId = await InsertSchemeRawAsync(shortName, nameSpace: typeof(NamingByTypeProps).Namespace); var scheme = await Redb.EnsureSchemeFromTypeAsync(); scheme.Id.Should().Be(legacyId, "a matching namespace proves ownership — adoption proceeds"); scheme.Name.Should().Be(fullName); (await SchemeNameSpaceAsync(fullName)).Should().Be(typeof(NamingByTypeProps).Namespace); } [Fact] public async Task X_ShortNameAdoption_ForeignNamespace_Throws() { var fullName = FullNameOf(); var shortName = nameof(NamingByTypeProps); await DropSchemesAsync(fullName, shortName); var foreignId = await InsertSchemeRawAsync(shortName, nameSpace: "Some.Other.Project"); var act = async () => await Redb.EnsureSchemeFromTypeAsync(); await act.Should().ThrowAsync( "a short name proves nothing — the scheme belongs to another project"); // Untouched: still under the short name, same id, same owner. (await SchemeIdAsync(shortName)).Should().Be(foreignId); (await SchemeNameSpaceAsync(shortName)).Should().Be("Some.Other.Project"); await DropSchemesAsync(shortName); } [Fact] public async Task Y_ExplicitNameAdoption_ForeignNamespace_Throws() { const string pinned = "naming.pinned"; await DropSchemesAsync(pinned, FullNameOf(), nameof(NamingPinnedProps)); var foreignId = await InsertSchemeRawAsync(pinned, nameSpace: "Some.Other.Project"); try { var act = async () => await Redb.EnsureSchemeFromTypeAsync(); await act.Should().ThrowAsync( "К7: a scheme has one owner - an explicit name from another project must not take it over"); (await SchemeIdAsync(pinned)).Should().Be(foreignId); (await SchemeNameSpaceAsync(pinned)).Should().Be("Some.Other.Project", "the row stays untouched"); } finally { await DropSchemesAsync(pinned); } } } Path: redb/redb.Tests.Integration/Tests/Base/SchemeRenameTestsBase.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/SchemeRenameTestsBase.cs ---- using redb.Core; using redb.Core.Exceptions; using redb.Core.Models.Entities; using redb.Core.Utils; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// RedbScheme.RenamedFrom: the sync renames the stored scheme in place (same id, same objects), a second sync does /// nothing, both names stored is an error, and a class whose scheme was renamed away by a version this application /// does not have stops instead of creating the old scheme again. Every scheme rename records the name it came from in /// _schemes._renamed_from, the FullName-to-explicit-name rename included. /// public abstract class SchemeRenameTestsBase : IAsyncLifetime { protected readonly IRedbService Redb; protected SchemeRenameTestsBase(IRedbService redb) => Redb = redb; private static readonly string[] Schemes = [ typeof(SchemeRenameV1).FullName!, "rename_scheme_v2", typeof(SchemeRenameBothV1).FullName!, "rename_scheme_both", "rename_scheme_chain", "rename_scheme_chain_a", "rename_scheme_chain_b", typeof(SchemeRenameGuardV1).FullName!, "rename_scheme_ghost", typeof(SchemeRenameReuseProps).FullName!, typeof(SchemeRenameLegacyProps).FullName!, "rename_scheme_legacy", ]; public async Task InitializeAsync() => await ResetAsync(); public async Task DisposeAsync() => await ResetAsync(); private async Task ResetAsync() { foreach (var name in Schemes) { await Redb.Context.ExecuteAsync( $"DELETE FROM _objects WHERE _id_scheme IN (SELECT _id FROM _schemes WHERE _name = '{name}')"); await Redb.Context.ExecuteAsync( $"DELETE FROM _structures WHERE _id_scheme IN (SELECT _id FROM _schemes WHERE _name = '{name}')"); await Redb.Context.ExecuteAsync($"DELETE FROM _schemes WHERE _name = '{name}'"); } Redb.Cache.Clear(); } private Task SchemeIdAsync(string name) => Redb.Context.ExecuteScalarAsync($"SELECT _id FROM _schemes WHERE _name = '{name}'"); private Task RenamedFromAsync(long schemeId) => Redb.Context.ExecuteScalarAsync($"SELECT _renamed_from FROM _schemes WHERE _id = {schemeId}"); /// A scheme row written directly: the state another application version left behind. private async Task InsertSchemeRawAsync(string name, string? renamedFrom = null) { var id = await Redb.Context.NextObjectIdAsync(); await Redb.Context.ExecuteAsync($"INSERT INTO _schemes (_id, _name, _type) VALUES ({id}, '{name}', {RedbTypeIds.Class})"); if (renamedFrom != null) await Redb.Context.ExecuteAsync($"UPDATE _schemes SET _renamed_from = '{renamedFrom}' WHERE _id = {id}"); Redb.Cache.Clear(); return id; } [Fact] public async Task RenamedFrom_RenamesTheStoredScheme_ObjectsStay() { var oldName = typeof(SchemeRenameV1).FullName!; var old = await Redb.SyncSchemeAsync(); var obj = new RedbObject { name = "scheme-rename", Props = new SchemeRenameV1 { Title = "s1" } }; obj.id = await Redb.SaveAsync(obj); (await Redb.Query().Where(x => x.Title == "s1").CountAsync()).Should().Be(1); var renamed = await Redb.SyncSchemeAsync(); renamed.Id.Should().Be(old.Id, "the rename keeps the scheme"); renamed.Name.Should().Be("rename_scheme_v2"); (await SchemeIdAsync(oldName)).Should().BeNull(); (await RenamedFromAsync(old.Id)).Should().Be($"[\"{oldName}\"]"); (await Redb.GetSchemeByTypeAsync())!.Id.Should().Be(old.Id, "the cached scheme follows the name"); (await Redb.LoadAsync(obj.id))!.Props.Title.Should().Be("s1"); (await Redb.Query().Where(x => x.Title == "s1").CountAsync()).Should().Be(1); // A second sync is a no-op. (await Redb.SyncSchemeAsync()).Id.Should().Be(old.Id); (await RenamedFromAsync(old.Id)).Should().Be($"[\"{oldName}\"]"); } [Fact] public async Task BothNamesStored_IsAnError_AndChangesNothing() { var oldName = typeof(SchemeRenameBothV1).FullName!; var oldId = (await Redb.SyncSchemeAsync()).Id; var newId = await InsertSchemeRawAsync("rename_scheme_both"); var act = () => Redb.SyncSchemeAsync(); var error = (await act.Should().ThrowAsync()).Which; error.StoredNames.Should().Equal(oldName); (await SchemeIdAsync(oldName)).Should().Be(oldId); (await SchemeIdAsync("rename_scheme_both")).Should().Be(newId); } [Fact] public async Task Chain_TheStoredPreviousName_IsRenamed_AndTheHistoryGrows() { var id = await InsertSchemeRawAsync("rename_scheme_chain_b", "[\"rename_scheme_chain_a\"]"); var scheme = await Redb.SyncSchemeAsync(); scheme.Id.Should().Be(id); (await RenamedFromAsync(id)).Should().Be("[\"rename_scheme_chain_a\",\"rename_scheme_chain_b\"]"); } [Fact] public async Task Chain_TwoPreviousNamesStored_IsAnError() { await InsertSchemeRawAsync("rename_scheme_chain_a"); await InsertSchemeRawAsync("rename_scheme_chain_b"); var act = () => Redb.SyncSchemeAsync(); (await act.Should().ThrowAsync()).Which.StoredNames .Should().BeEquivalentTo("rename_scheme_chain_a", "rename_scheme_chain_b"); (await SchemeIdAsync("rename_scheme_chain")).Should().BeNull("nothing is created"); } [Fact] public async Task OldClass_SchemeRenamedAwayByAnotherVersion_Stops() { var name = typeof(SchemeRenameGuardV1).FullName!; // A version this process does not have renamed the scheme of SchemeRenameGuardV1 to rename_scheme_ghost. var ghostId = await InsertSchemeRawAsync("rename_scheme_ghost", $"[\"{name}\"]"); var act = () => Redb.SyncSchemeAsync(); var error = (await act.Should().ThrowAsync()).Which; error.Name.Should().Be(name); error.StoredNames.Should().Equal("rename_scheme_ghost"); (await SchemeIdAsync(name)).Should().BeNull("the old scheme is not created again"); (await SchemeIdAsync("rename_scheme_ghost")).Should().Be(ghostId); } [Fact] public async Task FreedName_TakenByANewClass_IsAllowed_WhenTheRenamedSchemeIsDeclaredHere() { var name = typeof(SchemeRenameReuseProps).FullName!; // rename_scheme_v2 is declared by SchemeRenameV2 in this application, so the freed name may be taken again. var renamedId = await InsertSchemeRawAsync("rename_scheme_v2", $"[\"{name}\"]"); var scheme = await Redb.SyncSchemeAsync(); scheme.Name.Should().Be(name); scheme.Id.Should().NotBe(renamedId); } [Fact] public async Task FullNameToExplicitName_RecordsTheHistory() { var fullName = typeof(SchemeRenameLegacyProps).FullName!; var id = await InsertSchemeRawAsync(fullName); var scheme = await Redb.SyncSchemeAsync(); scheme.Id.Should().Be(id); scheme.Name.Should().Be("rename_scheme_legacy"); (await RenamedFromAsync(id)).Should().Be($"[\"{fullName}\"]"); } } Path: redb/redb.Tests.Integration/Tests/Base/SchemeSyncRace.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/SchemeSyncRace.cs ---- using redb.Core; using redb.Core.Data; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// Services syncing one scheme at the same moment, as the nodes of a Tsak cluster do when they load modules that share /// a Props class: a scheme new to the database (odd rounds) and a scheme an older version left without a field (even /// rounds: the field and the nested part are deleted first). Without the schema lock they inserted the same structure /// and the second failed on the unique key of _structures. /// public static class SchemeSyncRace { private const string SchemeName = "schema_lock_sync_probe"; /// Runs the rounds; returns the failures, each with its round. public static async Task> RunAsync(IReadOnlyList nodes, IRedbContext context, int rounds) { var failures = new List(); for (var round = 0; round < rounds; round++) { await nodes[0].SyncSchemeAsync(); var schemeId = await context.ExecuteScalarAsync($"SELECT _id FROM _schemes WHERE _name = '{SchemeName}'"); if (round % 2 == 1) { // A new scheme: the database has never seen it. await context.ExecuteAsync($"DELETE FROM _structures WHERE _id_scheme = {schemeId} AND _id_parent IS NOT NULL"); await context.ExecuteAsync($"DELETE FROM _structures WHERE _id_scheme = {schemeId}"); await context.ExecuteAsync($"DELETE FROM _scheme_metadata_cache WHERE _scheme_id = {schemeId}"); await context.ExecuteAsync($"DELETE FROM _schemes WHERE _id = {schemeId}"); } else { // A scheme of the previous version of the module: no Note, no Part. await context.ExecuteAsync( $"DELETE FROM _structures WHERE _id_scheme = {schemeId} AND _id_parent IS NOT NULL"); await context.ExecuteAsync( $"DELETE FROM _structures WHERE _id_scheme = {schemeId} AND _name IN ('Note', 'Part')"); } // Released together, so the syncs really meet. var start = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var syncs = nodes.Select(node => Task.Run(async () => { await start.Task; try { await node.SyncSchemeAsync(); return null; } catch (Exception ex) { return $"round {round}: {ex.GetType().Name}: {ex.Message}"; } })).ToList(); start.SetResult(); failures.AddRange((await Task.WhenAll(syncs)).Where(f => f != null).Select(f => f!)); var newId = await context.ExecuteScalarAsync($"SELECT _id FROM _schemes WHERE _name = '{SchemeName}'"); var structures = await context.ExecuteScalarAsync( $"SELECT CAST(COUNT(*) AS BIGINT) FROM _structures WHERE _id_scheme = {newId}"); var cached = await context.ExecuteScalarAsync( $"SELECT CAST(COUNT(*) AS BIGINT) FROM _scheme_metadata_cache WHERE _scheme_id = {newId}"); // Title, Count, Note, Part and the two fields of Part. if (structures != 6) failures.Add($"round {round}: {structures} structures instead of 6"); if (cached != structures) failures.Add($"round {round}: {cached} metadata cache rows for {structures} structures"); } return failures; } } Path: redb/redb.Tests.Integration/Tests/Base/SmallSaveTimingTestsBase.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/SmallSaveTimingTestsBase.cs ---- using System.Diagnostics; using Microsoft.Extensions.DependencyInjection; using redb.Core; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using redb.Tests.Integration.Helpers; using redb.Tests.Integration.Models; using Xunit.Abstractions; namespace redb.Tests.Integration.Tests.Base; /// /// Timing of top-level saves of new objects, one writer, median and 90th percentile over many runs: the evidence for /// how a provider writes small sets. Not an assertion; run explicitly (Category=Performance) and read the output. /// [Trait("Category", "Performance")] public abstract class SmallSaveTimingTestsBase { private readonly IServiceProvider _services; private readonly ITestOutputHelper _output; protected SmallSaveTimingTestsBase(IServiceProvider services, ITestOutputHelper output) { _services = services; _output = output; } [Fact] public async Task NewObjects_TopLevelSave_Timing() { await using var scope = _services.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); var tag = $"timing-{Guid.NewGuid():N}"; var next = 0; IRedbObject[] Employees(int count) => Enumerable.Range(0, count).Select(_ => (IRedbObject)TestDataFactory.CreateEmployee(next++)).ToArray(); IRedbObject[] Rows(int count) => Enumerable.Range(0, count).Select(_ => (IRedbObject)new RedbObject { name = $"{tag}-{next++}", Props = new ConcurrentWriterRowProps { Tag = tag, Key = $"{tag}-{next}", Payload = "p", WrittenAt = DateTimeOffset.UtcNow } }).ToArray(); // Warm-up: plans, pools, scheme caches. for (var i = 0; i < 10; i++) { await redb.SaveAsync(Employees(1)); await redb.SaveAsync(Rows(50)); } await MeasureAsync(redb, "1 employee", 100, () => Employees(1)); await MeasureAsync(redb, "50 small rows", 60, () => Rows(50)); await MeasureAsync(redb, "10 employees", 40, () => Employees(10)); await MeasureAsync(redb, "50 employees", 20, () => Employees(50)); if (PlanCacheReportSql is { } report) { foreach (var row in await redb.Context.QueryAsync(report)) _output.WriteLine($"PLANS {GetType().Name} | {row.Statement} | plans {row.Plans} | executions {row.Executions} | sample {row.Sample}"); } } /// /// A provider's read-only query of its plan cache for the insert statements of this database (columns Statement, /// Plans, Executions, Sample): how many plans the saves above compiled. Null where there is none. /// protected virtual string? PlanCacheReportSql => null; public class PlanCacheRow { public string Statement { get; set; } = ""; public int Plans { get; set; } public long Executions { get; set; } public string Sample { get; set; } = ""; } private async Task MeasureAsync(IRedbService redb, string label, int runs, Func make) { var times = new List(runs); long values = 0; for (var i = 0; i < runs; i++) { var objects = make(); var sw = Stopwatch.StartNew(); var ids = await redb.SaveAsync(objects); sw.Stop(); times.Add(sw.Elapsed.TotalMilliseconds); if (i == 0) { foreach (var id in ids) values += await redb.Context.ExecuteScalarAsync( "SELECT COUNT(*) FROM _values WHERE _id_object = @p0", id); } } times.Sort(); var median = times[times.Count / 2]; var p90 = times[(int)(times.Count * 0.9)]; _output.WriteLine($"TIMING {GetType().Name} | {label} | value rows {values} | runs {runs} | median {median:F1} ms | p90 {p90:F1} ms"); } } Path: redb/redb.Tests.Integration/Tests/Base/SqlPreviewTestsBase.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/SqlPreviewTestsBase.cs ---- using redb.Core; using redb.Core.Query; using redb.Core.Query.Aggregation; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// Golden-SQL preview tests for PostgreSQL dialects. /// Validates that the generated SQL contains expected fragments — does NOT /// execute queries against any data. /// /// Uses (plain /// queries) and /// (aggregates). Array-GroupBy preview is currently stubbed in core (returns /// "-- SQL preview not supported …") so it is intentionally NOT covered here. /// public abstract class SqlPreviewTestsBase { protected readonly IRedbService Redb; protected SqlPreviewTestsBase(IRedbService redb) => Redb = redb; // ────────────────────────────────────────────────────────────────── // Aggregation over array — must unnest // ────────────────────────────────────────────────────────────────── /// /// Aggregate-over-array preview, PostgreSQL Free and Pro /// (an aggregate over the _long column of _values). /// [Fact] public virtual async Task Preview_AggSumOverArray_ContainsUnnest() { var sql = await Redb.Query() .ToAggregateSqlStringAsync(x => new { Total = Agg.Sum(x.Props.SkillLevels.Select(s => s)) }); sql.Should().NotBeNullOrWhiteSpace(); sql.ToUpperInvariant().Should().Contain("SUM("); sql.Should().ContainEquivalentOf("_long", "Sum over int[] aggregates over the _long storage column"); } [Fact] public virtual async Task Preview_AggAvgOverArray_ContainsUnnestAndNullIf() { var sql = await Redb.Query() .ToAggregateSqlStringAsync(x => new { Avg = Agg.Average(x.Props.SkillLevels.Select(s => s)) }); sql.Should().NotBeNullOrWhiteSpace(); sql.ToUpperInvariant().Should().Contain("AVG("); sql.Should().ContainEquivalentOf("_long"); } // ────────────────────────────────────────────────────────────────── // Plain query preview // ────────────────────────────────────────────────────────────────── [Fact] public async Task Preview_PlainQuery_HasSelectAndFrom() { var sql = await Redb.Query().ToSqlStringAsync(); sql.Should().NotBeNullOrWhiteSpace(); sql.ToUpperInvariant().Should().Contain("SELECT"); sql.ToUpperInvariant().Should().Contain("FROM"); } [Fact] public async Task Preview_WhereWithStringContains_HasIlike() { var sql = await Redb.Query() .Where(e => e.Department.Contains("ing")) .ToSqlStringAsync(); // Plain PG lowers Contains(...) to ILIKE; PG Pro emits the case-sensitive // LIKE for ordinary `string.Contains`. Both contain the substring "LIKE". sql.ToUpperInvariant().Should().Contain("LIKE", "string.Contains(...) must compile to a LIKE/ILIKE predicate"); } [Fact] public async Task Preview_OrderBy_HasOrderByClause() { var sql = await Redb.Query() .OrderBy(e => e.Salary) .ToSqlStringAsync(); sql.ToUpperInvariant().Should().Contain("ORDER BY"); } } Path: redb/redb.Tests.Integration/Tests/Base/SqliteKeygenInTransactionTestsBase.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/SqliteKeygenInTransactionTestsBase.cs ---- using System.Diagnostics; using redb.Core; using redb.Core.Data; using redb.Tests.Integration.Helpers; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// The SQLite single-writer keygen trap (live worker storm, 2026-09-08): the id cache is /// process memory and starts EMPTY, so the first save after startup must fetch a block from /// the database - a write. When that save runs inside the caller's own BEGIN IMMEDIATE /// (ExecuteAtomicAsync around SaveAsync, the Tsak heartbeat shape), the old refill went /// through a SEPARATE pooled connection and waited for the file's only write lock - held by /// the very transaction waiting for the refill. Self-deadlock, unwound only by busy_timeout /// x retries (~15-20s), taking Quartz and every other writer down with it. The fix: inside /// an active scope transaction keys come through that same connection (the lock is already /// ours), bypassing the shared cache - a rollback takes the sequence bump back and those ids /// were never visible outside, so no duplicates on either outcome. /// public abstract class SqliteKeygenInTransactionTestsBase : IAsyncLifetime { protected readonly IRedbService Redb; protected SqliteKeygenInTransactionTestsBase(IRedbService redb) => Redb = redb; public async Task InitializeAsync() => await ResetAsync(); public async Task DisposeAsync() => await ResetAsync(); private async Task ResetAsync() => await Redb.Context.ExecuteAsync("DELETE FROM _objects WHERE _name LIKE 'keygen-tx-%'"); [Fact] public async Task SaveInsideUserTransaction_SurvivesColdKeyCache() { await Redb.SyncSchemeAsync(); // Cold start: the shared id cache is empty, exactly like a freshly launched worker. RedbKeyGeneratorBase.ClearAllCaches(); var sw = Stopwatch.StartNew(); await Redb.Context.ExecuteAtomicAsync(async () => { var obj = TestDataFactory.CreateSimple("keygen-tx-cold", 1m); await Redb.SaveAsync(obj); }); sw.Stop(); // The old path self-deadlocked here and either threw 'database is locked' or crawled // through the busy_timeout ladder; the ambient bypass must make this instant. sw.Elapsed.Should().BeLessThan(TimeSpan.FromSeconds(4), "keys inside the scope's own transaction must come through it, not wait on its lock"); var count = await Redb.Context.ExecuteScalarAsync( "SELECT COUNT(*) FROM _objects WHERE _name = 'keygen-tx-cold'"); count.Should().Be(1); } [Fact] public async Task AmbientKeysAfterRollback_DoNotCollide() { // A rollback takes the sequence bump back; the next writer may receive the same ids // again - which is correct, nothing outside the transaction ever saw them. The pin: // subsequent saves succeed with no primary-key collision and no shared-cache poison. await Redb.SyncSchemeAsync(); RedbKeyGeneratorBase.ClearAllCaches(); var act = async () => await Redb.Context.ExecuteAtomicAsync(async () => { await Redb.SaveAsync(TestDataFactory.CreateSimple("keygen-tx-rollback", 2m)); throw new InvalidOperationException("keygen-rollback-marker"); }); await act.Should().ThrowAsync().WithMessage("*keygen-rollback-marker*"); (await Redb.Context.ExecuteScalarAsync( "SELECT COUNT(*) FROM _objects WHERE _name = 'keygen-tx-rollback'")) .Should().Be(0, "the marker exception rolled the save back"); // Cold cache again so the next ids are re-read from the rolled-back sequence. RedbKeyGeneratorBase.ClearAllCaches(); var id = await Redb.SaveAsync(TestDataFactory.CreateSimple("keygen-tx-after", 3m)); id.Should().BeGreaterThan(0, "re-issued ids are free - the rollback returned them unused"); } } Path: redb/redb.Tests.Integration/Tests/Base/SqliteRowMapperTestsBase.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/SqliteRowMapperTestsBase.cs ---- using redb.Core; using redb.Core.Models.Entities; namespace redb.Tests.Integration.Tests.Base; /// /// The SQLite row mapper (review SL-57). A column value that did not convert to the property type went through two /// silent catches and the property kept its default - a row read as if the column were NULL. SQLite's dynamic typing /// lets any column hold text, so such a row is one bad write away. Free and Pro share the connection. /// public abstract class SqliteRowMapperTestsBase { protected readonly IRedbService Redb; protected SqliteRowMapperTestsBase(IRedbService redb) => Redb = redb; [Fact] public async Task AColumnValueThatDoesNotConvert_IsRefused() { var read = async () => await Redb.Context.QueryFirstOrDefaultAsync("SELECT 'abc' AS _value_long"); await read.Should().ThrowAsync().WithMessage("*_value_long*abc*"); } [Fact] public async Task AColumnValueThatConverts_IsRead() { var row = await Redb.Context.QueryFirstOrDefaultAsync("SELECT 42 AS _value_long, 'x' AS _name"); row!.ValueLong.Should().Be(42); } } Path: redb/redb.Tests.Integration/Tests/Base/SqliteSchemaNewerTestsBase.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/SqliteSchemaNewerTestsBase.cs ---- using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Core; using redb.Core.Data; using redb.Core.Exceptions; using redb.Core.Extensions; using redb.Tests.Integration.Fixtures; namespace redb.Tests.Integration.Tests.Base; /// /// A SQLite file written by a newer build is never taken back by an older one: the older build opens it when the /// file's _schema_compat row allows (a warning, nothing changed) and stops with RedbSchemaNewerException when it /// does not, or when the row is missing. Staged the way the other upgrade tests stage a file: create a current file, /// then rewrite its stamp and its row as a newer build would have left them, and reopen. /// public abstract class SqliteSchemaNewerTestsBase : IDisposable { private readonly string _dbPath = Path.Combine(Path.GetTempPath(), $"redb_newer_{Guid.NewGuid():N}.db"); /// The tier's registration (AddRedb or AddRedbPro) with the SQLite provider on the given connection string. protected abstract void AddRedbServices(IServiceCollection services, string connectionString); private ServiceProvider BuildServices(ILoggerProvider? logs = null) { var services = new ServiceCollection(); services.AddLogging(b => { b.SetMinimumLevel(LogLevel.Warning); if (logs != null) b.AddProvider(logs); }); AddRedbServices(services, $"Data Source={_dbPath};Pooling=False"); return services.BuildServiceProvider(); } /// Creates a current file and returns its schema version and its row. private async Task<(long Version, long MinReader, string Package)> CreateCurrentFileAsync() { await using var sp = BuildServices(); await sp.GetRequiredService().InitializeAsync(ensureCreated: true); var ctx = sp.GetRequiredService(); var version = await ctx.ExecuteScalarAsync("PRAGMA user_version"); var minReader = await ctx.ExecuteScalarAsync("SELECT _min_reader FROM _schema_compat"); var package = (await ctx.ExecuteScalarAsync("SELECT _package FROM _schema_compat"))!; return (version, minReader, package); } /// Rewrites the file as a newer build would have left it; a null row drops the table. private async Task MakeNewerAsync(long version, long? minReader, string package = "9.9.0") { await using var sp = BuildServices(); var ctx = sp.GetRequiredService(); if (minReader is null) await ctx.ExecuteAsync("DROP TABLE _schema_compat"); else { await ctx.ExecuteAsync("DELETE FROM _schema_compat"); await ctx.ExecuteAsync($"INSERT INTO _schema_compat(_min_reader, _package) VALUES ({minReader}, '{package}')"); } await ctx.ExecuteAsync($"PRAGMA user_version = {version}"); } private async Task FileVersionAsync() { await using var sp = BuildServices(); return await sp.GetRequiredService().ExecuteScalarAsync("PRAGMA user_version"); } [Fact] public async Task NewFile_CarriesItsCompatibilityRow() { var (version, minReader, package) = await CreateCurrentFileAsync(); minReader.Should().BeGreaterThan(0).And.BeLessThanOrEqualTo(version); package.Should().MatchRegex(@"^\d+\.\d+\.\d+$"); } [Fact] public async Task NewerFile_ThatAllowsThisBuild_IsOpened_AndLeftAsItIs() { var (version, _, _) = await CreateCurrentFileAsync(); var newer = version + 1000 + Random.Shared.Next(1, 1_000_000); await MakeNewerAsync(newer, minReader: version); var logs = new CapturingLoggerProvider(); await using (var sp = BuildServices(logs)) await sp.GetRequiredService().InitializeAsync(ensureCreated: true); (await FileVersionAsync()).Should().Be(newer, "an older build never takes a newer file back"); logs.Warnings.Should().ContainSingle(w => w.Contains(newer.ToString()) && w.Contains("left as it is")); } [Fact] public async Task NewerFile_ThatNoLongerAllowsThisBuild_StopsTheStart_AndChangesNothing() { var (version, _, _) = await CreateCurrentFileAsync(); var newer = version + 1000; await MakeNewerAsync(newer, minReader: newer); await using (var sp = BuildServices()) { var act = async () => await sp.GetRequiredService().InitializeAsync(ensureCreated: true); var ex = (await act.Should().ThrowAsync()).Which; ex.DeployedVersion.Should().Be(newer.ToString()); ex.PackageVersion.Should().Be(version.ToString()); ex.RequiredPackageVersion.Should().Be("9.9.0"); ex.Message.Should().Contain("from 9.9.0 on").And.Contain("the database was left unchanged"); } (await FileVersionAsync()).Should().Be(newer); } [Fact] public async Task NewerFile_WithoutTheRow_StopsTheStart() { var (version, _, _) = await CreateCurrentFileAsync(); await MakeNewerAsync(version + 1000, minReader: null); await using var sp = BuildServices(); var act = async () => await sp.GetRequiredService().InitializeAsync(ensureCreated: true); var ex = (await act.Should().ThrowAsync()).Which; ex.RequiredPackageVersion.Should().BeNull(); } [Fact] public async Task OlderFile_WithoutTheRow_IsUpgraded_AndGetsIt() { var (version, minReader, _) = await CreateCurrentFileAsync(); await MakeNewerAsync(version - 1, minReader: null); await using (var sp = BuildServices()) await sp.GetRequiredService().InitializeAsync(ensureCreated: true); await using var check = BuildServices(); var ctx = check.GetRequiredService(); (await ctx.ExecuteScalarAsync("PRAGMA user_version")).Should().Be(version); (await ctx.ExecuteScalarAsync("SELECT _min_reader FROM _schema_compat")).Should().Be(minReader); } public void Dispose() { Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools(); foreach (var path in new[] { _dbPath, _dbPath + "-wal", _dbPath + "-shm" }) try { File.Delete(path); } catch (IOException) { } } } 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"); } } Path: redb/redb.Tests.Integration/Tests/Base/StreamsIndexOnceTestsBase.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/StreamsIndexOnceTestsBase.cs ---- using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Core; using redb.Core.Data; using redb.Core.Models; using redb.Core.Models.Configuration; namespace redb.Tests.Integration.Tests.Base; /// /// Pro with the planner on builds the indexes of the streams query form once, at the module step that brings them (here: /// the database it creates). A start after that does not build a dropped one again: the index check reports it as a Pro /// module index, and the repair builds it. /// public abstract class StreamsIndexOnceTestsBase { protected abstract Task CreateDatabaseAsync(string name); protected abstract Task DropDatabaseAsync(string name); protected abstract void AddRedbPro(IServiceCollection services, string connectionString, Action configure); protected abstract string StreamsIndex { get; } protected abstract string DropStreamsIndexSql { get; } [Fact] public async Task DroppedStreamsIndex_IsNotRebuiltAtStart_ButReportedAndRepaired() { var name = $"redb_idxonce_{Guid.NewGuid():N}"[..24]; var connectionString = await CreateDatabaseAsync(name); try { await using (var sp = Build(connectionString)) { var redb = sp.GetRequiredService(); await redb.InitializeAsync(ensureCreated: true); (await redb.CheckBaseIndexesAsync()).Findings.Should().BeEmpty("a database Pro creates gets its streams indexes"); await sp.GetRequiredService().ExecuteAsync(DropStreamsIndexSql); } await using (var sp = Build(connectionString)) { var redb = sp.GetRequiredService(); await redb.InitializeAsync(); var finding = (await redb.CheckBaseIndexesAsync()).Findings.Should().ContainSingle().Subject; finding.Name.Should().Be(StreamsIndex, "a start that is not the module step builds nothing"); finding.State.Should().Be(RedbIndexState.Missing); finding.Expected.Origin.Should().Be(RedbIndexOrigin.ProModule); (await redb.RepairBaseIndexesAsync(allowOffline: true)).Built.Should().Equal([StreamsIndex]); (await redb.CheckBaseIndexesAsync()).Findings.Should().BeEmpty(); } } finally { await DropDatabaseAsync(name); } } private ServiceProvider Build(string connectionString) { var services = new ServiceCollection(); services.AddLogging(b => b.SetMinimumLevel(LogLevel.Warning)); AddRedbPro(services, connectionString, c => { c.EnablePropsCache = false; c.EnablePvtPrefilter = true; }); return services.BuildServiceProvider(); } } Path: redb/redb.Tests.Integration/Tests/Base/SubSecondUpdateTestsBase.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/SubSecondUpdateTestsBase.cs ---- using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Core; using redb.Core.Extensions; using redb.Core.Models.Configuration; using redb.Core.Models.Entities; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// A temporal property changed within the same second must be /// written. The ChangeTracking save skips an object whose hash equals the stored one, and the hash canon of a /// DateTime/DateTimeOffset had no sub-second digits - a heartbeat updated twice within a second was silently lost. /// The second fact guards the other side: the canon keeps milliseconds only, so the hash the save stores is the one /// the reloaded object recomputes on every database. /// public abstract class SubSecondUpdateTestsBase { protected abstract void UseProvider(RedbOptionsBuilder options); protected virtual void Register(IServiceCollection services, Action configure) => services.AddRedb(configure); /// The Pro hosts run the ChangeTracking save - the strategy with the hash shortcut. protected virtual PropsSaveStrategy SaveStrategy => PropsSaveStrategy.DeleteInsert; private ServiceProvider Build() { var services = new ServiceCollection(); services.AddLogging(b => b.SetMinimumLevel(LogLevel.Warning)); Register(services, options => { UseProvider(options); options.Configure(c => { c.EnablePropsCache = false; c.PropsSaveStrategy = SaveStrategy; c.AutoRecomputeHash = true; c.CacheDomain = $"sub-second-{GetType().Name}"; }); }); return services.BuildServiceProvider(); } private static readonly DateTimeOffset Moment = new(2026, 9, 16, 12, 30, 15, TimeSpan.Zero); private static async Task BootAsync(IRedbService redb) { await redb.InitializeAsync(ensureCreated: true); await redb.SyncSchemeAsync(); await redb.InitializeTypeRegistryAsync(); } private static async Task SeedAsync(ServiceProvider sp, DateTimeOffset moment) { await using var scope = sp.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); await BootAsync(redb); return await redb.SaveAsync(new RedbObject { name = $"sub-second-{Guid.NewGuid():N}", // Every temporal field set: a default DateOnly/DateTime (MinValue) does not survive SQLite's OLE-date // storage (ToOADate returns 0 for MinValue) - a separate finding, not this test's subject. Props = new TemporalRoundTripProps { When = moment.UtcDateTime, Moment = moment, Day = new DateOnly(2026, 9, 16), Clock = new TimeOnly(12, 30, 15), Span = TimeSpan.FromMinutes(90), Label = "seed" } }); } [Fact] public async Task AChangeWithinTheSameSecond_IsSaved() { await using var sp = Build(); var id = await SeedAsync(sp, Moment); await using (var scope = sp.CreateAsyncScope()) { var redb = scope.ServiceProvider.GetRequiredService(); var obj = (await redb.LoadAsync(id))!; obj.Props.Moment = obj.Props.Moment.AddMilliseconds(100); obj.Props.When = obj.Props.When.AddMilliseconds(100); await redb.SaveAsync(obj); } await using (var scope = sp.CreateAsyncScope()) { var redb = scope.ServiceProvider.GetRequiredService(); var reloaded = (await redb.LoadAsync(id))!; reloaded.Props.Moment.Should().Be(Moment.AddMilliseconds(100), "a 100 ms change is a change: the save must not skip it as unchanged"); reloaded.Props.When.Should().Be(Moment.UtcDateTime.AddMilliseconds(100)); } } [Fact] public async Task TheStoredHash_IsTheHashOfTheReloadedObject() { await using var sp = Build(); // Sub-millisecond noise the databases do not keep: the canon must not keep it either. var id = await SeedAsync(sp, Moment.AddMilliseconds(100).AddTicks(4567)); await using var scope = sp.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); var reloaded = (await redb.LoadAsync(id))!; reloaded.hash.Should().Be(reloaded.ComputeHash(), "the hash the save stored must equal the hash of the reloaded object - the props cache and the " + "ChangeTracking shortcut compare exactly these two"); } } Path: redb/redb.Tests.Integration/Tests/Base/TagsFieldTestsBase.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/TagsFieldTestsBase.cs ---- using redb.Core; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// The free-form _tags marker (V4): a reserved 450-character slot on _schemes and /// _structures (mirrored into the metadata cache, indexed on structures) for future and /// custom extensions. The contract pinned here: [RedbTags] writes it at synchronisation, /// and a column WITHOUT the attribute is never touched by sync - direct writes survive. /// public abstract class TagsFieldTestsBase : IAsyncLifetime { protected readonly IRedbService Redb; protected TagsFieldTestsBase(IRedbService redb) => Redb = redb; public async Task InitializeAsync() => await ResetAsync(); public async Task DisposeAsync() => await ResetAsync(); private async Task ResetAsync() { await Redb.Context.ExecuteAsync( "DELETE FROM _objects WHERE _id_scheme IN (SELECT _id FROM _schemes WHERE _name = 'TagsProbe')"); await Redb.Context.ExecuteAsync( "DELETE FROM _structures WHERE _id_scheme IN (SELECT _id FROM _schemes WHERE _name = 'TagsProbe')"); await Redb.Context.ExecuteAsync("DELETE FROM _schemes WHERE _name = 'TagsProbe'"); } [Fact] public async Task TagsColumns_AreDelivered_ByInitialize() { await Redb.InitializeAsync(); // The queries themselves are the pin: a missing column fails them on every provider. await Redb.Context.ExecuteScalarAsync("SELECT COUNT(*) FROM _schemes WHERE _tags IS NOT NULL"); await Redb.Context.ExecuteScalarAsync("SELECT COUNT(*) FROM _structures WHERE _tags IS NOT NULL"); await Redb.Context.ExecuteScalarAsync("SELECT COUNT(*) FROM _scheme_metadata_cache WHERE _tags IS NOT NULL"); } [Fact] public async Task RedbTags_WritesSchemeAndStructureMarkers_AtSync() { await Redb.SyncSchemeAsync(); var schemeTags = await Redb.Context.ExecuteScalarAsync( "SELECT _tags FROM _schemes WHERE _name = 'TagsProbe'"); schemeTags.Should().Be("scheme-level,reserved", "[RedbTags] on the Props class writes the scheme marker"); var markedTags = await Redb.Context.ExecuteScalarAsync( "SELECT _tags FROM _structures WHERE _name = 'Marked' AND _id_scheme = " + "(SELECT _id FROM _schemes WHERE _name = 'TagsProbe')"); markedTags.Should().Be("prop-level", "[RedbTags] on a property writes the structure marker"); var plainTags = await Redb.Context.ExecuteScalarAsync( "SELECT _tags FROM _structures WHERE _name = 'Plain' AND _id_scheme = " + "(SELECT _id FROM _schemes WHERE _name = 'TagsProbe')"); plainTags.Should().BeNull("a property without the attribute gets no marker"); } [Fact] public async Task DirectWrite_SurvivesResync() { await Redb.SyncSchemeAsync(); // An application or extension writes its own marker on an attribute-free structure... await Redb.Context.ExecuteAsync( "UPDATE _structures SET _tags = 'custom-extension' WHERE _name = 'Plain' AND _id_scheme = " + "(SELECT _id FROM _schemes WHERE _name = 'TagsProbe')"); // ...and synchronisation must leave it alone: no attribute - no write. await Redb.SyncSchemeAsync(); var plainTags = await Redb.Context.ExecuteScalarAsync( "SELECT _tags FROM _structures WHERE _name = 'Plain' AND _id_scheme = " + "(SELECT _id FROM _schemes WHERE _name = 'TagsProbe')"); plainTags.Should().Be("custom-extension", "sync never wipes a marker it did not write"); } } Path: redb/redb.Tests.Integration/Tests/Base/TemporalRoundTripTestsBase.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/TemporalRoundTripTestsBase.cs ---- using System.Globalization; using redb.Core; using redb.Core.Models.Entities; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// The temporal contract, end to end against a real database. /// /// /// DateTime carries no time zone. The clock reading is the datum: 14:00 written is 14:00 /// read, on any host, in any zone, through any read path — materialization, ordering, aggregate. /// DateTimeOffset is the opposite and deliberately untouched: it is the native .NET type and /// carries a real instant. /// /// /// /// No form follows the culture. and are stored as their Ticks in /// _values._Long, independent of the ambient ; a row written on one host loads on /// another. /// /// /// /// Why this suite exists: every other test in the repository uses DateTime.UtcNow or a /// DateTimeKind.Utc literal, where the zone-less and the instant reading coincide exactly, /// and none of them touches DateTimeOffset, DateOnly, TimeOnly or TimeSpan at all. The conversion /// paths below were unreachable from a test. /// /// public abstract class TemporalRoundTripTestsBase { protected readonly IRedbService Redb; private bool _seeded; protected TemporalRoundTripTestsBase(IRedbService redb) => Redb = redb; // A fixed non-UTC offset, so "instant" and "reading" are never accidentally equal. private static readonly TimeSpan Offset = TimeSpan.FromHours(3); private static DateTime Reading(int day, int hour) => new(2026, 3, day, hour, 30, 0, DateTimeKind.Unspecified); /// Runs under a specific culture, restoring the previous one. private static async Task UnderCultureAsync(string name, Func body) { var previous = CultureInfo.CurrentCulture; try { CultureInfo.CurrentCulture = new CultureInfo(name); await body(); } finally { CultureInfo.CurrentCulture = previous; } } /// /// Ten rows, one per day 1..10 of 2026-03, hour = 10 + (i % 3). Every temporal field moves /// together so a filter on one can be cross-checked against another. /// protected async Task EnsureSeededAsync() { if (_seeded) return; // Scheme name is the CLR FullName: the positional [RedbScheme("...")] argument is the // ALIAS, never the name. Deleting by the alias silently matched nothing and rows piled up // across tests, which is exactly how this line was wrong the first time. await Redb.Context.ExecuteAsync( "DELETE FROM _objects WHERE _id_scheme IN (SELECT _id FROM _schemes WHERE _name = " + $"'{typeof(TemporalProps).FullName}')"); var rows = Enumerable.Range(1, 10).Select(i => new RedbObject { name = $"temporal-{i:00}", Props = new TemporalProps { When = Reading(i, 10 + (i % 3)), Moment = new DateTimeOffset(2026, 3, i, 10 + (i % 3), 30, 0, Offset), Day = new DateOnly(2026, 3, i), Clock = new TimeOnly(10 + (i % 3), 30, 0), Span = TimeSpan.FromDays(i).Add(TimeSpan.FromHours(2)), Label = $"row-{i:00}" } }).ToList(); await Redb.SaveAsync(rows); _seeded = true; } // ===================================================================== // Round trip // ===================================================================== /// /// Every temporal type survives a save/load unchanged, whatever culture the host runs under. /// The DateOnly/TimeOnly/TimeSpan write path used to go through the current culture's short /// pattern ("23.08.2026", "2:30 PM") and the read path parsed it back the same /// way, so the pair only agreed while the culture stayed put. /// [Theory] [InlineData("ru-RU")] [InlineData("en-US")] [InlineData("de-DE")] public async Task RoundTrip_AllTemporalTypes_SurviveAnyCulture(string culture) { await UnderCultureAsync(culture, async () => { var source = new TemporalRoundTripProps { When = new DateTime(2026, 8, 23, 14, 0, 0, DateTimeKind.Unspecified), Moment = new DateTimeOffset(2026, 8, 23, 14, 0, 0, Offset), Day = new DateOnly(2026, 8, 23), Clock = new TimeOnly(14, 30, 15), Span = TimeSpan.FromDays(3).Add(TimeSpan.FromHours(2)), Label = $"roundtrip-{culture}" }; var obj = new RedbObject { name = source.Label, Props = source }; var id = await Redb.SaveAsync(obj); var loaded = await Redb.LoadAsync(id); // Zone-less: the reading comes back as written, labelled UTC. loaded.Props.When.Should().Be(new DateTime(2026, 8, 23, 14, 0, 0, DateTimeKind.Utc)); loaded.Props.When.Kind.Should().Be(DateTimeKind.Utc); // Zone-aware: the instant comes back, the offset is normalised away. loaded.Props.Moment.UtcDateTime.Should().Be(source.Moment.UtcDateTime); loaded.Props.Day.Should().Be(source.Day); loaded.Props.Clock.Should().Be(source.Clock); loaded.Props.Span.Should().Be(source.Span, "the day component must survive"); }); } /// /// A value keeps its reading rather than being shifted to the /// host's UTC offset. This is the whole point of the contract, and it is invisible on a host /// running in UTC — hence the explicit non-UTC assertion below. /// [Fact] public async Task RoundTrip_DateTime_KeepsReadingNotInstant() { var local = new DateTime(2026, 8, 23, 14, 0, 0, DateTimeKind.Local); var id = await Redb.SaveAsync(new RedbObject { name = "kind-local", Props = new TemporalRoundTripProps { When = local, Label = "kind-local" } }); var loaded = await Redb.LoadAsync(id); loaded.Props.When.Hour.Should().Be(14); loaded.Props.When.Should().Be(new DateTime(2026, 8, 23, 14, 0, 0, DateTimeKind.Utc)); } /// /// The edges of the CLR types come back as themselves: , /// and are what a model that never /// set them carries. SQLite encoded a datetime through the OLE automation date, whose zero stands for /// MinValue: a default date came back as 1899-12-30. /// [Fact] public async Task RoundTrip_TemporalMinValues_ComeBackAsThemselves() { var id = await Redb.SaveAsync(new RedbObject { name = $"temporal-min-{Guid.NewGuid():N}", Props = new TemporalRoundTripProps { When = DateTime.MinValue, Moment = DateTimeOffset.MinValue, Day = DateOnly.MinValue, Clock = TimeOnly.MinValue, Span = TimeSpan.Zero, Label = "min" } }); var loaded = (await Redb.LoadAsync(id))!; loaded.Props.When.Should().Be(DateTime.MinValue); loaded.Props.Moment.Should().Be(DateTimeOffset.MinValue); loaded.Props.Day.Should().Be(DateOnly.MinValue); loaded.Props.Clock.Should().Be(TimeOnly.MinValue); loaded.Props.Span.Should().Be(TimeSpan.Zero); } /// /// A time of day before 1899-12-30 is kept, and the row is found by the value it was written from. The OLE /// automation date encodes a day before its epoch as sign and magnitude, not as a linear count: through it /// 1850-05-03 12:34 moved a day on the way in and again on the way out, and a filter built from the same value /// compared against a day that was never stored. /// [Fact] public async Task RoundTrip_TimeOfDayBefore1900_IsKept_AndFoundByItsValue() { var label = $"pre1900-{Guid.NewGuid():N}"; var reading = new DateTime(1850, 5, 3, 12, 34, 56, DateTimeKind.Unspecified); var id = await Redb.SaveAsync(new RedbObject { name = label, Props = new TemporalRoundTripProps { When = reading, Moment = new DateTimeOffset(reading, Offset), Day = new DateOnly(1850, 5, 3), Clock = new TimeOnly(12, 34, 56), Span = TimeSpan.Zero, Label = label } }); var loaded = (await Redb.LoadAsync(id))!; loaded.Props.When.Should().Be(reading); loaded.Props.Moment.UtcDateTime.Should().Be(new DateTimeOffset(reading, Offset).UtcDateTime); loaded.Props.Day.Should().Be(new DateOnly(1850, 5, 3)); var found = await Redb.Query() .Where(t => t.Label == label && t.When == reading) .Take(5).ToListAsync(); found.Should().ContainSingle().Which.id.Should().Be(id); } // ===================================================================== // Comparison: DateTime // ===================================================================== [Fact] public async Task Where_DateTime_GreaterThan() { await EnsureSeededAsync(); var cutoff = Reading(5, 0); var results = await Redb.Query() .Where(t => t.When > cutoff) .Take(50).ToListAsync(); results.Should().NotBeEmpty(); results.Should().AllSatisfy(r => r.Props.When.Should().BeAfter(cutoff)); results.Should().HaveCount(6, "days 5..10 all start after 2026-03-05T00:30 except day 5 itself is 10:30+"); } [Fact] public async Task Where_DateTime_LessThan() { await EnsureSeededAsync(); var cutoff = Reading(5, 0); var results = await Redb.Query() .Where(t => t.When < cutoff) .Take(50).ToListAsync(); results.Should().NotBeEmpty(); results.Should().AllSatisfy(r => r.Props.When.Should().BeBefore(cutoff)); } [Fact] public async Task Where_DateTime_Between() { await EnsureSeededAsync(); var from = Reading(3, 0); var to = Reading(7, 0); var results = await Redb.Query() .Where(t => t.When >= from && t.When < to) .Take(50).ToListAsync(); results.Should().HaveCount(4); results.Should().AllSatisfy(r => { r.Props.When.Should().BeOnOrAfter(from); r.Props.When.Should().BeBefore(to); }); } /// /// Equality closes the loop: the value the filter is built from and the value the writer stored /// must be the same, or a saved row becomes unfindable by its own value. Write and search go /// through the same normalisation, which is what makes this hold. /// [Fact] public async Task Where_DateTime_Equal_FindsTheRowItWasWrittenFrom() { await EnsureSeededAsync(); var exact = Reading(4, 11); var results = await Redb.Query() .Where(t => t.When == exact) .Take(50).ToListAsync(); results.Should().ContainSingle(); results[0].Props.Label.Should().Be("row-04"); } // ===================================================================== // Comparison: DateTimeOffset // ===================================================================== [Fact] public async Task Where_DateTimeOffset_GreaterThan() { await EnsureSeededAsync(); var cutoff = new DateTimeOffset(2026, 3, 5, 0, 0, 0, Offset); var results = await Redb.Query() .Where(t => t.Moment > cutoff) .Take(50).ToListAsync(); results.Should().NotBeEmpty(); results.Should().AllSatisfy(r => r.Props.Moment.Should().BeAfter(cutoff)); } /// /// Two ways of writing the same instant must select the same rows. A DateTimeOffset carries a /// real moment, so 10:30+03:00 and 07:30Z are one and the same cutoff. /// [Fact] public async Task Where_DateTimeOffset_SameInstantDifferentOffset_SelectsSameRows() { await EnsureSeededAsync(); var withOffset = new DateTimeOffset(2026, 3, 5, 0, 0, 0, Offset); var asUtc = withOffset.ToUniversalTime(); var a = await Redb.Query().Where(t => t.Moment > withOffset).Take(50).ToListAsync(); var b = await Redb.Query().Where(t => t.Moment > asUtc).Take(50).ToListAsync(); a.Select(x => x.Id).OrderBy(x => x).Should().Equal(b.Select(x => x.Id).OrderBy(x => x)); } // ===================================================================== // Comparison: DateOnly // ===================================================================== [Fact] public async Task Where_DateOnly_GreaterThan() { await EnsureSeededAsync(); var cutoff = new DateOnly(2026, 3, 5); var results = await Redb.Query() .Where(t => t.Day > cutoff) .Take(50).ToListAsync(); results.Should().HaveCount(5); results.Should().AllSatisfy(r => r.Props.Day.Should().BeAfter(cutoff)); } [Fact] public async Task Where_DateOnly_Equal() { await EnsureSeededAsync(); var exact = new DateOnly(2026, 3, 7); var results = await Redb.Query() .Where(t => t.Day == exact) .Take(50).ToListAsync(); results.Should().ContainSingle(); results[0].Props.Label.Should().Be("row-07"); } // ===================================================================== // Ordering and the analytics path // ===================================================================== [Fact] public async Task OrderBy_DateTime_IsChronological() { await EnsureSeededAsync(); var results = await Redb.Query() .OrderBy(t => t.When) .Take(50).ToListAsync(); results.Select(r => r.Props.When).Should().BeInAscendingOrder(); } /// /// Base-field aggregates go through JsonValueConverter, a different converter from the /// one object materialization uses. It used to parse a zoned ISO string into the caller's LOCAL /// zone, so the same stored field answered differently depending on how it was read. The two /// paths must agree exactly, and must not follow the ambient culture. /// [Fact] public async Task Aggregate_BaseDateField_AgreesWithMaterialization() { await EnsureSeededAsync(); var min = await Redb.Query().MinRedbAsync(o => o.DateCreate); var max = await Redb.Query().MaxRedbAsync(o => o.DateCreate); var all = await Redb.Query().Take(50).ToListAsync(); min.Should().NotBeNull(); max.Should().NotBeNull(); min!.Value.UtcDateTime.Should().Be(all.Min(r => r.DateCreate).UtcDateTime); max!.Value.UtcDateTime.Should().Be(all.Max(r => r.DateCreate).UtcDateTime); } [Fact] public async Task Aggregate_BaseDateField_IsCultureIndependent() { await EnsureSeededAsync(); DateTimeOffset? underRu = default, underUs = default; await UnderCultureAsync("ru-RU", async () => underRu = await Redb.Query().MinRedbAsync(o => o.DateCreate)); await UnderCultureAsync("en-US", async () => underUs = await Redb.Query().MinRedbAsync(o => o.DateCreate)); underRu.Should().Be(underUs); } // KNOWN BOUNDARY, not covered by a test on purpose. // // MinAsync/MaxAsync over a *Props* field return through ExecuteAggregateAsync, whose contract // is Task. That works for a backend which stores datetimes as a number (SQLite, whose // REAL Julian day is decoded by TemporalDecoder) and cannot work on PostgreSQL or SQL Server, // where the aggregate comes back as an ISO string and the decimal conversion throws // FormatException. The failure is provider-shaped, so a shared assertion here would be either // wrong on one backend or vacuous on all. Widening the contract to a type-preserving one // touches every provider and both tiers — deferred, see DATETIME.md. // // Base-field aggregates (the two tests above) are unaffected: they return JSON and go through // JsonValueConverter. // ===================================================================== // TimeOnly / TimeSpan: equality works, ordering is a documented boundary // ===================================================================== [Fact] public async Task Where_TimeOnly_Equal() { await EnsureSeededAsync(); var exact = new TimeOnly(12, 30, 0); // i % 3 == 2 → days 2, 5, 8 var results = await Redb.Query() .Where(t => t.Clock == exact) .Take(50).ToListAsync(); results.Should().NotBeEmpty(); results.Should().AllSatisfy(r => r.Props.Clock.Should().Be(exact)); } [Fact] public async Task Where_TimeSpan_Equal() { await EnsureSeededAsync(); var exact = TimeSpan.FromDays(4).Add(TimeSpan.FromHours(2)); var results = await Redb.Query() .Where(t => t.Span == exact) .Take(50).ToListAsync(); results.Should().ContainSingle(); results[0].Props.Label.Should().Be("row-04"); } /// /// and are stored as their Ticks in _values._Long, so ordered /// comparison and sorting are chronological. As text they were lexicographic: "10.02:00:00" sorted before /// "2.02:00:00", and a filter Span > 9 days 2 hours left the row of 10 days out. /// [Fact] public async Task Where_TimeSpan_OrderedComparison_IsChronological() { await EnsureSeededAsync(); var results = await Redb.Query() .Where(t => t.Span > TimeSpan.FromDays(8).Add(TimeSpan.FromHours(2))) .Take(50).ToListAsync(); results.Select(r => r.Props.Label).Should().BeEquivalentTo(["row-09", "row-10"], "9 and 10 days are longer than 8 days"); } [Fact] public async Task OrderBy_TimeSpan_And_TimeOnly_AreChronological() { await EnsureSeededAsync(); var bySpan = await Redb.Query().OrderBy(t => t.Span).Take(50).ToListAsync(); bySpan.Select(r => r.Props.Span).Should().BeInAscendingOrder(); bySpan.Select(r => r.Props.Label).Should().Equal(Enumerable.Range(1, 10).Select(i => $"row-{i:00}")); var byClock = await Redb.Query().OrderByDescending(t => t.Clock).Take(50).ToListAsync(); byClock.Select(r => r.Props.Clock).Should().BeInDescendingOrder(); } } Path: redb/redb.Tests.Integration/Tests/Base/TimeTicksTestsBase.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/TimeTicksTestsBase.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.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// TimeSpan and TimeOnly are stored as their Ticks in _values._Long. As text ("c" form) they compared, sorted and /// grouped as strings: past a day ("10.02:00:00" below "2.02:00:00") and below zero the order was wrong, and a GroupBy /// over a TimeSpan? key failed to build its result. Values past a day, negative values, sub-second ticks, nulls, /// arrays, lists and dictionary values on every provider. /// public abstract class TimeTicksTestsBase { protected readonly IRedbService Redb; protected TimeTicksTestsBase(IRedbService redb) => Redb = redb; private static readonly TimeSpan[] SpanValues = [ TimeSpan.FromHours(-2), // negative TimeSpan.FromMinutes(-1), TimeSpan.Zero, TimeSpan.FromHours(23), TimeSpan.FromDays(1).Add(TimeSpan.FromHours(2)), // past a day TimeSpan.FromDays(2).Add(TimeSpan.FromTicks(1234567)), // sub-second ticks TimeSpan.FromDays(10).Add(TimeSpan.FromHours(2)), ]; private async Task<(string Tag, List Ids)> SeedAsync() { await Redb.SyncSchemeAsync(); var tag = "tt-" + Guid.NewGuid().ToString("N")[..8]; var rows = SpanValues.Select((s, i) => new TimeTicksProps { Tag = tag, Span = s, MaybeSpan = i % 3 == 0 ? null : s, Clock = new TimeOnly(i * 3, 15, 30, 123).Add(TimeSpan.FromTicks(4567)), MaybeClock = i % 2 == 0 ? null : new TimeOnly(23, 59, 59, 999), Spans = i == 0 ? [] : [s, TimeSpan.FromDays(i), TimeSpan.FromHours(-i)], Clocks = [new TimeOnly(0, 0), new TimeOnly(i, 30)], MaybeSpans = [s, null], SpanByName = new() { ["a"] = s, ["b"] = TimeSpan.FromDays(-i) }, }).ToList(); var ids = await Redb.SaveAsync(rows.Select((p, i) => (IRedbObject)new RedbObject { name = $"{tag}-{i}", Props = p }).ToList()); return (tag, ids); } private IRedbQueryable Tagged(string tag) => Redb.Query().Where(p => p.Tag == tag); [Fact] public async Task Values_AreStoredAsTicks_AndComeBackAsThemselves() { var (tag, ids) = await SeedAsync(); // The stored form: Ticks in _Long, no text. var stored = await Redb.Context.ExecuteScalarAsync( "SELECT v._Long FROM _values v JOIN _structures s ON s._id = v._id_structure " + $"WHERE v._id_object = {ids[4]} AND s._name = 'Span' AND v._array_index IS NULL"); stored.Should().Be(SpanValues[4].Ticks); (await Redb.Context.ExecuteScalarAsync( "SELECT COUNT(*) FROM _values v JOIN _structures s ON s._id = v._id_structure " + $"WHERE v._id_object = {ids[4]} AND s._name IN ('Span', 'Clock', 'MaybeSpan') AND v._String IS NOT NULL")) .Should().Be(0, "no TimeSpan or TimeOnly value is stored as text"); for (var i = 0; i < ids.Count; i++) { var o = await Redb.LoadAsync(ids[i]); var p = o!.Props; var s = SpanValues[i]; p.Span.Should().Be(s); p.MaybeSpan.Should().Be(i % 3 == 0 ? null : s); p.Clock.Should().Be(new TimeOnly(i * 3, 15, 30, 123).Add(TimeSpan.FromTicks(4567))); p.MaybeClock.Should().Be(i % 2 == 0 ? null : new TimeOnly(23, 59, 59, 999)); p.Spans.Should().Equal(i == 0 ? [] : [s, TimeSpan.FromDays(i), TimeSpan.FromHours(-i)]); p.Clocks.Should().Equal(new TimeOnly(0, 0), new TimeOnly(i, 30)); p.MaybeSpans.Should().Equal(s, null); p.SpanByName.Should().BeEquivalentTo(new Dictionary { ["a"] = s, ["b"] = TimeSpan.FromDays(-i) }); } // The query path materializes the same values. var listed = await Tagged(tag).ToListAsync(); listed.Select(o => o.Props.Span).Should().BeEquivalentTo(SpanValues); } [Fact] public async Task Filters_CompareChronologically_PastADay_AndBelowZero() { var (tag, _) = await SeedAsync(); async Task Spans(System.Linq.Expressions.Expression> filter) => (await Tagged(tag).Where(filter).ToListAsync()).Select(o => o.Props.Span).OrderBy(x => x).ToArray(); (await Spans(p => p.Span > TimeSpan.FromHours(20))).Should().Equal(SpanValues.Where(s => s > TimeSpan.FromHours(20))); (await Spans(p => p.Span < TimeSpan.Zero)).Should().Equal(SpanValues.Where(s => s < TimeSpan.Zero)); (await Spans(p => p.Span >= TimeSpan.FromDays(1) && p.Span <= TimeSpan.FromDays(3))) .Should().Equal(SpanValues.Where(s => s >= TimeSpan.FromDays(1) && s <= TimeSpan.FromDays(3))); (await Spans(p => p.Span == SpanValues[5])).Should().Equal(SpanValues[5]); var some = new List { SpanValues[0], SpanValues[6] }; (await Spans(p => some.Contains(p.Span))).Should().Equal(SpanValues[0], SpanValues[6]); (await Spans(p => p.MaybeSpan > TimeSpan.Zero)).Should().Equal( SpanValues.Where((s, i) => i % 3 != 0 && s > TimeSpan.Zero)); (await Tagged(tag).Where(p => p.Clock > new TimeOnly(9, 0)).CountAsync()) .Should().Be(SpanValues.Select((_, i) => new TimeOnly(i * 3, 15, 30)).Count(c => c > new TimeOnly(9, 0))); } [Fact] public async Task Sorting_IsChronological() { var (tag, _) = await SeedAsync(); (await Tagged(tag).OrderBy(p => p.Span).ToListAsync()).Select(o => o.Props.Span) .Should().Equal(SpanValues.OrderBy(s => s)); (await Tagged(tag).OrderByDescending(p => p.Span).ToListAsync()).Select(o => o.Props.Span) .Should().Equal(SpanValues.OrderByDescending(s => s)); (await Tagged(tag).OrderBy(p => p.Clock).ToListAsync()).Select(o => o.Props.Clock) .Should().BeInAscendingOrder(); } [Fact] public async Task GroupBy_And_MinMax_ReadTheTicks() { var (tag, _) = await SeedAsync(); var groups = await Tagged(tag).GroupBy(p => p.MaybeSpan).SelectAsync(g => new { g.Key, Count = Agg.Count(g) }); groups.Where(g => g.Key != null).Select(g => g.Key!.Value).OrderBy(x => x) .Should().Equal(SpanValues.Where((_, i) => i % 3 != 0).OrderBy(x => x)); groups.Single(g => g.Key == null).Count.Should().Be(SpanValues.Where((_, i) => i % 3 == 0).Count()); var minMax = await Tagged(tag).AggregateAsync(x => new { Min = Agg.Min(x.Props.Span), Max = Agg.Max(x.Props.Span) }); minMax.Min.Should().Be(SpanValues.Min()); minMax.Max.Should().Be(SpanValues.Max()); } /// /// The statement UPGRADING.md gives for this database turns values stored as text before the change (the "c" form /// of TimeSpan, the "O" form of TimeOnly, with days, signs and fractions, in plain fields, arrays and dictionary /// values) into Ticks, and the objects read back as they were saved. The statement is read from UPGRADING.md, so the /// text and the test cannot drift. /// [Fact] public async Task UpgradingStatement_ConvertsValuesStoredAsText() { var (tag, ids) = await SeedAsync(); var before = new List(); foreach (var id in ids) before.Add((await Redb.LoadAsync(id))!.Props); // Back to the stored form of earlier versions: the text in _String, no Ticks. var idList = string.Join(", ", ids); var rows = await Redb.Context.QueryAsync( "SELECT v._id AS Id, v._Long AS Ticks, t._name AS TypeName FROM _values v " + "JOIN _structures s ON s._id = v._id_structure JOIN _types t ON t._id = s._id_type " + $"WHERE v._id_object IN ({idList}) AND t._name IN ('TimeSpan', 'TimeOnly') AND v._Long IS NOT NULL"); rows.Should().NotBeEmpty(); foreach (var r in rows) { var text = r.TypeName == "TimeSpan" ? TimeSpan.FromTicks(r.Ticks!.Value).ToString("c", System.Globalization.CultureInfo.InvariantCulture) : new TimeOnly(r.Ticks!.Value).ToString("O", System.Globalization.CultureInfo.InvariantCulture); await Redb.Context.ExecuteAsync($"UPDATE _values SET _String = '{text}', _Long = NULL WHERE _id = {r.Id}"); } await Redb.Context.ExecuteAsync(UpgradingStatement()); (await Redb.Context.ExecuteScalarAsync( "SELECT COUNT(*) FROM _values v JOIN _structures s ON s._id = v._id_structure JOIN _types t ON t._id = s._id_type " + $"WHERE v._id_object IN ({idList}) AND t._name IN ('TimeSpan', 'TimeOnly') AND v._String IS NOT NULL")) .Should().Be(0, "every value written by an earlier version is converted"); for (var i = 0; i < ids.Count; i++) { var after = (await Redb.LoadAsync(ids[i]))!.Props; after.Should().BeEquivalentTo(before[i], $"object {i} reads back as it was saved"); } } private sealed class StoredValue { public long Id { get; set; } public long? Ticks { get; set; } public string TypeName { get; set; } = ""; } /// The SQL block that follows "PostgreSQL:", "SQL Server:" or "SQLite:" in the UPGRADING.md section. private string UpgradingStatement() { var ns = Redb.GetType().Namespace ?? ""; var label = ns.Contains("Postgres") ? "PostgreSQL:" : ns.Contains("MSSql") ? "SQL Server:" : "SQLite:"; var dir = new DirectoryInfo(AppContext.BaseDirectory); string? path = null; while (dir != null && path == null) { var candidate = Path.Combine(dir.FullName, "redb.DB", "UPGRADING.md"); if (File.Exists(candidate)) path = candidate; else if (File.Exists(Path.Combine(dir.FullName, "UPGRADING.md")) && Directory.Exists(Path.Combine(dir.FullName, "tests"))) path = Path.Combine(dir.FullName, "UPGRADING.md"); dir = dir.Parent; } path.Should().NotBeNull("UPGRADING.md is found above the test output"); var text = File.ReadAllText(path!).Replace("\r\n", "\n"); var section = text[text.IndexOf("### TimeSpan and TimeOnly are stored as ticks", StringComparison.Ordinal)..]; var at = section.IndexOf("\n" + label + "\n", StringComparison.Ordinal); at.Should().BeGreaterThan(0, $"the section has a statement for {label}"); var start = section.IndexOf("```sql\n", at, StringComparison.Ordinal) + "```sql\n".Length; var end = section.IndexOf("\n```", start, StringComparison.Ordinal); return section[start..end]; } } Path: redb/redb.Tests.Integration/Tests/Base/TopLevelCollectionsTestsBase.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/TopLevelCollectionsTestsBase.cs ---- using System.Collections.ObjectModel; using redb.Core; using redb.Core.Exceptions; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// Collection types at the top of a property. HashSet, ISet, ObservableCollection, Queue, Stack, IReadOnlyList, /// SortedDictionary and IReadOnlyDictionary were stored as one text value holding the name of the type, and the object /// could not be loaded. Now the scheme sync refuses such a property before it writes anything, naming the class, the /// property, its type and the supported collection types; a save against a scheme synced before the refusal existed /// refuses the same way before any row is written. The supported shapes read back as saved. /// public abstract class TopLevelCollectionsTestsBase { protected readonly IRedbService Redb; protected TopLevelCollectionsTestsBase(IRedbService redb) => Redb = redb; private async Task SyncIsRefusedAsync(string owner, string property, string typeName) where TProps : class, new() { var act = () => Redb.SyncSchemeAsync(); var refusal = (await act.Should().ThrowAsync()).Which; refusal.OwnerName.Should().Be(owner); refusal.PropertyName.Should().Be(property); refusal.PropertyTypeName.Should().Be(typeName); refusal.Message.Should().Contain(RedbUnsupportedCollectionException.SupportedTypes); var schemes = await Redb.Context.ExecuteScalarAsync( $"SELECT COUNT(*) FROM _schemes WHERE _name = '{typeof(TProps).FullName}'"); schemes.Should().Be(0, "the sync refuses before it writes the scheme row"); } [Fact] public Task HashSet_SyncIsRefused() => SyncIsRefusedAsync("TopHashSetProps", "Value", "HashSet"); [Fact] public Task ISet_SyncIsRefused() => SyncIsRefusedAsync("TopISetProps", "Value", "ISet"); [Fact] public Task ObservableCollection_SyncIsRefused() => SyncIsRefusedAsync("TopObservableCollectionProps", "Value", "ObservableCollection"); [Fact] public Task Queue_SyncIsRefused() => SyncIsRefusedAsync("TopQueueProps", "Value", "Queue"); [Fact] public Task Stack_SyncIsRefused() => SyncIsRefusedAsync("TopStackProps", "Value", "Stack"); [Fact] public Task IReadOnlyList_SyncIsRefused() => SyncIsRefusedAsync("TopIReadOnlyListProps", "Value", "IReadOnlyList"); [Fact] public Task SortedDictionary_SyncIsRefused() => SyncIsRefusedAsync("TopSortedDictionaryProps", "Value", "SortedDictionary"); [Fact] public Task IReadOnlyDictionary_SyncIsRefused() => SyncIsRefusedAsync("TopIReadOnlyDictionaryProps", "Value", "IReadOnlyDictionary"); [Fact] public Task HashSetInsideAClassElement_SyncIsRefused_NamingTheElementClass() => SyncIsRefusedAsync("TopHashSetHolder", "Tags", "HashSet"); // --- supported shapes, pinned --- private async Task AssertRoundTripAsync(TProps props, Func value) where TProps : class, new() { await Redb.SyncSchemeAsync(); var id = await Redb.SaveAsync(new RedbObject { name = "top-" + Guid.NewGuid().ToString("N")[..8], Props = props }); var loaded = (await Redb.LoadAsync(id))!.Props; value(loaded).Should().BeEquivalentTo(value(props)); } [Fact] public Task ListOfInt_RoundTrips() => AssertRoundTripAsync(new TopListOfIntProps { Value = [3, 1, 2] }, p => p.Value); [Fact] public Task IEnumerableOfLong_RoundTrips() => AssertRoundTripAsync(new TopIEnumerableOfLongProps { Value = new List { 3, 1, 2 } }, p => p.Value); [Fact] public Task IEnumerableOfString_RoundTrips() => AssertRoundTripAsync(new TopIEnumerableOfStringProps { Value = new List { "c", "a" } }, p => p.Value); [Fact] public Task ICollectionOfString_RoundTrips() => AssertRoundTripAsync(new TopICollectionOfStringProps { Value = new List { "c", "a" } }, p => p.Value); [Fact] public Task IDictionary_RoundTrips() => AssertRoundTripAsync(new TopIDictionaryProps { Value = new Dictionary { ["b"] = 2, ["a"] = 1 } }, p => p.Value); // --- save against a scheme synced before the refusal existed --- private async Task SaveIsRefusedAsync(TProps props, string property, string found) where TShape : class, new() where TProps : class, new() { var scheme = await Redb.SyncSchemeAsync(); var name = "top-guard-" + Guid.NewGuid().ToString("N")[..8]; var obj = new RedbObject { name = name, Props = props }; ((IRedbObject)obj).SchemeId = scheme.Id; var act = () => Redb.SaveAsync(obj); var refusal = (await act.Should().ThrowAsync()).Which; refusal.PropertyName.Should().Be(property); refusal.PropertyTypeName.Should().Be(found); var objects = await Redb.Context.ExecuteScalarAsync($"SELECT COUNT(*) FROM _objects WHERE _name = '{name}'"); objects.Should().Be(0, "the save refuses while the value rows are built, before anything is written"); } [Fact] public Task HashSet_OnASchemeSyncedBefore_SaveIsRefused() => SaveIsRefusedAsync(new() { Value = [1, 2] }, "Value", "HashSet"); [Fact] public Task SortedDictionary_OnASchemeSyncedBefore_SaveIsRefused() => SaveIsRefusedAsync( new() { Value = new() { ["a"] = 1 } }, "Value", "SortedDictionary"); [Fact] public Task HashSetInsideAClassElement_OnASchemeSyncedBefore_SaveIsRefused() => SaveIsRefusedAsync( new() { Items = [new TopHashSetHolder { Label = "a", Tags = [1] }] }, "Tags", "HashSet"); } Path: redb/redb.Tests.Integration/Tests/Base/TransactionIsolationTestsBase.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/TransactionIsolationTestsBase.cs ---- using System.Data; using redb.Core; using redb.Core.Models.Entities; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// BR-1 (owner decision 2026-09-02): the transaction isolation level is an optional parameter of /// BeginTransactionAsync / ExecuteAtomicAsync. Without it nothing changes - each /// provider keeps its own default. PostgreSQL and MSSQL apply the requested level to the /// transaction they open; SQLite accepts the parameter for portability and stays what it always /// is, a single serial writer (BEGIN IMMEDIATE). An active or ambient transaction is joined as it /// is - its level is never changed. Free and Pro share the connection classes, so the three Free /// suites cover both editions. /// public abstract class TransactionIsolationTestsBase { protected readonly IRedbService Redb; protected TransactionIsolationTestsBase(IRedbService redb) => Redb = redb; /// SQL returning the current isolation level as text; null when the provider has no readout (SQLite). protected abstract string? ReadLevelSql { get; } protected virtual string SerializableLevelText => "serializable"; protected virtual string DefaultLevelText => "read committed"; [Fact] public async Task ExplicitLevel_IsApplied_AndTheDefaultIsUntouched() { if (ReadLevelSql is { } sql) { await using (var tx = await Redb.Context.BeginTransactionAsync(IsolationLevel.Serializable)) { (await Redb.Context.ExecuteScalarAsync(sql)).Should().Be(SerializableLevelText, "the requested level must reach the transaction the provider opens"); await tx.RollbackAsync(); } await using (var tx = await Redb.Context.BeginTransactionAsync()) { (await Redb.Context.ExecuteScalarAsync(sql)).Should().Be(DefaultLevelText, "the parameter is optional and the default must stay exactly what it was"); await tx.RollbackAsync(); } } else { // SQLite: no readout - the parameter must be accepted and the transaction fully usable. await using var tx = await Redb.Context.BeginTransactionAsync(IsolationLevel.Serializable); (await Redb.Context.ExecuteScalarAsync("SELECT 1")).Should().Be(1); await tx.RollbackAsync(); } } [Fact] public async Task ExecuteAtomic_WithLevel_CommitsTheWork() { long id = 0; await Redb.Context.ExecuteAtomicAsync(IsolationLevel.Serializable, async () => { id = await Redb.SaveAsync(new RedbObject { name = "iso-atomic", Props = new SimpleProps { Title = "iso", Count = 7 } }); }); (await Redb.LoadAsync(id, depth: 1))!.Props.Title.Should().Be("iso", "work done under the isolation-level overload commits like the plain form"); } } Path: redb/redb.Tests.Integration/Tests/Base/TrashBackgroundServiceTestsBase.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/TrashBackgroundServiceTestsBase.cs ---- using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Core; using redb.Core.Extensions; using redb.Core.Models.Entities; using redb.Core.Services; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// The background deletion worker against a trash container it can never finish (trash review, /// 2026-09-14): a live object references one of the container's objects. The container must end up /// 'failed' - no longer claimed every 30 minutes - while the worker keeps purging the other containers. /// The worker drains EVERY container of its database, so the suite runs on a throwaway database of its /// own instead of the shared fixtures, where it would purge the trash other suites are asserting on. /// public abstract class TrashBackgroundServiceTestsBase { /// Creates an empty database and returns its connection string. protected abstract Task CreateEmptyDatabaseAsync(); /// Drops the database created by . protected abstract Task DropDatabaseAsync(string connectionString); protected abstract void UseProvider(RedbOptionsBuilder options, string connectionString); protected static string ConnString(string name) => new ConfigurationBuilder() .SetBasePath(AppContext.BaseDirectory) .AddJsonFile("appsettings.json") .Build() .GetConnectionString(name)!; private ServiceProvider Build(string connectionString) { var services = new ServiceCollection(); services.AddLogging(b => b.SetMinimumLevel(LogLevel.Warning)); services.AddRedb(options => { UseProvider(options, connectionString); options.Configure(c => { c.EnablePropsCache = false; c.CacheDomain = $"trash-background-{GetType().Name}"; }); }); return services.BuildServiceProvider(); } [Fact] public async Task PoisonedContainer_EndsFailed_AndTheWorkerKeepsPurgingTheOthers() { var cs = await CreateEmptyDatabaseAsync(); try { await using var sp = Build(cs); long poisonedTrash, goodTrash; await using (var scope = sp.CreateAsyncScope()) { var redb = scope.ServiceProvider.GetRequiredService(); await redb.InitializeAsync(ensureCreated: true); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); var keptId = await redb.SaveAsync(new RedbObject { name = "kept", Props = new TrashTargetProps { Title = "kept" } }); var goodId = await redb.SaveAsync(new RedbObject { name = "good", Props = new TrashTargetProps { Title = "good" } }); // The poisoned container is the older one, so the worker meets it first in its page. poisonedTrash = (await redb.SoftDeleteAsync(new[] { keptId })).TrashId; goodTrash = (await redb.SoftDeleteAsync(new[] { goodId })).TrashId; await redb.SaveAsync(new RedbObject { name = "holder", Props = new TrashHolderProps { Target = new RedbObject { id = keptId } } }); } var worker = new BackgroundDeletionService(sp); await worker.StartAsync(CancellationToken.None); PurgeProgress? poisoned = null, good = null; try { var deadline = DateTime.UtcNow.AddSeconds(30); while (DateTime.UtcNow < deadline) { await using var scope = sp.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); poisoned = await redb.GetDeletionProgressAsync(poisonedTrash); good = await redb.GetDeletionProgressAsync(goodTrash); if (poisoned?.Status == PurgeStatus.Failed && (good is null || good.Status == PurgeStatus.Completed)) break; await Task.Delay(250); } } finally { await worker.StopAsync(CancellationToken.None); } poisoned.Should().NotBeNull(); poisoned!.Status.Should().Be(PurgeStatus.Failed, "a container blocked by a live reference ends failed instead of being retried forever"); (good is null || good.Status == PurgeStatus.Completed).Should().BeTrue( "the blocked container must not stop the worker from purging the others"); } finally { await DropDatabaseAsync(cs); } } } Path: redb/redb.Tests.Integration/Tests/Base/TrashPurgeTestsBase.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/TrashPurgeTestsBase.cs ---- using System.Diagnostics; using System.Transactions; using Microsoft.Extensions.DependencyInjection; using redb.Core; using redb.Core.Exceptions; using redb.Core.Models.Entities; using redb.Core.Services; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// Purging a trash container whose objects are referenced (trash review, 2026-09-14). A /// RedbObject<T> reference is a _values._Object row with a foreign key and no /// ON DELETE action, so the physical delete of a referenced object fails on every provider. Before the /// fix one such object failed the whole batch, the container stayed 'running' and the background /// worker retried it every 30 minutes forever; on SQLite the failed batch also left its transaction and /// the database write lock on the pooled handle. /// /// A reference held by an object that is itself in the trash dies with it - it never blocks. /// A reference held by a live object blocks: the purge removes everything else, marks the container /// 'failed' and throws naming both sides. redb does not null /// the reference - that would hide the caller's bug inside another object's data. /// /// public abstract class TrashPurgeTestsBase { private readonly IServiceProvider _services; protected TrashPurgeTestsBase(IServiceProvider services) => _services = services; private static string NewTag() => Guid.NewGuid().ToString("N")[..12]; private static async Task SyncAsync(IRedbService redb) { await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); } private static RedbObject Target(string tag, string role) => new() { name = $"trash-{role}-{tag}", Props = new TrashTargetProps { Title = role } }; private static Task CountAsync(IRedbService redb, string where) => redb.Context.ExecuteScalarAsync($"SELECT COUNT(*) FROM _objects WHERE {where}"); /// /// Whether a second connection may write while a transaction holds rows. SQLite has one writer: a purge waiting for /// the lock a transaction holds is the classical SQLite deadlock (the transaction cannot commit past the purge's open /// read), so there the race of is played /// sequentially - the same rows gone and moved before the purge, no lock held meanwhile. /// protected virtual bool ConcurrentWriters => true; [Fact] public async Task Purge_ObjectReferencedOnlyFromTheTrash_Completes() { await using var scope = _services.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); await SyncAsync(redb); var tag = NewTag(); var targetId = await redb.SaveAsync(Target(tag, "target")); var holderId = await redb.SaveAsync(new RedbObject { name = $"trash-holder-{tag}", Props = new TrashHolderProps { Title = tag, Target = new RedbObject { id = targetId } } }); var holderTrash = await redb.SoftDeleteAsync(new[] { holderId }); var targetTrash = await redb.SoftDeleteAsync(new[] { targetId }); // The target's container first: its only reference is held by an object already in the trash. await redb.PurgeTrashAsync(targetTrash.TrashId, targetTrash.MarkedCount); await redb.PurgeTrashAsync(holderTrash.TrashId, holderTrash.MarkedCount); (await CountAsync(redb, $"_id IN ({targetId}, {holderId})")).Should().Be(0, "a reference held by a trashed object dies with it and never blocks the purge"); } [Fact] public async Task Purge_ObjectReferencedByALiveObject_FailsTheContainer_AndPurgesTheRest() { await using var scope = _services.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); await SyncAsync(redb); var tag = NewTag(); var keptId = await redb.SaveAsync(Target(tag, "kept")); var freeId = await redb.SaveAsync(Target(tag, "free")); var mark = await redb.SoftDeleteAsync(new[] { keptId, freeId }); // A live reference to an object already in the trash (a concurrent writer, or code that saved a // reference it should not have). var holderId = await redb.SaveAsync(new RedbObject { name = $"trash-holder-{tag}", Props = new TrashHolderProps { Title = tag, Target = new RedbObject { id = keptId } } }); var act = async () => await redb.PurgeTrashAsync(mark.TrashId, mark.MarkedCount); var thrown = await act.Should().ThrowAsync( "a live reference must surface loudly, with both sides named"); thrown.Which.TrashId.Should().Be(mark.TrashId); thrown.Which.RemainingCount.Should().Be(1); thrown.Which.ReferencedObjectIds.Should().Contain(keptId); thrown.Which.ReferencingObjectIds.Should().Contain(holderId); (await CountAsync(redb, $"_id = {freeId}")).Should().Be(0, "everything nobody references is purged"); (await CountAsync(redb, $"_id = {keptId} AND _id_scheme = -10")).Should().Be(1, "the referenced object stays in the trash - the reference is not nulled behind the caller's back"); (await CountAsync(redb, $"_id = {holderId} AND _id_scheme <> -10")).Should().Be(1, "the holder is untouched"); (await redb.GetDeletionProgressAsync(mark.TrashId))!.Status.Should().Be(PurgeStatus.Failed); (await redb.GetOrphanedDeletionTasksAsync(30)).Should().NotContain(t => t.TrashId == mark.TrashId, "a failed container is not retried by the background worker"); // Nothing of the failed purge is left on any connection. await redb.SaveAsync(Target(tag, "same-scope-after")); await using var other = _services.CreateAsyncScope(); var clock = Stopwatch.StartNew(); await other.ServiceProvider.GetRequiredService().SaveAsync(Target(tag, "other-scope-after")); clock.Elapsed.Should().BeLessThan(TimeSpan.FromSeconds(4), "no connection keeps a lock after the purge"); (await CountAsync(redb, $"_name LIKE 'trash-%-scope-after-{tag}'")).Should().Be(2); } [Fact] public async Task Purge_CollectionElementReferenceFromALiveObject_BlocksLikeASingleReference() { await using var scope = _services.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); await SyncAsync(redb); var tag = NewTag(); var targetId = await redb.SaveAsync(Target(tag, "element")); var mark = await redb.SoftDeleteAsync(new[] { targetId }); var holderId = await redb.SaveAsync(new RedbObject { name = $"trash-holder-{tag}", Props = new TrashHolderProps { Title = tag, Targets = [new RedbObject { id = targetId }] } }); var act = async () => await redb.PurgeTrashAsync(mark.TrashId, mark.MarkedCount); var thrown = await act.Should().ThrowAsync(); thrown.Which.ReferencingObjectIds.Should().Contain(holderId); (await CountAsync(redb, $"_id = {targetId}")).Should().Be(1); } /// /// Two purgers on one container - the background worker beside a caller's PurgeTrashAsync, two cluster nodes: a /// batch chosen by one and deleted by the other meanwhile deleted nothing here, and "nothing deleted while objects /// remain" was read as "every remaining object is referenced by a live object". The container was marked 'failed' /// with nothing blocking it, the worker stopped claiming it, and the caller got a /// naming no referrer. The race is played by a transaction that deletes /// the container's objects, moves one more in, and commits only once the purge waits on the rows it holds. On /// PostgreSQL the purge chooses its batch from the snapshot and then waits on the delete; SQL Server and SQLite /// wait while choosing and never see the race - there the fact holds as a plain concurrent purge. /// [Fact] public async Task Purge_BatchDeletedByAConcurrentPurger_IsRetried_NotFailed() { await using var scope = _services.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); await SyncAsync(redb); var tag = NewTag(); var ids = new List(); for (var i = 0; i < 6; i++) ids.Add(await redb.SaveAsync(Target(tag, $"race-{i}"))); var mark = await redb.SoftDeleteAsync(ids); var lateId = await redb.SaveAsync(Target(tag, "race-late")); await using var otherScope = _services.CreateAsyncScope(); var other = otherScope.ServiceProvider.GetRequiredService(); var purge = Task.CompletedTask; await other.Context.ExecuteAtomicAsync(async () => { var batch = string.Join(", ", ids); await other.Context.ExecuteAsync($"DELETE FROM _values WHERE _id_object IN ({batch})"); await other.Context.ExecuteAsync($"DELETE FROM _objects WHERE _id IN ({batch})"); await other.Context.ExecuteAsync($"UPDATE _objects SET _id_parent = {mark.TrashId} WHERE _id = {lateId}"); if (!ConcurrentWriters) return; // The purge runs on its own scope, outside this transaction's flow, and blocks on the rows held here. using (new TransactionScope(TransactionScopeOption.Suppress, TransactionScopeAsyncFlowOption.Enabled)) purge = redb.PurgeTrashAsync(mark.TrashId, mark.MarkedCount, batchSize: ids.Count); await Task.WhenAny(purge, Task.Delay(TimeSpan.FromSeconds(2))); }); if (!ConcurrentWriters) purge = redb.PurgeTrashAsync(mark.TrashId, mark.MarkedCount, batchSize: ids.Count); await purge; (await CountAsync(redb, $"_id_parent = {mark.TrashId}")).Should().Be(0, "the purge goes on with the next batch"); (await CountAsync(redb, $"_id = {mark.TrashId}")).Should().Be(0, "a completed container is removed"); } } Path: redb/redb.Tests.Integration/Tests/Base/TrashedReferenceTargetTestsBase.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/TrashedReferenceTargetTestsBase.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 reference whose target left for the trash loads as null in its place, in a collection too: an array keeps its /// length and a dictionary keeps the key. The PostgreSQL and SQLite Free builders and every Pro materializer agree; the /// MSSQL Free builder dropped the element (STRING_AGG skips the NULL of the nested get_object_json) and the dictionary /// key with it. Found by the Free host of . /// public abstract class TrashedReferenceTargetTestsBase { protected abstract void UseProvider(RedbOptionsBuilder options); /// /// The Pro props cache: a query caches the nested objects of its rows by their ids, and a cached graph is checked /// against the rows of its loaded references before it is served. The Free loaders do neither yet (Free parity). /// protected virtual bool ProPropsCache => false; protected virtual void Register(IServiceCollection services, Action configure) => services.AddRedb(configure); private ServiceProvider Build(bool propsCache = false, string? cacheDomain = null) { var services = new ServiceCollection(); services.AddLogging(b => b.SetMinimumLevel(LogLevel.Warning)); Register(services, options => { UseProvider(options); options.Configure(c => { c.EnablePropsCache = propsCache; c.CacheDomain = cacheDomain ?? (propsCache ? "trashed-reference-target-cached" : "trashed-reference-target"); }); }); return services.BuildServiceProvider(); } private sealed record Seed(long RootId, long KeptId); private static async Task SeedAsync(ServiceProvider sp) { var tag = Guid.NewGuid().ToString("N")[..8]; var redb = sp.GetRequiredService(); await redb.InitializeAsync(ensureCreated: true); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.InitializeTypeRegistryAsync(); var kept = await redb.SaveAsync(new RedbObject { name = $"trashref-kept-{tag}", Props = new CtProbeChildProps { Tag = "kept" } }); var gone = await redb.SaveAsync(new RedbObject { name = $"trashref-gone-{tag}", Props = new CtProbeChildProps { Tag = "gone" } }); var rootId = await redb.SaveAsync(new RedbObject { name = $"trashref-root-{tag}", Props = new CtProbeProps { Label = "root", Refs = [new RedbObject { id = kept }, new RedbObject { id = gone }], RefDict = new() { ["kept"] = new RedbObject { id = kept }, ["gone"] = new RedbObject { id = gone } } } }); await redb.SoftDeleteAsync(new[] { gone }); return new Seed(rootId, kept); } private async Task<(CtProbeProps Props, Seed Seed)> LoadAsync() { await using var sp = Build(); var seed = await SeedAsync(sp); await using var scope = sp.CreateAsyncScope(); var root = await scope.ServiceProvider.GetRequiredService().LoadAsync(seed.RootId, depth: 10); return (root!.Props, seed); } [Fact] public async Task Load_TrashedTargetInArray_IsNullInItsPlace() { var (props, seed) = await LoadAsync(); props.Refs.Should().HaveCount(2, "the array keeps its length: a trashed target is null in its place, never dropped"); props.Refs![0].id.Should().Be(seed.KeptId); props.Refs[0].Props.Tag.Should().Be("kept"); props.Refs[1].Should().BeNull("the target left for the trash"); } [Fact] public async Task Load_TrashedTargetInDictionary_KeepsItsKeyWithNull() { var (props, seed) = await LoadAsync(); props.RefDict.Should().NotBeNull(); props.RefDict!.Keys.Should().BeEquivalentTo(new[] { "kept", "gone" }, "the dictionary keeps the key of a trashed target, with null as its value"); props.RefDict["kept"].id.Should().Be(seed.KeptId); props.RefDict["kept"].Props.Tag.Should().Be("kept"); props.RefDict["gone"].Should().BeNull("the target left for the trash"); } /// /// With the props cache on, an object loaded before its reference went to the trash is not served from the /// cache with the trashed target still materialized inside: its hash does not move, so the read checks the /// loaded objects of the graph against their rows, the object reaching the target through another one /// (A -> B -> C) included. /// [Fact] public async Task Load_WithPropsCache_ReferenceTrashedAfterCaching_IsNull() { if (!ProPropsCache) return; await using var sp = Build(propsCache: true); var redb = sp.GetRequiredService(); await redb.InitializeAsync(ensureCreated: true); await redb.SyncSchemeAsync(); var tag = Guid.NewGuid().ToString("N")[..8]; var c = await redb.SaveAsync(new RedbObject { name = $"trashref-c-{tag}", Props = new GraphNodeProps { Title = "c" } }); var b = await redb.SaveAsync(new RedbObject { name = $"trashref-b-{tag}", Props = new GraphNodeProps { Title = "b", Left = new RedbObject { id = c } } }); var a = await redb.SaveAsync(new RedbObject { name = $"trashref-a-{tag}", Props = new GraphNodeProps { Title = "a", Left = new RedbObject { id = b } } }); // Loaded and cached with the whole chain. (await redb.LoadAsync(b, depth: 10))!.Props.Left!.Props.Title.Should().Be("c"); (await redb.LoadAsync(a, depth: 10))!.Props.Left!.Props.Left!.Props.Title.Should().Be("c"); await redb.SoftDeleteAsync(new[] { c }); (await redb.LoadAsync(b, depth: 10))!.Props.Left .Should().BeNull("the direct referrer is dropped from the cache and reloaded"); (await redb.LoadAsync(a, depth: 10))!.Props.Left!.Props.Left .Should().BeNull("the object reaching the target through another one is dropped as well"); } /// /// A cluster: a referenced object changed by another node, whose cache this node never hears about. The graph /// cached here is checked against the rows when it is read, and the change shows up. /// [Fact] public async Task Load_WithPropsCache_ReferenceChangedOnAnotherNode_IsReloaded() { if (!ProPropsCache) return; await using var sp = Build(propsCache: true, cacheDomain: "trashed-reference-node-1"); await using var other = Build(propsCache: true, cacheDomain: "trashed-reference-node-2"); var redb = sp.GetRequiredService(); var node2 = other.GetRequiredService(); await redb.InitializeAsync(ensureCreated: true); await node2.InitializeAsync(); await redb.SyncSchemeAsync(); var tag = Guid.NewGuid().ToString("N")[..8]; var b = await redb.SaveAsync(new RedbObject { name = $"trashref-nb-{tag}", Props = new GraphNodeProps { Title = "before" } }); var a = await redb.SaveAsync(new RedbObject { name = $"trashref-na-{tag}", Props = new GraphNodeProps { Title = "a", Left = new RedbObject { id = b } } }); (await redb.LoadAsync(a, depth: 10))!.Props.Left!.Props.Title.Should().Be("before"); var onNode2 = (await node2.LoadAsync(b))!; onNode2.Props.Title = "after"; await node2.SaveAsync(onNode2); (await redb.LoadAsync(a, depth: 10))!.Props.Left!.Props.Title .Should().Be("after", "the cached graph is checked against the row of its loaded reference"); } /// /// A nested object is cached by its own id whichever way its root was loaded: LoadAsync and a query alike. /// [Fact] public async Task Load_WithPropsCache_NestedObjectCachedByItsOwnId() { await using var sp = Build(propsCache: true, cacheDomain: "trashed-reference-nested-by-id"); var redb = sp.GetRequiredService(); await redb.InitializeAsync(ensureCreated: true); await redb.SyncSchemeAsync(); var tag = Guid.NewGuid().ToString("N")[..8]; var viaLoadLeaf = await redb.SaveAsync(new RedbObject { name = $"trashref-ll-{tag}", Props = new GraphNodeProps { Title = "leaf" } }); var viaLoadRoot = await redb.SaveAsync(new RedbObject { name = $"trashref-lr-{tag}", Props = new GraphNodeProps { Title = $"load-{tag}", Left = new RedbObject { id = viaLoadLeaf } } }); var viaQueryLeaf = await redb.SaveAsync(new RedbObject { name = $"trashref-ql-{tag}", Props = new GraphNodeProps { Title = "leaf" } }); var queryTitle = $"query-{tag}"; await redb.SaveAsync(new RedbObject { name = $"trashref-qr-{tag}", Props = new GraphNodeProps { Title = queryTitle, Left = new RedbObject { id = viaQueryLeaf } } }); await redb.LoadAsync(viaLoadRoot, depth: 10); (await redb.Query().Where(p => p.Title == queryTitle).ToListAsync()).Should().HaveCount(1); redb.PropsCache.GetWithoutHashValidation(viaLoadLeaf).Should().NotBeNull("LoadAsync caches the nested object by its id"); if (ProPropsCache) redb.PropsCache.GetWithoutHashValidation(viaQueryLeaf).Should().NotBeNull("a query caches the nested object by its id"); } /// /// References inside collections (a list and a dictionary of references) take part in the check of a cached graph /// the same way, and the referenced objects are cached by their own ids. /// [Fact] public async Task Load_WithPropsCache_ReferencesInCollections_TrashedAfterCaching_AreNull() { if (!ProPropsCache) return; await using var sp = Build(propsCache: true, cacheDomain: "trashed-reference-collections"); var redb = sp.GetRequiredService(); await redb.InitializeAsync(ensureCreated: true); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.InitializeTypeRegistryAsync(); var tag = Guid.NewGuid().ToString("N")[..8]; var kept = new RedbObject { name = $"trashref-ckept-{tag}", Props = new CtProbeChildProps { Tag = "kept" } }; var gone = new RedbObject { name = $"trashref-cgone-{tag}", Props = new CtProbeChildProps { Tag = "gone" } }; await redb.SaveAsync(kept); await redb.SaveAsync(gone); var rootId = await redb.SaveAsync(new RedbObject { name = $"trashref-croot-{tag}", Props = new CtProbeProps { Label = "root", Refs = [kept, gone], RefDict = new() { ["kept"] = kept, ["gone"] = gone } } }); var before = (await redb.LoadAsync(rootId, depth: 10))!; before.Props.Refs![1].Props.Tag.Should().Be("gone"); redb.PropsCache.GetWithoutHashValidation(kept.Id).Should().NotBeNull("a referenced object is cached by its id"); await redb.SoftDeleteAsync(new[] { gone.Id }); var after = (await redb.LoadAsync(rootId, depth: 10))!; after.Props.Refs.Should().HaveCount(2); after.Props.Refs![0].Props.Tag.Should().Be("kept"); after.Props.Refs[1].Should().BeNull("the list reference to the trashed object is checked against its row"); after.Props.RefDict!["gone"].Should().BeNull("the dictionary reference is checked the same way"); after.Props.RefDict["kept"].Props.Tag.Should().Be("kept"); } /// A hard delete drops the object from the cache, and a later load finds nothing. [Fact] public async Task Delete_WithPropsCache_RemovesTheObjectFromTheCache() { await using var sp = Build(propsCache: true); var redb = sp.GetRequiredService(); await redb.InitializeAsync(ensureCreated: true); await redb.SyncSchemeAsync(); var id = await redb.SaveAsync(new RedbObject { name = $"trashref-del-{Guid.NewGuid():N}", Props = new GraphNodeProps { Title = "x" } }); (await redb.LoadAsync(id)).Should().NotBeNull(); redb.PropsCache.GetWithoutHashValidation(id).Should().NotBeNull("the load cached it"); (await redb.DeleteAsync(id)).Should().BeTrue(); redb.PropsCache.GetWithoutHashValidation(id).Should().BeNull("the delete dropped it from the cache"); (await redb.LoadAsync(id)).Should().BeNull(); } } Path: redb/redb.Tests.Integration/Tests/Base/TreeAggregateTestsBase.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/TreeAggregateTestsBase.cs ---- using redb.Core; using redb.Core.Models.Entities; using redb.Core.Query; using redb.Core.Query.Aggregation; using redb.Tests.Integration.Helpers; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// An aggregate over a tree query ranges over the subtree of that query, not over the scheme. /// /// SumAsync, AverageAsync, MinAsync, MaxAsync, GetStatisticsAsync, AggregateAsync and the *RedbAsync /// twins of a tree query used to be answered by the flat provider, which knows the scheme and the /// filter but not the root: a sum under one manager came back as the sum over every employee in /// the database. GroupBy and windows over the same tree were right, so the same Where gave /// different object sets depending on the terminal operation. /// /// The scheme holds employees seeded by other tests, which is what makes these facts meaningful: /// a whole-scheme answer cannot match the four children seeded here. /// public abstract class TreeAggregateTestsBase { protected readonly IRedbService Redb; protected TreeAggregateTestsBase(IRedbService redb) => Redb = redb; /// A root with four children earning 1000, 2000, 3000 and 4000; two of them know "tree-skill". private async Task SeedAsync() { await Redb.SyncSchemeAsync(); var tag = Guid.NewGuid().ToString("N")[..8]; var root = new TreeRedbObject { name = $"agg-root-{tag}", Props = TestDataFactory.CreateEmployee(0, department: $"Root-{tag}", salary: 50_000m).Props }; root.id = await Redb.SaveAsync(root); for (var i = 1; i <= 4; i++) { var props = TestDataFactory.CreateEmployee(i, department: $"Dept-{tag}", salary: 1000m * i).Props; props.Skills = i % 2 == 0 ? ["tree-skill", "other"] : ["other"]; await Redb.CreateChildAsync(new TreeRedbObject { name = $"agg-child-{tag}-{i}", Props = props }, root); } return root.id; } [Fact] public async Task SingleAggregates_RangeOverTheSubtree() { var rootId = await SeedAsync(); IRedbQueryable Tree() => Redb.TreeQuery(rootId); (await Tree().CountAsync()).Should().Be(4, "precondition: the subtree is the four children"); (await Tree().SumAsync(e => e.Salary)).Should().Be(10_000m); (await Tree().AverageAsync(e => e.Salary)).Should().Be(2_500m); (await Tree().MinAsync(e => e.Salary)).Should().Be(1_000m); (await Tree().MaxAsync(e => e.Salary)).Should().Be(4_000m); } [Fact] public async Task SingleAggregates_HonourTheFilterInsideTheSubtree() { var rootId = await SeedAsync(); IRedbQueryable Tree() => Redb.TreeQuery(rootId).Where(e => e.Salary > 1_500m); (await Tree().SumAsync(e => e.Salary)).Should().Be(9_000m); (await Tree().MinAsync(e => e.Salary)).Should().Be(2_000m); } [Fact] public async Task BatchAggregates_RangeOverTheSubtree() { var rootId = await SeedAsync(); var all = await Redb.TreeQuery(rootId) .AggregateAsync(x => new { Count = Agg.Count(), Sum = Agg.Sum(x.Props.Salary), Max = Agg.Max(x.Props.Salary) }); all.Count.Should().Be(4); all.Sum.Should().Be(10_000m); all.Max.Should().Be(4_000m); var filtered = await Redb.TreeQuery(rootId) .Where(e => e.Salary > 1_500m) .AggregateAsync(x => new { Count = Agg.Count(), Sum = Agg.Sum(x.Props.Salary) }); filtered.Count.Should().Be(3); filtered.Sum.Should().Be(9_000m); var statistics = await Redb.TreeQuery(rootId).GetStatisticsAsync(e => e.Salary); statistics.Count.Should().Be(4); statistics.Sum.Should().Be(10_000m); statistics.Min.Should().Be(1_000m); statistics.Max.Should().Be(4_000m); } [Fact] public async Task BaseFieldAggregates_RangeOverTheSubtree() { var rootId = await SeedAsync(); var ids = (await Redb.TreeQuery(rootId).ToListAsync()).Select(o => o.Id).ToList(); ids.Should().HaveCount(4); (await Redb.TreeQuery(rootId).SumRedbAsync(o => o.Id)).Should().Be(ids.Sum()); var batch = await Redb.TreeQuery(rootId) .AggregateRedbAsync(o => new { Count = Agg.Count(), MaxId = Agg.Max(o.Id) }); batch.Count.Should().Be(4); batch.MaxId.Should().Be(ids.Max()); } [Fact] public async Task ArrayContains_FiltersAndAggregatesInsideTheSubtree() { var rootId = await SeedAsync(); IRedbQueryable Tree() => Redb.TreeQuery(rootId).Where(e => e.Skills!.Contains("tree-skill")); (await Tree().CountAsync()).Should().Be(2, "children 2 and 4 carry the skill"); (await Tree().ToListAsync()).Should().HaveCount(2); (await Tree().SumAsync(e => e.Salary)).Should().Be(6_000m); var batch = await Tree().AggregateAsync(x => new { Count = Agg.Count(), Sum = Agg.Sum(x.Props.Salary) }); batch.Count.Should().Be(2); batch.Sum.Should().Be(6_000m); } } Path: redb/redb.Tests.Integration/Tests/Base/TreeDistinctTestsBase.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/TreeDistinctTestsBase.cs ---- using redb.Core; using redb.Core.Models.Entities; using redb.Tests.Integration.Helpers; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// DISTINCT ON a tree query, six hosts. A tree query ignored the distinct key and returned every node (SQLite Pro /// and the three Free providers), where the same distinct on a flat query of the same objects returned one object /// per key; the count of a distinct tree query was wrong on all three Pro (review 2026-09-24). Each tree fact has a /// flat twin over the same seed, so a wrong expectation fails on both. /// public abstract class TreeDistinctTestsBase { protected readonly IRedbService Redb; protected TreeDistinctTestsBase(IRedbService redb) => Redb = redb; /// A root and six children: names in three pairs, departments in two groups of three. private async Task<(long RootId, string Tag)> SeedAsync() { await Redb.SyncSchemeAsync(); var tag = Guid.NewGuid().ToString("N")[..8]; var root = new TreeRedbObject { name = $"distinct-root-{tag}", Props = TestDataFactory.CreateEmployee(0, department: $"Root-{tag}", salary: 1m).Props }; root.id = await Redb.SaveAsync(root); for (var i = 0; i < 6; i++) { var child = new TreeRedbObject { name = $"distinct-{tag}-{i / 2}", Props = TestDataFactory.CreateEmployee(i + 1, department: $"D{i % 2}-{tag}", salary: 100m * (i + 1)).Props }; await Redb.CreateChildAsync(child, root); } return (root.id, tag); } [Fact] public async Task TreeDistinctByRedb_ReturnsOneNodePerName() { var (rootId, _) = await SeedAsync(); var all = await Redb.TreeQuery(rootId).ToListAsync(); var distinct = await Redb.TreeQuery(rootId).DistinctByRedb(o => o.Name).ToListAsync(); var names = all.Select(o => o.Name).Distinct().ToList(); all.Count.Should().BeGreaterThan(names.Count, "precondition: children share names"); distinct.Select(o => o.Name).Should().OnlyHaveUniqueItems() .And.BeEquivalentTo(names, "one node per distinct name, and every name kept"); } [Fact] public async Task FlatDistinctByRedb_ReturnsOneObjectPerName() { var (_, tag) = await SeedAsync(); var distinct = await Redb.Query() .WhereRedb(o => o.Name.StartsWith($"distinct-{tag}-")) .DistinctByRedb(o => o.Name) .ToListAsync(); distinct.Select(o => o.Name).Should() .BeEquivalentTo(new[] { $"distinct-{tag}-0", $"distinct-{tag}-1", $"distinct-{tag}-2" }); } [Fact] public async Task TreeDistinctByRedb_CountsOneNodePerName() { var (rootId, _) = await SeedAsync(); var names = (await Redb.TreeQuery(rootId).ToListAsync()).Select(o => o.Name).Distinct().Count(); var count = await Redb.TreeQuery(rootId).DistinctByRedb(o => o.Name).CountAsync(); count.Should().Be(names, "the count of a distinct query is the number of distinct keys"); } [Fact] public async Task TreeDistinctBy_ReturnsOneNodePerDepartment() { var (rootId, _) = await SeedAsync(); var all = await Redb.TreeQuery(rootId).ToListAsync(); var distinct = await Redb.TreeQuery(rootId).DistinctBy(e => e.Department).ToListAsync(); var departments = all.Select(o => o.Props.Department).Distinct().ToList(); all.Count.Should().BeGreaterThan(departments.Count, "precondition: children share departments"); distinct.Select(o => o.Props.Department).Should().OnlyHaveUniqueItems() .And.BeEquivalentTo(departments, "one node per department, and every department kept"); } } 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); } } Path: redb/redb.Tests.Integration/Tests/Base/TreeOrderAndPreviewTestsBase.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/TreeOrderAndPreviewTestsBase.cs ---- using redb.Core; using redb.Core.Models.Entities; using redb.Core.Query; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// A tree query keeps the order OrderBy asks for, and can show its SQL. /// /// The order used to depend on the plan: the provider sorted the ids in an inner query and then /// aggregated the rows over a join with no ORDER BY, so the result came back sorted only while /// the planner chose a nested loop. The seed inserts in an order that is neither the ascending /// nor the descending one, so insertion order cannot pass for either. /// /// The preview used to ask the database for a function of the retired search module. /// public abstract class TreeOrderAndPreviewTestsBase { protected readonly IRedbService Redb; protected TreeOrderAndPreviewTestsBase(IRedbService redb) => Redb = redb; private async Task SeedAsync() { var tag = Guid.NewGuid().ToString("N")[..8]; foreach (var (mail, age) in new[] { ("b", 20), ("c", 30), ("a", 10) }) { await Redb.SaveAsync(new RedbObject { name = $"order-{tag}-{mail}", Props = new PersonProps { Name = $"n-{mail}", Age = age, Email = $"{mail}@order-{tag}" } }); } return tag; } private IRedbQueryable Tree(string tag) => Redb.TreeQuery().Where(p => p.Email.EndsWith($"@order-{tag}")); [Fact] public async Task TreeQuery_OrderBy_ReturnsRowsInThatOrder() { var tag = await SeedAsync(); (await Tree(tag).OrderBy(p => p.Age).ToListAsync()) .Select(r => r.Props.Age).Should().Equal([10, 20, 30], "OrderBy(Age)"); (await Tree(tag).OrderByDescending(p => p.Age).ToListAsync()) .Select(r => r.Props.Age).Should().Equal([30, 20, 10], "OrderByDescending(Age)"); (await Tree(tag).OrderBy(p => p.Email).ToListAsync()) .Select(r => r.Props.Age).Should().Equal([10, 20, 30], "OrderBy(Email): a, b, c"); (await Tree(tag).OrderByDescending(p => p.Email).Take(2).ToListAsync()) .Select(r => r.Props.Age).Should().Equal([30, 20], "OrderByDescending(Email) with Take"); } [Fact] public async Task TreeQuery_ToSqlString_ReturnsAStatement() { var tag = await SeedAsync(); var sql = await Tree(tag).OrderBy(p => p.Age).ToSqlStringAsync(); sql.Should().NotBeNullOrWhiteSpace(); sql.Should().Contain("SELECT", "the preview is the statement the query runs"); } } Path: redb/redb.Tests.Integration/Tests/Base/TreeQueryShapesTestsBase.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/TreeQueryShapesTestsBase.cs ---- using redb.Core; using redb.Core.Models.Entities; using redb.Core.Query; using redb.Core.Query.Aggregation; using redb.Core.Query.Base; using redb.Core.Query.Window; using redb.Tests.Integration.Helpers; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// Tree queries and groupings that returned a plausible wrong answer, or none, where the flat twin was right /// (review 2026-09-24: FRM-2, TQP-1, GRP-9, TGR-1, TQB-10). Each fact compares with what the query must return, /// not with what the engine happens to produce. /// public abstract class TreeQueryShapesTestsBase { protected readonly IRedbService Redb; protected TreeQueryShapesTestsBase(IRedbService redb) => Redb = redb; /// A root employee with four children in two departments; every employee carries contacts. private async Task SeedEmployeeTreeAsync() { await Redb.SyncSchemeAsync(); var tag = Guid.NewGuid().ToString("N")[..8]; var root = new TreeRedbObject { name = $"tree-root-{tag}", Props = TestDataFactory.CreateEmployee(0, department: $"Root-{tag}", salary: 5000m).Props }; root.id = await Redb.SaveAsync(root); for (var i = 1; i <= 4; i++) { var child = new TreeRedbObject { name = $"tree-child-{tag}-{i}", Props = TestDataFactory.CreateEmployee(i, department: i % 2 == 0 ? $"A-{tag}" : $"B-{tag}", salary: 1000m * i).Props }; await Redb.CreateChildAsync(child, root); } return root.id; } [Fact] public async Task TreeWindow_WithAFrame_SumsTheWholeFrame() { // FRM-2: the Pro tree window read the frame as three strings while the core writes objects, found nothing, and // dropped the frame without a word - a sum over the whole tree came back as a running total. var rootId = await SeedEmployeeTreeAsync(); var rows = await Redb.TreeQuery(rootId) .WithWindow(w => w .OrderBy(e => e.Salary) .Frame(Frame.Rows().UnboundedPreceding().AndUnboundedFollowing())) .SelectAsync(e => new { e.Props.Salary, Total = Win.Sum(e.Props.Salary) }); rows.Should().HaveCountGreaterThan(1, "precondition: the tree holds several employees"); var total = rows.Sum(r => r.Salary); rows.Should().AllSatisfy(r => r.Total.Should().BeApproximately(total, 0.01m, "a frame over the whole tree sums every salary in it")); } [Fact] public async Task TreeArrayGrouping_Having_WithoutWhere_FiltersTheGroups() { // TQP-1: without a Where the tree took a path that dropped the HAVING - every group came back. var rootId = await SeedEmployeeTreeAsync(); var rows = await Redb.TreeQuery(rootId) .GroupByArray(e => e.Contacts!, c => c.Type) .Having(g => Agg.Count(g) > 1_000_000) .SelectAsync(g => new { Type = g.Key, Count = Agg.Count(g) }); rows.Should().BeEmpty("no contact type is that frequent, so HAVING leaves no group"); } [Fact] public async Task TreeGrouping_CompositeKey_WithAMemberItCannotRead_IsRefused() { // GRP-9: a key member the parser did not understand was skipped without a word, and the grouping ran on // fewer fields - other groups, other totals, no error. var rootId = await SeedEmployeeTreeAsync(); var grouping = async () => await Redb.TreeQuery(rootId) .GroupBy(e => new { e.Department, Initial = e.FirstName.Substring(0, 1) }) .SelectAsync(g => new { g.Key.Department, Count = Agg.Count(g) }); await grouping.Should().ThrowAsync().WithMessage("*Initial*"); } [Fact] public async Task ArrayGrouping_CompositeKey_WithAMemberItCannotRead_IsRefused() { // GRP-9, the array grouping's copy of the same parser. await SeedEmployeeTreeAsync(); var grouping = async () => await Redb.Query() .GroupByArray(e => e.Contacts!, c => new { c.Type, Length = c.Value.Length }) .SelectAsync(g => new { g.Key.Type, Count = Agg.Count(g) }); await grouping.Should().ThrowAsync().WithMessage("*Length*"); } [Fact] public async Task TreeGrouping_Having_DoesNotLeakIntoASiblingQuery() { // TGR-1: the tree grouping's Having changed the builder itself, so a second query branched from the same // grouping inherited the first one's condition. The flat grouping was fixed as G-4. var rootId = await SeedEmployeeTreeAsync(); var grouped = Redb.TreeQuery(rootId).GroupBy(e => e.Department); var strict = grouped.Having(g => Agg.Count(g) > 1_000_000); var loose = grouped.Having(g => Agg.Count(g) > 0); var looseRows = await loose.SelectAsync(g => new { Department = g.Key, Count = Agg.Count(g) }); looseRows.Should().NotBeEmpty("the sibling's condition must not leak into this query"); var strictRows = await strict.SelectAsync(g => new { Department = g.Key, Count = Agg.Count(g) }); strictRows.Should().BeEmpty(); } private IRedbProjectedQueryable ProjectTree(long rootId) => ((TreeQueryableBase)Redb.TreeQuery(rootId)) .Select(e => new EmployeeRow(e.Props.Salary, e.Props.Department)); public sealed record EmployeeRow(decimal Salary, string Department); [Fact] public async Task TreeProjection_TakeAfterOrderBy_TakesFromTheSortedRows() { // TPQ-1: OrderBy ran in memory after the projection, Take went to SQL before it - the page was cut from // the unsorted rows (the first child, salary 1000) and then sorted. var rootId = await SeedEmployeeTreeAsync(); var top = await ProjectTree(rootId).OrderByDescending(x => x.Salary).Take(1).ToListAsync(); top.Select(x => x.Salary).Should().Equal(4000m); } [Fact] public async Task TreeProjection_TakeAfterWhere_TakesFromTheFilteredRows() { // TPQ-1: the filter ran on the page SQL had already cut. var rootId = await SeedEmployeeTreeAsync(); var rows = await ProjectTree(rootId).Where(x => x.Salary > 2500m).Take(1).ToListAsync(); rows.Should().ContainSingle().Which.Salary.Should().BeGreaterThan(2500m); } [Fact] public async Task TreeProjection_Distinct_IsOverTheProjectedRows() { // TPQ-1: Distinct went to the source query, where every node is distinct, so projected duplicates stayed. var rootId = await SeedEmployeeTreeAsync(); var departments = await ((TreeQueryableBase)Redb.TreeQuery(rootId)) .Select(e => e.Props.Department).Distinct().ToListAsync(); departments.Should().OnlyHaveUniqueItems().And.HaveCount(2); } [Fact] public async Task TreePropsDepth_SurvivesWithMaxDepth() { // TQB-10: WithMaxDepth rebuilt the tree context by hand and dropped eight of its settings - the props depth, // the lazy references, the projection and the distinct among them - so the query quietly lost them. await Redb.SyncSchemeAsync(); var tag = Guid.NewGuid().ToString("N")[..8]; var root = new TreeRedbObject { name = $"depth-root-{tag}", Props = new LazyNodeProps { Label = "root" } }; root.id = await Redb.SaveAsync(root); for (var i = 0; i < 3; i++) { var leafId = await Redb.SaveAsync(new RedbObject { name = $"depth-leaf-{tag}-{i}", Props = new LazyNodeProps { Label = $"leaf-{i}" } }); var child = new TreeRedbObject { name = $"depth-child-{tag}-{i}", Props = new LazyNodeProps { Label = $"child-{i}", Next = new RedbObject { id = leafId } } }; await Redb.CreateChildAsync(child, root); } var shallow = await Redb.TreeQuery(root.id).WithPropsDepth(1).ToListAsync(); var shallowWithDepth = await Redb.TreeQuery(root.id).WithPropsDepth(1).WithMaxDepth(5).ToListAsync(); var children = shallow.Where(o => o.Props?.Next != null).ToList(); children.Should().NotBeEmpty("precondition: the children reference a leaf each"); children.Should().OnlyContain(o => !o.Props.Next!.IsPropsLoaded, "precondition: props depth 1 leaves references as stubs"); shallowWithDepth.Where(o => o.Props?.Next != null).Should().OnlyContain(o => !o.Props.Next!.IsPropsLoaded, "a depth limit on the tree does not undo the props depth set before it"); } [Fact] public async Task TreeArrayGrouping_CountsOnlyTheSubtree() { // A10: TreeQueryableBase did not override GroupByArray, so the grouping ran over the whole scheme. var rootId = await SeedEmployeeTreeAsync(); var nodes = await Redb.TreeQuery(rootId).ToListAsync(); nodes.Should().NotBeEmpty("precondition: the subtree holds employees"); var rows = await Redb.TreeQuery(rootId) .GroupByArray(e => e.Contacts!, c => c.Type) .SelectAsync(g => new { Type = g.Key, Count = Agg.Count(g) }); var expected = nodes.SelectMany(n => n.Props.Contacts ?? []).GroupBy(c => c.Type).ToDictionary(g => g.Key, g => g.Count()); rows.ToDictionary(r => r.Type, r => r.Count).Should().BeEquivalentTo(expected); } [Fact] public async Task TreeArrayGrouping_TwoElementFields_CountsOnlyTheSubtree() { // Two fields of the element (Type and IsVerified), each joined to its element, over the subtree. var rootId = await SeedEmployeeTreeAsync(); var nodes = await Redb.TreeQuery(rootId).ToListAsync(); nodes.Should().NotBeEmpty("precondition: the subtree holds employees"); var rows = await Redb.TreeQuery(rootId) .GroupByArray(e => e.Contacts!, c => c.Type) .SelectAsync(g => new { Type = g.Key, Count = Agg.Count(g), Verified = Agg.Count(g, c => c.IsVerified == true) }); var expected = nodes.SelectMany(n => n.Props.Contacts ?? []).GroupBy(c => c.Type) .Select(g => new { Type = g.Key, Count = g.Count(), Verified = g.Count(c => c.IsVerified) }) .ToList(); rows.Should().BeEquivalentTo(expected); } [Fact] public async Task TreeArrayGrouping_WithWhereAndLevel_CountsTheNodesTheListReturns() { var rootId = await SeedEmployeeTreeAsync(); var nodes = await Redb.TreeQuery(rootId).WhereLevel(1).Where(e => e.Salary > 1500m).ToListAsync(); var rows = await Redb.TreeQuery(rootId).WhereLevel(1).Where(e => e.Salary > 1500m) .GroupByArray(e => e.Contacts!, c => c.Type) .SelectAsync(g => new { Type = g.Key, Count = Agg.Count(g) }); var expected = nodes.SelectMany(n => n.Props.Contacts ?? []).GroupBy(c => c.Type).ToDictionary(g => g.Key, g => g.Count()); rows.ToDictionary(r => r.Type, r => r.Count).Should().BeEquivalentTo(expected); } } Path: redb/redb.Tests.Integration/Tests/Base/TreeSqlPreviewTestsBase.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/TreeSqlPreviewTestsBase.cs ---- using redb.Core; using redb.Core.Query; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// SQL preview of a tree query, for the Free providers. The base implementation of /// TreeQueryProviderBase.GetSqlPreviewAsync asked the database for a preview routine of the retired search /// module (get_search_tree_sql_preview_base / dbo.get_search_tree_sql_preview_base), which no provider /// installs any more, so ToSqlStringAsync on a tree query failed instead of returning SQL. Each Free provider /// now returns the statement its pvt module compiles for the query, and these tests pin that down. /// public abstract class TreeSqlPreviewTestsBase { protected readonly IRedbService Redb; protected TreeSqlPreviewTestsBase(IRedbService redb) => Redb = redb; [Fact] public async Task Preview_TreeQuery_ReturnsCompiledSql() { var sql = await Redb.TreeQuery() .Where(n => n.IsActive) .Take(10) .ToSqlStringAsync(); sql.Should().NotBeNullOrWhiteSpace("the preview of a tree query must return the statement the provider compiles"); sql.ToUpperInvariant().Should().Contain("SELECT"); sql.Should().Contain("_values", "the Props filter is read from the value rows"); sql.Should().NotContain("get_search_tree_sql_preview_base", "no provider installs the preview routine of the retired search module"); } [Fact] public async Task Preview_TreeQueryWithOrdering_ContainsOrderBy() { var sql = await Redb.TreeQuery() .Where(n => n.IsActive) .OrderBy(n => n.Budget) .Take(10) .ToSqlStringAsync(); sql.Should().NotBeNullOrWhiteSpace(); sql.ToUpperInvariant().Should().Contain("ORDER BY"); } } Path: redb/redb.Tests.Integration/Tests/Base/TreeTestsBase.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/TreeTestsBase.cs ---- using redb.Core; using redb.Core.Query; using redb.Core.Models.Entities; using redb.Tests.Integration.Helpers; using redb.Tests.Integration.Models; using System.Linq; namespace redb.Tests.Integration.Tests.Base; /// /// Tree CRUD and query tests. /// public abstract class TreeTestsBase { protected readonly IRedbService Redb; protected TreeTestsBase(IRedbService redb) => Redb = redb; /// /// Build a tree: Company -> Engineering -> Backend, Frontend /// -> Marketing /// private async Task<(long root, long eng, long backend, long frontend, long marketing)> SeedTreeAsync() { var root = TestDataFactory.CreateTreeNode("Company", "ROOT", 1000000m); root.id = await Redb.SaveAsync(root); var eng = TestDataFactory.CreateTreeNode("Engineering", "ENG", 500000m); eng.id = await Redb.CreateChildAsync(eng, root); var backend = TestDataFactory.CreateTreeNode("Backend", "BE", 200000m); backend.id = await Redb.CreateChildAsync(backend, eng); var frontend = TestDataFactory.CreateTreeNode("Frontend", "FE", 150000m); frontend.id = await Redb.CreateChildAsync(frontend, eng); var marketing = TestDataFactory.CreateTreeNode("Marketing", "MKT", 300000m); marketing.id = await Redb.CreateChildAsync(marketing, root); return (root.id, eng.id, backend.id, frontend.id, marketing.id); } [Fact] public async Task CreateChild_ReturnsPositiveId() { var root = TestDataFactory.CreateTreeNode("Root", "R1"); root.id = await Redb.SaveAsync(root); var child = TestDataFactory.CreateTreeNode("Child", "C1"); child.id = await Redb.CreateChildAsync(child, root); child.id.Should().BeGreaterThan(0); } [Fact] public async Task LoadTree_FromRoot_ReturnsHierarchy() { var (root, eng, be, fe, mkt) = await SeedTreeAsync(); var tree = await Redb.LoadTreeAsync(root); tree.Should().NotBeNull(); tree.Props.Name.Should().Be("Company"); tree.Children.Should().HaveCount(2); } [Fact] public async Task LoadTree_WithMaxDepth_LimitsDepth() { var (root, eng, be, fe, mkt) = await SeedTreeAsync(); var tree = await Redb.LoadTreeAsync(root, maxDepth: 1); tree.Children.Should().HaveCount(2); // At depth 1, engineering children should not be loaded or should be empty var engChild = tree.Children.OfType>().FirstOrDefault(c => c.Props.Name == "Engineering"); engChild.Should().NotBeNull(); } [Fact] public async Task GetChildren_ReturnsDirectChildren() { var (root, eng, be, fe, mkt) = await SeedTreeAsync(); var rootObj = await Redb.LoadAsync(root); var children = (await Redb.GetChildrenAsync(rootObj!)).ToList(); children.Should().HaveCount(2); children.Select(c => c.Props.Name).Should().BeEquivalentTo(["Engineering", "Marketing"]); } [Fact] public async Task GetPathToRoot_ReturnsAncestorChain() { var (root, eng, be, fe, mkt) = await SeedTreeAsync(); var beObj = await Redb.LoadAsync(be); var path = (await Redb.GetPathToRootAsync(beObj!)).ToList(); path.Should().HaveCountGreaterThanOrEqualTo(2); path.Select(p => p.Props.Name).Should().Contain("Engineering"); path.Select(p => p.Props.Name).Should().Contain("Company"); } [Fact] public async Task GetDescendants_ReturnsAllBelow() { var (root, eng, be, fe, mkt) = await SeedTreeAsync(); var rootObj = await Redb.LoadAsync(root); var descendants = (await Redb.GetDescendantsAsync(rootObj!)).ToList(); descendants.Should().HaveCount(4); // eng, be, fe, mkt } [Fact] public async Task MoveObject_ChangesParent() { var (root, eng, be, fe, mkt) = await SeedTreeAsync(); // Move Frontend under Marketing var feObj = await Redb.LoadAsync(fe); var mktObj = await Redb.LoadAsync(mkt); await Redb.MoveObjectAsync(feObj!, mktObj); var mktChildren = (await Redb.GetChildrenAsync(mktObj!)).ToList(); mktChildren.Should().Contain(c => c.Props.Name == "Frontend"); var engObj = await Redb.LoadAsync(eng); var engChildren = (await Redb.GetChildrenAsync(engObj!)).ToList(); engChildren.Should().NotContain(c => c.Props.Name == "Frontend"); } [Fact] public async Task TreeQuery_CountAll_ReturnsTotal() { var (root, eng, be, fe, mkt) = await SeedTreeAsync(); var count = await Redb.TreeQuery() .CountAsync(); count.Should().BeGreaterThanOrEqualTo(5); } [Fact] public async Task TreeQuery_WhereRoots_OnlyRoots() { var (root, eng, be, fe, mkt) = await SeedTreeAsync(); var roots = await Redb.TreeQuery() .WhereRoots() .ToListAsync(); roots.Should().NotBeEmpty(); roots.Should().Contain(r => r.id == root); } [Fact] public async Task TreeQuery_WhereLeaves_OnlyLeaves() { var (root, eng, be, fe, mkt) = await SeedTreeAsync(); var leaves = await Redb.TreeQuery() .WhereLeaves() .ToListAsync(); leaves.Should().NotBeEmpty(); leaves.Select(l => l.Props.Name).Should().Contain("Backend"); leaves.Select(l => l.Props.Name).Should().Contain("Frontend"); leaves.Select(l => l.Props.Name).Should().Contain("Marketing"); } [Fact] public async Task TreeQuery_WhereLeaves_ScopedToRoot_DoesNotLeakOtherTrees() { // Regression for the cross-tree leak: WhereLeaves() replaced the root-scoped CTE with a // scheme-wide leaf scan, so TreeQuery(rootObj).WhereLeaves() returned the newest leaf of ANY // tree in the scheme — a critical data leak (a fresh conversation received another user's leaf). var (rootA, eng, be, fe, mkt) = await SeedTreeAsync(); // Tree B: a lone root with NO children — a brand-new, empty "conversation". var rootB = TestDataFactory.CreateTreeNode("IsolationEmptyRoot", "ISO_EMPTY", 1m); rootB.id = await Redb.SaveAsync(rootB); // Scoped to A → exactly A's three leaves, and nothing from B. var rootAObj = await Redb.LoadAsync(rootA); var leavesA = await Redb.TreeQuery(rootAObj) .WhereLeaves() .ToListAsync(); leavesA.Select(l => l.Props.Name).Should().BeEquivalentTo(new[] { "Backend", "Frontend", "Marketing" }); leavesA.Should().NotContain(l => l.id == rootB.id, "B's root is not part of A's subtree"); leavesA.Should().NotContain(l => l.id == rootA, "A's root has children, so it is not a leaf"); // Scoped to the EMPTY B → NO leaves. This is the exact leak path: before the fix it returned // A's freshest leaf instead of empty. var rootBObj = await Redb.LoadAsync(rootB.id); var leavesB = await Redb.TreeQuery(rootBObj) .WhereLeaves() .ToListAsync(); leavesB.Should().BeEmpty("a root with no children has no leaves — other trees' leaves must not leak in"); } [Fact] public async Task TreeQuery_WhereLevel_FiltersLevel() { var (root, eng, be, fe, mkt) = await SeedTreeAsync(); // Level 0 = root, Level 1 = eng/mkt, Level 2 = be/fe var level1 = await Redb.TreeQuery() .WhereLevel(1) .ToListAsync(); level1.Should().HaveCountGreaterThanOrEqualTo(2); } [Fact] public async Task TreeQuery_WhereFilter_CombinesWithTree() { var (root, eng, be, fe, mkt) = await SeedTreeAsync(); var results = await Redb.TreeQuery() .Where(n => n.Budget > 200000m) .ToListAsync(); results.Should().NotBeEmpty(); results.Should().AllSatisfy(r => r.Props.Budget.Should().BeGreaterThan(200000m)); } [Fact] public async Task TreeQuery_FromRoot_ScopedQuery() { var (root, eng, be, fe, mkt) = await SeedTreeAsync(); var engObj = await Redb.LoadAsync(eng); var results = await Redb.TreeQuery(engObj) .ToListAsync(); // Should include eng itself and its descendants (be, fe) results.Should().HaveCountGreaterThanOrEqualTo(2); } [Fact] public async Task DeleteSubtree_RemovesBranch() { var (root, eng, be, fe, mkt) = await SeedTreeAsync(); var engObj = await Redb.LoadAsync(eng); var deleted = await Redb.DeleteSubtreeAsync(engObj!); deleted.Should().BeGreaterThanOrEqualTo(2); // eng subtree: eng, be, fe var remaining = await Redb.TreeQuery() .CountAsync(); // root + mkt should remain remaining.Should().BeGreaterThanOrEqualTo(2); } // ===== WhereRedb on TreeQuery: base field ValueString tests ===== private async Task<(long root, List childIds)> SeedTreeWithValueStringAsync() { var root = new TreeRedbObject { name = "VSTree_Root", value_string = "root-node", Props = new TreeNodeProps { Name = "VSTree_Root", Description = "Root", IsActive = true, Budget = 100000m, Code = "RT" } }; root.id = await Redb.SaveAsync(root); var childData = new[] { ("alpha-bravo-charlie", "Node_A", "NA", 50000m), ("delta-echo-foxtrot", "Node_B", "NB", 60000m), ("golf-hotel-india", "Node_C", "NC", 70000m), ("alpha-juliet-kilo", "Node_D", "ND", 40000m), ("lima-echo-mike", "Node_E", "NE", 80000m), }; var childIds = new List(); foreach (var (vs, nm, code, budget) in childData) { var child = new TreeRedbObject { name = nm, value_string = vs, Props = new TreeNodeProps { Name = nm, Description = $"Child {nm}", IsActive = true, Budget = budget, Code = code } }; child.id = await Redb.CreateChildAsync(child, root); childIds.Add(child.id); } return (root.id, childIds); } [Fact] public async Task TreeQuery_WhereRedb_ValueString_Contains_Filters() { var (rootId, childIds) = await SeedTreeWithValueStringAsync(); var results = await Redb.TreeQuery() .WhereRedb(o => o.ValueString!.Contains("echo")) .ToListAsync(); results.Should().NotBeEmpty(); results.Should().OnlyContain(r => r.value_string != null && r.value_string.Contains("echo")); results.Should().HaveCountGreaterThanOrEqualTo(2); } [Fact] public async Task TreeQuery_WhereRedb_ValueString_Equal_Filters() { var (rootId, childIds) = await SeedTreeWithValueStringAsync(); var results = await Redb.TreeQuery() .WhereRedb(o => o.ValueString == "alpha-bravo-charlie") .ToListAsync(); results.Should().NotBeEmpty(); results.Should().OnlyContain(r => r.value_string == "alpha-bravo-charlie"); } [Fact] public async Task TreeQuery_WhereRedb_ValueString_StartsWith_Filters() { var (rootId, childIds) = await SeedTreeWithValueStringAsync(); var results = await Redb.TreeQuery() .WhereRedb(o => o.ValueString!.StartsWith("alpha")) .ToListAsync(); results.Should().HaveCountGreaterThanOrEqualTo(2); results.Should().OnlyContain(r => r.value_string != null && r.value_string.StartsWith("alpha")); } [Fact] public async Task TreeQuery_WhereRedb_ValueString_Contains_ThenWhereProps() { var (rootId, childIds) = await SeedTreeWithValueStringAsync(); var results = await Redb.TreeQuery() .WhereRedb(o => o.ValueString!.Contains("echo")) .Where(n => n.Budget > 50000m) .ToListAsync(); results.Should().NotBeEmpty(); results.Should().OnlyContain(r => r.value_string != null && r.value_string.Contains("echo") && r.Props.Budget > 50000m); } [Fact] public async Task TreeQuery_WhereRedb_ValueString_Contains_ThenMultipleWhereProps() { var (rootId, childIds) = await SeedTreeWithValueStringAsync(); // Full chain: WhereRedb(Contains) + multiple Where(props) + OrderBy + Count + ToList var query = Redb.TreeQuery() .WhereRedb(o => o.ValueString!.Contains("echo")) .Where(n => n.IsActive) .Where(n => n.Budget > 0m) .OrderBy(n => n.Name); var count = await query.CountAsync(); count.Should().BeGreaterThanOrEqualTo(0); var results = await query.ToListAsync(); results.Should().OnlyContain(r => r.value_string != null && r.value_string.Contains("echo") && r.Props.IsActive && r.Props.Budget > 0m); } [Fact] public async Task TreeQuery_WhereRedb_ValueString_Contains_CountAsync() { var (rootId, childIds) = await SeedTreeWithValueStringAsync(); var count = await Redb.TreeQuery() .WhereRedb(o => o.ValueString!.Contains("echo")) .Where(n => n.Budget > 0m) .CountAsync(); count.Should().BeGreaterThanOrEqualTo(2); } [Fact] public async Task TreeQuery_WhereRedb_Name_Contains_Filters() { var (rootId, childIds) = await SeedTreeWithValueStringAsync(); var results = await Redb.TreeQuery() .WhereRedb(o => o.Name.Contains("Node_")) .ToListAsync(); results.Should().NotBeEmpty(); results.Should().OnlyContain(r => r.name != null && r.name.Contains("Node_")); } [Fact] public async Task Aggregates_And_GroupBy_OverATree_CountOnlyItsNodes() { // Two roots, each with children of its own; every aggregate over one subtree reads that subtree only. var tag = Guid.NewGuid().ToString("N")[..8]; async Task> Root(string name, params decimal[] budgets) { var root = TestDataFactory.CreateTreeNode($"{name}-{tag}", $"{name}-{tag}", 1m); root.id = await Redb.SaveAsync(root); for (var i = 0; i < budgets.Length; i++) await Redb.CreateChildAsync(TestDataFactory.CreateTreeNode($"{name}-{tag}-{i}", $"{name}{i}-{tag}", budgets[i]), root); return root; } var a = await Root("aggA", 100m, 200m, 300m); await Root("aggB", 5000m, 7000m); IRedbQueryable A() => Redb.TreeQuery(a.id); (await A().CountAsync()).Should().Be(3); (await A().SumAsync(n => n.Budget)).Should().Be(600m); (await A().AverageAsync(n => n.Budget)).Should().Be(200m); (await A().MinAsync(n => n.Budget)).Should().Be(100m); (await A().MaxAsync(n => n.Budget)).Should().Be(300m); (await A().Where(n => n.Budget > 150m).SumAsync(n => n.Budget)).Should().Be(500m); var groups = await A().GroupBy(n => n.IsActive) .SelectAsync(g => new { g.Key, N = global::redb.Core.Query.Aggregation.Agg.Count(g), S = global::redb.Core.Query.Aggregation.Agg.Sum(g, n => n.Budget) }); groups.Should().ContainSingle().Which.S.Should().Be(600m); groups.Single().N.Should().Be(3); } } Path: redb/redb.Tests.Integration/Tests/Base/TypeChangeTicksAndKeysTestsBase.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/TypeChangeTicksAndKeysTestsBase.cs ---- using AwesomeAssertions.Execution; using Microsoft.Extensions.DependencyInjection; using redb.Core; using redb.Core.Attributes; using redb.Core.Models.Entities; using redb.Core.Query; namespace redb.Tests.Integration.Tests.Base; [RedbScheme("Type change: date to time span", Name = "type_change_date_to_span", Version = 1)] public class TypeChangeDateToSpanProps { /// Staged as DateTime, declared here as TimeSpan. public TimeSpan Span { get; set; } } [RedbScheme("Type change: time span to date", Name = "type_change_span_to_date", Version = 1)] public class TypeChangeSpanToDateProps { /// Staged as TimeSpan, declared here as DateTime. public DateTime When { get; set; } } [RedbScheme("Type change: dictionary key text to int", Name = "type_change_dictionary_key", Version = 1)] public class TypeChangeDictionaryKeyProps { /// Staged with a string key type and a key that is not a number, declared here with int keys. public Dictionary Items { get; set; } = new(); } /// /// Type changes at scheme sync whose stored values the sync does not convert honestly. A TimeSpan lives in the long /// column as ticks, while the long-to-date conversion and back reads and writes Unix seconds: the value changes its /// meaning and the sync reports success. A dictionary key type change only updates the structure: keys that do not /// parse under the new key type pass the sync and fail later, at read. Staged as the type tests do: values written /// through the current class, then the structure and the column rewritten to the shape an earlier class left. /// public abstract class TypeChangeTicksAndKeysTestsBase : IAsyncLifetime { protected readonly IRedbService Redb; private readonly ISqlDialect _dialect; private static readonly string[] Schemes = ["type_change_date_to_span", "type_change_span_to_date", "type_change_dictionary_key"]; protected TypeChangeTicksAndKeysTestsBase(IRedbService redb, IServiceProvider services) { Redb = redb; _dialect = services.GetRequiredService(); } public async Task InitializeAsync() { foreach (var scheme in Schemes) await ResetSchemeAsync(scheme); } public async Task DisposeAsync() { foreach (var scheme in Schemes) await ResetSchemeAsync(scheme); } [Fact] public async Task DateTimeToTimeSpan_WithStoredValues_IsRefused() { await Redb.SyncSchemeAsync(); var id = await Redb.SaveAsync(new RedbObject { name = "date-to-span", Props = new TypeChangeDateToSpanProps { Span = TimeSpan.FromHours(1) } }); var structureId = await StructureIdAsync("type_change_date_to_span", "Span"); var stagedDate = new DateTimeOffset(2026, 1, 1, 0, 0, 0, TimeSpan.Zero); await Redb.Context.ExecuteAsync( $"UPDATE _values SET _DateTimeOffset = {_dialect.FormatDateTimeOffsetLiteral(stagedDate)}, _Long = NULL " + $"WHERE _id_structure = {structureId}"); await SetStructureTypeAsync(structureId, "DateTime"); var syncError = await Record.ExceptionAsync(() => Redb.SyncSchemeAsync()); var storedLong = await Redb.Context.ExecuteScalarAsync( $"SELECT _Long FROM _values WHERE _id_structure = {structureId}"); TimeSpan? read = null; if (syncError == null) read = (await Redb.LoadAsync(id))!.Props.Span; using (new AssertionScope()) { syncError.Should().NotBeNull( $"a date has no time span meaning; the sync stored {storedLong} in _Long and the property reads {read}"); (await StructureTypeNameAsync(structureId)).Should().Be("DateTime", "a refused change keeps the type"); } } [Fact] public async Task TimeSpanToDateTime_WithStoredValues_IsRefused() { await Redb.SyncSchemeAsync(); var id = await Redb.SaveAsync(new RedbObject { name = "span-to-date", Props = new TypeChangeSpanToDateProps { When = new DateTime(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc) } }); var structureId = await StructureIdAsync("type_change_span_to_date", "When"); await Redb.Context.ExecuteAsync( $"UPDATE _values SET _Long = {TimeSpan.FromHours(1).Ticks}, _DateTimeOffset = NULL WHERE _id_structure = {structureId}"); await SetStructureTypeAsync(structureId, "TimeSpan"); var syncError = await Record.ExceptionAsync(() => Redb.SyncSchemeAsync()); var storedDate = await Redb.Context.ExecuteScalarAsync( $"SELECT CAST(_DateTimeOffset AS {TextType}) FROM _values WHERE _id_structure = {structureId}"); object? read = null; if (syncError == null) read = await Record.ExceptionAsync(() => Redb.LoadAsync(id)) is { } loadError ? loadError.GetType().Name : (await Redb.LoadAsync(id))!.Props.When; using (new AssertionScope()) { syncError.Should().NotBeNull( $"a time span has no date meaning; the sync stored {storedDate} in _DateTimeOffset and the property reads {read}"); (await StructureTypeNameAsync(structureId)).Should().Be("TimeSpan", "a refused change keeps the type"); } } [Fact] public async Task DictionaryKeyTextToInt_WithAKeyThatIsNotANumber_IsRefusedAtSync() { await Redb.SyncSchemeAsync(); var id = await Redb.SaveAsync(new RedbObject { name = "dictionary-key", Props = new TypeChangeDictionaryKeyProps { Items = new Dictionary { [1] = "x" } } }); var structureId = await StructureIdAsync("type_change_dictionary_key", "Items"); var stringType = await TypeIdAsync("String"); await Redb.Context.ExecuteAsync( $"UPDATE _values SET _array_index = 'abc' WHERE _id_structure = {structureId} AND _array_index = '1'"); await Redb.Context.ExecuteAsync($"UPDATE _structures SET _key_type = {stringType} WHERE _id = {structureId}"); await Redb.Context.ExecuteAsync( $"UPDATE _schemes SET _version = NULL WHERE _id = (SELECT _id_scheme FROM _structures WHERE _id = {structureId})"); Redb.Cache.Clear(); (await Redb.Context.ExecuteScalarAsync( $"SELECT CAST(COUNT(*) AS BIGINT) FROM _values WHERE _id_structure = {structureId} AND _array_index = 'abc'")) .Should().Be(1, "precondition: the staged key is stored"); var syncError = await Record.ExceptionAsync(() => Redb.SyncSchemeAsync()); var loadError = syncError == null ? await Record.ExceptionAsync(() => Redb.LoadAsync(id)) : null; using (new AssertionScope()) { syncError.Should().NotBeNull( $"a stored key 'abc' does not parse as int; without a refusal the load fails later: {loadError?.GetType().Name}: {loadError?.Message}"); (await Redb.Context.ExecuteScalarAsync($"SELECT _key_type FROM _structures WHERE _id = {structureId}")) .Should().Be(stringType, "a refused change keeps the key type"); } } /// The engine's text type for a cast in a read-back query. protected abstract string TextType { get; } private async Task ResetSchemeAsync(string schemeName) { await Redb.Context.ExecuteAsync( $"DELETE FROM _values WHERE _id_object IN (SELECT _id FROM _objects WHERE _id_scheme IN (SELECT _id FROM _schemes WHERE _name = '{schemeName}'))"); await Redb.Context.ExecuteAsync( $"DELETE FROM _objects WHERE _id_scheme IN (SELECT _id FROM _schemes WHERE _name = '{schemeName}')"); await Redb.Context.ExecuteAsync( $"DELETE FROM _structures WHERE _id_scheme IN (SELECT _id FROM _schemes WHERE _name = '{schemeName}')"); await Redb.Context.ExecuteAsync($"DELETE FROM _schemes WHERE _name = '{schemeName}'"); Redb.Cache.Clear(); } private async Task TypeIdAsync(string typeName) => (await Redb.Context.ExecuteScalarAsync($"SELECT _id FROM _types WHERE _name = '{typeName}'"))!.Value; private async Task StructureIdAsync(string schemeName, string propertyName) => (await Redb.Context.ExecuteScalarAsync( $"SELECT _id FROM _structures WHERE _name = '{propertyName}' AND _id_scheme IN " + $"(SELECT _id FROM _schemes WHERE _name = '{schemeName}')"))!.Value; private Task StructureTypeNameAsync(long structureId) => Redb.Context.ExecuteScalarAsync( $"SELECT t._name FROM _structures s JOIN _types t ON t._id = s._id_type WHERE s._id = {structureId}"); /// Repoints the structure at another type, as an earlier class left it (no scheme version recorded). private async Task SetStructureTypeAsync(long structureId, string typeName) { var typeId = await TypeIdAsync(typeName); await Redb.Context.ExecuteAsync($"UPDATE _structures SET _id_type = {typeId} WHERE _id = {structureId}"); await Redb.Context.ExecuteAsync( $"UPDATE _schemes SET _version = NULL WHERE _id = (SELECT _id_scheme FROM _structures WHERE _id = {structureId})"); Redb.Cache.Clear(); } } Path: redb/redb.Tests.Integration/Tests/Base/TypeMigrationSyncTestsBase.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/TypeMigrationSyncTestsBase.cs ---- using redb.Core; using redb.Core.Exceptions; using redb.Core.Models.Entities; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// Type migration as it is reached through SyncSchemeAsync — the path that had no test at all. /// /// /// The pre-existing migration tests all call the public MigrateStructureTypeAsync with correct /// type names, which is why they stayed green while the sync path passed a numeric id into a lookup /// keyed by name, resolved the old type to the literal "unknown", got an error back from every /// provider, discarded it, and switched _structures._id_type anyway. Values were left in the /// old column, read as null, and were physically deleted by the next save under the default /// DeleteInsert strategy. /// /// /// /// How a type change is staged. Sharing one [RedbScheme(Name = "...")] between two /// classes is refused by the library, so instead each test writes values through the current class and /// then rewrites _structures._id_type and the storage column with raw SQL into the shape an /// earlier version of that class would have left behind. The sync path cannot tell the difference from /// a real deployment where the property's type changed. /// /// /// /// Why cleanup is mandatory, not tidiness. Half of these tests deliberately leave a scheme the /// library refuses to sync — that IS the behaviour under test. The fixture's InitializeAsync /// runs auto-sync across the whole assembly, so one such scheme left behind fails every test in the /// collection on the next run, not just this suite. Cleanup therefore runs in DisposeAsync, /// which xUnit calls even when the test fails. /// /// public abstract class TypeMigrationSyncTestsBase : IAsyncLifetime { protected readonly IRedbService Redb; protected TypeMigrationSyncTestsBase(IRedbService redb) => Redb = redb; /// Every scheme this suite touches, dropped before and after each test. private static readonly string[] Schemes = [ "type_migration_supported", "type_migration_unsupported", "type_migration_samecolumn", "type_migration_partial", "type_migration_bool_from_text" ]; public async Task InitializeAsync() { foreach (var scheme in Schemes) await ResetSchemeAsync(scheme); } public async Task DisposeAsync() { foreach (var scheme in Schemes) await ResetSchemeAsync(scheme); } // ============================================================ // === helpers === // ============================================================ /// Objects first (values cascade off them), then structures, then the scheme itself. private async Task ResetSchemeAsync(string schemeName) { await Redb.Context.ExecuteAsync( $"DELETE FROM _objects WHERE _id_scheme IN (SELECT _id FROM _schemes WHERE _name = '{schemeName}')"); await Redb.Context.ExecuteAsync( $"DELETE FROM _structures WHERE _id_scheme IN (SELECT _id FROM _schemes WHERE _name = '{schemeName}')"); await Redb.Context.ExecuteAsync($"DELETE FROM _schemes WHERE _name = '{schemeName}'"); // Raw SQL is invisible to the metadata cache; without this the next sync answers from a scheme // that no longer exists. Redb.Cache.Clear(); } private Task TypeIdAsync(string typeName) => Redb.Context.ExecuteScalarAsync($"SELECT _id FROM _types WHERE _name = '{typeName}'"); private Task StructureIdAsync(string schemeName, string propertyName) => Redb.Context.ExecuteScalarAsync( $"SELECT _id FROM _structures WHERE _name = '{propertyName}' AND _id_scheme IN " + $"(SELECT _id FROM _schemes WHERE _name = '{schemeName}')"); private Task StructureTypeIdAsync(long structureId) => Redb.Context.ExecuteScalarAsync($"SELECT _id_type FROM _structures WHERE _id = {structureId}"); private Task CountAsync(string columnName, long structureId) => Redb.Context.ExecuteScalarAsync( $"SELECT CAST(COUNT(*) AS BIGINT) FROM _values WHERE _id_structure = {structureId} " + $"AND {columnName} IS NOT NULL"); /// /// Repoints a structure at another REDB type without touching its values, as the earlier build left it: that build /// had no scheme version, so the recorded version goes back to none and the class (Version = 1) is the newer one. /// private async Task SetStructureTypeAsync(long structureId, string typeName) { var typeId = await TypeIdAsync(typeName); typeId.Should().NotBeNull($"the seed type '{typeName}' must exist in _types"); await Redb.Context.ExecuteAsync( $"UPDATE _structures SET _id_type = {typeId!.Value} WHERE _id = {structureId}"); await Redb.Context.ExecuteAsync( $"UPDATE _schemes SET _version = NULL WHERE _id = (SELECT _id_scheme FROM _structures WHERE _id = {structureId})"); Redb.Cache.Clear(); } // ============================================================ // === supported conversion: the values must actually move === // ============================================================ /// /// Boolean to Int on every provider. Red before the fix in the most concrete way possible: the /// migration never ran, so _Long stayed empty while _id_type said Int. /// [Fact] public async Task SupportedConversion_MovesValuesAndUpdatesType() { const string scheme = "type_migration_supported"; await Redb.SyncSchemeAsync(); var ids = new List(); foreach (var (flag, tag) in new[] { (1, "a"), (0, "b"), (1, "c") }) { var obj = new RedbObject { name = $"probe-{tag}", Props = new TypeMigrationIntProps { Flag = flag, Tag = tag } }; ids.Add(await Redb.SaveAsync(obj)); } var structureId = (await StructureIdAsync(scheme, nameof(TypeMigrationIntProps.Flag)))!.Value; // Stage the database as an earlier build with `bool Flag` would have left it. await Redb.Context.ExecuteAsync( $"UPDATE _values SET _Boolean = CASE WHEN _Long <> 0 THEN {BoolTrue} ELSE {BoolFalse} END, _Long = NULL " + $"WHERE _id_structure = {structureId}"); await SetStructureTypeAsync(structureId, "Boolean"); (await CountAsync("_Boolean", structureId)).Should().Be(3, "staging must put every value in _Boolean"); (await CountAsync("_Long", structureId)).Should().Be(0); await Redb.SyncSchemeAsync(); (await CountAsync("_Long", structureId)).Should().Be(3, "the migration must move every value"); (await CountAsync("_Boolean", structureId)).Should().Be(0, "and must clear the old column"); (await StructureTypeIdAsync(structureId)).Should().Be(await TypeIdAsync("Int")); // The point of the whole exercise: the objects still read back what they were saved with. var loadedA = await Redb.LoadAsync(ids[0]); var loadedB = await Redb.LoadAsync(ids[1]); loadedA!.Props.Flag.Should().Be(1); loadedA.Props.Tag.Should().Be("a", "a neighbouring property must not be disturbed"); loadedB!.Props.Flag.Should().Be(0); } /// /// Int and Long share the _Long column, so there is nothing to move. The type still has to /// change, and no value may be touched. /// [Fact] public async Task SameStorageColumn_ChangesTypeWithoutTouchingValues() { const string scheme = "type_migration_samecolumn"; await Redb.SyncSchemeAsync(); var obj = new RedbObject { name = "probe-same-column", Props = new TypeMigrationLongProps { Flag = 42, Tag = "same" } }; var id = await Redb.SaveAsync(obj); var structureId = (await StructureIdAsync(scheme, nameof(TypeMigrationLongProps.Flag)))!.Value; await SetStructureTypeAsync(structureId, "Int"); await Redb.SyncSchemeAsync(); (await StructureTypeIdAsync(structureId)).Should().Be(await TypeIdAsync("Long")); (await CountAsync("_Long", structureId)).Should().Be(1); var loaded = await Redb.LoadAsync(id); loaded!.Props.Flag.Should().Be(42); } // ============================================================ // === refusal: sync must stop and leave the type alone === // ============================================================ /// /// Boolean to Guid is in no provider's conversion matrix. Synchronisation must fail, and — the part /// that actually protects the data — it must not switch the structure type on the way out. /// [Fact] public async Task UnsupportedConversion_ThrowsAndLeavesTypeAndValuesIntact() { const string scheme = "type_migration_unsupported"; await Redb.SyncSchemeAsync(); var obj = new RedbObject { name = "probe-unsupported", Props = new TypeMigrationGuidProps { Flag = Guid.NewGuid(), Tag = "keep" } }; await Redb.SaveAsync(obj); var structureId = (await StructureIdAsync(scheme, nameof(TypeMigrationGuidProps.Flag)))!.Value; await Redb.Context.ExecuteAsync( $"UPDATE _values SET _Boolean = {BoolTrue}, _Guid = NULL WHERE _id_structure = {structureId}"); await SetStructureTypeAsync(structureId, "Boolean"); var booleanTypeId = await TypeIdAsync("Boolean"); var act = async () => await Redb.SyncSchemeAsync(); var ex = (await act.Should().ThrowAsync()).Which; ex.OldTypeName.Should().Be("Boolean"); ex.NewTypeName.Should().Be("Guid"); ex.PropertyName.Should().Be(nameof(TypeMigrationGuidProps.Flag)); ex.StructureId.Should().Be(structureId); ex.Message.Should().Contain("migrate_structure_type", "the message has to carry the manual fix"); (await StructureTypeIdAsync(structureId)).Should().Be(booleanTypeId, "a refused migration must not change the type"); (await CountAsync("_Boolean", structureId)).Should().Be(1, "and must not touch the values"); } /// /// A type with no scalar storage column of its own (Class) makes every provider report an unknown /// source type. With values present that is a genuine refusal. /// [Fact] public async Task TypeWithoutStorageColumn_WithValues_Throws() { const string scheme = "type_migration_supported"; await Redb.SyncSchemeAsync(); var obj = new RedbObject { name = "probe-class-with-values", Props = new TypeMigrationIntProps { Flag = 7, Tag = "x" } }; await Redb.SaveAsync(obj); var structureId = (await StructureIdAsync(scheme, nameof(TypeMigrationIntProps.Flag)))!.Value; await SetStructureTypeAsync(structureId, "Class"); var classTypeId = await TypeIdAsync("Class"); var act = async () => await Redb.SyncSchemeAsync(); var ex = (await act.Should().ThrowAsync()).Which; // The provider bails out before it counts anything, so it reports zero affected rows while a // value is sitting right there. Reporting that zero would say nothing is at stake. ex.AffectedRows.Should().Be(1, "the count must fall back to the rows actually stored"); ex.StrandedRows.Should().Be(1); (await StructureTypeIdAsync(structureId)).Should().Be(classTypeId); (await CountAsync("_Long", structureId)).Should().Be(1); } /// /// The same unmigratable pair with no values at all must NOT fail: there is nothing to strand, and /// refusing would break type changes on empty schemes for no gain. This is the boundary of the /// previous test, and the reason the check counts rows instead of trusting the error string. /// [Fact] public async Task TypeWithoutStorageColumn_NoValues_Succeeds() { const string scheme = "type_migration_supported"; await Redb.SyncSchemeAsync(); var structureId = (await StructureIdAsync(scheme, nameof(TypeMigrationIntProps.Flag)))!.Value; await SetStructureTypeAsync(structureId, "Class"); await Redb.SyncSchemeAsync(); (await StructureTypeIdAsync(structureId)).Should().Be(await TypeIdAsync("Int")); } // ============================================================ // === partial conversion === // ============================================================ /// /// Text to number where one row is not a number. The readable rows move, the unreadable one stays, /// and that half-done state is a failure: synchronisation stops and the type stays put, so the next /// start fails the same way instead of quietly presenting the leftovers as missing. /// [Fact] public async Task PartialConversion_ThrowsAndReportsWhatWasLeftBehind() { const string scheme = "type_migration_partial"; await Redb.SyncSchemeAsync(); foreach (var (flag, tag) in new[] { (1L, "one"), (2L, "two"), (3L, "three") }) { var obj = new RedbObject { name = $"probe-partial-{tag}", Props = new TypeMigrationPartialProps { Flag = flag, Tag = tag } }; await Redb.SaveAsync(obj); } var structureId = (await StructureIdAsync(scheme, nameof(TypeMigrationPartialProps.Flag)))!.Value; // Stage as text, and make one row unreadable as a number. await Redb.Context.ExecuteAsync( $"UPDATE _values SET _String = CAST(_Long AS {TextTypeName}), _Long = NULL " + $"WHERE _id_structure = {structureId}"); await Redb.Context.ExecuteAsync( $"UPDATE _values SET _String = 'not-a-number' WHERE _id_structure = {structureId} AND _String = '3'"); await SetStructureTypeAsync(structureId, "String"); var stringTypeId = await TypeIdAsync("String"); var act = async () => await Redb.SyncSchemeAsync(); var ex = (await act.Should().ThrowAsync()).Which; ex.StrandedRows.Should().Be(1, "exactly one value could not be read as a number"); ex.MigratedRows.Should().Be(2); (await StructureTypeIdAsync(structureId)).Should().Be(stringTypeId, "a partial migration must not switch the type either"); (await CountAsync("_String", structureId)).Should().Be(1, "the unreadable value stays where it was"); } /// Boolean literals for the staging SQL: PostgreSQL has a real boolean, the others use 1/0. protected abstract string BoolTrue { get; } /// protected abstract string BoolFalse { get; } /// /// Text to Boolean used to be the one conversion that DESTROYED what it could not read. The CASE /// mapped an unrecognised token to NULL while the same statement cleared the source column, and /// because success is measured by rows updated, the loss was reported as a success — no error, no /// count, nothing to notice. Every neighbouring text conversion was already guarded; this one was /// not, on both PostgreSQL and MSSQL. /// /// /// The value the migration cannot read must survive, exactly like an unparseable number does. /// /// [Fact] public async Task TextToBoolean_KeepsValuesItCannotRead() { const string scheme = "type_migration_bool_from_text"; await Redb.SyncSchemeAsync(); foreach (var (flag, tag) in new[] { (true, "yes"), (false, "no"), (true, "odd") }) { var obj = new RedbObject { name = $"probe-bool-{tag}", Props = new TypeMigrationBoolProps { Flag = flag, Tag = tag } }; await Redb.SaveAsync(obj); } var structureId = (await StructureIdAsync(scheme, nameof(TypeMigrationBoolProps.Flag)))!.Value; // Stage as text, and make one row a token no provider accepts. await Redb.Context.ExecuteAsync( $"UPDATE _values SET _String = CASE WHEN _Boolean = {BoolTrue} THEN 'true' ELSE 'false' END, " + $"_Boolean = NULL WHERE _id_structure = {structureId}"); await Redb.Context.ExecuteAsync( $"UPDATE _values SET _String = 'maybe' WHERE _id = " + $"(SELECT _id FROM _values WHERE _id_structure = {structureId} AND _String = 'false')"); await SetStructureTypeAsync(structureId, "String"); var stringTypeId = await TypeIdAsync("String"); var act = async () => await Redb.SyncSchemeAsync(); var ex = (await act.Should().ThrowAsync()).Which; ex.StrandedRows.Should().Be(1); // The assertion the whole test exists for: 'maybe' is still there, not silently erased. (await CountAsync("_String", structureId)).Should().Be(1, "an unreadable token must not be destroyed"); (await StructureTypeIdAsync(structureId)).Should().Be(stringTypeId); } /// /// Cast target for "number as text" in the staging SQL. Spelled by the provider because the type /// name is the one part of a CAST that is not portable. /// protected abstract string TextTypeName { get; } } Path: redb/redb.Tests.Integration/Tests/Base/UniqueKeyTestsBase.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/UniqueKeyTestsBase.cs ---- using System.Text; using redb.Core.Utils; using redb.Core; using redb.Core.Exceptions; using redb.Core.Models.Entities; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// The [RedbUnique] contract (V4, UNIQUE stage 2): a key field's value is unique within its /// scheme, enforced by the database over the hash of the canonical form /// (UniqueKeyEncoder → _values._unique → UIX__values__structure_unique), and a /// violation surfaces as on every provider. /// /// /// The suite owns three schemes (UniqueOrder, UniqueInvoice, UniqueFree) and /// resets them before and after every test: half of the scenarios deliberately leave duplicates or /// raw-SQL damage behind, and the shared database accumulates state across runs. /// /// public abstract class UniqueKeyTestsBase : IAsyncLifetime { protected readonly IRedbService Redb; protected UniqueKeyTestsBase(IRedbService redb) => Redb = redb; /// SQL literal for boolean TRUE in raw statements (MSSQL BIT wants 1). protected virtual string BoolTrue => "TRUE"; /// /// Whether the driver's violation message carries the key tuple, so the exception can name the /// property. PostgreSQL and MSSQL do; SQLite names only the columns. /// protected virtual bool ReportsKeyTuple => true; /// /// Whether two objects may swap their keys inside one batch save. True under DeleteInsert /// (all deletes before all inserts); under ChangeTracking the in-place update path may hit the /// index mid-way — the documented boundary of §4.6, surfacing as the typed exception. /// protected virtual bool KeySwapMustPass => true; private static readonly string[] Schemes = ["UniqueOrder", "UniqueInvoice", "UniqueFree", "ByteHolder", "UniqueNested", "UniqueDeep", "UniqueSubtree", "UniqueElems", "redb.Tests.Integration.Models.UniqueInElementProps", "redb.Tests.Integration.Models.ScopedScalarProps"]; public async Task InitializeAsync() { foreach (var scheme in Schemes) await ResetSchemeAsync(scheme); } public async Task DisposeAsync() { foreach (var scheme in Schemes) await ResetSchemeAsync(scheme); } private async Task ResetSchemeAsync(string schemeName) { await Redb.Context.ExecuteAsync( $"DELETE FROM _objects WHERE _id_scheme IN (SELECT _id FROM _schemes WHERE _name = '{schemeName}')"); await Redb.Context.ExecuteAsync( $"DELETE FROM _structures WHERE _id_scheme IN (SELECT _id FROM _schemes WHERE _name = '{schemeName}')"); await Redb.Context.ExecuteAsync($"DELETE FROM _schemes WHERE _name = '{schemeName}'"); } private async Task SyncAllAsync() { await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); } private static RedbObject Order(Action set) { var props = new UniqueOrderProps(); set(props); return new RedbObject { name = "order", Props = props }; } private async Task StructureIdAsync(string schemeName, string propertyName) => (await Redb.Context.ExecuteScalarAsync( $"SELECT _id FROM _structures WHERE _name = '{propertyName}' AND _id_scheme = " + $"(SELECT _id FROM _schemes WHERE _name = '{schemeName}')"))!.Value; // ============================================================ // === enforcement === // ============================================================ [Fact] public async Task DuplicateKey_IsRejected_WithTypedException() { await SyncAllAsync(); await Redb.SaveAsync(Order(p => { p.Code = "ORD-1"; p.Note = "first"; })); var act = async () => await Redb.SaveAsync(Order(p => { p.Code = "ORD-1"; p.Note = "second"; })); var ex = (await act.Should().ThrowAsync( "one typed exception on every provider, not three driver errors")).Which; ex.Cause.Should().NotBeNull("the driver exception is always attached"); if (ReportsKeyTuple) { ex.PropertyName.Should().Be("Code"); ex.SchemeName.Should().Be("UniqueOrder"); } } [Fact] public async Task SameKey_InDifferentSchemes_IsAllowed() { await SyncAllAsync(); await Redb.SaveAsync(Order(p => p.Code = "SHARED")); var invoice = new RedbObject { name = "invoice", Props = new UniqueInvoiceProps { Code = "SHARED" } }; var id = await Redb.SaveAsync(invoice); id.Should().BeGreaterThan(0, "uniqueness is per scheme: _id_structure is part of the index key"); } [Fact] public async Task SameValue_InDifferentFieldsOfOneScheme_IsAllowed() { await SyncAllAsync(); await Redb.SaveAsync(Order(p => p.Number = 5)); var id = await Redb.SaveAsync(Order(p => p.Amount = 5m)); id.Should().BeGreaterThan(0, "each field is its own structure, its own uniqueness namespace"); } [Fact] public async Task MultipleNullKeys_AreAllowed() { await SyncAllAsync(); for (var i = 0; i < 3; i++) await Redb.SaveAsync(Order(p => p.Note = $"empty-{i}")); (await Redb.Context.ExecuteScalarAsync( "SELECT COUNT(*) FROM _objects WHERE _id_scheme = (SELECT _id FROM _schemes WHERE _name = 'UniqueOrder')")) .Should().Be(3, "NULL never takes part in uniqueness"); } [Fact] public async Task RaceOnOneKey_ExactlyOneWins() { await SyncAllAsync(); // One service instance is deliberately single-writer (the 3.3.0 captive-singleton guard): // a truly concurrent second save may be refused by the SERVICE with // InvalidOperationException before the database ever sees it. Both outcomes are legal for // the loser - but after the dust settles, exactly one object holds the key, and a retry of // the refused save must get the typed violation from the INDEX. var results = await Task.WhenAll(TrySave(), TrySave()); results.Count(r => r is null).Should().BeGreaterThanOrEqualTo(1, "at least one save takes the key"); results.Where(r => r != null).Should().OnlyContain( r => r is RedbUniqueViolationException || r is InvalidOperationException); // Whatever the interleaving, the key has exactly one holder now, and the next claim gets // the typed rejection. var retry = async () => await Redb.SaveAsync(Order(p => p.Code = "RACE")); await retry.Should().ThrowAsync(); (await Redb.Context.ExecuteScalarAsync( "SELECT COUNT(*) FROM _values WHERE _unique IS NOT NULL AND _id_structure = " + "(SELECT _id FROM _structures WHERE _name = 'Code' AND _id_scheme = " + "(SELECT _id FROM _schemes WHERE _name = 'UniqueOrder'))")) .Should().Be(1, "exactly one row holds the key"); async Task TrySave() { try { await Redb.SaveAsync(Order(p => p.Code = "RACE")); return null; } catch (Exception ex) { return ex; } } } [Fact] public async Task UpdatingObject_KeepsItsOwnKey() { await SyncAllAsync(); var obj = Order(p => { p.Code = "SELF"; p.Note = "v1"; }); var id = await Redb.SaveAsync(obj); obj.Props.Note = "v2"; await Redb.SaveAsync(obj); var loaded = await Redb.LoadAsync(id, depth: 1); loaded!.Props.Note.Should().Be("v2"); loaded.Props.Code.Should().Be("SELF", "an object never conflicts with itself"); } [Fact] public async Task KeyChange_OnUpdate_ReleasesOldValue_AndGuardsNew() { await SyncAllAsync(); var obj = Order(p => { p.Code = "K-OLD"; p.Note = "v1"; }); await Redb.SaveAsync(obj); obj.Props.Code = "K-NEW"; await Redb.SaveAsync(obj); // The stored key is the hash of the CURRENT value: the lookup recomputes the hash from // the value it is given, so a hit proves the stored key and the encoder agree. (await Redb.GetByUniqueAsync(p => p.Code, "K-NEW"))!.id.Should().Be(obj.id); (await Redb.GetByUniqueAsync(p => p.Code, "K-OLD")).Should().BeNull( "the old value's key is gone with the value"); var takeNew = async () => await Redb.SaveAsync(Order(p => p.Code = "K-NEW")); await takeNew.Should().ThrowAsync("the new value is guarded"); (await Redb.SaveAsync(Order(p => p.Code = "K-OLD"))).Should().BeGreaterThan(0, "the old value is free for the next claimant"); } [Fact] public async Task NullToValue_OnUpdate_KeysFollowTheValues() { // The scenario of the 2026-09-10 MSSQL report: objects created with a NULL key get their // values later, one update each. Every update must store the hash OF ITS VALUE - if the // written key is not a function of the value, the second update collides with the first // as a false duplicate. await SyncAllAsync(); var a = Order(p => p.Note = "late-a"); var b = Order(p => p.Note = "late-b"); await Redb.SaveAsync(a); await Redb.SaveAsync(b); a.Props.Code = "LATE-A"; await Redb.SaveAsync(a); b.Props.Code = "LATE-B"; var actB = async () => await Redb.SaveAsync(b); await actB.Should().NotThrowAsync("different values are different keys, never a duplicate"); (await Redb.GetByUniqueAsync(p => p.Code, "LATE-A"))!.id.Should().Be(a.id); (await Redb.GetByUniqueAsync(p => p.Code, "LATE-B"))!.id.Should().Be(b.id); var dup = async () => await Redb.SaveAsync(Order(p => p.Code = "LATE-A")); await dup.Should().ThrowAsync("the late-written keys are live"); } [Fact] public async Task NullToValue_OnQueryLoadedObjects_KeysFollowTheValues() { // The exact shape of a mirror backfill (Identity V4, MSSQL report 2026-09-10): the value // lives in _objects._value_string, the [RedbUnique] prop is NULL, the object comes back // through the QUERY pipeline (with its change-tracking snapshot), the key is copied in and // the object re-saved one at a time. Every save must store the hash of its own value. await SyncAllAsync(); var a = Order(p => p.Note = "mirror-a"); a.value_string = "MIR-A"; var b = Order(p => p.Note = "mirror-b"); b.value_string = "MIR-B"; await Redb.SaveAsync(a); await Redb.SaveAsync(b); var candidates = await Redb.Query() .WhereRedb(o => o.ValueString != null) .ToListAsync(); candidates.Should().HaveCount(2); foreach (var obj in candidates.OrderBy(o => o.Id)) { obj.Props.Code = obj.value_string; var act = async () => await Redb.SaveAsync(obj); await act.Should().NotThrowAsync( $"'{obj.value_string}' is this object's own value, not a duplicate of a neighbour"); } (await Redb.GetByUniqueAsync(p => p.Code, "MIR-A"))!.id.Should().Be(a.id); (await Redb.GetByUniqueAsync(p => p.Code, "MIR-B"))!.id.Should().Be(b.id); } [Fact] public async Task NullToValue_OnHashIdenticalObjects_LoadedByOneQuery_KeysFollowTheValues() { // The 2026-09-10 MSSQL Pro report, second round - the discriminating shape: the objects // are BYTE-IDENTICAL in Props (all empty, one content hash for all of them, exactly what // legacy backfill candidates look like), they come back through ONE query, and the // [RedbUnique] prop is set and saved object by object in one scope. The observed defect: // from the second object on, the written key is the FIRST object's hash - a false // duplicate - while hash-distinct objects (the other NullToValue pins) pass. await SyncAllAsync(); var mirrors = new[] { "HID-A", "HID-B", "HID-C" }; foreach (var mirror in mirrors) { // The SAME Note everywhere: identical Props content, identical content hash. var obj = Order(p => p.Note = "hash-identical"); obj.value_string = mirror; await Redb.SaveAsync(obj); } var candidates = (await Redb.Query() .WhereRedb(o => o.ValueString != null) .ToListAsync()) .Where(o => o.value_string!.StartsWith("HID-")) .OrderBy(o => o.Id) .ToList(); candidates.Should().HaveCount(3); foreach (var obj in candidates) { obj.Props.Code = obj.value_string; var act = async () => await Redb.SaveAsync(obj); await act.Should().NotThrowAsync( $"'{obj.value_string}' is this object's own value, not a duplicate of a hash-identical neighbour"); } foreach (var (mirror, i) in mirrors.Select((m, i) => (m, i))) (await Redb.GetByUniqueAsync(p => p.Code, mirror))!.id .Should().Be(candidates[i].id, "each stored key is the hash of its own object's value"); } [Fact] public async Task AfterALegitimateDuplicateFailure_TheNextSaveIsClean() { // The 2026-09-10 MSSQL report, round 3 (the concurrency one) - distilled to its // deterministic core, no concurrency needed: a save that fails on a LEGITIMATE // duplicate must not poison the saves that follow in the same scope. The failed // save's insert rows (carrying ITS unique hash) must die with the failure - a later // save of an unrelated object that gets rejected with the FAILED value's hash while // its own Props are intact is exactly the "foreign hash" from the report. await SyncAllAsync(); await Redb.SaveAsync(Order(p => { p.Code = "LEAK-DUP"; p.Note = "holder"; })); // An UPDATE transition into the taken value: the insert-change of the diff carries // hash(LEAK-DUP) and fails on the index - legitimately. var loser = Order(p => p.Note = "loser"); await Redb.SaveAsync(loser); loser.Props.Code = "LEAK-DUP"; var legit = async () => await Redb.SaveAsync(loser); await legit.Should().ThrowAsync("the value is genuinely taken"); // An unrelated object with its OWN value, same scope: must save cleanly. var clean = Order(p => p.Note = "clean"); await Redb.SaveAsync(clean); clean.Props.Code = "LEAK-CLEAN"; var act = async () => await Redb.SaveAsync(clean); await act.Should().NotThrowAsync( "a failed save's pending rows must not leak into the next save of the scope"); (await Redb.GetByUniqueAsync(p => p.Code, "LEAK-CLEAN"))!.id .Should().Be(clean.id, "the clean object holds the key of its own value"); } [Fact] public async Task NullToValue_OnBatchUpdate_EachKeyFollowsItsValue() { // Same transition as NullToValue_OnUpdate_KeysFollowTheValues, but the updates ride ONE // batch save - the shape of a backfill job. Each row must get the hash of ITS OWN value; // a key computed from a neighbour's value surfaces as a false duplicate inside the batch. await SyncAllAsync(); var objects = Enumerable.Range(1, 5) .Select(i => Order(p => p.Note = $"late-{i}")) .ToList(); await Redb.SaveAsync(objects.Cast().ToList()); for (var i = 0; i < objects.Count; i++) objects[i].Props.Code = $"BATCH-{i + 1}"; var act = async () => await Redb.SaveAsync(objects.Cast().ToList()); await act.Should().NotThrowAsync("five different values are five different keys"); foreach (var obj in objects) (await Redb.GetByUniqueAsync(p => p.Code, obj.Props.Code))!.id.Should().Be(obj.id, "the stored key must be the hash of this object's value"); } [Fact] public async Task KeySwap_InOneBatchSave() { await SyncAllAsync(); var a = Order(p => p.Code = "SWAP-A"); var b = Order(p => p.Code = "SWAP-B"); await Redb.SaveAsync(new[] { a, b }.Cast().ToList()); a.Props.Code = "SWAP-B"; b.Props.Code = "SWAP-A"; var act = async () => await Redb.SaveAsync(new[] { a, b }.Cast().ToList()); if (KeySwapMustPass) { await act.Should().NotThrowAsync( "under DeleteInsert all deletes run before all inserts, so an in-batch swap is legal"); (await Redb.LoadAsync(a.id, depth: 1))!.Props.Code.Should().Be("SWAP-B"); } else { // §4.6: under ChangeTracking the in-place update can hit the index mid-way. The boundary // is a typed error, never silent corruption. try { await act(); (await Redb.LoadAsync(a.id, depth: 1))!.Props.Code.Should().Be("SWAP-B"); } catch (RedbUniqueViolationException) { // documented boundary - and the batch is one transaction: nothing half-written (await Redb.LoadAsync(a.id, depth: 1))!.Props.Code.Should().Be("SWAP-A"); (await Redb.LoadAsync(b.id, depth: 1))!.Props.Code.Should().Be("SWAP-B"); } } } // ============================================================ // === canonical form, end to end === // ============================================================ [Fact] public async Task CanonicalForm_DecimalTrailingZeros_AreOneKey() { await SyncAllAsync(); await Redb.SaveAsync(Order(p => p.Amount = 1.50m)); var act = async () => await Redb.SaveAsync(Order(p => p.Amount = 1.5m)); await act.Should().ThrowAsync("1.50 and 1.5 are one number"); } [Fact] public async Task CanonicalForm_SameInstantDifferentOffset_IsOneKey() { await SyncAllAsync(); await Redb.SaveAsync(Order(p => p.IssuedAt = new DateTimeOffset(2026, 8, 31, 12, 0, 0, TimeSpan.FromHours(3)))); var act = async () => await Redb.SaveAsync(Order(p => p.IssuedAt = new DateTimeOffset(2026, 8, 31, 9, 0, 0, TimeSpan.Zero))); await act.Should().ThrowAsync("12:00+03:00 and 09:00Z are one moment"); } [Fact] public async Task CanonicalForm_NfcNfd_AreOneKey_CaseIsNot() { await SyncAllAsync(); const string nfc = "caf\u00e9"; // e-acute, one code point const string nfdCode = "cafe\u0301"; // e + combining acute, two code points nfdCode.Should().NotBe(nfc, "the staged literals must really be two spellings"); await Redb.SaveAsync(Order(p => p.Code = nfc)); var nfd = async () => await Redb.SaveAsync(Order(p => p.Code = nfdCode)); await nfd.Should().ThrowAsync("NFC and NFD spell one string"); var otherCase = await Redb.SaveAsync(Order(p => p.Code = "CAFÉ")); otherCase.Should().BeGreaterThan(0, "no case folding: the application owns the notion of its key"); } [Fact] public async Task ByteArrayKey_MegabytePayload_Works() { await SyncAllAsync(); var payload = new byte[1 << 20]; for (var i = 0; i < payload.Length; i++) payload[i] = (byte)(i % 251); await Redb.SaveAsync(Order(p => p.Fingerprint = payload)); var same = (byte[])payload.Clone(); var dup = async () => await Redb.SaveAsync(Order(p => p.Fingerprint = same)); await dup.Should().ThrowAsync( "dedup by content is the ordinary byte[] key scenario (plan decision 4)"); var different = (byte[])payload.Clone(); different[^1] ^= 0xFF; (await Redb.SaveAsync(Order(p => p.Fingerprint = different))).Should().BeGreaterThan(0); } [Fact] public async Task ByteArrayProp_IsStoredAsSingleScalarRow() { await SyncAllAsync(); var payload = new byte[] { 1, 2, 3, 250, 251, 252, 0, 255 }; var id = await Redb.SaveAsync(Order(p => p.Fingerprint = payload)); var loaded = await Redb.LoadAsync(id, depth: 1); loaded!.Props.Fingerprint.Should().BeEquivalentTo(payload, "byte[] rides the JSON projection as base64 on every builder"); var structureId = await StructureIdAsync("UniqueOrder", "Fingerprint"); (await Redb.Context.ExecuteScalarAsync( $"SELECT COUNT(*) FROM _values WHERE _id_structure = {structureId} AND _id_object = {id}")) .Should().Be(1, "Б1: one scalar row, not a base row plus a row per byte"); (await Redb.Context.ExecuteScalarAsync( $"SELECT COUNT(*) FROM _values WHERE _id_structure = {structureId} AND _id_object = {id} AND _ByteArray IS NOT NULL")) .Should().Be(1); } [Fact] public async Task LegacyByteArrayLayout_IsConvertedOnSync() { await SyncAllAsync(); var payload = new byte[] { 10, 20, 30, 40, 200 }; var id = await Redb.SaveAsync(Order(p => p.Fingerprint = payload)); var structureId = await StructureIdAsync("UniqueOrder", "Fingerprint"); // Stage the pre-V4 layout by hand: structure Array-of-Byte, base row with a hash in _Guid, // one element row per byte in _Long. Exactly what an old build left behind. var ctx = Redb.Context; await StageLegacyByteLayoutAsync(structureId, id, payload); // The next synchronisation must convert in place - self-healing, no manual step. await Redb.SyncSchemeAsync(); (await ctx.ExecuteScalarAsync( $"SELECT COUNT(*) FROM _values WHERE _id_structure = {structureId} AND _id_object = {id}")) .Should().Be(1, "element rows are gone, one scalar row remains"); var loaded = await Redb.LoadAsync(id, depth: 1); loaded!.Props.Fingerprint.Should().BeEquivalentTo(payload, "the bytes were reassembled in index order"); } [Fact] public async Task ByteArrayNestedInClass_RoundTrips() { await Redb.SyncSchemeAsync(); var data = new byte[] { 9, 8, 7, 6 }; var id = await Redb.SaveAsync(new RedbObject { name = "holder", Props = new ByteHolderProps { Root = new byte[] { 1 }, File = new ByteAttachment { Name = "f", Data = data } } }); var loaded = await Redb.LoadAsync(id, depth: 1); loaded!.Props.File.Should().NotBeNull(); loaded.Props.File!.Name.Should().Be("f"); loaded.Props.File.Data.Should().BeEquivalentTo(data, "Б1: a byte[] inside a nested class is the same scalar as at the root"); } [Fact] public async Task LegacyByteArrayLayout_NestedInClass_IsConvertedWithoutLoss() { await Redb.SyncSchemeAsync(); var root = new byte[] { 1, 2, 3 }; var data = new byte[] { 9, 8, 7, 6 }; var id = await Redb.SaveAsync(new RedbObject { name = "holder", Props = new ByteHolderProps { Root = root, File = new ByteAttachment { Name = "f", Data = data } } }); var rootStructure = await StructureIdAsync("ByteHolder", "Root"); var dataStructure = await StructureIdAsync("ByteHolder", "Data"); // Both byte[] in the old shape. The nested one keeps what a class member always has: its // base row points at the class row (_array_parent_id) and carries a pseudo index. await StageLegacyByteLayoutAsync(rootStructure, id, root); await StageLegacyByteLayoutAsync(dataStructure, id, data); await Redb.SyncSchemeAsync(); var ctx = Redb.Context; (await ctx.ExecuteScalarAsync( $"SELECT COUNT(*) FROM _values WHERE _id_structure = {rootStructure} AND _id_object = {id}")) .Should().Be(1); (await ctx.ExecuteScalarAsync( $"SELECT COUNT(*) FROM _values WHERE _id_structure = {dataStructure} AND _id_object = {id}")) .Should().Be(1, "the nested base row is a base row, not an element row of the class"); var loaded = await Redb.LoadAsync(id, depth: 1); loaded!.Props.Root.Should().BeEquivalentTo(root); loaded.Props.File.Should().NotBeNull(); loaded.Props.File!.Name.Should().Be("f"); loaded.Props.File.Data.Should().BeEquivalentTo(data, "a byte[] nested in a class is told apart by membership, not by a NULL parent"); } [Fact] public async Task LegacyByteArrayLayout_AlreadyAssembledRow_IsNotBlankedByARetry() { await Redb.SyncSchemeAsync(); var root = new byte[] { 5, 4, 3, 2, 1 }; var id = await Redb.SaveAsync(new RedbObject { name = "holder", Props = new ByteHolderProps { Root = root } }); var structureId = await StructureIdAsync("ByteHolder", "Root"); // The state a crash between the element delete and the type flip leaves behind, and the // state a second node sees after the first one finished: bytes already in _ByteArray, no // element rows, the structure still Array-of-Byte. Nothing to assemble; keep the payload. var ctx = Redb.Context; await ctx.ExecuteAsync( $"UPDATE _structures SET _id_type = {redb.Core.Utils.RedbTypeIds.Byte}, " + $"_collection_type = {redb.Core.Utils.RedbTypeIds.Array} WHERE _id = {structureId}"); await Redb.SyncSchemeAsync(); var loaded = await Redb.LoadAsync(id, depth: 1); loaded!.Props.Root.Should().BeEquivalentTo(root, "a retry over an already converted row must recognise it, not overwrite it with an empty payload"); } /// /// Turns the scalar row of one object into the pre-V4 Array-of-Byte layout: _ByteArray cleared, /// one element row per byte (_Long, _array_parent_id = base row, _array_index = position), and /// the structure retyped to Byte/Array. The base row keeps its own _array_parent_id, so a byte[] /// nested in a class stays attached to its class row exactly as an old build left it. /// private async Task StageLegacyByteLayoutAsync(long structureId, long objectId, byte[] payload) { var ctx = Redb.Context; var baseRowId = (await ctx.ExecuteScalarAsync( $"SELECT _id FROM _values WHERE _id_structure = {structureId} AND _id_object = {objectId}"))!.Value; await ctx.ExecuteAsync($"UPDATE _values SET _ByteArray = NULL WHERE _id = {baseRowId}"); for (var i = 0; i < payload.Length; i++) { var elementId = await ctx.Keys.NextValueIdAsync(); await ctx.ExecuteAsync( $"INSERT INTO _values (_id, _id_structure, _id_object, _Long, _array_parent_id, _array_index) " + $"VALUES ({elementId}, {structureId}, {objectId}, {payload[i]}, {baseRowId}, '{i}')"); } await ctx.ExecuteAsync( $"UPDATE _structures SET _id_type = {redb.Core.Utils.RedbTypeIds.Byte}, " + $"_collection_type = {redb.Core.Utils.RedbTypeIds.Array} WHERE _id = {structureId}"); } // ============================================================ // === soft delete releases keys (decision 9) === // ============================================================ [Fact] public async Task SoftDelete_ReleasesKey_RepeatedDelete() { await SyncAllAsync(); var first = Order(p => p.Code = "DEL-1"); await Redb.SaveAsync(first); await Redb.SoftDeleteAsync(new[] { first.id }); (await Redb.Context.ExecuteScalarAsync($"SELECT _id_scheme FROM _objects WHERE _id = {first.id}")) .Should().Be(-10, "soft delete moves the object to the trash scheme"); (await Redb.Context.ExecuteScalarAsync( $"SELECT COUNT(*) FROM _values WHERE _id_object = {first.id} AND _unique IS NOT NULL")) .Should().Be(0, "decision 9: the trash holds no keys - mark_for_deletion nulls them in the same statement"); var second = Order(p => p.Code = "DEL-1"); await Redb.SaveAsync(second); await Redb.SoftDeleteAsync(new[] { second.id }); (await Redb.Context.ExecuteScalarAsync($"SELECT _id_scheme FROM _objects WHERE _id = {second.id}")) .Should().Be(-10, "without key release the trash scheme is one more uniqueness namespace and the second delete dies"); } [Fact] public async Task SoftDelete_ReleasesKey_CrossScheme() { await SyncAllAsync(); var order = Order(p => p.Code = "CROSS"); await Redb.SaveAsync(order); var invoice = new RedbObject { name = "invoice", Props = new UniqueInvoiceProps { Code = "CROSS" } }; await Redb.SaveAsync(invoice); await Redb.SoftDeleteAsync(new[] { order.id }); await Redb.SoftDeleteAsync(new[] { invoice.id }); // both land in scheme -10; released keys cannot collide there (await Redb.Context.ExecuteScalarAsync( $"SELECT COUNT(*) FROM _objects WHERE _id IN ({order.id}, {invoice.id}) AND _id_scheme = -10")) .Should().Be(2); (await Redb.SaveAsync(Order(p => p.Code = "CROSS"))).Should().BeGreaterThan(0, "a key released by deletion is immediately available"); } // ============================================================ // === recompute (2.8) and the SQL-writer rule (P3) === // ============================================================ [Fact] public async Task SqlWriterDamage_IsReportedAndHealed_ByRecompute() { await SyncAllAsync(); var winner = Order(p => p.Code = "P1"); var winnerId = await Redb.SaveAsync(winner); var victim = Order(p => p.Code = $"TMP-{Guid.NewGuid():N}"); var victimId = await Redb.SaveAsync(victim); // A SQL-side writer that does not know the canonical form: value overwritten, key released. var structureId = await StructureIdAsync("UniqueOrder", "Code"); await Redb.Context.ExecuteAsync( $"UPDATE _values SET _String = 'P1', _unique = NULL WHERE _id_object = {victimId} AND _id_structure = {structureId}"); var report = await Redb.RecomputeUniqueAsync("Code"); report.HasDuplicates.Should().BeTrue(); report.Duplicates.Should().ContainSingle().Which.ObjectIds.Should().BeEquivalentTo([winnerId, victimId]); report.LosingRows.Should().Be(1); // The winner (lowest value id - saved first) holds the key; the loser is outside the index. (await Redb.GetByUniqueAsync(p => p.Code, "P1"))!.id.Should().Be(winnerId); var third = async () => await Redb.SaveAsync(Order(p => p.Code = "P1")); await third.Should().ThrowAsync( "after the recompute the key is enforced for every keyed row"); } [Fact] public async Task EncoderVersionBehind_TriggersRecompute_OnSync() { await SyncAllAsync(); var id = await Redb.SaveAsync(Order(p => { p.Code = "VER-1"; p.Number = 41; })); var codeStructure = await StructureIdAsync("UniqueOrder", "Code"); var numberStructure = await StructureIdAsync("UniqueOrder", "Number"); // A version behind the encoder with keys PRESENT but stale: the Code row carries the key of // the Number row (another structure, so the index does not object). The "unhashed rows" // self-heal sees nothing here - only the version trigger can repair it. await Redb.Context.ExecuteAsync( $"UPDATE _values SET _unique = (SELECT _unique FROM _values WHERE _id_structure = {numberStructure} AND _id_object = {id}) " + $"WHERE _id_structure = {codeStructure} AND _id_object = {id}"); await Redb.Context.ExecuteAsync($"UPDATE _structures SET _unique_version = 0 WHERE _id = {codeStructure}"); await Redb.SyncSchemeAsync(); (await Redb.Context.ExecuteScalarAsync($"SELECT _unique_version FROM _structures WHERE _id = {codeStructure}")) .Should().Be(UniqueKeyEncoder.Version, "the structure is stamped with the encoder version after the recompute"); (await Redb.GetByUniqueAsync(p => p.Code, "VER-1"))!.id.Should().Be(id, "a version stamp behind the encoder recomputes every key of the structure at synchronisation"); } [Fact] public async Task RemovingTheAttribute_ClearsFlagAndKeys() { await SyncAllAsync(); // Stage a scheme whose CLR class has NO attribute but whose database state says "key": // exactly what a deploy of a class with the attribute removed looks like. The staged key is // real: the same value in UniqueOrder.Code has the same canonical form, so its hash is // borrowed (keys are unique per structure, the index does not object). var free = new RedbObject { name = "free", Props = new UniqueFreeProps { Code = "F-1" } }; var freeId = await Redb.SaveAsync(free); var orderId = await Redb.SaveAsync(Order(p => p.Code = "F-1")); var structureId = await StructureIdAsync("UniqueFree", "Code"); var orderStructure = await StructureIdAsync("UniqueOrder", "Code"); await Redb.Context.ExecuteAsync( $"UPDATE _values SET _unique = (SELECT _unique FROM _values WHERE _id_structure = {orderStructure} AND _id_object = {orderId}) " + $"WHERE _id_structure = {structureId} AND _id_object = {freeId}"); await Redb.Context.ExecuteAsync( $"UPDATE _structures SET _unique = {BoolTrue}, _unique_version = 1 WHERE _id = {structureId}"); (await Redb.Context.ExecuteScalarAsync( $"SELECT COUNT(*) FROM _values WHERE _id_structure = {structureId} AND _unique IS NOT NULL")) .Should().Be(1, "the staging must plant a real key"); await Redb.SyncSchemeAsync(); (await Redb.Context.ExecuteScalarAsync($"SELECT _unique FROM _structures WHERE _id = {structureId}")) .Should().NotBe(true, "no attribute - no flag"); (await Redb.Context.ExecuteScalarAsync($"SELECT _unique_version FROM _structures WHERE _id = {structureId}")) .Should().BeNull("no attribute - no encoder version"); (await Redb.Context.ExecuteScalarAsync( $"SELECT COUNT(*) FROM _values WHERE _id_structure = {structureId} AND _unique IS NOT NULL")) .Should().Be(0, "a key that no longer guards anything must not keep rejecting values"); // And duplicates are legal again. var duplicateId = await Redb.SaveAsync(new RedbObject { name = "free2", Props = new UniqueFreeProps { Code = "F-1" } }); duplicateId.Should().BeGreaterThan(0); } [Fact] public async Task SchemeWithoutKeys_IsUntouched() { await SyncAllAsync(); await Redb.SaveAsync(new RedbObject { name = "a", Props = new UniqueFreeProps { Code = "DUP" } }); await Redb.SaveAsync(new RedbObject { name = "b", Props = new UniqueFreeProps { Code = "DUP" } }); (await Redb.Context.ExecuteScalarAsync( "SELECT COUNT(*) FROM _values WHERE _unique IS NOT NULL AND _id_structure IN " + "(SELECT _id FROM _structures WHERE _id_scheme = (SELECT _id FROM _schemes WHERE _name = 'UniqueFree'))")) .Should().Be(0); } // ============================================================ // === lookup API and bulk alignment === // ============================================================ [Fact] public async Task GetByUnique_FindsMisses_AndRejectsNonKey() { await SyncAllAsync(); var id = await Redb.SaveAsync(Order(p => { p.Code = "ORD-9"; p.Note = "target"; })); var found = await Redb.GetByUniqueAsync(p => p.Code, "ORD-9"); found!.id.Should().Be(id); found.Props.Note.Should().Be("target"); (await Redb.GetByUniqueAsync(p => p.Code, "NO-SUCH")).Should().BeNull(); (await Redb.GetByUniqueAsync(p => p.Code, null)).Should().BeNull( "NULL never takes part in uniqueness"); var nonKey = async () => await Redb.GetByUniqueAsync(p => p.Note, "x"); await nonKey.Should().ThrowAsync(); } [Fact] public async Task BatchOfHundreds_InsertAndUpdate_KeepColumnsAligned() { await SyncAllAsync(); // 200 objects x 3 filled fields crosses every bulk chunk boundary (MSSQL MERGE packs 140 // rows of 14 columns per statement - the exact place where a miscounted offset writes // values into the wrong columns without any exception, §4.7). var objects = Enumerable.Range(1, 200) .Select(i => Order(p => { p.Code = $"B-{i:D3}"; p.Number = 1000 + i; p.Note = $"n{i}"; })) .Cast() .ToList(); var ids = await Redb.SaveAsync(objects); ids.Should().HaveCount(200); foreach (var obj in objects.Cast>()) obj.Props.Note = obj.Props.Note + "+"; await Redb.SaveAsync(objects); foreach (var probe in new[] { 0, 99, 199 }) { var loaded = await Redb.LoadAsync(ids[probe], depth: 1); loaded!.Props.Code.Should().Be($"B-{probe + 1:D3}"); loaded.Props.Number.Should().Be(1000 + probe + 1); loaded.Props.Note.Should().Be($"n{probe + 1}+"); } var dup = async () => await Redb.SaveAsync(Order(p => p.Code = "B-100")); await dup.Should().ThrowAsync("the batch-written keys are live"); } // ============================================================ // === S2: keys on scalars inside nested classes === // ============================================================ private static RedbObject Nested(string? passport, string? title = null) => new() { name = "nested", Props = new UniqueNestedProps { Title = title ?? "t", Identity = passport == null ? null : new NestedIdentity { Passport = passport, Issuer = "MVD" } } }; [Fact] public async Task NestedKey_SchemeSync_SetsTheFlag() { await Redb.SyncSchemeAsync(); var flagged = await Redb.Context.ExecuteScalarAsync( $"SELECT COUNT(*) FROM _structures WHERE _name = 'Passport' AND _unique = {BoolTrue} AND _id_parent = " + "(SELECT _id FROM _structures WHERE _name = 'Identity' AND _id_scheme = " + "(SELECT _id FROM _schemes WHERE _name = 'UniqueNested'))"); flagged.Should().Be(1, "a [RedbUnique] scalar inside a nested class (collection-free path) is a legal key (S2)"); } [Fact] public async Task NestedKey_Duplicate_IsRejected_WithTypedException() { await Redb.SyncSchemeAsync(); await Redb.SaveAsync(Nested("P-100")); var act = async () => await Redb.SaveAsync(Nested("P-100")); var ex = (await act.Should().ThrowAsync( "the nested field's rows carry their own structure id, the same index enforces them")).Which; if (ReportsKeyTuple) ex.PropertyName.Should().Be("Passport"); } [Fact] public async Task NestedKey_Nulls_Coexist() { await Redb.SyncSchemeAsync(); await Redb.SaveAsync(Nested(null, "no identity a")); await Redb.SaveAsync(Nested(null, "no identity b")); var nullPassportA = Nested("x"); nullPassportA.Props.Identity!.Passport = null; var nullPassportB = Nested("x"); nullPassportB.Props.Identity!.Passport = null; await Redb.SaveAsync(nullPassportA); await Redb.SaveAsync(nullPassportB); var count = await Redb.Query().CountAsync(); count.Should().Be(4, "a NULL nested class and a NULL key both claim nothing"); } [Fact] public async Task NestedKey_KeyChange_OnUpdate_ReleasesOldValue_AndGuardsNew() { await Redb.SyncSchemeAsync(); var firstId = await Redb.SaveAsync(Nested("P-OLD")); var loaded = await Redb.LoadAsync(firstId, depth: 2); loaded!.Props.Identity!.Passport = "P-NEW"; await Redb.SaveAsync(loaded); await Redb.SaveAsync(Nested("P-OLD", "successor of the released value")); var act = async () => await Redb.SaveAsync(Nested("P-NEW")); await act.Should().ThrowAsync("the moved key guards its new value"); } [Fact] public async Task NestedKey_GetByUnique_FindsByPath() { await Redb.SyncSchemeAsync(); var id = await Redb.SaveAsync(Nested("P-LOOKUP", "the one")); var byLambda = await Redb.GetByUniqueAsync(p => p.Identity!.Passport, "P-LOOKUP"); byLambda.Should().NotBeNull("the lambda path walks the nested structure chain"); byLambda!.Id.Should().Be(id); byLambda.Props.Title.Should().Be("the one"); var byName = await Redb.GetByUniqueAsync("Identity.Passport", "P-LOOKUP"); byName!.Id.Should().Be(id); } [Fact] public async Task NestedKey_SoftDelete_ReleasesKey() { await Redb.SyncSchemeAsync(); var id = await Redb.SaveAsync(Nested("P-TRASH")); await Redb.DeleteAsync(id); var successorId = await Redb.SaveAsync(Nested("P-TRASH", "successor")); successorId.Should().BeGreaterThan(0, "the trash does not squat on nested keys either"); } [Fact] public async Task NestedKey_Recompute_RestoresKeys_AfterSqlWipe() { await Redb.SyncSchemeAsync(); await Redb.SaveAsync(Nested("P-R1")); await Redb.SaveAsync(Nested("P-R2")); // A SQL-side writer wiped the keys: rows with a value but no key are exactly the // recompute trigger's trace, and the explicit recompute must repair a NESTED structure. await Redb.Context.ExecuteAsync( "UPDATE _values SET _unique = NULL WHERE _id_structure = " + "(SELECT _id FROM _structures WHERE _name = 'Passport' AND _id_parent = " + "(SELECT _id FROM _structures WHERE _name = 'Identity' AND _id_scheme = " + "(SELECT _id FROM _schemes WHERE _name = 'UniqueNested')))"); var report = await Redb.RecomputeUniqueAsync("Identity.Passport"); report.HashedRows.Should().Be(2, "both stored passports get their keys back"); var act = async () => await Redb.SaveAsync(Nested("P-R1")); await act.Should().ThrowAsync("the restored keys are live again"); } [Fact] public async Task NestedKey_NullToValue_OnUpdate_ClaimsKey() { await Redb.SyncSchemeAsync(); var holder = Nested("x"); holder.Props.Identity!.Passport = null; var id = await Redb.SaveAsync(holder); var loaded = await Redb.LoadAsync(id, depth: 2); loaded!.Props.Identity!.Passport = "P-CLAIMED"; await Redb.SaveAsync(loaded); var act = async () => await Redb.SaveAsync(Nested("P-CLAIMED")); await act.Should().ThrowAsync( "a key claimed by a null-to-value UPDATE transition must be live"); } [Fact] public async Task NestedKey_ClassAppears_OnUpdate_ClaimsKey() { await Redb.SyncSchemeAsync(); var id = await Redb.SaveAsync(Nested(null, "class appears later")); // The whole nested class materialises on UPDATE - its rows go through the insert // channel of the save strategy, which must fill the key exactly like a fresh save. var loaded = await Redb.LoadAsync(id, depth: 2); loaded!.Props.Identity = new NestedIdentity { Passport = "P-BORN", Issuer = "MVD" }; await Redb.SaveAsync(loaded); var act = async () => await Redb.SaveAsync(Nested("P-BORN")); await act.Should().ThrowAsync( "a key of a nested class that appeared on update must be live"); } [Fact] public async Task NestedKey_TwoLevelsDeep_Enforces_AndResolvesPath() { await Redb.SyncSchemeAsync(); var deep = new RedbObject { name = "deep", Props = new UniqueDeepProps { Outer = new DeepOuter { Inner = new DeepInner { Code = "D-1" } } } }; var id = await Redb.SaveAsync(deep); var act = async () => await Redb.SaveAsync(new RedbObject { name = "deep-dup", Props = new UniqueDeepProps { Outer = new DeepOuter { Inner = new DeepInner { Code = "D-1" } } } }); await act.Should().ThrowAsync("the machinery is depth-agnostic"); var found = await Redb.GetByUniqueAsync(p => p.Outer!.Inner!.Code, "D-1"); found!.Id.Should().Be(id); } [Fact] public async Task NestedKey_BatchSave_EnforcesKeys() { await Redb.SyncSchemeAsync(); var batch = new[] { Nested("B-1"), Nested("B-2"), Nested("B-3") } .Cast().ToList(); (await Redb.SaveAsync(batch)).Should().HaveCount(3); var dupAgainstStored = async () => await Redb.SaveAsync(Nested("B-2")); await dupAgainstStored.Should().ThrowAsync( "batch-written nested keys are live"); var dupInsideBatch = async () => await Redb.SaveAsync( new[] { Nested("B-4"), Nested("B-4") }.Cast().ToList()); await dupInsideBatch.Should().ThrowAsync( "two claimants of one key inside a single batch must not both land"); } [Fact] public async Task NestedKey_GetByUnique_WrongPath_Throws() { await Redb.SyncSchemeAsync(); var act = async () => await Redb.GetByUniqueAsync("Identity.Nope", "x"); await act.Should().ThrowAsync( "a wrong path must name the missing segment, not return null as if the key were free"); } // ============================================================ // === S1: subtree keys - the whole nested class / collection content === // ============================================================ private static RedbObject Subtree(Action set) { var props = new UniqueSubtreeProps(); set(props); return new RedbObject { name = "subtree", Props = props }; } [Fact] public async Task SubtreeKey_SchemeSync_SetsTheFlag_OnClassArrayAndDictionary() { await Redb.SyncSchemeAsync(); var flagged = await Redb.Context.ExecuteScalarAsync( $"SELECT COUNT(*) FROM _structures WHERE _unique = {BoolTrue} AND _id_parent IS NULL " + "AND _name IN ('Config', 'Slots', 'Limits') AND _id_scheme = " + "(SELECT _id FROM _schemes WHERE _name = 'UniqueSubtree')"); flagged.Should().Be(3, "a root class, array and dictionary are all legal subtree keys (S1)"); } [Fact] public async Task SubtreeKey_Class_DuplicateContentRejected() { await Redb.SyncSchemeAsync(); await Redb.SaveAsync(Subtree(p => p.Config = new SubtreeConfig { Region = "eu", Tier = 2 })); await Redb.SaveAsync(Subtree(p => p.Config = new SubtreeConfig { Region = "eu", Tier = 3 })); var act = async () => await Redb.SaveAsync(Subtree(p => p.Config = new SubtreeConfig { Region = "eu", Tier = 2 })); await act.Should().ThrowAsync( "two objects with byte-for-byte equal subtree CONTENT are the duplicate; different content is not"); } [Fact] public async Task SubtreeKey_Dictionary_IsOrderInsensitive() { await Redb.SyncSchemeAsync(); await Redb.SaveAsync(Subtree(p => p.Limits = new Dictionary { ["a"] = 1, ["b"] = 2 })); var act = async () => await Redb.SaveAsync(Subtree(p => p.Limits = new Dictionary { ["b"] = 2, ["a"] = 1 })); await act.Should().ThrowAsync( "a dictionary is an unordered set of pairs: {a:1,b:2} IS {b:2,a:1}"); } [Fact] public async Task SubtreeKey_Array_OrderMatters() { await Redb.SyncSchemeAsync(); await Redb.SaveAsync(Subtree(p => p.Slots = [1, 2, 3])); await Redb.SaveAsync(Subtree(p => p.Slots = [3, 2, 1])); var act = async () => await Redb.SaveAsync(Subtree(p => p.Slots = [1, 2, 3])); await act.Should().ThrowAsync( "a list is ordered: [1,2,3] equals only [1,2,3]"); } [Fact] public async Task SubtreeKey_NullSubtrees_Coexist() { await Redb.SyncSchemeAsync(); await Redb.SaveAsync(Subtree(p => p.Note = "empty a")); await Redb.SaveAsync(Subtree(p => p.Note = "empty b")); (await Redb.Query().CountAsync()).Should().Be(2, "an absent subtree claims no key"); } [Fact] public async Task SubtreeKey_GetByUnique_ByObjectValue() { await Redb.SyncSchemeAsync(); var id = await Redb.SaveAsync(Subtree(p => { p.Config = new SubtreeConfig { Region = "apac", Tier = 7 }; p.Note = "the one"; })); var found = await Redb.GetByUniqueAsync( p => p.Config, new SubtreeConfig { Region = "apac", Tier = 7 }); found.Should().NotBeNull("the probe canonicalises the object value the same way the save did"); found!.Id.Should().Be(id); found.Props.Note.Should().Be("the one"); } [Fact] public async Task SubtreeKey_ContentEdit_MovesKey() { await Redb.SyncSchemeAsync(); var id = await Redb.SaveAsync(Subtree(p => p.Config = new SubtreeConfig { Region = "us", Tier = 1 })); var loaded = await Redb.LoadAsync(id, depth: 2); loaded!.Props.Config!.Tier = 9; await Redb.SaveAsync(loaded); await Redb.SaveAsync(Subtree(p => p.Config = new SubtreeConfig { Region = "us", Tier = 1 })); var act = async () => await Redb.SaveAsync(Subtree(p => p.Config = new SubtreeConfig { Region = "us", Tier = 9 })); await act.Should().ThrowAsync( "an edited subtree releases its old content key and guards the new one"); } // ============================================================ // === S3: element keys on collections - [RedbUnique(Scope = ...)] === // ============================================================ private static RedbObject Elems(Action set) { var props = new UniqueElementsProps(); set(props); return new RedbObject { name = "elems", Props = props }; } [Fact] public async Task ElemKey_ScopeOnScalar_IsRejectedAtSync() { var act = async () => await Redb.SyncSchemeAsync(); await act.Should().ThrowAsync( "Scope on a scalar is meaningless - the bare attribute already carries the strongest reading"); } [Fact] public async Task ElemKey_Collection_DuplicateInsideOneCollection_Rejected() { await Redb.SyncSchemeAsync(); var act = async () => await Redb.SaveAsync(Elems(p => p.Codes = ["A", "B", "A"])); await act.Should().ThrowAsync( "Collection scope means no duplicate elements INSIDE one collection"); } [Fact] public async Task ElemKey_Collection_SameValueInTwoObjects_Coexists() { await Redb.SyncSchemeAsync(); await Redb.SaveAsync(Elems(p => p.Codes = ["A", "B"])); var id = await Redb.SaveAsync(Elems(p => p.Codes = ["A", "C"])); id.Should().BeGreaterThan(0, "Collection scope is per collection: different objects may repeat each other freely"); } [Fact] public async Task ElemKey_Scheme_ValueUniqueAcrossObjects() { await Redb.SyncSchemeAsync(); await Redb.SaveAsync(Elems(p => p.Emails = ["a@x.io", "b@x.io"])); var act = async () => await Redb.SaveAsync(Elems(p => p.Emails = ["a@x.io"])); await act.Should().ThrowAsync( "Scheme scope: an element value appears once across every object of the scheme"); (await Redb.SaveAsync(Elems(p => p.Emails = ["c@x.io"]))).Should().BeGreaterThan(0); } [Fact] public async Task ElemKey_Scheme_DuplicateInsideOneCollection_AlsoRejected() { await Redb.SyncSchemeAsync(); var act = async () => await Redb.SaveAsync(Elems(p => p.Emails = ["dup@x.io", "dup@x.io"])); await act.Should().ThrowAsync( "scheme-wide uniqueness subsumes uniqueness inside one collection"); } [Fact] public async Task ElemKey_Refs_Collection_NoDuplicateLinks() { await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); var target = new RedbObject { name = "target", Props = new UniqueFreeProps { Code = "T" } }; await Redb.SaveAsync(target); var holder = Elems(p => p.Note = "links"); holder.Props.Links = [target, target]; var act = async () => await Redb.SaveAsync(holder); await act.Should().ThrowAsync( "a reference element canonicalises by target id: no duplicate links in one collection"); } [Fact] public async Task ElemKey_NullAndEmpty_Coexist() { await Redb.SyncSchemeAsync(); await Redb.SaveAsync(Elems(p => p.Note = "null lists a")); await Redb.SaveAsync(Elems(p => p.Note = "null lists b")); await Redb.SaveAsync(Elems(p => p.Codes = [])); await Redb.SaveAsync(Elems(p => p.Codes = [])); (await Redb.Query().CountAsync()).Should().Be(4, "neither an absent nor an empty collection claims element keys"); } [Fact] public async Task ElemKey_CT_AddedDuplicateOnUpdate_Rejected() { await Redb.SyncSchemeAsync(); var id = await Redb.SaveAsync(Elems(p => p.Codes = ["A", "B"])); var loaded = await Redb.LoadAsync(id, depth: 2); loaded!.Props.Codes!.Add("A"); var act = async () => await Redb.SaveAsync(loaded); await act.Should().ThrowAsync( "an element added on UPDATE goes through the insert channel and must be keyed the same way"); } [Fact] public async Task ElemKey_GetByUnique_SchemeScope_FindsTheHolder() { await Redb.SyncSchemeAsync(); var id = await Redb.SaveAsync(Elems(p => { p.Emails = ["find@x.io"]; p.Note = "holder"; })); var found = await Redb.GetByUniqueAsync(p => p.Emails, "find@x.io"); found.Should().NotBeNull("a scheme-scoped element key is globally probeable by the element value"); found!.Id.Should().Be(id); } [Fact] public async Task ElemKey_GetByUnique_CollectionScope_IsRejected() { await Redb.SyncSchemeAsync(); var act = async () => await Redb.GetByUniqueAsync(p => p.Codes, "A"); await act.Should().ThrowAsync( "a collection-scoped key is unique only within its collection - a global by-value probe has no meaning"); } [Fact] public async Task ElemKey_Recompute_RestoresKeys_AfterSqlWipe() { await Redb.SyncSchemeAsync(); await Redb.SaveAsync(Elems(p => p.Emails = ["r1@x.io"])); await Redb.SaveAsync(Elems(p => p.Emails = ["r2@x.io"])); await Redb.Context.ExecuteAsync( "UPDATE _values SET _unique = NULL WHERE _id_structure = " + "(SELECT _id FROM _structures WHERE _name = 'Emails' AND _id_scheme = " + "(SELECT _id FROM _schemes WHERE _name = 'UniqueElems'))"); var report = await Redb.RecomputeUniqueAsync("Emails"); report.HashedRows.Should().Be(2, "both stored element values get their keys back"); var act = async () => await Redb.SaveAsync(Elems(p => p.Emails = ["r1@x.io"])); await act.Should().ThrowAsync("the restored element keys are live"); } [Fact] public async Task KeyInsideCollectionElement_IsRejectedAtSync() { var act = async () => await Redb.SyncSchemeAsync(); await act.Should().ThrowAsync( "every element of every object shares one structure, so a key inside a collection " + "element would degenerate to one value across the whole database"); } } Path: redb/redb.Tests.Integration/Tests/Base/UnregisteredTreeTargetTestsBase.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/UnregisteredTreeTargetTestsBase.cs ---- using redb.Core; using redb.Core.Models.Entities; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// WhereHasAncestor / WhereHasDescendant over a type that has no scheme fail at the query, naming the type, as /// Query<T>() fails for it. Pro dropped the filter and returned every node; Free ran into a removed legacy path /// ("Legacy ... SQL path is removed"). /// public abstract class UnregisteredTreeTargetTestsBase { /// A plain class: no [RedbScheme], never synced. public sealed class NotAScheme { public string Name { get; set; } = ""; } protected readonly IRedbService Redb; protected UnregisteredTreeTargetTestsBase(IRedbService redb) => Redb = redb; private async Task SeedRootAsync() { await Redb.SyncSchemeAsync(); var tag = "utt-" + Guid.NewGuid().ToString("N")[..8]; var root = new TreeRedbObject { name = tag, Props = new SimpleProps { Title = tag } }; return await Redb.SaveAsync(root); } [Fact] public async Task WhereHasAncestor_TypeWithoutScheme_FailsNamingTheType() { var root = await SeedRootAsync(); var unrooted = () => Redb.TreeQuery().WhereHasAncestor(a => a.Name == "x"); var rooted = () => Redb.TreeQuery(root).WhereHasAncestor(a => a.Name == "x"); unrooted.Should().Throw().WithMessage("WhereHasAncestor: scheme for type 'NotAScheme' not found*"); rooted.Should().Throw().WithMessage("WhereHasAncestor:*"); } [Fact] public async Task WhereHasDescendant_TypeWithoutScheme_FailsNamingTheType() { var root = await SeedRootAsync(); var unrooted = () => Redb.TreeQuery().WhereHasDescendant(a => a.Name == "x"); var rooted = () => Redb.TreeQuery(root).WhereHasDescendant(a => a.Name == "x"); unrooted.Should().Throw().WithMessage("WhereHasDescendant: scheme for type 'NotAScheme' not found*"); rooted.Should().Throw().WithMessage("WhereHasDescendant:*"); } /// The same type in a plain query fails the same way: same exception type, same words. [Fact] public void Query_TypeWithoutScheme_FailsTheSameWay() { var act = () => Redb.Query(); act.Should().Throw().WithMessage("*for type 'NotAScheme' not found*"); } } Path: redb/redb.Tests.Integration/Tests/Base/UntypedLinkedObjectTestsBase.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/UntypedLinkedObjectTestsBase.cs ---- using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Core; using redb.Core.Extensions; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// The object behind a list item whose scheme has no CLR type loads untyped, through the Free in-database JSON builder. /// The SQLite service sent the PostgreSQL text of that call (::text cast included), which SQLite cannot parse, so /// on Free SQLite such a load never worked. Free hosts only: the Pro answer for an untyped scheme is a separate decision. /// public abstract class UntypedLinkedObjectTestsBase { protected abstract void UseProvider(RedbOptionsBuilder options); private ServiceProvider Build() { var services = new ServiceCollection(); services.AddLogging(b => b.SetMinimumLevel(LogLevel.Warning)); services.AddRedb(options => { UseProvider(options); options.Configure(c => { c.EnablePropsCache = false; c.PreloadListItemLinkedObjects = false; c.CacheDomain = "untyped-linked-object"; }); }); return services.BuildServiceProvider(); } private async Task RunAsync(Func touch) { var tag = Guid.NewGuid().ToString("N")[..8]; await using var sp = Build(); var redb = sp.GetRequiredService(); await redb.InitializeAsync(ensureCreated: true); await redb.SyncSchemeAsync(); await redb.InitializeTypeRegistryAsync(); // An object of a scheme no CLR type maps to: saved typed, then moved to an untyped object scheme. var name = $"untyped-linked-{tag}"; var objectId = await redb.SaveAsync(new RedbObject { name = name, Props = new SimpleProps { Title = "untyped" } }); var untypedScheme = await redb.EnsureObjectSchemeAsync($"untyped_linked_scheme_{tag}"); await redb.Context.ExecuteAsync($"UPDATE _objects SET _id_scheme = {untypedScheme.Id} WHERE _id = {objectId}"); var list = await redb.ListProvider.SaveListAsync(RedbList.Create($"untyped-linked-{tag}", "untyped")); var item = await redb.ListProvider.SaveListItemAsync(new RedbListItem { IdList = list.Id, Value = "untyped", IdObject = objectId }); await using var scope = sp.CreateAsyncScope(); var reader = scope.ServiceProvider.GetRequiredService(); reader.Cache.GetClrType(untypedScheme.Id).Should().BeNull("precondition: no CLR type maps to the scheme"); var handed = await reader.ListProvider.GetListItemAsync(item.Id); handed.Should().NotBeNull(); handed!.IsObjectLoaded.Should().BeFalse("precondition: no preload, the single loader resolves the object"); await touch(handed, objectId, name); } private static void AssertLoaded(IRedbObject? loaded, long objectId, string name) { loaded.Should().NotBeNull("an object of an untyped scheme loads untyped rather than failing"); loaded!.Id.Should().Be(objectId); loaded.Name.Should().Be(name); } [Fact] public Task SyncGetter_SchemeWithoutClrType_LoadsTheLinkedObjectUntyped() => RunAsync((item, objectId, name) => { AssertLoaded(item.Object, objectId, name); return Task.CompletedTask; }); [Fact] public Task AsyncLoad_SchemeWithoutClrType_LoadsTheLinkedObjectUntyped() => RunAsync(async (item, objectId, name) => AssertLoaded(await item.GetObjectAsync(), objectId, name)); } Path: redb/redb.Tests.Integration/Tests/Base/UserConfigurationServiceTestsBase.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/UserConfigurationServiceTestsBase.cs ---- #pragma warning disable CS0618 // implements or uses the deprecated object permissions and roles (RedbDeprecation) using Microsoft.Extensions.DependencyInjection; using redb.Core; using redb.Core.Configuration; using redb.Core.Models.Configuration; using redb.Core.Models.Roles; using redb.Core.Models.Users; namespace redb.Tests.Integration.Tests.Base; /// /// The user configuration service is the core class on every provider and takes its statements from the dialect. /// PostgreSQL and SQLite registered copies of it with the SQL written into them. /// public abstract class UserConfigurationServiceTestsBase { protected readonly IRedbService Redb; private readonly IServiceProvider _services; protected UserConfigurationServiceTestsBase(IRedbService redb, IServiceProvider services) { Redb = redb; _services = services; } [Fact] public void TheRegisteredService_IsTheCoreClass() { using var scope = _services.CreateScope(); scope.ServiceProvider.GetRequiredService().Should().BeOfType(); } /// /// A role configuration and a user configuration merge, the user's over the role's; clearing the user's falls back /// to the role's, clearing the role's falls back further. Writes a configuration id and NULL for both, and reads /// the roles of the user and the users of a role. /// [Fact] public async Task RoleAndUserConfigurations_Merge_AndClearingFallsBack() { using var scope = _services.CreateScope(); var service = scope.ServiceProvider.GetRequiredService(); var tag = Guid.NewGuid().ToString("N")[..10]; var user = await Redb.UserProvider.CreateUserAsync(new CreateUserRequest { Login = "ucfg_" + tag, Name = "ucfg_" + tag, Password = "p-" + tag }); var role = await Redb.RoleProvider.CreateRoleAsync(new CreateRoleRequest { Name = "ucfg-role-" + tag }); (await Redb.RoleProvider.AssignUserToRoleAsync(user, role)).Should().BeTrue(); var roleConfig = await service.CreateConfigurationAsync("ucfg-role-" + tag, new UserConfigurationProps { MaxBatchSize = 111, MaxLoadDepth = 7 }); var userConfig = await service.CreateConfigurationAsync("ucfg-user-" + tag, new UserConfigurationProps { MaxBatchSize = 222 }); await service.SetRoleConfigurationAsync(role.Id, roleConfig.id); await service.SetUserConfigurationAsync(user.Id, userConfig.id); var both = await service.GetEffectiveConfigurationAsync(user.Id); both.MaxBatchSize.Should().Be(222, "the user's configuration wins over the role's"); both.MaxLoadDepth.Should().Be(7, "the role's configuration fills what the user's leaves out"); await service.SetUserConfigurationAsync(user.Id, null); var roleOnly = await service.GetEffectiveConfigurationAsync(user.Id); roleOnly.MaxBatchSize.Should().Be(111, "with the user's cleared, the role's applies"); await service.SetRoleConfigurationAsync(role.Id, null); var neither = await service.GetEffectiveConfigurationAsync(user.Id); neither.MaxLoadDepth.Should().NotBe(7, "the role's configuration is cleared and the cache of its users dropped"); } [Fact] public async Task SetConfiguration_OfAnUnknownUserOrRole_Throws() { using var scope = _services.CreateScope(); var service = scope.ServiceProvider.GetRequiredService(); await service.Invoking(s => s.SetUserConfigurationAsync(long.MaxValue - 7, null)).Should().ThrowAsync(); await service.Invoking(s => s.SetRoleConfigurationAsync(long.MaxValue - 7, null)).Should().ThrowAsync(); } } Path: redb/redb.Tests.Integration/Tests/Base/ValueOnlyObjectSaveTestsBase.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/ValueOnlyObjectSaveTestsBase.cs ---- using redb.Core; using redb.Core.Models.Entities; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// An object without Props - a scheme with no properties, or an object saved with Props = null - is a loaded /// object like any other: it lives in its base fields (Identity report REPORT-CORE-UNLOADED-REFERENCE-PROPSLESS-SCHEME, /// 2026-09-17). Hydration never called the Props setter for it, so the "loaded" flag stayed down and the save's /// refusal of unloaded references (fbf4e9f1) took every such object for a reference. What redb materializes as a /// root is loaded by definition; a reference is a stub redb attached a lazy loader to. /// public abstract class ValueOnlyObjectSaveTestsBase { protected readonly IRedbService Redb; protected ValueOnlyObjectSaveTestsBase(IRedbService redb) => Redb = redb; private static string NewTag() => Guid.NewGuid().ToString("N")[..8]; [Fact] public async Task AnObjectOfASchemeWithoutProperties_LoadsAsLoaded_AndSavesAgain() { await Redb.SyncSchemeAsync(); var tag = NewTag(); var id = await Redb.SaveAsync(new RedbObject { name = $"flag-{tag}", Props = new ValueOnlyProps() }); var loaded = (await Redb.LoadAsync(id))!; loaded.IsPropsLoaded.Should().BeTrue("what redb materialized as a root is loaded, Props or no Props"); loaded.name = $"flag-{tag}-renamed"; await Redb.SaveAsync(loaded); (await Redb.LoadAsync(id))!.name.Should().Be($"flag-{tag}-renamed"); } [Fact] public async Task AnObjectOfASchemeWithoutProperties_FromAQuery_SavesAgain() { await Redb.SyncSchemeAsync(); var tag = NewTag(); var id = await Redb.SaveAsync(new RedbObject { name = $"queried-{tag}", Props = new ValueOnlyProps() }); var queried = (await Redb.Query().ToListAsync()).Single(o => o.id == id); queried.IsPropsLoaded.Should().BeTrue(); queried.name = $"queried-{tag}-renamed"; await Redb.SaveAsync(queried); (await Redb.LoadAsync(id))!.name.Should().Be($"queried-{tag}-renamed"); } [Fact] public async Task AnObjectSavedWithNullProps_LoadsAsLoaded_AndSavesAgain() { await Redb.SyncSchemeAsync(); var tag = NewTag(); var id = await Redb.SaveAsync(new RedbObject { name = $"nullprops-{tag}", Props = null! }); var loaded = (await Redb.LoadAsync(id))!; loaded.IsPropsLoaded.Should().BeTrue("Props may be null on a loaded object"); loaded.name = $"nullprops-{tag}-renamed"; await Redb.SaveAsync(loaded); (await Redb.LoadAsync(id))!.name.Should().Be($"nullprops-{tag}-renamed"); } } Path: redb/redb.Tests.Integration/Tests/Base/ValueUniqueTestsBase.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/ValueUniqueTestsBase.cs ---- using Microsoft.Extensions.DependencyInjection; using redb.Core; using redb.Core.Exceptions; using redb.Core.Models.Entities; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// The object key contract (V4, UNIQUE stage 1): _objects._value_unique is an ordinary /// readable base field the application fills itself — like _value_string, plus the partial /// unique index over (_id_scheme, _value_unique). Full radius by decision: the column rides /// JSON projections, LINQ over base fields, sorting/prefix search — not just a dedicated lookup. /// /// /// Comparison semantics are each database's own (closed question of 2026-08-26): no trimming, no /// case folding by redb. The 440-character limit is enforced in C#, because SQLite checks no /// VARCHAR lengths and the same key must be accepted or rejected identically everywhere. /// /// public abstract class ValueUniqueTestsBase : IAsyncLifetime { protected readonly IRedbService Redb; protected readonly IServiceProvider Services; protected ValueUniqueTestsBase(IRedbService redb, IServiceProvider services) { Redb = redb; Services = services; } private static readonly string[] Schemes = ["UniqueOrder", "UniqueInvoice"]; public async Task InitializeAsync() { foreach (var scheme in Schemes) await ResetSchemeObjectsAsync(scheme); } public async Task DisposeAsync() { foreach (var scheme in Schemes) await ResetSchemeObjectsAsync(scheme); } /// Objects only: the schemes themselves are shared with the stage-2 suite. private async Task ResetSchemeObjectsAsync(string schemeName) { await Redb.Context.ExecuteAsync( $"DELETE FROM _objects WHERE _id_scheme IN (SELECT _id FROM _schemes WHERE _name = '{schemeName}')"); } private async Task SyncAsync() { await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); } private static RedbObject Order(string? key, string note = "n") => new() { name = "vu-order", ValueUnique = key, Props = new UniqueOrderProps { Note = note } }; /// SQLite's driver names only columns in a unique violation - no key tuple, so the /// violated structure/property is not resolved there (the Kind still classifies). protected virtual bool DriverReportsViolatedStructure => true; [Fact] public async Task UniqueViolation_OnTheObjectKey_IsClassifiedAsObjectKey() { // BR-8 (Tsak report, 2026-09-02): callers used to discriminate indexes by matching // provider-specific constraint-name strings. Kind is the first-class answer. await SyncAsync(); var key = $"VU-KIND-{Guid.NewGuid():N}"; await Redb.SaveAsync(Order(key)); var act = async () => await Redb.SaveAsync(Order(key, "loser")); (await act.Should().ThrowAsync()) .Which.Kind.Should().Be(RedbUniqueViolationKind.ObjectKey); } [Fact] public async Task UniqueViolation_OnARedbUniqueProperty_IsClassifiedAsProperty_AndNeverRetriedByTheUpsert() { // The other half of BR-8: a [RedbUnique] FIELD collision inside SaveByUniqueAsync used to // ride the object-key catch (re-resolve by ValueUnique, rethrow) - Tsak's api-key rotation // fell exactly there. Property violations surface directly, classified. await SyncAsync(); var code = $"VU-CODE-{Guid.NewGuid():N}"; await Redb.SaveAsync(new RedbObject { name = "vu-a", ValueUnique = $"VU-A-{Guid.NewGuid():N}", Props = new UniqueOrderProps { Code = code } }); var dup = new RedbObject { name = "vu-b", ValueUnique = $"VU-B-{Guid.NewGuid():N}", Props = new UniqueOrderProps { Code = code } }; var act = async () => await Redb.SaveByUniqueAsync(dup); var uve = (await act.Should().ThrowAsync( "a property collision is not the object key's business and must surface")).Which; uve.Kind.Should().Be(RedbUniqueViolationKind.Property); if (DriverReportsViolatedStructure) { uve.PropertyName.Should().Be("Code"); uve.SchemeName.Should().NotBeNullOrEmpty(); } } // ============================================================ // === the field behaves like _value_string === // ============================================================ [Fact] public async Task Key_RoundTrips_ThroughSaveAndLoad() { await SyncAsync(); var obj = Order("ORD-2026-0001"); var id = await Redb.SaveAsync(obj); var loaded = await Redb.LoadAsync(id, depth: 1); loaded!.ValueUnique.Should().Be("ORD-2026-0001", "the key is a readable base field and rides the JSON projection on every provider"); loaded.ValueUnique = "ORD-2026-0002"; await Redb.SaveAsync(loaded); (await Redb.LoadAsync(id, depth: 1))!.ValueUnique.Should().Be("ORD-2026-0002"); } [Fact] public async Task DuplicateKey_InOneScheme_IsRejected_Typed() { await SyncAsync(); await Redb.SaveAsync(Order("DUP-1")); var act = async () => await Redb.SaveAsync(Order("DUP-1", "second")); var ex = (await act.Should().ThrowAsync()).Which; ex.Cause.Should().NotBeNull(); } [Fact] public async Task SameKey_InDifferentSchemes_IsAllowed() { await SyncAsync(); await Redb.SaveAsync(Order("SHARED-KEY")); var invoice = new RedbObject { name = "vu-invoice", ValueUnique = "SHARED-KEY", Props = new UniqueInvoiceProps { Note = "inv" } }; (await Redb.SaveAsync(invoice)).Should().BeGreaterThan(0, "_id_scheme is part of the index key: independent domains may share business identifiers"); } [Fact] public async Task MultipleNullKeys_AreAllowed() { await SyncAsync(); for (var i = 0; i < 3; i++) await Redb.SaveAsync(Order(null, $"free-{i}")); (await Redb.Context.ExecuteScalarAsync( "SELECT COUNT(*) FROM _objects WHERE _id_scheme = (SELECT _id FROM _schemes WHERE _name = 'UniqueOrder')")) .Should().Be(3); } [Fact] public async Task KeyLongerThan440_IsRejectedInCSharp_OnEveryProvider() { await SyncAsync(); var tooLong = new string('K', 441); var act = async () => await Redb.SaveAsync(Order(tooLong)); await act.Should().ThrowAsync( "SQLite does not check VARCHAR lengths, so without the C# guard the same key would pass " + "there and fail on PostgreSQL and MSSQL"); (await Redb.SaveAsync(Order(new string('K', 440)))).Should().BeGreaterThan(0, "440 exactly fits"); } [Fact] public async Task DuplicateInsideCallerTransaction_LeavesTheTransactionAlive() { // Bug report п.2 (2026-09-02): on PostgreSQL a caught unique violation used to leave the // CALLER's transaction aborted (25P02) - every follow-up statement of a catch-and-recover // pattern died. The batch now runs under a savepoint inside a foreign transaction. await SyncAsync(); await Redb.SaveAsync(Order("TX-DUP")); long recoveredId = 0; await Redb.Context.ExecuteAtomicAsync(async () => { var act = async () => await Redb.SaveAsync(Order("TX-DUP", "loser")); await act.Should().ThrowAsync(); // The whole point: the transaction is still usable after the typed error. (await Redb.Context.ExecuteScalarAsync("SELECT 1")).Should().Be(1, "the caller's transaction must survive a caught unique violation"); recoveredId = await Redb.SaveAsync(Order("TX-RECOVERED", "winner")); recoveredId.Should().BeGreaterThan(0); }); (await Redb.LoadAsync(recoveredId, depth: 1))!.ValueUnique.Should().Be("TX-RECOVERED", "work done after the recovery commits with the transaction"); } [Fact] public async Task ValueStringLongerThan450_IsRejectedInCSharp_OnEveryProvider() { // Owner decision 2026-09-02: _value_string is an identifier column - 450 is the MSSQL // index-key width, enforced in C# so the text-typed PostgreSQL and SQLite columns hold // the same contract. Long text belongs in _note or in a Props field. await SyncAsync(); var act = async () => await Redb.SaveAsync(new RedbObject { name = "vs-long", ValueString = new string('S', 451), Props = new UniqueOrderProps() }); await act.Should().ThrowAsync(); (await Redb.SaveAsync(new RedbObject { name = "vs-fit", ValueString = new string('S', 450), Props = new UniqueOrderProps() })).Should().BeGreaterThan(0, "450 exactly fits"); } [Fact] public async Task ChangingTheKey_MovesTheObjectHash() { // Reversal of P5 (full-object-hash plan, 2026-09-11): _hash covers the header, the key // included - a key change on another node must invalidate the cached copy. await SyncAsync(); var obj = Order("H-1"); var id = await Redb.SaveAsync(obj); var hashBefore = (await Redb.LoadAsync(id, depth: 1))!.hash; var loaded = await Redb.LoadAsync(id, depth: 1); loaded!.ValueUnique = "H-2"; await Redb.SaveAsync(loaded); (await Redb.LoadAsync(id, depth: 1))!.hash.Should().NotBe(hashBefore!.Value, "the object key is header content: _hash must move with it, or the props cache serves the old key"); } // ============================================================ // === query surface === // ============================================================ [Fact] public async Task WhereRedb_ByKey_Works_EqualityAndPrefix() { await SyncAsync(); var a = await Redb.SaveAsync(Order("ORD-2026-0001")); await Redb.SaveAsync(Order("ORD-2026-0002")); await Redb.SaveAsync(Order("INV-2026-0001")); var exact = await Redb.Query() .WhereRedb(o => o.ValueUnique == "ORD-2026-0001") .ToListAsync(); exact.Should().ContainSingle().Which.id.Should().Be(a); var prefix = await Redb.Query() .WhereRedb(o => o.ValueUnique!.StartsWith("ORD-2026")) .ToListAsync(); prefix.Should().HaveCount(2, "a readable string key keeps prefix search - the reason it is a string"); } // ============================================================ // === soft delete releases the key (decision 9) === // ============================================================ [Fact] public async Task SoftDelete_ReleasesObjectKey_RepeatedAndCross() { await SyncAsync(); var first = Order("DEL-K"); await Redb.SaveAsync(first); await Redb.SoftDeleteAsync(new[] { first.id }); (await Redb.Context.ExecuteScalarAsync($"SELECT _value_unique FROM _objects WHERE _id = {first.id}")) .Should().BeNull("decision 9: the trash holds no keys - mark_for_deletion nulls the key as it moves the row"); (await Redb.Context.ExecuteScalarAsync($"SELECT _id_scheme FROM _objects WHERE _id = {first.id}")) .Should().Be(-10); var second = Order("DEL-K"); await Redb.SaveAsync(second); await Redb.SoftDeleteAsync(new[] { second.id }); // the trash is one more point of the same index; without the release the second delete dies var order = Order("CROSS-K"); await Redb.SaveAsync(order); var invoice = new RedbObject { name = "vu-invoice", ValueUnique = "CROSS-K", Props = new UniqueInvoiceProps() }; await Redb.SaveAsync(invoice); await Redb.SoftDeleteAsync(new[] { order.id }); await Redb.SoftDeleteAsync(new[] { invoice.id }); (await Redb.SaveAsync(Order("DEL-K"))).Should().BeGreaterThan(0, "a released key is immediately reusable"); } // ============================================================ // === in-batch key exchange (P7) === // ============================================================ [Fact] public async Task KeySwap_InOneBatchSave_Passes() { await SyncAsync(); var a = Order("SW-A"); var b = Order("SW-B"); await Redb.SaveAsync(new[] { a, b }.Cast().ToList()); a.ValueUnique = "SW-B"; b.ValueUnique = "SW-A"; await Redb.SaveAsync(new[] { a, b }.Cast().ToList()); (await Redb.LoadAsync(a.id, depth: 1))!.ValueUnique.Should().Be("SW-B", "P7: the batch releases every key it is about to retake before the row updates run"); (await Redb.LoadAsync(b.id, depth: 1))!.ValueUnique.Should().Be("SW-A"); } [Fact] public async Task KeyHandover_InOneBatch_GiverGoesNull_TakerGetsIt() { await SyncAsync(); var a = Order("HO-J"); var b = Order("HO-K"); await Redb.SaveAsync(new[] { a, b }.Cast().ToList()); // A takes the key B gives up, A first in the list: the taker is written before the giver. a.ValueUnique = "HO-K"; b.ValueUnique = null; await Redb.SaveAsync(new[] { a, b }.Cast().ToList()); (await Redb.LoadAsync(a.id, depth: 1))!.ValueUnique.Should().Be("HO-K", "P7 releases the keys of every existing object in the batch, not only of those taking one"); (await Redb.LoadAsync(b.id, depth: 1))!.ValueUnique.Should().BeNull(); } // ============================================================ // === upsert by key (P1) === // ============================================================ [Fact] public async Task SaveByUnique_InsertsThenUpdatesTheSameRow() { await SyncAsync(); var first = Order("UP-1", "v1"); var id1 = await Redb.SaveByUniqueAsync(first); id1.Should().BeGreaterThan(0); var second = Order("UP-1", "v2"); var id2 = await Redb.SaveByUniqueAsync(second); id2.Should().Be(id1, "the key resolves to the same row; the accept is idempotent"); var loaded = await Redb.LoadAsync(id1, depth: 1); loaded!.Props.Note.Should().Be("v2", "last writer's content"); (await Redb.Context.ExecuteScalarAsync( "SELECT COUNT(*) FROM _objects WHERE _value_unique = 'UP-1' AND _id_scheme = " + "(SELECT _id FROM _schemes WHERE _name = 'UniqueOrder')")) .Should().Be(1); } /// /// An object built in memory (as from JSON: no dates) and saved onto an existing row came back /// with DateCreate and DateModify 0001-01-01, while a reload showed the stored dates. After a /// save the object carries what its row holds: on insert both dates, on update the stored /// creation date and the new modification date. /// [Fact] public async Task SaveByUnique_TheSavedObjectCarriesTheStoredDates_OnInsertAndUpdate() { await SyncAsync(); var key = $"UP-DATES-{Guid.NewGuid():N}"; var first = Order(key, "v1"); var id = await Redb.SaveByUniqueAsync(first); var stored = (await Redb.LoadAsync(id, depth: 1))!; first.DateCreate.Should().BeCloseTo(stored.DateCreate, TimeSpan.FromMilliseconds(1)); first.DateModify.Should().BeCloseTo(stored.DateModify, TimeSpan.FromMilliseconds(1)); var second = Order(key, "v2"); second.DateCreate.Should().Be(default, "the case is an object without dates, as deserialized from JSON"); (await Redb.SaveByUniqueAsync(second)).Should().Be(id); var reloaded = (await Redb.LoadAsync(id, depth: 1))!; reloaded.DateCreate.Should().Be(stored.DateCreate, "an update keeps the creation date of the row"); second.DateCreate.Should().Be(reloaded.DateCreate); second.DateModify.Should().BeCloseTo(reloaded.DateModify, TimeSpan.FromMilliseconds(1)); second.DateModify.Should().BeOnOrAfter(stored.DateModify); } [Fact] public async Task SaveByUnique_WithoutKey_IsRefused() { await SyncAsync(); var act = async () => await Redb.SaveByUniqueAsync(Order(null)); await act.Should().ThrowAsync(); } /// /// The race SaveByUniqueAsync is built for: two callers, each with its own scoped service and connection, upsert one /// key at once. Both answer with the same object and the key has one row: the loser of the creation race retries /// onto the winner's row. Several rounds, so the interleavings vary. /// [Fact] public async Task ConcurrentSaveByUnique_FromTwoScopes_ConvergesOnOneObject() { await SyncAsync(); for (var round = 0; round < 20; round++) { var key = $"RACE-{round}-{Guid.NewGuid():N}"; var ids = await Task.WhenAll(SaveInOwnScope(key, "c1"), SaveInOwnScope(key, "c2")); ids[1].Should().Be(ids[0], "both callers upsert the one object of the key"); (await RowsOfKeyAsync(key)).Should().Be(1, "one key - one object"); } async Task SaveInOwnScope(string key, string note) { await using var scope = Services.CreateAsyncScope(); return await scope.ServiceProvider.GetRequiredService().SaveByUniqueAsync(Order(key, note)); } } /// /// One service instance is one connection and is not for two threads: a second command entered while the first /// runs is refused (CommandGate). SaveByUniqueAsync is several commands, so the refused caller may interleave /// between the commands of the other and break it too: both may fail. What holds however it interleaves: the key /// has at most one row, and an id returned is an object that is stored. /// [Fact] public async Task ConcurrentSaveByUnique_OnOneInstance_LeavesAtMostOneObject() { await SyncAsync(); var key = $"RACE-ONE-{Guid.NewGuid():N}"; var results = await Task.WhenAll(Try("c1"), Try("c2")); var rows = await RowsOfKeyAsync(key); rows.Should().BeLessThanOrEqualTo(1, "however the race interleaves, one key - one object"); if (results.Any(r => r.Id.HasValue)) rows.Should().Be(1, "an id returned is an object that is stored"); async Task<(long? Id, Exception? Error)> Try(string note) { try { return (await Redb.SaveByUniqueAsync(Order(key, note)), null); } catch (Exception ex) { return (null, ex); } } } private Task RowsOfKeyAsync(string key) => Redb.Context.ExecuteScalarAsync( $"SELECT COUNT(*) FROM _objects WHERE _value_unique = '{key}' AND _id_scheme = " + "(SELECT _id FROM _schemes WHERE _name = 'UniqueOrder')"); } Path: redb/redb.Tests.Integration/Tests/Base/ValuesFkIndexesTestsBase.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/ValuesFkIndexesTestsBase.cs ---- using redb.Core; namespace redb.Tests.Integration.Tests.Base; /// /// Schema-delivery pin for the FK-column indexes of _values (perf finding, 2026-09-10): /// _values._Object and _values._ListItem carry foreign keys, and without a leading /// index every DELETE of a referenced object or list item scans the whole table to check for /// referencing rows (measured on ~8.4M rows: SQLite 1.5-5.5s, PostgreSQL 5.9s, MSSQL 6.5-7s per /// check - milliseconds with the indexes, which stay nearly empty thanks to the partial form). /// /// The pin asserts DELIVERY, not just DDL: both a fresh database and an existing one upgraded /// through the provider's versioned mechanism (PG/MSSQL: pvt module version + block 0; /// SQLite: PRAGMA user_version + ApplySchemaUpgradesAsync) must end up with both indexes. /// public abstract class ValuesFkIndexesTestsBase { protected readonly IRedbService Redb; protected ValuesFkIndexesTestsBase(IRedbService redb) => Redb = redb; /// Provider-specific catalog probe: does an index with this exact name exist? protected abstract Task IndexExistsAsync(string indexName); [Theory] [InlineData("IX__values__ListItem_not_null")] [InlineData("IX__values__Object_not_null")] public async Task FkIndex_IsDelivered_ByInitialize(string indexName) { // Idempotent on a current database; on a database behind the schema version it applies // the upgrade pass - exactly the path an existing installation takes on package update. await Redb.InitializeAsync(); (await IndexExistsAsync(indexName)).Should().BeTrue( $"{indexName} must exist after InitializeAsync - without it every DELETE of a " + "referenced row scans the whole _values table for the FK check"); } } Path: redb/redb.Tests.Integration/Tests/Base/WhereTestsBase.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/WhereTestsBase.cs ---- using redb.Core; using redb.Core.Models.Entities; using redb.Core.Query.Aggregation; using redb.Tests.Integration.Helpers; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; public abstract class WhereTestsBase { protected readonly IRedbService Redb; private bool _seeded; private List _seededIds = new(); protected WhereTestsBase(IRedbService redb) => Redb = redb; protected async Task EnsureSeededAsync() { if (_seeded) return; _seededIds = await TestDataFactory.SeedEmployees(Redb, 20); _seeded = true; } [Fact] public async Task Where_EqualString_Filters() { await EnsureSeededAsync(); var results = await Redb.Query() .Where(e => e.Position == "Senior Developer") .Take(20) .ToListAsync(); results.Should().NotBeEmpty(); results.Should().AllSatisfy(r => r.Props.Position.Should().Be("Senior Developer")); } [Fact] public async Task Where_EqualInt_Filters() { await EnsureSeededAsync(); var results = await Redb.Query() .Where(e => e.Age > 30) .Take(20) .ToListAsync(); results.Should().NotBeEmpty(); results.Should().AllSatisfy(r => r.Props.Age.Should().BeGreaterThan(30)); } [Fact] public async Task Where_And_CombinesConditions() { await EnsureSeededAsync(); var results = await Redb.Query() .Where(e => e.Salary > 50000m && e.IsRemote) .Take(20) .ToListAsync(); results.Should().AllSatisfy(r => { r.Props.Salary.Should().BeGreaterThan(50000m); r.Props.IsRemote.Should().BeTrue(); }); } [Fact] public async Task Where_Or_CombinesConditions() { await EnsureSeededAsync(); var results = await Redb.Query() .Where(e => e.Department == "Engineering" || e.Department == "Marketing") .Take(20) .ToListAsync(); results.Should().NotBeEmpty(); results.Should().AllSatisfy(r => r.Props.Department.Should().BeOneOf("Engineering", "Marketing")); } [Fact] public async Task Where_Not_InvertsCondition() { await EnsureSeededAsync(); var all = await Redb.Query().CountAsync(); var notRemote = await Redb.Query() .Where(e => !e.IsRemote) .CountAsync(); var remote = await Redb.Query() .Where(e => e.IsRemote) .CountAsync(); (remote + notRemote).Should().Be(all); } [Fact] public async Task Where_GreaterThan_Decimal() { await EnsureSeededAsync(); var results = await Redb.Query() .Where(e => e.Salary >= 80000m) .Take(20) .ToListAsync(); results.Should().AllSatisfy(r => r.Props.Salary.Should().BeGreaterThanOrEqualTo(80000m)); } [Fact] public async Task Where_LessThan_Int() { await EnsureSeededAsync(); var results = await Redb.Query() .Where(e => e.Age < 30) .Take(20) .ToListAsync(); results.Should().AllSatisfy(r => r.Props.Age.Should().BeLessThan(30)); } [Fact] public async Task Where_Range_BetweenValues() { await EnsureSeededAsync(); var results = await Redb.Query() .Where(e => e.Salary >= 50000m && e.Salary <= 90000m) .Take(20) .ToListAsync(); results.Should().NotBeEmpty(); results.Should().AllSatisfy(r => { r.Props.Salary.Should().BeGreaterThanOrEqualTo(50000m); r.Props.Salary.Should().BeLessThanOrEqualTo(90000m); }); } [Fact] public async Task Where_ChainedFilters_Accumulate() { await EnsureSeededAsync(); var results = await Redb.Query() .Where(e => e.Age > 25) .Where(e => e.IsRemote) .Take(20) .ToListAsync(); results.Should().AllSatisfy(r => { r.Props.Age.Should().BeGreaterThan(25); r.Props.IsRemote.Should().BeTrue(); }); } [Fact] public async Task Where_DateTime_Comparison() { await EnsureSeededAsync(); var cutoff = new DateTime(2020, 6, 1, 0, 0, 0, DateTimeKind.Utc); var results = await Redb.Query() .Where(e => e.HireDate > cutoff) .Take(20) .ToListAsync(); results.Should().NotBeEmpty(); results.Should().AllSatisfy(r => r.Props.HireDate.Should().BeAfter(cutoff)); } [Fact] public async Task Where_StringContains_Filters() { await EnsureSeededAsync(); var results = await Redb.Query() .Where(e => e.Position.Contains("Developer")) .Take(20) .ToListAsync(); results.Should().NotBeEmpty(); results.Should().AllSatisfy(r => r.Props.Position.Should().Contain("Developer")); } [Fact] public async Task Where_StringStartsWith_Filters() { await EnsureSeededAsync(); var results = await Redb.Query() .Where(e => e.Position.StartsWith("Senior")) .Take(20) .ToListAsync(); results.Should().AllSatisfy(r => r.Props.Position.Should().StartWith("Senior")); } [Fact] public async Task Where_BoolField_True() { await EnsureSeededAsync(); var results = await Redb.Query() .Where(e => e.IsRemote) .Take(20) .ToListAsync(); results.Should().NotBeEmpty(); results.Should().AllSatisfy(r => r.Props.IsRemote.Should().BeTrue()); } [Fact] public async Task Where_NestedField_Filters() { await EnsureSeededAsync(); var results = await Redb.Query() .Where(e => e.HomeAddress!.City == "Berlin") .ToListAsync(); results.Should().AllSatisfy(r => r.Props.HomeAddress!.City.Should().Be("Berlin")); } [Fact] public async Task Where_Nullable_IsNull() { var obj = new RedbObject { name = "NullableTest", Props = new EmployeeProps { FirstName = "Null", LastName = "Test", Position = "Temp", Department = "QA", Age = 20, Salary = 30000m, HireDate = DateTime.UtcNow, IsRemote = false, Rating = null } }; obj.id = await Redb.SaveAsync(obj); var results = await Redb.Query() .Where(e => e.Rating == null) .ToListAsync(); results.Should().NotBeEmpty(); results.Should().Contain(r => r.id == obj.id); } [Fact] public async Task CountAsync_ReturnsCorrectCount() { await EnsureSeededAsync(); var count = await Redb.Query().CountAsync(); count.Should().BeGreaterThanOrEqualTo(20); } [Fact] public async Task AnyAsync_WithMatchingCondition_ReturnsTrue() { await EnsureSeededAsync(); var any = await Redb.Query() .Where(e => e.Department == "Engineering") .AnyAsync(); any.Should().BeTrue(); } [Fact] public async Task FirstOrDefaultAsync_ReturnsFirstMatch() { await EnsureSeededAsync(); var first = await Redb.Query() .Where(e => e.Department == "Engineering") .FirstOrDefaultAsync(); first.Should().NotBeNull(); first!.Props.Department.Should().Be("Engineering"); } // ===== WhereRedb: base field ValueString tests ===== private async Task> SeedWithValueString() { var ids = new List(); var entries = new[] { ("alpha-bravo-charlie", "First"), ("delta-echo-foxtrot", "Second"), ("golf-hotel-india", "Third"), ("alpha-juliet-kilo", "Fourth"), ("lima-echo-mike", "Fifth"), }; foreach (var (vs, fn) in entries) { var obj = new RedbObject { value_string = vs, name = $"VS_{fn}", Props = new EmployeeProps { FirstName = fn, LastName = "VSTest", Position = "Developer", Department = "Engineering", Age = 30, Salary = 60000m, HireDate = DateTime.UtcNow, IsRemote = false } }; obj.id = await Redb.SaveAsync(obj); ids.Add(obj.id); } return ids; } [Fact] public async Task WhereRedb_ValueString_Contains_Filters() { var ids = await SeedWithValueString(); var results = await Redb.Query() .WhereRedb(o => o.ValueString!.Contains("echo")) .ToListAsync(); results.Should().NotBeEmpty(); results.Should().OnlyContain(r => r.value_string != null && r.value_string.Contains("echo")); // "delta-echo-foxtrot" and "lima-echo-mike" results.Should().HaveCountGreaterThanOrEqualTo(2); } [Fact] public async Task WhereRedb_ValueString_Equal_Filters() { var ids = await SeedWithValueString(); var results = await Redb.Query() .WhereRedb(o => o.ValueString == "alpha-bravo-charlie") .ToListAsync(); results.Should().NotBeEmpty(); results.Should().OnlyContain(r => r.value_string == "alpha-bravo-charlie"); } [Fact] public async Task WhereRedb_ValueString_StartsWith_Filters() { var ids = await SeedWithValueString(); var results = await Redb.Query() .WhereRedb(o => o.ValueString!.StartsWith("alpha")) .ToListAsync(); results.Should().HaveCountGreaterThanOrEqualTo(2); results.Should().OnlyContain(r => r.value_string != null && r.value_string.StartsWith("alpha")); } [Fact] public async Task WhereRedb_ValueString_CombinedWithPropsFilter() { var ids = await SeedWithValueString(); var results = await Redb.Query() .WhereRedb(o => o.ValueString!.Contains("alpha")) .Where(e => e.LastName == "VSTest") .ToListAsync(); results.Should().NotBeEmpty(); results.Should().OnlyContain(r => r.value_string != null && r.value_string.Contains("alpha") && r.Props.LastName == "VSTest"); } [Fact] public async Task WhereRedb_ValueString_Contains_ThenMultipleWhereProps() { var ids = await SeedWithValueString(); // Reproduces: WhereRedb(ValueString.Contains) + multiple .Where(props) + OrderBy + Count // Bug: Pro query provider puts _value_string in PVT CTE instead of o._value_string var query = Redb.Query() .WhereRedb(o => o.ValueString!.Contains("echo")) .Where(e => e.Department == "Engineering") .Where(e => e.Age == 30) .Where(e => e.IsRemote == false) .Where(e => e.HireDate >= new DateTime(2019, 1, 1, 0, 0, 0, DateTimeKind.Utc)) .OrderBy(e => e.FirstName); // Count must also work (separate SQL path) var count = await query.CountAsync(); count.Should().BeGreaterThanOrEqualTo(0); // ToList var results = await query.ToListAsync(); results.Should().OnlyContain(r => r.value_string != null && r.value_string.Contains("echo") && r.Props.Department == "Engineering" && r.Props.Age == 30); } [Fact] public async Task WhereRedb_ValueString_Contains_ThenWhereProps_CountAsync() { var ids = await SeedWithValueString(); // Minimal repro: WhereRedb(Contains) + one Where(props) → CountAsync var count = await Redb.Query() .WhereRedb(o => o.ValueString!.Contains("echo")) .Where(e => e.Salary > 0m) .CountAsync(); count.Should().BeGreaterThanOrEqualTo(2); } [Fact] public async Task WhereRedb_Name_Contains_Filters() { var ids = await SeedWithValueString(); var results = await Redb.Query() .WhereRedb(o => o.Name.Contains("VS_")) .ToListAsync(); results.Should().NotBeEmpty(); results.Should().OnlyContain(r => r.name != null && r.name.Contains("VS_")); } // ===== WhereRedb: nullable base field .Value / .HasValue tests ===== private bool _nullableSeeded; private long _parentId, _childId, _orphanId; private async Task EnsureNullableSeededAsync() { if (_nullableSeeded) return; // Create parent var parent = new RedbObject { name = "NullableTest_Parent", value_long = 42, key = 100, Props = new EmployeeProps { FirstName = "Parent", LastName = "NullableTest", Position = "Manager", Department = "Engineering", Age = 40, Salary = 100000m, HireDate = DateTime.UtcNow, IsRemote = false } }; parent.id = await Redb.SaveAsync(parent); // Create child with ParentId set var child = new RedbObject { name = "NullableTest_Child", parent_id = parent.id, value_long = 99, key = 200, Props = new EmployeeProps { FirstName = "Child", LastName = "NullableTest", Position = "Developer", Department = "Engineering", Age = 25, Salary = 60000m, HireDate = DateTime.UtcNow, IsRemote = true } }; child.id = await Redb.SaveAsync(child); // Create orphan (no parent, no value_long, no key) var orphan = new RedbObject { name = "NullableTest_Orphan", Props = new EmployeeProps { FirstName = "Orphan", LastName = "NullableTest", Position = "Intern", Department = "Engineering", Age = 20, Salary = 30000m, HireDate = DateTime.UtcNow, IsRemote = false } }; orphan.id = await Redb.SaveAsync(orphan); _parentId = parent.id; _childId = child.id; _orphanId = orphan.id; _nullableSeeded = true; } [Fact] public async Task WhereRedb_ParentId_Value_Equal_Filters() { await EnsureNullableSeededAsync(); // BUG REPRO: o.ParentId.Value used to resolve to o._id instead of o._id_parent var results = await Redb.Query() .WhereRedb(o => o.ParentId.HasValue && o.ParentId.Value == _parentId) .ToListAsync(); results.Should().NotBeEmpty(); results.Should().OnlyContain(r => r.parent_id == _parentId); results.Should().Contain(r => r.id == _childId); } [Fact] public async Task WhereRedb_ParentId_HasValue_Filters() { await EnsureNullableSeededAsync(); var withParent = await Redb.Query() .WhereRedb(o => o.ParentId.HasValue) .Where(e => e.LastName == "NullableTest") .ToListAsync(); withParent.Should().NotBeEmpty(); withParent.Should().OnlyContain(r => r.parent_id.HasValue); withParent.Should().Contain(r => r.id == _childId); withParent.Should().NotContain(r => r.id == _orphanId); } [Fact] public async Task WhereRedb_ParentId_IsNull_Filters() { await EnsureNullableSeededAsync(); var withoutParent = await Redb.Query() .WhereRedb(o => o.ParentId == null) .Where(e => e.LastName == "NullableTest") .ToListAsync(); withoutParent.Should().NotBeEmpty(); withoutParent.Should().OnlyContain(r => !r.parent_id.HasValue); withoutParent.Should().Contain(r => r.id == _parentId); withoutParent.Should().Contain(r => r.id == _orphanId); } [Fact] public async Task WhereRedb_ValueLong_Value_GreaterThan_Filters() { await EnsureNullableSeededAsync(); // parent.value_long = 42, child.value_long = 99, orphan = null var results = await Redb.Query() .WhereRedb(o => o.ValueLong.HasValue && o.ValueLong.Value > 50) .Where(e => e.LastName == "NullableTest") .ToListAsync(); results.Should().NotBeEmpty(); results.Should().OnlyContain(r => r.value_long.HasValue && r.value_long.Value > 50); results.Should().Contain(r => r.id == _childId); // value_long = 99 results.Should().NotContain(r => r.id == _parentId); // value_long = 42 } [Fact] public async Task WhereRedb_Key_Value_Equal_Filters() { await EnsureNullableSeededAsync(); // parent.key = 100, child.key = 200, orphan = null var results = await Redb.Query() .WhereRedb(o => o.Key.HasValue && o.Key.Value == 200) .Where(e => e.LastName == "NullableTest") .ToListAsync(); results.Should().NotBeEmpty(); results.Should().OnlyContain(r => r.key == 200); results.Should().Contain(r => r.id == _childId); } [Fact] public async Task WhereRedb_NullableValue_CombinedWithProps_Filters() { await EnsureNullableSeededAsync(); // Combines nullable .Value base field with props filter var results = await Redb.Query() .WhereRedb(o => o.ParentId.Value == _parentId) .Where(e => e.Department == "Engineering" && e.IsRemote) .ToListAsync(); results.Should().NotBeEmpty(); results.Should().OnlyContain(r => r.parent_id == _parentId); } // ===== Pushdown regression: base predicate + props filter must produce correct results ===== // After perf fix base WhereRedb on _id_parent is pushed INTO the inner _objects subquery // of the PVT CTE (no longer applied as outer WHERE after PVT aggregation). // These tests validate functional equivalence of the new SQL shape. [Fact] public async Task WhereRedb_ParentId_In_Array_Combined_With_Props_Filter() { await EnsureNullableSeededAsync(); // Reproduces the original 80x perf-bug scenario: // WhereRedb(o => parents.Contains(o.ParentId.Value)) + Where(props) // Compiles to `_id_parent = ANY(@p)` (Postgres) or `_id_parent IN (...)` (MSSql). // Must be pushed inside the (SELECT _id FROM _objects WHERE _id_scheme = X AND ...) subquery. var parentIds = new[] { _parentId }; var results = await Redb.Query() .WhereRedb(o => o.ParentId.HasValue && parentIds.Contains(o.ParentId.Value)) .Where(e => e.Department == "Engineering") .ToListAsync(); results.Should().NotBeEmpty(); results.Should().OnlyContain(r => r.parent_id == _parentId); results.Should().OnlyContain(r => r.Props.Department == "Engineering"); results.Should().Contain(r => r.id == _childId); } [Fact] public async Task WhereRedb_ParentId_In_Array_Combined_With_Props_CountAsync_Matches_ToList() { await EnsureNullableSeededAsync(); var parentIds = new[] { _parentId }; var query = Redb.Query() .WhereRedb(o => o.ParentId.HasValue && parentIds.Contains(o.ParentId.Value)) .Where(e => e.Department == "Engineering"); var count = await query.CountAsync(); var list = await query.ToListAsync(); count.Should().Be(list.Count); count.Should().BeGreaterThan(0); } [Fact] public async Task WhereRedb_ParentId_Equal_PropsFilter_OrderByProps_TopN() { await EnsureNullableSeededAsync(); // Validates pushdown does not break ORDER BY / TOP combined with mixed filters. var results = await Redb.Query() .WhereRedb(o => o.ParentId.HasValue && o.ParentId.Value == _parentId) .Where(e => e.Salary > 0m) .OrderBy(e => e.Salary) .Take(10) .ToListAsync(); results.Should().NotBeEmpty(); results.Should().OnlyContain(r => r.parent_id == _parentId); // Ordering preserved for (int i = 1; i < results.Count; i++) { results[i].Props.Salary.Should().BeGreaterThanOrEqualTo(results[i - 1].Props.Salary); } } // ────────────────────────────────────────────────────────────────── // String equality and membership on values longer than the string index holds // ────────────────────────────────────────────────────────────────── [Fact] public async Task Where_StringEquality_FindsValuesLongerThanTheIndexBound() { // PostgreSQL writes a string equality with the byte bound of its partial string index // (octet_length < 2000) so the planner can use it. The bound is added only for a short // value: a long one must still be found, through equality, membership and Any alike. // 1500 Cyrillic characters are 3000 bytes. var tag = Guid.NewGuid().ToString("N"); var longText = tag + new string('ж', 1500); var shortText = "short-" + tag; var longObj = TestDataFactory.CreateSimple("long-string-" + tag); longObj.Props.Description = longText; var shortObj = TestDataFactory.CreateSimple("short-string-" + tag); shortObj.Props.Description = shortText; var ids = new[] { await Redb.SaveAsync(longObj), await Redb.SaveAsync(shortObj) }; try { (await Redb.Query().Where(p => p.Description == longText).CountAsync()) .Should().Be(1, "a value longer than the index bound is not covered by it and must still match"); (await Redb.Query().AnyAsync(p => p.Description == longText)).Should().BeTrue(); (await Redb.Query().WhereIn(p => p.Description, new[] { longText, shortText }).CountAsync()) .Should().Be(2, "membership with a long value among short ones takes no bound"); (await Redb.Query().Where(p => p.Description == shortText).CountAsync()) .Should().Be(1); (await Redb.Query().WhereIn(p => p.Description, new[] { shortText, "absent-" + tag }).CountAsync()) .Should().Be(1); (await Redb.Query().Where(p => p.Description != shortText && p.Description!.StartsWith(tag)).CountAsync()) .Should().Be(1, "NOT of a bounded equality keeps the long value"); } finally { await Redb.DeleteAsync(ids); } } // ────────────────────────────────────────────────────────────────── // AllAsync: the answer of every form, absent values included // ────────────────────────────────────────────────────────────────── [Fact] public async Task AllAsync_CounterexampleSemantics_AbsentValueFails() { // PostgreSQL Pro answers AllAsync as "no counterexample" (NOT EXISTS of an object for which the predicate is // not TRUE), the other providers by two counts. Both must agree: an object without a value for the field // fails the check, an empty set passes it, and Take/Skip do not narrow it. var tag = "all-" + Guid.NewGuid().ToString("N"); var objects = new[] { (Price: 10m, Active: true, Description: (string?)"x"), (Price: 20m, Active: true, Description: (string?)null), (Price: 30m, Active: false, Description: (string?)"y"), }.Select((d, i) => { var o = TestDataFactory.CreateSimple($"{tag}-{i}", d.Price); o.Props.IsActive = d.Active; o.Props.Description = d.Description; return o; }).ToList(); var ids = new List(); foreach (var o in objects) ids.Add(await Redb.SaveAsync(o)); try { var set = Redb.Query().Where(p => p.Title.StartsWith(tag)); (await set.AllAsync(p => p.Price > 5m)).Should().BeTrue(); (await set.AllAsync(p => p.Price > 10m)).Should().BeFalse("one object has Price 10"); (await set.AllAsync(p => p.Description != null)).Should().BeFalse("one object has no Description"); (await set.AllAsync(p => p.Description == "x" || p.Description == "y")) .Should().BeFalse("the object without a Description is a counterexample of a condition on it"); (await set.AllAsync(p => p.Price >= 10m && p.Price <= 30m)).Should().BeTrue(); (await set.AllAsync(p => p.Price >= 10m && p.IsActive)).Should().BeFalse("one object is not active"); (await set.Where(p => p.IsActive).AllAsync(p => p.Price < 25m)).Should().BeTrue(); (await set.Take(1).AllAsync(p => p.Price > 10m)).Should().BeFalse("Take does not narrow the checked set"); var noneTitle = tag + "-none"; var empty = Redb.Query().Where(p => p.Title == noneTitle); (await empty.AllAsync(p => p.Price > 100m)).Should().BeTrue("every element of an empty set satisfies anything"); } finally { await Redb.DeleteAsync(ids); } } // ────────────────────────────────────────────────────────────────── // Soft-deleted objects stay out of counts and checks until the purge // ────────────────────────────────────────────────────────────────── [Fact] public async Task CountAnyAll_ByValue_LeaveOutSoftDeletedObjectsBeforeThePurge() { // PostgreSQL Pro reads a count or an existence check filtered by Props values off the index of values and // subtracts the trash: the soft delete moves an object to the trash scheme and leaves its values until the // purge, so they still match the filter. The other providers check the scheme of every object. var tag = "trash-" + Guid.NewGuid().ToString("N"); var objects = new[] { 10m, 20m, 30m }.Select((price, i) => { var o = TestDataFactory.CreateSimple($"{tag}-{i}", price); o.Props.Description = tag; return o; }).ToList(); var ids = new List(); foreach (var o in objects) ids.Add(await Redb.SaveAsync(o)); try { await Redb.SoftDeleteAsync(new[] { ids[1] }); (await Redb.Context.ExecuteScalarAsync( $"SELECT COUNT(*) FROM _objects WHERE _id = {ids[1]} AND _id_scheme = -10")) .Should().Be(1, "the object waits in the trash with its values, which is the case under test"); (await Redb.Query().Where(p => p.Description == tag).CountAsync()) .Should().Be(2, "the soft-deleted object is not counted"); (await Redb.Query().AnyAsync(p => p.Description == tag && p.Price == 20m)) .Should().BeFalse("the soft-deleted object is not found"); (await Redb.Query().Where(p => p.Description == tag).AllAsync(p => p.Price != 20m)) .Should().BeTrue("the soft-deleted object is not a counterexample"); (await Redb.Query().Where(p => p.Description == tag).SumAsync(p => p.Price)) .Should().Be(40m, "the soft-deleted object is not summed"); var groups = await Redb.Query().Where(p => p.Description == tag) .GroupBy(p => p.Description) .SelectAsync(g => new { Key = g.Key, Count = Agg.Count(g), Total = Agg.Sum(g, p => p.Price) }); groups.Should().ContainSingle().Which.Count.Should().Be(2, "the soft-deleted object is not grouped"); groups[0].Total.Should().Be(40m); var page = await Redb.Query().Where(p => p.Description == tag).OrderBy(p => p.Price).Take(2).ToListAsync(); page.Select(o => o.Props.Price).Should().Equal(new[] { 10m, 30m }, "the soft-deleted object takes no place in the page: the page is still full"); } finally { await Redb.DeleteAsync(ids); } } [Fact] public async Task Count_NullCheckAlone_AddsUpAndLeavesOutSoftDeletedObjects() { // PostgreSQL Pro counts Field == null alone as the objects of the scheme less the rows with a value outside // the trash, and Field != null off the rows of the field it drives from. Both answers must add up to the // objects of the scheme, and a soft-deleted object leaves the count it was in, whether it had a value or not. var tag = "nullcount-" + Guid.NewGuid().ToString("N"); var withValue = TestDataFactory.CreateSimple($"{tag}-value"); withValue.Props.OptionalNumber = 42; var withoutValue = TestDataFactory.CreateSimple($"{tag}-none"); withoutValue.Props.OptionalNumber = null; var ids = new List { await Redb.SaveAsync(withValue), await Redb.SaveAsync(withoutValue) }; async Task<(int Nulls, int Values, int All)> CountsAsync() => ( await Redb.Query().Where(p => p.OptionalNumber == null).CountAsync(), await Redb.Query().Where(p => p.OptionalNumber != null).CountAsync(), await Redb.Query().CountAsync()); try { var before = await CountsAsync(); (before.Nulls + before.Values).Should().Be(before.All, "every object either has the value or has not"); await Redb.SoftDeleteAsync(new[] { ids[1] }); var afterNone = await CountsAsync(); afterNone.Nulls.Should().Be(before.Nulls - 1, "the soft-deleted object without a value is not counted"); afterNone.Values.Should().Be(before.Values); await Redb.SoftDeleteAsync(new[] { ids[0] }); var afterValue = await CountsAsync(); afterValue.Nulls.Should().Be(afterNone.Nulls, "a soft-deleted object with a value never was among the nulls"); afterValue.Values.Should().Be(afterNone.Values - 1, "the soft-deleted object with a value is not counted"); (afterValue.Nulls + afterValue.Values).Should().Be(afterValue.All); } finally { await Redb.DeleteAsync(ids); } } [Fact] public async Task Page_NullCheckInTheTopLevelAnd_ReturnsOnlyTheObjectsWithoutAValue() { // SQL Server Pro checks Field == null in the top-level AND with NOT EXISTS instead of joining the field and // testing its column; the page must hold exactly the objects without a value, a field of a nested class too. var tag = Guid.NewGuid().ToString("N")[..8]; var full = TestDataFactory.CreateEmployee(9101, firstName: $"absent-{tag}-full"); full.Props.EmployeeCode = "EMP-FULL"; var empty = TestDataFactory.CreateEmployee(9102, firstName: $"absent-{tag}-empty"); empty.Props.EmployeeCode = null; empty.Props.HomeAddress = null; var ids = new List { await Redb.SaveAsync(full), await Redb.SaveAsync(empty) }; var prefix = $"absent-{tag}-"; try { var byCode = await Redb.Query() .Where(e => e.FirstName.StartsWith(prefix) && e.EmployeeCode == null) .OrderByRedb(o => o.Id).Take(10).ToListAsync(); byCode.Select(o => o.Id).Should().Equal(new[] { ids[1] }); byCode[0].Props.EmployeeCode.Should().BeNull(); var byCity = await Redb.Query() .Where(e => e.FirstName.StartsWith(prefix) && e.HomeAddress!.City == null) .OrderByRedb(o => o.Id).Take(10).ToListAsync(); byCity.Select(o => o.Id).Should().Equal(new[] { ids[1] }); (await Redb.Query().Where(e => e.FirstName.StartsWith(prefix) && e.EmployeeCode == null).CountAsync()) .Should().Be(1); (await Redb.Query().Where(e => e.FirstName.StartsWith(prefix) && e.EmployeeCode != null).CountAsync()) .Should().Be(1); } finally { await Redb.DeleteAsync(ids); } } [Fact] public async Task Count_NullCheckAlone_FieldOfANestedClass() { // A field of a nested class hangs off its parent row (_array_parent_id set): counting Field == null alone must // see those rows as values. An employee without a home address has no City; one with an address has it. var tag = Guid.NewGuid().ToString("N")[..8]; var withAddress = TestDataFactory.CreateEmployee(9001, firstName: $"nested-{tag}-a"); var withoutAddress = TestDataFactory.CreateEmployee(9002, firstName: $"nested-{tag}-b"); withoutAddress.Props.HomeAddress = null; var ids = new List { await Redb.SaveAsync(withAddress), await Redb.SaveAsync(withoutAddress) }; try { var nulls = await Redb.Query().Where(e => e.HomeAddress!.City == null).CountAsync(); var values = await Redb.Query().Where(e => e.HomeAddress!.City != null).CountAsync(); var all = await Redb.Query().CountAsync(); var nullsTheLongWay = await Redb.Query().Where(e => e.HomeAddress!.City == null && e.Age >= 0).CountAsync(); nulls.Should().Be(nullsTheLongWay, "the count of the null check alone and the count with a second condition agree"); nulls.Should().BeGreaterThan(0, "the employee without an address has no City"); (nulls + values).Should().Be(all); } finally { await Redb.DeleteAsync(ids); } } } Path: redb/redb.Tests.Integration/Tests/Base/WideEqualityLeadsTestsBase.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/WideEqualityLeadsTestsBase.cs ---- using redb.Core; using redb.Core.Models.Entities; using redb.Core.Query; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// A page sorted by a field with an index of values and filtered by one equality: the equality drives while a capped /// count finds fewer matches than PvtPrefilterPlanner.WideEqualityCap, and the sort field's index is walked from the cap /// on. Both sides of the cap must give the answer computed from the loaded objects, with the planner off and on: 4 000 /// objects, "wide" on 3 240 of them, "rare" on 40; descending (an object without the sort value comes last), ascending, /// with Skip, and with a second condition on the sort field. /// public abstract class WideEqualityLeadsTestsBase { private const int Objects = 4000; private static readonly SemaphoreSlim SeedLock = new(1, 1); protected readonly IRedbService Redb; protected WideEqualityLeadsTestsBase(IRedbService redb) => Redb = redb; private static string Tag(int i) => i % 100 == 0 ? "rare" : i < 3600 && i % 10 != 5 ? "wide" : "other"; private async Task>> SeedAsync() { await SeedLock.WaitAsync(); try { var all = await Redb.Query().ToListAsync(); if (all.Count == Objects) return all; if (all.Count > 0) await Redb.DeleteAsync(all.Select(o => o.Id).ToList()); var start = new DateTime(2025, 1, 1, 0, 0, 0, DateTimeKind.Utc); var objects = Enumerable.Range(0, Objects).Select(i => new RedbObject { name = $"wide-equality-{i:0000}", Props = new WideEqualityLeadsProps { Tag = Tag(i), Bucket = Tag(i) switch { "rare" => 1, "wide" => 2, _ => 3 }, Score = (i * 37L) % Objects, When = i % 50 == 7 ? null : start.AddMinutes((i * 53L) % Objects) } }).ToList(); for (var i = 0; i < objects.Count; i += 1000) await Redb.SaveAsync(objects.Skip(i).Take(1000).ToList()); all = await Redb.Query().ToListAsync(); all.Should().HaveCount(Objects); all.Count(o => o.Props.Tag == "wide").Should().BeGreaterThan(redb.Core.Pro.Query.PvtPrefilterPlanner.WideEqualityCap, "the wide value is past the cap"); return all; } finally { SeedLock.Release(); } } private async Task EachFormAsync(Func check) { var restore = Redb.Configuration.EnablePvtPrefilter; try { foreach (var on in new[] { false, true }) { Redb.UpdateConfiguration(c => c.EnablePvtPrefilter = on); await check(on ? "planner on" : "planner off"); } } finally { Redb.UpdateConfiguration(c => c.EnablePvtPrefilter = restore); } } [Theory] [InlineData("wide", 0)] [InlineData("wide", 30)] [InlineData("rare", 0)] [InlineData("rare", 30)] public async Task ByNumberDescending_BothSidesOfTheCap(string tag, int skip) { var all = await SeedAsync(); var expected = all.Where(o => o.Props.Tag == tag).OrderByDescending(o => o.Props.Score).ThenBy(o => o.Id) .Skip(skip).Take(20).Select(o => o.Id).ToList(); await EachFormAsync(async form => { var page = await Redb.Query().Where(p => p.Tag == tag) .OrderByDescending(p => p.Score).ThenByRedb(o => o.Id).Skip(skip).Take(20).ToListAsync(); page.Select(o => o.Id).Should().Equal(expected, $"{tag}, skip {skip}, {form}"); // The same split as a number, the equality SQL Server can count. long bucket = tag == "rare" ? 1 : 2; var byBucket = await Redb.Query().Where(p => p.Bucket == bucket) .OrderByDescending(p => p.Score).ThenByRedb(o => o.Id).Skip(skip).Take(20).ToListAsync(); byBucket.Select(o => o.Id).Should().Equal(expected, $"bucket {bucket}, skip {skip}, {form}"); }); } [Theory] [InlineData("wide")] [InlineData("rare")] public async Task ByDateDescending_AbsentDatesComeLast(string tag) { var all = await SeedAsync(); // LINQ puts null last when descending. var expected = all.Where(o => o.Props.Tag == tag).OrderByDescending(o => o.Props.When).ThenBy(o => o.Id) .Take(20).Select(o => o.Id).ToList(); var lastPage = all.Where(o => o.Props.Tag == tag).OrderByDescending(o => o.Props.When).ThenBy(o => o.Id) .Skip(all.Count(o => o.Props.Tag == tag) - 10).Take(20).Select(o => o.Id).ToList(); await EachFormAsync(async form => { var page = await Redb.Query().Where(p => p.Tag == tag) .OrderByDescending(p => p.When).ThenByRedb(o => o.Id).Take(20).ToListAsync(); page.Select(o => o.Id).Should().Equal(expected, $"{tag}, first page, {form}"); var tail = await Redb.Query().Where(p => p.Tag == tag) .OrderByDescending(p => p.When).ThenByRedb(o => o.Id).Skip(all.Count(o => o.Props.Tag == tag) - 10).Take(20).ToListAsync(); tail.Select(o => o.Id).Should().Equal(lastPage, $"{tag}, the page with the absent dates, {form}"); }); } [Theory] [InlineData("wide")] [InlineData("rare")] public async Task Ascending_AndWithAConditionOnTheSortField(string tag) { var all = await SeedAsync(); var ascending = all.Where(o => o.Props.Tag == tag).OrderBy(o => o.Props.When).ThenBy(o => o.Id) .Take(20).Select(o => o.Id).ToList(); var bounded = all.Where(o => o.Props.Tag == tag && o.Props.Score >= 100).OrderBy(o => o.Props.Score).ThenBy(o => o.Id) .Take(20).Select(o => o.Id).ToList(); await EachFormAsync(async form => { var page = await Redb.Query().Where(p => p.Tag == tag) .OrderBy(p => p.When).ThenByRedb(o => o.Id).Take(20).ToListAsync(); page.Select(o => o.Id).Should().Equal(ascending, $"{tag}, ascending, absent dates first, {form}"); var withRange = await Redb.Query().Where(p => p.Tag == tag && p.Score >= 100) .OrderBy(p => p.Score).ThenByRedb(o => o.Id).Take(20).ToListAsync(); withRange.Select(o => o.Id).Should().Equal(bounded, $"{tag}, ascending with Score >= 100, {form}"); }); } } Path: redb/redb.Tests.Integration/Tests/Base/WindowTestsBase.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/WindowTestsBase.cs ---- using redb.Core; 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; public abstract class WindowTestsBase { protected readonly IRedbService Redb; protected WindowTestsBase(IRedbService redb) => Redb = redb; private async Task> SeedAsync() { return await TestDataFactory.SeedEmployees(Redb, 15); } public class WindowRowDto { public string? FirstName { get; set; } public long RowNum { get; set; } } [Fact] public async Task Window_SelectAsync_IntoDtoMemberInit() { // G-1 доехал до оконных (решение владельца 2026-09-04): раньше DTO давал громкий отказ, // а до ревью - молча пустой результат. await SeedAsync(); var results = await Redb.Query() .WithWindow(w => w .PartitionBy(e => e.Department) .OrderByDesc(e => e.Salary)) .SelectAsync(e => new WindowRowDto { FirstName = e.Props.FirstName, RowNum = Win.RowNumber(), }); results.Should().NotBeEmpty(); results.Should().AllSatisfy(r => { r.FirstName.Should().NotBeNullOrEmpty(); r.RowNum.Should().BeGreaterThan(0); }); } [Fact] public async Task Window_RowNumber_PartitionByDept() { var ids = await SeedAsync(); var results = await Redb.Query() .WithWindow(w => w .PartitionBy(e => e.Department) .OrderByDesc(e => e.Salary)) .SelectAsync(e => new { e.Props.FirstName, e.Props.Department, e.Props.Salary, RowNum = Win.RowNumber() }); results.Should().NotBeEmpty(); results.Should().AllSatisfy(r => r.RowNum.Should().BeGreaterThan(0)); // Within each department, row numbers should start at 1 var grouped = results.GroupBy(r => r.Department); foreach (var group in grouped) { group.Min(r => r.RowNum).Should().Be(1); } } [Fact] public async Task Window_RunningSum_OverSalary() { var ids = await SeedAsync(); var results = await Redb.Query() .WithWindow(w => w .PartitionBy(e => e.Department) .OrderByDesc(e => e.Salary) .Frame(Frame.Rows().UnboundedPreceding())) .SelectAsync(e => new { e.Props.FirstName, e.Props.Department, e.Props.Salary, RunSum = Win.Sum(e.Props.Salary) }); results.Should().NotBeEmpty(); results.Should().AllSatisfy(r => { r.RunSum.Should().BeGreaterThanOrEqualTo(r.Salary); }); } [Fact] public async Task Window_Rank_ByDepartment() { var ids = await SeedAsync(); var results = await Redb.Query() .WithWindow(w => w .PartitionBy(e => e.Department) .OrderByDesc(e => e.Salary)) .SelectAsync(e => new { e.Props.FirstName, e.Props.Department, e.Props.Salary, RankNum = Win.Rank() }); results.Should().NotBeEmpty(); results.Should().AllSatisfy(r => r.RankNum.Should().BeGreaterThan(0)); } [Fact] public async Task Window_DenseRank() { var ids = await SeedAsync(); var results = await Redb.Query() .WithWindow(w => w .PartitionBy(e => e.Department) .OrderByDesc(e => e.Salary)) .SelectAsync(e => new { e.Props.Department, e.Props.Salary, DRank = Win.DenseRank() }); results.Should().NotBeEmpty(); results.Should().AllSatisfy(r => r.DRank.Should().BeGreaterThan(0)); } [Fact] public async Task Window_Ntile_SplitsIntoBuckets() { var ids = await SeedAsync(); var results = await Redb.Query() .WithWindow(w => w.OrderByDesc(e => e.Salary)) .SelectAsync(e => new { e.Props.FirstName, e.Props.Salary, Bucket = Win.Ntile(3) }); results.Should().NotBeEmpty(); results.Should().AllSatisfy(r => r.Bucket.Should().BeInRange(1, 3)); } [Fact] public async Task Window_Lag_PreviousValue() { var ids = await SeedAsync(); var results = await Redb.Query() .WithWindow(w => w .PartitionBy(e => e.Department) .OrderByDesc(e => e.Salary)) .SelectAsync(e => new { e.Props.FirstName, e.Props.Department, e.Props.Salary, PrevSalary = Win.Lag(e.Props.Salary) }); results.Should().NotBeEmpty(); } [Fact] public async Task Window_Lead_NextValue() { var ids = await SeedAsync(); var results = await Redb.Query() .WithWindow(w => w .PartitionBy(e => e.Department) .OrderByDesc(e => e.Salary)) .SelectAsync(e => new { e.Props.FirstName, e.Props.Salary, NextSalary = Win.Lead(e.Props.Salary) }); results.Should().NotBeEmpty(); } [Fact] public async Task Window_FirstValue_LastValue() { var ids = await SeedAsync(); var results = await Redb.Query() .WithWindow(w => w .PartitionBy(e => e.Department) .OrderByDesc(e => e.Salary) .Frame(Frame.Rows().UnboundedPreceding().AndUnboundedFollowing())) .SelectAsync(e => new { e.Props.Department, e.Props.Salary, TopSalary = Win.FirstValue(e.Props.Salary), LowestSalary = Win.LastValue(e.Props.Salary) }); results.Should().NotBeEmpty(); results.Should().AllSatisfy(r => { r.TopSalary.Should().BeGreaterThanOrEqualTo(r.Salary); r.LowestSalary.Should().BeLessThanOrEqualTo(r.Salary); }); } // An explicit frame must reach SQL as written. The checks above compare with >= and <=, which a // one-row frame also satisfies, so a frame silently turned into CURRENT ROW passed them (review // 2026-09-24, FRM-1: the Pro providers read another JSON shape than the core writes). The two facts // below compare exact sums, computed from the very rows the query returned. [Fact] public async Task Window_FullPartitionFrame_SumsTheWholeDepartment() { await SeedAsync(); var results = await Redb.Query() .WithWindow(w => w .PartitionBy(e => e.Department) .OrderByDesc(e => e.Salary) .Frame(Frame.Rows().UnboundedPreceding().AndUnboundedFollowing())) .SelectAsync(e => new { e.Props.Department, e.Props.Salary, DeptSum = Win.Sum(e.Props.Salary) }); results.Should().NotBeEmpty(); var totals = results.GroupBy(r => r.Department).ToDictionary(g => g.Key, g => g.Sum(r => r.Salary)); results.Should().AllSatisfy(r => r.DeptSum.Should().BeApproximately(totals[r.Department], 0.01m, "a frame over the whole partition sums every salary of the department, not the current row alone")); totals.Should().Contain(t => results.Count(r => r.Department == t.Key) > 1, "precondition: some department has more than one employee, or a one-row frame could not be told apart"); } [Fact] public async Task Window_SlidingFrame_SumsThePreviousRowAndThisOne() { await SeedAsync(); var results = await Redb.Query() .WithWindow(w => w .PartitionBy(e => e.Department) .OrderByDesc(e => e.Salary) .Frame(Frame.Rows().Preceding(1).AndCurrentRow())) .SelectAsync(e => new { e.Props.Department, e.Props.Salary, PairSum = Win.Sum(e.Props.Salary) }); results.Should().NotBeEmpty(); foreach (var department in results.GroupBy(r => r.Department)) { // Ties in salary may swap which employee stands where, but not the sequence of salaries, so the // multiset of "this salary plus the one before it" is fixed. var ordered = department.Select(r => r.Salary).OrderByDescending(s => s).ToList(); var expected = ordered.Select((s, i) => i == 0 ? s : s + ordered[i - 1]).OrderBy(s => s).ToList(); var actual = department.Select(r => r.PairSum).OrderBy(s => s).ToList(); actual.Should().HaveCount(expected.Count); for (var i = 0; i < expected.Count; i++) actual[i].Should().BeApproximately(expected[i], 0.01m, $"ROWS BETWEEN 1 PRECEDING AND CURRENT ROW in department '{department.Key}'"); } } } Path: redb/redb.Tests.Integration/Tests/Collation/MsSqlCaseFoldingTests.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/Collation/MsSqlCaseFoldingTests.cs ---- using redb.Tests.Integration.Fixtures; using redb.Tests.Integration.Tests.Base; namespace redb.Tests.Integration.Tests.Collation; /// /// SQL Server, with NO setting configured. /// /// /// This is not a copy of the other two: it asserts that MSSQL needs nothing. Its default collation /// (SQL_Latin1_General_CP1_CI_AS and its regional siblings) already folds every script, so the same /// language matrix must pass on the ordinary fixture with StringCollation unset. If it ever /// stops passing, the claim in COLLATION.md that MSSQL is unaffected has become false, and this is /// the test that says so. /// /// [Collection("MsSql")] public class MsSqlCaseFoldingTests : CaseFoldingTestsBase { public MsSqlCaseFoldingTests(MsSqlFixture fixture) : base(fixture.Redb) { } // Measured, not assumed: SQL Server CI_AS folds BOTH, unlike the ICU root collation. // This asymmetry is the reason the boundaries are per-provider rather than shared. protected override bool FoldsSharpSToDoubleS => true; protected override bool FoldsTurkishDottedI => true; protected override bool PlainStartsWithIsCaseSensitive => false; } Path: redb/redb.Tests.Integration/Tests/Collation/PostgresCaseFoldingTests.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/Collation/PostgresCaseFoldingTests.cs ---- using redb.Tests.Integration.Fixtures; using redb.Tests.Integration.Tests.Base; namespace redb.Tests.Integration.Tests.Collation; /// /// PostgreSQL, feature ON, against a database created with LC_CTYPE=C. Without that database the /// suite is vacuous: on a normal locale every assertion passes with the feature removed. /// [Collection("PostgresCollation")] public class PostgresCaseFoldingTests : CaseFoldingTestsBase { public PostgresCaseFoldingTests(PostgresCollationFixture fixture) : base(fixture.Redb) { } // ICU root collation: neither fold applies. protected override bool FoldsSharpSToDoubleS => false; protected override bool FoldsTurkishDottedI => false; protected override bool PlainStartsWithIsCaseSensitive => true; } Path: redb/redb.Tests.Integration/Tests/Collation/PostgresNoCollationTests.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/Collation/PostgresNoCollationTests.cs ---- using redb.Core; using redb.Core.Models.Entities; using redb.Tests.Integration.Fixtures; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Collation; /// /// The other half of the contract: with StringCollation unset, behaviour on the very same /// C-ctype database is exactly what it was before the feature existed. /// /// /// This is the test that makes the feature safe to ship. It runs against a database where the /// defect is real, and asserts that REDB still reproduces it when nobody asked for a fix. Without /// it, "the default is unchanged" would be a claim rather than a fact, and an existing deployment /// could silently start returning different rows after an upgrade. /// /// /// /// It is also the mirror of : the same rows, the same /// query, the opposite expectation. Should someone later make the folding unconditional, both /// suites cannot stay green, and this one is the one that will say so. /// /// [Collection("PostgresNoCollation")] public class PostgresNoCollationTests { private readonly IRedbService _redb; public PostgresNoCollationTests(PostgresNoCollationFixture fixture) => _redb = fixture.Redb; private async Task SeedAsync() { await _redb.Context.ExecuteAsync( "DELETE FROM _objects WHERE _id_scheme IN (SELECT _id FROM _schemes WHERE _name = " + $"'{typeof(CollationProps).FullName}')"); await _redb.SaveAsync(new List> { new() { name = "cyrillic", Props = new CollationProps { Text = "ПРИВЕТ МИР", Label = "cyrillic" } }, new() { name = "ascii", Props = new CollationProps { Text = "HELLO WORLD", Label = "ascii" } }, }); } private async Task> FindAsync(string needle) { var results = await _redb.Query() .Where(c => c.Text.Contains(needle, StringComparison.OrdinalIgnoreCase)) .Take(50).ToListAsync(); return results.Select(r => r.Props.Label).ToList(); } /// /// The defect, reproduced deliberately. On LC_CTYPE=C the database folds ASCII and nothing else, /// so a lower-case Cyrillic needle finds nothing. This is not a wish, it is the documented /// behaviour of an unconfigured PostgreSQL, and REDB must not change it behind anyone's back. /// [Fact] public async Task WithoutSetting_CyrillicSearchStillFindsNothing() { await SeedAsync(); (await FindAsync("привет")).Should().BeEmpty(); } /// ASCII keeps working, which is what made the defect easy to miss. [Fact] public async Task WithoutSetting_AsciiSearchStillWorks() { await SeedAsync(); (await FindAsync("hello")).Should().Contain("ascii"); } /// An exactly-cased Cyrillic needle matches: the text itself is intact, only folding is absent. [Fact] public async Task WithoutSetting_ExactCaseCyrillicStillMatches() { await SeedAsync(); (await FindAsync("ПРИВЕТ")).Should().Contain("cyrillic"); } } Path: redb/redb.Tests.Integration/Tests/Collation/PostgresProCaseFoldingTests.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/Collation/PostgresProCaseFoldingTests.cs ---- using redb.Tests.Integration.Fixtures; using redb.Tests.Integration.Tests.Base; namespace redb.Tests.Integration.Tests.Collation; /// /// PostgreSQL Pro, feature ON, C-ctype database, PVT prefilter forced on. /// /// /// Pro does not share the Free path: it builds SQL in C# and attaches the collation through the /// dialect, where Free builds SQL inside the database and reads a GUC. The first version of this /// suite covered Free only, which would have left every Pro user unprotected while the tests stayed /// green. /// /// [Collection("PostgresProCollation")] public class PostgresProCaseFoldingTests : CaseFoldingTestsBase { public PostgresProCaseFoldingTests(PostgresProCollationFixture fixture) : base(fixture.Redb) { } // ICU root collation: neither fold applies. protected override bool FoldsSharpSToDoubleS => false; protected override bool FoldsTurkishDottedI => false; protected override bool PlainStartsWithIsCaseSensitive => true; } Path: redb/redb.Tests.Integration/Tests/Collation/PostgresStringCollationIndexTests.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/Collation/PostgresStringCollationIndexTests.cs ---- using System.Text.RegularExpressions; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Npgsql; using redb.Core; using redb.Core.Extensions; using redb.Core.Models.Configuration; using redb.Core.Models.Entities; using redb.Core.Pro.Extensions; using redb.Postgres.Extensions; using redb.Postgres.Pro.Extensions; using redb.Tests.Integration.Fixtures; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Collation; /// /// With StringCollation set, Pro with the planner on pushes an ignore-case search onto _values as /// (_String COLLATE "und-x-icu") ILIKE, which the stock trigram index over bare _String cannot serve. /// Pro start-up looks for a trigram index over the collated column and logs a Warning when there is none, or only an /// INVALID one. The free forms filter the pivoted value and read no trigram index, so the free provider and Pro with /// the planner off check nothing. The plan test pins why the index is wanted. /// /// /// The database of the fixture has ctype C, under which pg_trgm builds no trigram from Cyrillic: the plan test searches /// a Latin pattern, the only kind a trigram index can serve there. /// [Collection("PostgresCollation")] public class PostgresStringCollationIndexTests { private const string IndexName = "IX__values__String_pattern_und_x_icu"; private const string WarningMark = "StringCollation is"; private const string OptionMark = "CreateStringCollationIndex is on"; private readonly PostgresCollationFixture _fixture; public PostgresStringCollationIndexTests(PostgresCollationFixture fixture) => _fixture = fixture; [Fact] public async Task Pro_MissingIndex_LogsAWarningNamingTheCollationTheIndexTheScriptAndTheCtype() { await DropIndexAsync(); var warnings = await StartAsync(Tier.Pro, PostgresCollationFixture.Collation); warnings.Should().ContainSingle(); warnings[0].Should().Contain("StringCollation is \"und-x-icu\"") .And.Contain("has no trigram index") .And.Contain("USING gin ((_String COLLATE \"und-x-icu\") gin_trgm_ops)") .And.Contain(IndexName) .And.Contain("string_collation_index.sql") .And.Contain("The database ctype is C") .And.Contain("ASCII letters only"); } [Fact] public async Task Pro_InvalidIndex_LogsAWarningToBuildItAgain() { await CreateIndexAsync(); // An interrupted CREATE INDEX CONCURRENTLY leaves the index INVALID; the catalog flag stands in for the // interruption (the test role is a superuser). await ExecuteAsync($"UPDATE pg_index SET indisvalid = false WHERE indexrelid = '\"{IndexName}\"'::regclass"); var warnings = await StartAsync(Tier.Pro, PostgresCollationFixture.Collation); warnings.Should().ContainSingle().Which.Should().Contain("INVALID"); await DropIndexAsync(); } [Fact] public async Task Pro_ValidIndex_NoWarning() { await CreateIndexAsync(); (await StartAsync(Tier.Pro, PostgresCollationFixture.Collation)).Should().BeEmpty(); } [Fact] public async Task Pro_IndexMatchedByStructure_NotByName() { await DropIndexAsync(); await ExecuteAsync( "CREATE INDEX IF NOT EXISTS ix_values_trgm_by_hand ON _values USING gin ((_String COLLATE \"ru-x-icu\") gin_trgm_ops)"); try { // An index over another collation serves no search of this one. (await StartAsync(Tier.Pro, PostgresCollationFixture.Collation)).Should().ContainSingle(); await ExecuteAsync("DROP INDEX ix_values_trgm_by_hand"); await ExecuteAsync( "CREATE INDEX ix_values_trgm_by_hand ON _values USING gin ((_String COLLATE \"und-x-icu\") gin_trgm_ops)"); (await StartAsync(Tier.Pro, PostgresCollationFixture.Collation)).Should().BeEmpty(); } finally { await ExecuteAsync("DROP INDEX IF EXISTS ix_values_trgm_by_hand"); } } [Fact] public async Task Pro_NoCollation_NoCheck() { await DropIndexAsync(); (await StartAsync(Tier.Pro, collation: null)).Should().BeEmpty(); } [Fact] public async Task ProPlannerOff_NoCheck() { await DropIndexAsync(); (await StartAsync(Tier.ProPlannerOff, PostgresCollationFixture.Collation)).Should().BeEmpty(); } [Fact] public async Task Free_NoCheck() { await DropIndexAsync(); (await StartAsync(Tier.Free, PostgresCollationFixture.Collation)).Should().BeEmpty(); } [Fact] public async Task Pro_IgnoreCaseContains_StockIndexNeverServesIt_CollatedIndexDoes() { await SeedAsync(); try { await AssertPlansAsync(); } finally { await DeleteObjectsAsync(); } } private async Task AssertPlansAsync() { await using var provider = BuildProvider(Tier.Pro, PostgresCollationFixture.Collation, capture: null); var redb = provider.GetRequiredService(); await redb.InitializeAsync(); var sql = await redb.Query() .Where(c => c.Text.Contains("hello", StringComparison.OrdinalIgnoreCase)) .ToSqlStringAsync(); sql.Should().Contain("(dv._string COLLATE \"und-x-icu\") ILIKE", sql); await DropIndexAsync(); var without = await ExplainAsync(sql); without.Should().NotContain("IX__values__String_pattern", without); await CreateIndexAsync(); var with = await ExplainAsync(sql); with.Should().Contain($"Bitmap Index Scan on \"{IndexName}\"", with); } // === CreateStringCollationIndex === [Fact] public async Task Pro_OptIn_BuildsTheIndexOnce_ASecondStartBuildsNothing() { await DropIndexAsync(); var first = await StartCapturingAsync(Tier.Pro, PostgresCollationFixture.Collation, create: true); IndexWarnings(first).Should().BeEmpty(); first.Entries.Should().Contain(e => e.Message.Contains($"{IndexName} built")); (await IndexValidAsync()).Should().BeTrue(); var second = await StartCapturingAsync(Tier.Pro, PostgresCollationFixture.Collation, create: true); IndexWarnings(second).Should().BeEmpty(); second.Entries.Should().NotContain(e => e.Message.Contains("Building") && e.Message.Contains(IndexName)); } [Fact] public async Task Pro_OptIn_RebuildsAnInvalidLeftover() { await CreateIndexAsync(); await ExecuteAsync($"UPDATE pg_index SET indisvalid = false WHERE indexrelid = '\"{IndexName}\"'::regclass"); var capture = await StartCapturingAsync(Tier.Pro, PostgresCollationFixture.Collation, create: true); IndexWarnings(capture).Should().BeEmpty(); (await IndexValidAsync()).Should().BeTrue(); } [Fact] public async Task Pro_OptIn_AutoApplyOff_WarnsAndBuildsNothing() { await DropIndexAsync(); var capture = await StartCapturingAsync(Tier.Pro, PostgresCollationFixture.Collation, create: true, autoApply: false); IndexWarnings(capture).Should().ContainSingle().Which.Should().Contain("AutoApplyDatabaseUpgrades is off"); (await IndexValidAsync()).Should().BeNull(); } [Fact] public async Task Free_OptIn_WarnsNoEffect_BuildsNothing() { await DropIndexAsync(); var capture = await StartCapturingAsync(Tier.Free, PostgresCollationFixture.Collation, create: true); IndexWarnings(capture).Should().ContainSingle().Which.Should().Contain("no effect on this tier (free provider)"); (await IndexValidAsync()).Should().BeNull(); } [Fact] public async Task ProPlannerOff_OptIn_WarnsNoEffect_BuildsNothing() { await DropIndexAsync(); var capture = await StartCapturingAsync(Tier.ProPlannerOff, PostgresCollationFixture.Collation, create: true); IndexWarnings(capture).Should().ContainSingle().Which.Should().Contain("no effect on this tier (Pro with EnablePvtPrefilter off)"); (await IndexValidAsync()).Should().BeNull(); } [Fact] public async Task OptIn_WithoutCollation_Warns() { var capture = await StartCapturingAsync(Tier.Pro, collation: null, create: true); IndexWarnings(capture).Should().ContainSingle().Which.Should().Contain("StringCollation is not set"); } // === helpers === private Task IndexValidAsync() => _fixture.Redb.Context.ExecuteScalarAsync( "SELECT i.indisvalid FROM pg_index i JOIN pg_class c ON c.oid = i.indexrelid " + $"WHERE c.relname = '{IndexName}' AND c.relnamespace = current_schema()::regnamespace"); private enum Tier { Free, Pro, ProPlannerOff } /// /// Two rows to find among a few thousand of the same field: enough for the planner to prefer a selective trigram /// index over the index of the structure, which it takes on a handful of rows whatever the trigram index. /// private async Task SeedAsync() { await DeleteObjectsAsync(); var objects = Enumerable.Range(1, 4000) .Select(i => new RedbObject { name = "noise-" + i, Props = new CollationProps { Text = $"Order {i} shipped {Guid.NewGuid():N}", Label = "noise-" + i } }) .ToList(); objects.Add(new() { name = "ci-1", Props = new CollationProps { Text = "ПРИВЕТ МИР", Label = "ci-1" } }); objects.Add(new() { name = "ci-2", Props = new CollationProps { Text = "HELLO WORLD", Label = "ci-2" } }); await _fixture.Redb.SaveAsync(objects); // Both tables: with stale statistics of _objects the planner takes the scheme for one object and drives the // plan from _objects, reading each value by object instead of searching the values. await ExecuteAsync("ANALYZE _objects"); await ExecuteAsync("ANALYZE _values"); } private Task DeleteObjectsAsync() => ExecuteAsync( "DELETE FROM _objects WHERE _id_scheme IN (SELECT _id FROM _schemes WHERE _name = " + $"'{typeof(CollationProps).FullName}')"); /// /// EXPLAIN of a Pro preview on a connection of its own, with sequential scans off: the plan shows whether an index /// CAN serve the predicate, where on a handful of rows the planner would read the table either way. The parameters /// come from the header the preview writes (-- $n=value (Type)). /// private static async Task ExplainAsync(string preview) { await using var connection = new NpgsqlConnection(PostgresCollationFixture.ConnectionString); await connection.OpenAsync(); await using (var off = new NpgsqlCommand("SET enable_seqscan = off", connection)) await off.ExecuteNonQueryAsync(); await using var explain = new NpgsqlCommand("EXPLAIN " + preview, connection); foreach (Match m in Regex.Matches(preview, @"^-- \$(\d+)=(.*) \((\w+)\)\r?$", RegexOptions.Multiline)) { var raw = m.Groups[2].Value; object value = m.Groups[3].Value switch { "Int64" => long.Parse(raw, System.Globalization.CultureInfo.InvariantCulture), "String" => raw.Substring(1, raw.Length - 2).Replace("''", "'"), var type => throw new InvalidOperationException($"Parameter type {type} is not handled by the test.") }; explain.Parameters.Add(new NpgsqlParameter { Value = value }); } await using var reader = await explain.ExecuteReaderAsync(); var lines = new List(); while (await reader.ReadAsync()) lines.Add(reader.GetString(0)); return string.Join("\n", lines); } private Task CreateIndexAsync() => ExecuteAsync( $"CREATE INDEX IF NOT EXISTS \"{IndexName}\" ON _values USING gin ((_String COLLATE \"und-x-icu\") gin_trgm_ops) " + "WHERE _String IS NOT NULL"); private Task DropIndexAsync() => ExecuteAsync($"DROP INDEX IF EXISTS \"{IndexName}\""); private Task ExecuteAsync(string sql) => _fixture.Redb.Context.ExecuteAsync(sql); /// Starts a service of its own on the collation database and returns the Warnings about the index. private static async Task> StartAsync(Tier tier, string? collation) => IndexWarnings(await StartCapturingAsync(tier, collation)); private static IReadOnlyList IndexWarnings(CapturingLoggerProvider capture) => capture.Warnings.Where(w => w.Contains(WarningMark) || w.Contains(OptionMark)).ToList(); private static async Task StartCapturingAsync(Tier tier, string? collation, bool create = false, bool autoApply = true) { var capture = new CapturingLoggerProvider(); await using (var provider = BuildProvider(tier, collation, capture, create, autoApply)) await provider.GetRequiredService().InitializeAsync(); return capture; } private static ServiceProvider BuildProvider(Tier tier, string? collation, CapturingLoggerProvider? capture, bool create = false, bool autoApply = true) { var services = new ServiceCollection(); services.AddLogging(b => { if (capture != null) b.AddProvider(capture); b.SetMinimumLevel(LogLevel.Information); }); void Configure(RedbServiceConfiguration c) { c.EnablePropsCache = false; c.StringCollation = collation; c.EnablePvtPrefilter = tier != Tier.ProPlannerOff; c.CreateStringCollationIndex = create; c.AutoApplyDatabaseUpgrades = autoApply; c.CacheDomain = tier == Tier.Free ? "collation-c" : "collation-c-pro"; } if (tier == Tier.Free) { services.AddRedb(options => PostgresOptionsExtensions.UsePostgres(options, PostgresCollationFixture.ConnectionString).Configure(Configure)); } else { var license = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build()["Redb:License"]; services.AddRedbPro(options => { PostgresProOptionsExtensions.UsePostgres(options, PostgresCollationFixture.ConnectionString).Configure(Configure); if (!string.IsNullOrWhiteSpace(license)) options.WithLicense(license); }); } return services.BuildServiceProvider(); } } Path: redb/redb.Tests.Integration/Tests/Collation/SqliteCaseFoldingTests.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/Collation/SqliteCaseFoldingTests.cs ---- using redb.Tests.Integration.Fixtures; using redb.Tests.Integration.Tests.Base; namespace redb.Tests.Integration.Tests.Collation; /// /// SQLite, feature ON. No special database is needed: ASCII-only folding is unconditional there, /// so an ordinary file reproduces it. /// [Collection("SqliteCollation")] public class SqliteCaseFoldingTests : CaseFoldingTestsBase { public SqliteCaseFoldingTests(SqliteCollationFixture fixture) : base(fixture.Redb) { } // .NET ToLowerInvariant folds character by character, like ICU root. protected override bool FoldsSharpSToDoubleS => false; protected override bool FoldsTurkishDottedI => false; protected override bool PlainStartsWithIsCaseSensitive => false; } Path: redb/redb.Tests.Integration/Tests/Collation/SqliteLikeSemanticsTests.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/Collation/SqliteLikeSemanticsTests.cs ---- using redb.Core; using redb.Tests.Integration.Fixtures; namespace redb.Tests.Integration.Tests.Collation; /// /// SQLite is the one provider where the fix replaces a built-in function rather than adding a clause /// to the SQL, so the replacement has to reproduce SQLite's own LIKE semantics exactly. Folding the /// case is the easy half; the wildcards, the ESCAPE form and NULL propagation are where a /// hand-written matcher silently diverges. /// /// /// These run raw SQL on purpose. Going through LINQ would test the query builder as well and would /// not reach the ESCAPE form at all, which is emitted only by the user-search path. /// /// [Collection("SqliteCollation")] public class SqliteLikeSemanticsTests { private readonly IRedbService _redb; public SqliteLikeSemanticsTests(SqliteCollationFixture fixture) => _redb = fixture.Redb; private Task ScalarAsync(string sql) => _redb.Context.ExecuteScalarAsync(sql); // ---------------------------------------------------------------- folding [Theory] [InlineData("'ПРИВЕТ' LIKE '%привет%'")] [InlineData("'привет' LIKE '%ПРИВЕТ%'")] [InlineData("'ΑΘΗΝΑ' LIKE '%αθηνα%'")] [InlineData("'ŐSZ' LIKE '%ősz%'")] [InlineData("'HELLO' LIKE '%hello%'")] public async Task Folds_EveryScript(string expression) => (await ScalarAsync($"SELECT ({expression})")).Should().Be(1); [Fact] public async Task DoesNotMatch_UnrelatedText() => (await ScalarAsync("SELECT ('ПРОЧЕЕ' LIKE '%привет%')")).Should().Be(0); // ---------------------------------------------------------------- wildcards [Theory] [InlineData("'abc' LIKE 'abc'", 1)] [InlineData("'abc' LIKE 'a%'", 1)] [InlineData("'abc' LIKE '%c'", 1)] [InlineData("'abc' LIKE '%b%'", 1)] [InlineData("'abc' LIKE 'a_c'", 1)] [InlineData("'abc' LIKE 'a_'", 0)] // _ is exactly one character [InlineData("'abc' LIKE '%'", 1)] [InlineData("'' LIKE '%'", 1)] // % matches the empty string [InlineData("'abc' LIKE ''", 0)] [InlineData("'abc' LIKE 'abcd'", 0)] [InlineData("'aXbXc' LIKE 'a%b%c'", 1)] // backtracking across two wildcards [InlineData("'aaa' LIKE '%a'", 1)] [InlineData("'abc' LIKE '%%%'", 1)] // consecutive wildcards collapse public async Task Wildcards_MatchSqliteSemantics(string expression, long expected) => (await ScalarAsync($"SELECT ({expression})")).Should().Be(expected); // ---------------------------------------------------------------- ESCAPE /// /// The three-argument form. REDB emits it on the user-search path, where a literal underscore in /// an email address must not become a wildcard. Registering only the two-argument override would /// leave this on the ASCII-only built-in, silently. /// [Theory] [InlineData(@"'a_c' LIKE 'a\_c' ESCAPE '\'", 1)] // escaped _ is literal and matches [InlineData(@"'aXc' LIKE 'a\_c' ESCAPE '\'", 0)] // ... and no longer matches any character [InlineData(@"'a%c' LIKE 'a\%c' ESCAPE '\'", 1)] [InlineData(@"'aXc' LIKE 'a\%c' ESCAPE '\'", 0)] [InlineData(@"'ПРИВЕТ_МИР' LIKE '%\_мир' ESCAPE '\'", 1)] // escape and folding together public async Task Escape_MakesWildcardsLiteral(string expression, long expected) => (await ScalarAsync($"SELECT ({expression})")).Should().Be(expected); // ---------------------------------------------------------------- code points /// /// In SQLite a character is a CODE POINT, not a UTF-16 code unit, so _ matches an emoji /// as one character. The first version of the override counted units and returned 0 here while /// the built-in returned 1 — found by running the same expression against a connection without /// the override, which is the only way to catch a divergence like this. /// [Theory] [InlineData("'a😀b' LIKE 'a_b'", 1)] [InlineData("'a😀b' LIKE 'a%b'", 1)] [InlineData("'a😀b' LIKE 'a__b'", 0)] // one code point, not two [InlineData("'😀' LIKE '_'", 1)] [InlineData("'ПРИВЕТ😀' LIKE '%привет_'", 1)] // folding and code points together public async Task Wildcards_CountCodePointsNotUtf16Units(string expression, long expected) => (await ScalarAsync($"SELECT ({expression})")).Should().Be(expected); /// /// A pattern ending with the escape character matches nothing, which is what the built-in does. /// The override originally treated the dangling escape as a literal and returned 1. /// [Fact] public async Task Escape_TrailingEscapeCharacterMatchesNothing() => (await ScalarAsync(@"SELECT ('a\' LIKE 'a\' ESCAPE '\')")).Should().Be(0); /// NOT LIKE runs through the same overridden function and must stay consistent with it. [Theory] [InlineData("'ПРИВЕТ' NOT LIKE '%привет%'", 0)] [InlineData("'ПРОЧЕЕ' NOT LIKE '%привет%'", 1)] public async Task NotLike_IsConsistentWithLike(string expression, long expected) => (await ScalarAsync($"SELECT ({expression})")).Should().Be(expected); // ---------------------------------------------------------------- NULL /// SQLite's like() yields NULL when either side is NULL; the override must not turn that into 0. [Theory] [InlineData("SELECT (NULL LIKE '%a%') IS NULL")] [InlineData("SELECT ('abc' LIKE NULL) IS NULL")] public async Task Null_PropagatesRatherThanBecomingFalse(string sql) => (await ScalarAsync(sql)).Should().Be(1); // ---------------------------------------------------------------- lower / upper [Theory] [InlineData("lower('ПРИВЕТ')", "привет")] [InlineData("upper('привет')", "ПРИВЕТ")] [InlineData("lower('ŐSZ')", "ősz")] [InlineData("lower('HELLO')", "hello")] public async Task LowerUpper_FoldEveryScript(string expression, string expected) { var actual = await _redb.Context.ExecuteScalarAsync($"SELECT {expression}"); actual.Should().Be(expected); } /// /// KNOWN BOUNDARY. SQLite maps the case-sensitive and case-insensitive operators onto the same /// LIKE — the native extension says so in as many words ("both map to LIKE"), and it has always /// been that way because SQLite's LIKE is case-insensitive for ASCII regardless. Enabling the /// feature therefore widens that collapse to every script: a case-SENSITIVE Contains starts /// matching a differently-cased Cyrillic string too. Opt-in, and documented, but real. /// [Fact] public async Task KnownBoundary_CaseSensitiveOperatorsAreAlsoFolded() => (await ScalarAsync("SELECT ('ПРИВЕТ' LIKE '%привет%')")).Should().Be(1); } Path: redb/redb.Tests.Integration/Tests/Diagnostics/RedbTelemetryTests.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/Diagnostics/RedbTelemetryTests.cs ---- using System.Diagnostics; using AwesomeAssertions; using redb.Core.Diagnostics; using Xunit; namespace redb.Tests.Integration.Tests.Diagnostics; /// /// The redb.Core ActivitySource: one span per database command, carrying the operation name and /// the database system only. The source is inert without a subscriber, so nothing is emitted by default. /// Asserted through an , the way redb.Route reads its own spans. /// public class RedbTelemetryTests { private static (ActivityListener Listener, List Spans) Listen() { var spans = new List(); var listener = new ActivityListener { ShouldListenTo = source => source.Name == RedbActivitySource.SourceName, Sample = (ref ActivityCreationOptions _) => ActivitySamplingResult.AllDataAndRecorded, ActivityStopped = spans.Add, }; ActivitySource.AddActivityListener(listener); return (listener, spans); } [Fact] public void WithNoSubscriber_TheSourceIsOff() { RedbActivitySource.SourceName.Should().Be("redb.Core"); RedbTelemetry.Enabled.Should().BeFalse("nothing subscribes, so a command is run straight through"); } [Fact] public async Task AQuery_OpensOneSpan_CarryingOnlyTheOperation() { var (listener, spans) = Listen(); try { var rows = await RedbTelemetry.RunAsync( RedbTelemetry.Query, () => Task.FromResult(new List { 1, 2, 3 })); rows.Should().Equal(1, 2, 3); var span = spans.Should().ContainSingle().Which; span.DisplayName.Should().Be("redb.query"); span.GetTagItem("db.system").Should().Be("redb"); span.GetTagItem("db.operation").Should().Be("query"); span.GetTagItem("db.statement").Should().BeNull("the statement text is never captured"); } finally { listener.Dispose(); } } [Fact] public async Task AFailingCommand_MarksTheSpanAnError_AndRethrows() { var (listener, spans) = Listen(); try { var act = () => RedbTelemetry.RunAsync( RedbTelemetry.Execute, () => Task.FromException(new InvalidOperationException("boom"))); (await act.Should().ThrowAsync()).WithMessage("boom"); spans.Should().ContainSingle().Which.Status.Should().Be(ActivityStatusCode.Error); } finally { listener.Dispose(); } } [Fact] public async Task ACancelledCommand_DoesNotMarkTheSpanAnError() { var (listener, spans) = Listen(); try { var act = () => RedbTelemetry.RunAsync( RedbTelemetry.Query, () => Task.FromException(new OperationCanceledException())); await act.Should().ThrowAsync(); spans.Should().ContainSingle().Which.Status.Should().NotBe(ActivityStatusCode.Error); } finally { listener.Dispose(); } } } Path: redb/redb.Tests.Integration/Tests/MsSql/MsSqlAbsentValuesTests.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/MsSql/MsSqlAbsentValuesTests.cs ---- using redb.Tests.Integration.Fixtures; using redb.Tests.Integration.Tests.Base; namespace redb.Tests.Integration.Tests.MsSql; [Collection("MsSql")] public class MsSqlAbsentValuesTests : AbsentValuesTestsBase { public MsSqlAbsentValuesTests(MsSqlFixture fixture) : base(fixture.Redb) { } } Path: redb/redb.Tests.Integration/Tests/MsSql/MsSqlAggregatePathTests.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/MsSql/MsSqlAggregatePathTests.cs ---- using redb.Tests.Integration.Fixtures; using redb.Tests.Integration.Tests.Base; namespace redb.Tests.Integration.Tests.MsSql; [Collection("MsSql")] public class MsSqlAggregatePathTests : AggregatePathTestsBase { public MsSqlAggregatePathTests(MsSqlFixture fixture) : base(fixture.Redb) { } } Path: redb/redb.Tests.Integration/Tests/MsSql/MsSqlAggregatePreviewTests.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/MsSql/MsSqlAggregatePreviewTests.cs ---- using redb.Tests.Integration.Fixtures; using redb.Tests.Integration.Tests.Base; namespace redb.Tests.Integration.Tests.MsSql; [Collection("MsSql")] public class MsSqlAggregatePreviewTests : FreeAggregatePreviewTestsBase { public MsSqlAggregatePreviewTests(MsSqlFixture fixture) : base(fixture.Redb) { } } Path: redb/redb.Tests.Integration/Tests/MsSql/MsSqlAggregationTests.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/MsSql/MsSqlAggregationTests.cs ---- using redb.Tests.Integration.Fixtures; using redb.Tests.Integration.Tests.Base; namespace redb.Tests.Integration.Tests.MsSql; [Collection("MsSql")] public class MsSqlAggregationTests : AggregationTestsBase { public MsSqlAggregationTests(MsSqlFixture fixture) : base(fixture.Redb, isPro: false) { } } Path: redb/redb.Tests.Integration/Tests/MsSql/MsSqlAmbientTransactionTests.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/MsSql/MsSqlAmbientTransactionTests.cs ---- using redb.Core.Data; using redb.MSSql.Data; using redb.Tests.Integration.Fixtures; using redb.Tests.Integration.Tests.Base; namespace redb.Tests.Integration.Tests.MsSql; [Collection("MsSql")] public class MsSqlAmbientTransactionTests : AmbientTransactionTestsBase { public MsSqlAmbientTransactionTests(MsSqlFixture fixture) : base(fixture.ServiceProvider) { } protected override string CreateProbeTableSql => "IF OBJECT_ID(N'dbo.ambient_tx_rows', N'U') IS NULL CREATE TABLE dbo.ambient_tx_rows (tag nvarchar(100) NOT NULL);"; protected override string SlowStatementSql => "WAITFOR DELAY '00:00:02'; SELECT 1"; protected override IRedbConnection CreateStandaloneConnection(IServiceProvider services, bool differentSessionSettings) => new SqlRedbConnection(ConnString("MSSql"), lazyReferences: differentSessionSettings); } Path: redb/redb.Tests.Integration/Tests/MsSql/MsSqlAnalyticsTelemetryTests.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/MsSql/MsSqlAnalyticsTelemetryTests.cs ---- using redb.Tests.Integration.Fixtures; using redb.Tests.Integration.Tests.Base; namespace redb.Tests.Integration.Tests.MsSql; [Collection("MsSql")] public class MsSqlAnalyticsTelemetryTests : AnalyticsTelemetryTestsBase { public MsSqlAnalyticsTelemetryTests(MsSqlFixture fixture) : base(fixture.Redb) { } protected override int CommandsPerCall => 2; } Path: redb/redb.Tests.Integration/Tests/MsSql/MsSqlAnyExistsTests.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/MsSql/MsSqlAnyExistsTests.cs ---- using redb.Tests.Integration.Fixtures; using redb.Tests.Integration.Tests.Base; namespace redb.Tests.Integration.Tests.MsSql; [Collection("MsSql")] public class MsSqlAnyExistsTests : FreeAnyExistsTestsBase { public MsSqlAnyExistsTests(MsSqlFixture fixture) : base(fixture.Redb) { } } Path: redb/redb.Tests.Integration/Tests/MsSql/MsSqlArrayAnyTests.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/MsSql/MsSqlArrayAnyTests.cs ---- using redb.Tests.Integration.Fixtures; using redb.Tests.Integration.Tests.Base; namespace redb.Tests.Integration.Tests.MsSql; [Collection("MsSql")] public class MsSqlArrayAnyTests : ArrayAnyTestsBase { public MsSqlArrayAnyTests(MsSqlFixture fixture) : base(fixture.Redb) { } } Path: redb/redb.Tests.Integration/Tests/MsSql/MsSqlArrayGroupByDeepTests.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/MsSql/MsSqlArrayGroupByDeepTests.cs ---- using redb.Tests.Integration.Fixtures; using redb.Tests.Integration.Tests.Base; namespace redb.Tests.Integration.Tests.MsSql; [Collection("MsSql")] public class MsSqlArrayGroupByDeepTests : ArrayGroupByDeepTestsBase { public MsSqlArrayGroupByDeepTests(MsSqlFixture fixture) : base(fixture.Redb) { } } Path: redb/redb.Tests.Integration/Tests/MsSql/MsSqlArrayGroupByFieldsTests.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/MsSql/MsSqlArrayGroupByFieldsTests.cs ---- using redb.Core; using redb.Tests.Integration.Fixtures; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.MsSql; /// /// dbo.pvt_build_array_groupby_sql on SQL Server Free skipped a key or aggregate field the array item does /// not have: a grouping on one known and one unknown key grouped on the known one, an unknown aggregate vanished /// from the result, and when no key resolved the function returned the flat list of items instead of groups. /// The core refuses such keys before they reach SQL (GRP-9), so the function is called directly - the SQL is the /// public surface for callers that submit the JSON themselves. /// [Collection("MsSql")] public class MsSqlArrayGroupByFieldsTests { private readonly IRedbService _redb; public MsSqlArrayGroupByFieldsTests(MsSqlFixture fixture) => _redb = fixture.Redb; private async Task BuildAsync(string groupByJson, string aggregationsJson) { var scheme = await _redb.SyncSchemeAsync(); return await _redb.Context.ExecuteScalarAsync( "SELECT dbo.pvt_build_array_groupby_sql(" + scheme.Id + ", N'Contacts', NULL, $1, $2, NULL, N'flat')", new object[] { groupByJson, aggregationsJson }); } private const string CountAll = "[{\"field\":\"*\",\"func\":\"COUNT\",\"alias\":\"Count\"}]"; [Fact] public async Task AKeyTheItemDoesNotHave_RefusesTheQuery() { var sql = await BuildAsync("[{\"field\":\"Type\",\"alias\":\"Type\"},{\"field\":\"NoSuchField\",\"alias\":\"X\"}]", CountAll); sql.Should().Be("--error: \"NoSuchField\" is not a field of the elements of \"Contacts\"", "grouping on the known key alone is a different grouping"); } [Fact] public async Task NoKeyTheItemHas_RefusesTheQuery() { var sql = await BuildAsync("[{\"field\":\"NoSuchField\",\"alias\":\"X\"}]", CountAll); sql.Should().Be("--error: \"NoSuchField\" is not a field of the elements of \"Contacts\"", "a flat list of items is not a grouping"); } [Fact] public async Task AnAggregateOnAFieldTheItemDoesNotHave_RefusesTheQuery() { var sql = await BuildAsync("[{\"field\":\"Type\",\"alias\":\"Type\"}]", "[{\"field\":\"NoSuchField\",\"func\":\"MAX\",\"alias\":\"M\"}]"); sql.Should().Be("--error: \"NoSuchField\" is not a field of the elements of \"Contacts\"", "the aggregate would be missing from the result"); } [Fact] public async Task KnownKeysAndAggregates_AreBuilt() { var sql = await BuildAsync("[{\"field\":\"Type\",\"alias\":\"Type\"}]", "[{\"field\":\"Value\",\"func\":\"MAX\",\"alias\":\"M\"}]"); sql.Should().Contain("GROUP BY").And.Contain("AS [M]"); } private async Task BuildOnAsync(string arrayPath, string groupByJson) { var scheme = await _redb.SyncSchemeAsync(); return await _redb.Context.ExecuteScalarAsync( "SELECT dbo.pvt_build_array_groupby_sql(" + scheme.Id + ", $1, NULL, $2, NULL, NULL, N'flat')", new object[] { arrayPath, groupByJson }); } [Theory] [InlineData("Contacts", "[{\"field\":\"$foo\",\"alias\":\"x\"}]", "--error: \"$foo\" is not a field of the elements of \"Contacts\"")] [InlineData("Contacts", "[{\"field\":\"$element\",\"alias\":\"x\"}]", "--error: \"$element\" names the element itself*")] [InlineData("Skills", "[{\"field\":\"Name\",\"alias\":\"x\"}]", "*simple values and have no field \"Name\"*")] [InlineData("Contacts.Metadata", "[{\"field\":\"Type\",\"alias\":\"x\"}]", "--error: \"Type\" is not a field of the elements of \"Contacts.Metadata\"")] [InlineData("PhoneDirectory", "[{\"field\":\"$element\",\"alias\":\"x\"}]", "*dictionary*")] [InlineData("HomeAddress", "[{\"field\":\"City\",\"alias\":\"x\"}]", "--error: \"HomeAddress\" is not an array")] public async Task WhatItCannotAnswer_ComesBackAsAnError(string arrayPath, string groupByJson, string message) { // A14: a scalar function cannot raise; the provider throws the text after "--error:". (await BuildOnAsync(arrayPath, groupByJson)).Should().Match(message); } } Path: redb/redb.Tests.Integration/Tests/MsSql/MsSqlArrayHavingTranslatorTests.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/MsSql/MsSqlArrayHavingTranslatorTests.cs ---- using redb.Core; using redb.Tests.Integration.Fixtures; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.MsSql; /// /// The HAVING translator of the SQL Server Free array grouping (dbo.pvt_build_array_having_expr) turned a /// node it did not know into 1=1: the condition was dropped and every group came back. The core's HAVING /// parser writes no such node today, so the function is called directly - the SQL is the public surface for /// callers that submit the JSON themselves. /// [Collection("MsSql")] public class MsSqlArrayHavingTranslatorTests { private readonly IRedbService _redb; public MsSqlArrayHavingTranslatorTests(MsSqlFixture fixture) => _redb = fixture.Redb; private async Task BuildAsync(string havingJson) { var scheme = await _redb.SyncSchemeAsync(); return await _redb.Context.ExecuteScalarAsync( "SELECT dbo.pvt_build_array_groupby_sql(" + scheme.Id + ", N'Contacts', NULL, " + "N'[{\"field\":\"Type\",\"alias\":\"Type\"}]', N'[{\"field\":\"*\",\"func\":\"COUNT\",\"alias\":\"Count\"}]', $1, N'flat')", new object[] { havingJson }); } [Fact] public async Task AHavingNodeItDoesNotKnow_RefusesTheQuery() { var sql = await BuildAsync("{\"$regex\":[{\"$count\":\"*\"},{\"$const\":\"x\"}]}"); sql.Should().Be("--error: the HAVING does not translate", "a HAVING the translator cannot read must not be replaced by 1=1"); } [Fact] public async Task AHavingItKnows_IsEmitted() { var sql = await BuildAsync("{\"$gt\":[{\"$count\":\"*\"},{\"$const\":1}]}"); sql.Should().Contain("HAVING (COUNT(*) > 1)"); } } Path: redb/redb.Tests.Integration/Tests/MsSql/MsSqlArrayOfClassesAnyTests.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/MsSql/MsSqlArrayOfClassesAnyTests.cs ---- using redb.Tests.Integration.Fixtures; using redb.Tests.Integration.Tests.Base; namespace redb.Tests.Integration.Tests.MsSql; [Collection("MsSql")] public class MsSqlArrayOfClassesAnyTests : ArrayOfClassesAnyTestsBase { public MsSqlArrayOfClassesAnyTests(MsSqlFixture fixture) : base(fixture.Redb) { } protected override bool ReadsAnyOverClasses => false; } Path: redb/redb.Tests.Integration/Tests/MsSql/MsSqlArrayTests.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/MsSql/MsSqlArrayTests.cs ---- using redb.Tests.Integration.Fixtures; using redb.Tests.Integration.Tests.Base; namespace redb.Tests.Integration.Tests.MsSql; [Collection("MsSql")] public class MsSqlArrayTests : ArrayTestsBase { public MsSqlArrayTests(MsSqlFixture fixture) : base(fixture.Redb) { } } Path: redb/redb.Tests.Integration/Tests/MsSql/MsSqlBareRedbObjectFieldTests.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/MsSql/MsSqlBareRedbObjectFieldTests.cs ---- using redb.Tests.Integration.Fixtures; using redb.Tests.Integration.Tests.Base; namespace redb.Tests.Integration.Tests.MsSql; [Collection("MsSql")] public class MsSqlBareRedbObjectFieldTests : BareRedbObjectFieldTestsBase { public MsSqlBareRedbObjectFieldTests(MsSqlFixture fixture) : base(fixture.Redb) { } } Path: redb/redb.Tests.Integration/Tests/MsSql/MsSqlBugRegressionTests.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/MsSql/MsSqlBugRegressionTests.cs ---- using redb.Tests.Integration.Fixtures; using redb.Tests.Integration.Tests.Base; namespace redb.Tests.Integration.Tests.MsSql; [Collection("MsSql")] public class MsSqlBugRegressionTests : BugRegressionTestsBase { public MsSqlBugRegressionTests(MsSqlFixture fixture) : base(fixture.Redb) { } } Path: redb/redb.Tests.Integration/Tests/MsSql/MsSqlBulkDeletePlanTests.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/MsSql/MsSqlBulkDeletePlanTests.cs ---- using redb.Core; using redb.Core.Attributes; using redb.Core.Models.Entities; using redb.Tests.Integration.Fixtures; namespace redb.Tests.Integration.Tests.MsSql; /// /// Plan-shape pin for BulkDeleteValuesByListItemIdsAsync (E114 finding, 2026-09-11): /// _values._ListItem is covered by a FILTERED index (IX__values__ListItem_not_null), /// and SQL Server does not match a filtered index through a STRING_SPLIT semi-join - that form /// degrades to a full clustered scan of _values (33s cold on a seeded 8.4M-row table, /// surfaced by E114 recreating its list). A parameterized IN list seeks the filtered index. /// /// The pin executes the REAL provider method and asserts the cached plan's ACCESS operator /// (a DELETE plan name-drops every index it maintains, so index-name presence proves /// nothing). MSSQL-only: the unfiltered-index bulk deletes of this provider seek fine /// through STRING_SPLIT, and the other providers' partial indexes match their IN/ANY forms. /// [Collection("MsSql")] public class MsSqlBulkDeletePlanTests { protected readonly IRedbService Redb; public MsSqlBulkDeletePlanTests(MsSqlFixture fixture) => Redb = fixture.Redb; [Fact] public async Task BulkDeleteValuesByListItemIds_PlanSeeksTheFilteredIndex() { await Redb.SyncSchemeAsync(); // The filtered-index matching failure is size-independent (verified by SHOWPLAN on // both a seeded 8.4M-row table and a near-empty one), but a few hundred rows keep the // cost model from ever rating a scan competitive, so the pin cannot flake on an // unusually empty fixture database. var padding = Enumerable.Range(0, 200).Select(i => new RedbObject { name = $"plan-pin-{i}", Props = new PlanPinPaddingProps { A = i, B = $"pad-{i}" } }).ToList(); await Redb.SaveAsync(padding); // The ids need not exist: DELETE ... WHERE _ListItem IN (...) compiles and caches its // plan no matter how many rows match. await Redb.Context.Bulk.BulkDeleteValuesByListItemIdsAsync([-101L, -102L, -103L]); var plan = await Redb.Context.ExecuteScalarAsync( """ SELECT TOP 1 CAST(qp.query_plan AS NVARCHAR(MAX)) FROM sys.dm_exec_query_stats qs CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) st CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) qp WHERE st.text LIKE N'%DELETE FROM [_]values WHERE [_]ListItem IN%' AND st.text NOT LIKE N'%dm[_]exec%' ORDER BY qs.last_execution_time DESC """); plan.Should().NotBeNullOrEmpty( "the bulk delete just executed, so its plan must be in the plan cache"); // The index NAME proves nothing: a DELETE plan lists every index it maintains, the // filtered one included. The tell is the ACCESS operator - the STRING_SPLIT semi-join // cannot match the filtered index and reads _values through a Clustered Index Scan // (33s cold on a seeded 8.4M-row table); the parameterized IN form seeks. plan.Should().NotContain("Clustered Index Scan", "the delete-by-list-item form must locate rows through the filtered FK index, " + "not a full clustered scan of _values"); } } [RedbScheme(Name = "MsSqlPlanPinPadding")] public class PlanPinPaddingProps { public long? A { get; set; } public string? B { get; set; } } Path: redb/redb.Tests.Integration/Tests/MsSql/MsSqlBytesRoundTripTests.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/MsSql/MsSqlBytesRoundTripTests.cs ---- using redb.Tests.Integration.Fixtures; using redb.Tests.Integration.Tests.Base; namespace redb.Tests.Integration.Tests.MsSql; [Collection("MsSql")] public class MsSqlBytesRoundTripTests : BytesRoundTripTestsBase { public MsSqlBytesRoundTripTests(MsSqlFixture fixture) : base(fixture.Redb) { } } Path: redb/redb.Tests.Integration/Tests/MsSql/MsSqlCacheBehaviorTests.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/MsSql/MsSqlCacheBehaviorTests.cs ---- using redb.Tests.Integration.Fixtures; using redb.Tests.Integration.Tests.Base; namespace redb.Tests.Integration.Tests.MsSql; [Collection("MsSql")] public class MsSqlCacheBehaviorTests : CacheBehaviorTestsBase { public MsSqlCacheBehaviorTests(MsSqlFixture fixture) : base(fixture.Redb) { } } Path: redb/redb.Tests.Integration/Tests/MsSql/MsSqlCancellationTests.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/MsSql/MsSqlCancellationTests.cs ---- using redb.Tests.Integration.Fixtures; using redb.Tests.Integration.Tests.Base; namespace redb.Tests.Integration.Tests.MsSql; [Collection("MsSql")] public class MsSqlCancellationTests : CancellationTestsBase { public MsSqlCancellationTests(MsSqlFixture fixture) : base(fixture.Redb) { } protected override string? SleepSql => "WAITFOR DELAY '00:00:30'"; } Path: redb/redb.Tests.Integration/Tests/MsSql/MsSqlColdSchemeLinkedObjectTests.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/MsSql/MsSqlColdSchemeLinkedObjectTests.cs ---- using Microsoft.Extensions.Configuration; using redb.Core.Extensions; using redb.MSSql.Extensions; using redb.Tests.Integration.Tests.Base; namespace redb.Tests.Integration.Tests.MsSql; public class MsSqlColdSchemeLinkedObjectTests : ColdSchemeLinkedObjectTestsBase { protected override void UseProvider(RedbOptionsBuilder options) { var cs = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build().GetConnectionString("MSSql")!; options.UseMsSql(cs); } } Path: redb/redb.Tests.Integration/Tests/MsSql/MsSqlColdSchemeTreeFilterTests.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/MsSql/MsSqlColdSchemeTreeFilterTests.cs ---- using Microsoft.Extensions.Configuration; using redb.Core.Extensions; using redb.MSSql.Extensions; using redb.Tests.Integration.Tests.Base; namespace redb.Tests.Integration.Tests.MsSql; public class MsSqlColdSchemeTreeFilterTests : ColdSchemeTreeFilterTestsBase { protected override void UseProvider(RedbOptionsBuilder options) { var cs = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build().GetConnectionString("MSSql")!; options.UseMsSql(cs); } } Path: redb/redb.Tests.Integration/Tests/MsSql/MsSqlCollectionFilterAnalyticsTests.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/MsSql/MsSqlCollectionFilterAnalyticsTests.cs ---- using redb.Tests.Integration.Fixtures; using redb.Tests.Integration.Tests.Base; namespace redb.Tests.Integration.Tests.MsSql; [Collection("MsSql")] public class MsSqlCollectionFilterAnalyticsTests : CollectionFilterAnalyticsTestsBase { public MsSqlCollectionFilterAnalyticsTests(MsSqlFixture fixture) : base(fixture.Redb) { } } Path: redb/redb.Tests.Integration/Tests/MsSql/MsSqlComputedComparisonTests.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/MsSql/MsSqlComputedComparisonTests.cs ---- using redb.Tests.Integration.Fixtures; using redb.Tests.Integration.Tests.Base; namespace redb.Tests.Integration.Tests.MsSql; [Collection("MsSql")] public class MsSqlComputedComparisonTests : ComputedComparisonTestsBase { public MsSqlComputedComparisonTests(MsSqlFixture fixture) : base(fixture.Redb) { } } Path: redb/redb.Tests.Integration/Tests/MsSql/MsSqlConcurrencyStressTests.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/MsSql/MsSqlConcurrencyStressTests.cs ---- using redb.Tests.Integration.Fixtures; using redb.Tests.Integration.Tests.Base; namespace redb.Tests.Integration.Tests.MsSql; [Collection("MsSql")] public class MsSqlConcurrencyStressTests : ConcurrencyStressTestsBase { public MsSqlConcurrencyStressTests(MsSqlFixture fixture) : base(fixture.Redb, fixture.ServiceProvider) { } } Path: redb/redb.Tests.Integration/Tests/MsSql/MsSqlConcurrentDeleteCountTests.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/MsSql/MsSqlConcurrentDeleteCountTests.cs ---- using redb.Tests.Integration.Fixtures; using redb.Tests.Integration.Tests.Base; namespace redb.Tests.Integration.Tests.MsSql; [Collection("MsSql")] public class MsSqlConcurrentDeleteCountTests : ConcurrentDeleteCountTestsBase { public MsSqlConcurrentDeleteCountTests(MsSqlFixture fixture) : base(fixture.Redb, fixture.ServiceProvider) { } protected override async Task HoldRowAsync(long objectId) => await RowHolders.SqlServerAsync(objectId); } Path: redb/redb.Tests.Integration/Tests/MsSql/MsSqlConcurrentDeleteListTests.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/MsSql/MsSqlConcurrentDeleteListTests.cs ---- using Microsoft.Extensions.Configuration; using redb.Core.Extensions; using redb.MSSql.Extensions; using redb.Tests.Integration.Tests.Base; namespace redb.Tests.Integration.Tests.MsSql; public class MsSqlConcurrentDeleteListTests : ConcurrentDeleteListTestsBase { protected override void UseProvider(RedbOptionsBuilder options) { var cs = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build().GetConnectionString("MSSql")!; options.UseMsSql(cs); } } Path: redb/redb.Tests.Integration/Tests/MsSql/MsSqlConcurrentWritersTests.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/MsSql/MsSqlConcurrentWritersTests.cs ---- using redb.Tests.Integration.Fixtures; using redb.Tests.Integration.Tests.Base; namespace redb.Tests.Integration.Tests.MsSql; [Collection("MsSql")] public class MsSqlConcurrentWritersTests : ConcurrentWritersTestsBase { public MsSqlConcurrentWritersTests(MsSqlFixture fixture) : base(fixture.ServiceProvider) { } } Path: redb/redb.Tests.Integration/Tests/MsSql/MsSqlConnectionTeardownTests.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/MsSql/MsSqlConnectionTeardownTests.cs ---- using redb.Core.Data; using redb.MSSql.Data; using redb.Tests.Integration.Tests.Base; namespace redb.Tests.Integration.Tests.MsSql; [Collection("MsSql")] public class MsSqlConnectionTeardownTests : ConnectionTeardownTestsBase { protected override IRedbConnection CreateConnection() => new SqlRedbConnection(ConnString("MSSql")); protected override string SleepSql(double seconds) { var span = TimeSpan.FromSeconds(seconds); return $"WAITFOR DELAY '{span:hh\\:mm\\:ss\\.fff}'; SELECT CAST(1 AS BIGINT)"; } } Path: redb/redb.Tests.Integration/Tests/MsSql/MsSqlConstantPredicateTests.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/MsSql/MsSqlConstantPredicateTests.cs ---- using redb.Tests.Integration.Fixtures; using redb.Tests.Integration.Tests.Base; namespace redb.Tests.Integration.Tests.MsSql; [Collection("MsSql")] public class MsSqlConstantPredicateTests : ConstantPredicateTestsBase { public MsSqlConstantPredicateTests(MsSqlFixture fixture) : base(fixture.Redb) { } } Path: redb/redb.Tests.Integration/Tests/MsSql/MsSqlCrudTests.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/MsSql/MsSqlCrudTests.cs ---- using redb.Tests.Integration.Fixtures; using redb.Tests.Integration.Tests.Base; namespace redb.Tests.Integration.Tests.MsSql; [Collection("MsSql")] public class MsSqlCrudTests : CrudTestsBase { public MsSqlCrudTests(MsSqlFixture fixture) : base(fixture.Redb) { } } Path: redb/redb.Tests.Integration/Tests/MsSql/MsSqlCtSaveInvariantsTests.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/MsSql/MsSqlCtSaveInvariantsTests.cs ---- using redb.Tests.Integration.Fixtures; using redb.Tests.Integration.Tests.Base; namespace redb.Tests.Integration.Tests.MsSql; [Collection("MsSql")] public class MsSqlCtSaveInvariantsTests : CtSaveInvariantsTestsBase { public MsSqlCtSaveInvariantsTests(MsSqlFixture fixture) : base(fixture.Redb) { } } Path: redb/redb.Tests.Integration/Tests/MsSql/MsSqlDbInfoTests.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/MsSql/MsSqlDbInfoTests.cs ---- using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using redb.Core.Extensions; using redb.MSSql.Extensions; using redb.Tests.Integration.Tests.Base; namespace redb.Tests.Integration.Tests.MsSql; public class MsSqlDbInfoTests : DbInfoTestsBase { protected override void UseProvider(RedbOptionsBuilder options) { var cs = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build().GetConnectionString("MSSql")!; options.UseMsSql(cs); } protected override string VersionMarker => "Microsoft SQL Server"; // sys.database_files.size is in 8 KB pages. protected override string SizeInBytesSql => "SELECT SUM(CAST(size AS BIGINT)) * 8192 FROM sys.database_files"; } Path: redb/redb.Tests.Integration/Tests/MsSql/MsSqlDecimalRoundTripTests.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/MsSql/MsSqlDecimalRoundTripTests.cs ---- using redb.Tests.Integration.Fixtures; using redb.Tests.Integration.Tests.Base; namespace redb.Tests.Integration.Tests.MsSql; [Collection("MsSql")] public class MsSqlDecimalRoundTripTests : DecimalRoundTripTestsBase { public MsSqlDecimalRoundTripTests(MsSqlFixture fixture) : base(fixture.Redb) { } } Path: redb/redb.Tests.Integration/Tests/MsSql/MsSqlDeleteBatchCountTests.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/MsSql/MsSqlDeleteBatchCountTests.cs ---- using redb.Tests.Integration.Fixtures; using redb.Tests.Integration.Tests.Base; namespace redb.Tests.Integration.Tests.MsSql; [Collection("MsSql")] public class MsSqlDeleteBatchCountTests : DeleteBatchCountTestsBase { public MsSqlDeleteBatchCountTests(MsSqlFixture fixture) : base(fixture.Redb) { } } Path: redb/redb.Tests.Integration/Tests/MsSql/MsSqlDeleteSubtreeCountTests.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/MsSql/MsSqlDeleteSubtreeCountTests.cs ---- using Microsoft.Extensions.Configuration; using redb.Core.Extensions; using redb.MSSql.Extensions; using redb.Tests.Integration.Tests.Base; namespace redb.Tests.Integration.Tests.MsSql; public class MsSqlDeleteSubtreeCountTests : DeleteSubtreeCountTestsBase { protected override void UseProvider(RedbOptionsBuilder options) { var cs = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build().GetConnectionString("MSSql")!; options.UseMsSql(cs); } } Path: redb/redb.Tests.Integration/Tests/MsSql/MsSqlDictionaryOrderTests.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/MsSql/MsSqlDictionaryOrderTests.cs ---- using redb.Tests.Integration.Fixtures; using redb.Tests.Integration.Tests.Base; namespace redb.Tests.Integration.Tests.MsSql; [Collection("MsSql")] public class MsSqlDictionaryOrderTests : DictionaryOrderTestsBase { public MsSqlDictionaryOrderTests(MsSqlFixture fixture) : base(fixture.Redb) { } } Path: redb/redb.Tests.Integration/Tests/MsSql/MsSqlDictionaryTests.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/MsSql/MsSqlDictionaryTests.cs ---- using redb.Tests.Integration.Fixtures; using redb.Tests.Integration.Tests.Base; namespace redb.Tests.Integration.Tests.MsSql; [Collection("MsSql")] public class MsSqlDictionaryTests : DictionaryTestsBase { public MsSqlDictionaryTests(MsSqlFixture fixture) : base(fixture.Redb) { } protected override int? DictionaryKeyBound => 430; } Path: redb/redb.Tests.Integration/Tests/MsSql/MsSqlDisposedScopeGuardTests.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/MsSql/MsSqlDisposedScopeGuardTests.cs ---- using redb.Tests.Integration.Fixtures; using redb.Tests.Integration.Tests.Base; namespace redb.Tests.Integration.Tests.MsSql; [Collection("MsSql")] public class MsSqlDisposedScopeGuardTests : DisposedScopeGuardTestsBase { public MsSqlDisposedScopeGuardTests(MsSqlFixture fixture) : base(fixture.ServiceProvider) { } } Path: redb/redb.Tests.Integration/Tests/MsSql/MsSqlExportBulkCopyOptionsTests.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/MsSql/MsSqlExportBulkCopyOptionsTests.cs ---- using System.Data; using Microsoft.Data.SqlClient; using Microsoft.Extensions.Configuration; using redb.Export.Providers; namespace redb.Tests.Integration.Tests.MsSql; /// /// The bulk load of the SQL Server export provider writes the rows exactly as given: a key written into an IDENTITY /// column is kept, not replaced by a generated one, and a null written into a column with a default stays null. /// public class MsSqlExportBulkCopyOptionsTests : IAsyncLifetime { private string _server = null!; private string _database = null!; public async Task InitializeAsync() { _server = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build().GetConnectionString("MSSql")!; _database = $"redb_export_bulk_{Guid.NewGuid().ToString("N")[..12]}"; await ExecuteAsync(Master(), $"CREATE DATABASE [{_database}]"); await ExecuteAsync(Target(), """ CREATE TABLE dbo.bulk_probe ( _id BIGINT IDENTITY(1, 1) NOT NULL PRIMARY KEY, _note NVARCHAR(50) NULL DEFAULT N'from default') """); } public async Task DisposeAsync() { SqlConnection.ClearAllPools(); await ExecuteAsync(Master(), $"IF DB_ID('{_database}') IS NOT NULL BEGIN ALTER DATABASE [{_database}] SET SINGLE_USER WITH ROLLBACK IMMEDIATE; DROP DATABASE [{_database}] END"); } [Fact] public async Task ABulkLoad_KeepsWrittenKeysAndNulls() { var data = new DataTable(); data.Columns.Add("_id", typeof(long)); data.Columns.Add("_note", typeof(string)); data.Rows.Add(42L, DBNull.Value); data.Rows.Add(7L, "written"); await using (var provider = ProviderFactory.Create("mssql")) { await provider.OpenAsync(Target()); await provider.BulkInsertAsync("dbo.bulk_probe", data); } (await RowsAsync()).Should().Equal("7=written", "42="); } private async Task> RowsAsync() { var rows = new List(); await using var connection = new SqlConnection(Target()); await connection.OpenAsync(); await using var command = new SqlCommand("SELECT _id, _note FROM dbo.bulk_probe ORDER BY _id", connection); await using var reader = await command.ExecuteReaderAsync(); while (await reader.ReadAsync()) rows.Add($"{reader.GetInt64(0)}={(reader.IsDBNull(1) ? "" : reader.GetString(1))}"); return rows; } private string Master() => new SqlConnectionStringBuilder(_server) { InitialCatalog = "master" }.ConnectionString; private string Target() => new SqlConnectionStringBuilder(_server) { InitialCatalog = _database }.ConnectionString; private static async Task ExecuteAsync(string cs, string sql) { await using var connection = new SqlConnection(cs); await connection.OpenAsync(); await using var command = new SqlCommand(sql, connection); await command.ExecuteNonQueryAsync(); } } Path: redb/redb.Tests.Integration/Tests/MsSql/MsSqlExportRenameHistoryTests.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/MsSql/MsSqlExportRenameHistoryTests.cs ---- using Microsoft.Data.SqlClient; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Core.Extensions; using redb.MSSql.Extensions; using redb.Tests.Integration.Tests.Base; namespace redb.Tests.Integration.Tests.MsSql; /// on SQL Server, scratch databases dropped afterwards. public class MsSqlExportRenameHistoryTests : ExportRenameHistoryTestsBase, IAsyncLifetime { private string _server = null!; private readonly List _databases = []; private readonly List _files = []; protected override string ProviderName => "mssql"; public Task InitializeAsync() { var config = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build(); _server = config.GetConnectionString("MSSql")!; return Task.CompletedTask; } public async Task DisposeAsync() { SqlConnection.ClearAllPools(); foreach (var database in _databases) await ExecuteAsync(Master(), $"IF DB_ID('{database}') IS NOT NULL BEGIN ALTER DATABASE [{database}] SET SINGLE_USER WITH ROLLBACK IMMEDIATE; DROP DATABASE [{database}] END"); foreach (var file in _files) File.Delete(file); } protected override async Task NewDatabaseAsync(string suffix) { var name = $"redb_export_ren_{Guid.NewGuid().ToString("N")[..12]}_{suffix}"; _databases.Add(name); await ExecuteAsync(Master(), $"CREATE DATABASE [{name}]"); return new SqlConnectionStringBuilder(_server) { InitialCatalog = name }.ConnectionString; } protected override ServiceProvider Build(string cs) { var services = new ServiceCollection(); services.AddLogging(b => b.SetMinimumLevel(LogLevel.Warning)); services.AddRedb(options => options .UseMsSql(cs) .Configure(c => c.CacheDomain = $"export-ren-{Guid.NewGuid():N}")); return services.BuildServiceProvider(); } protected override string NewFile() { var file = Path.Combine(Path.GetTempPath(), $"redb-export-ren-{Guid.NewGuid():N}.redb"); _files.Add(file); return file; } protected override async Task ScalarAsync(string cs, string sql) { await using var connection = new SqlConnection(cs); await connection.OpenAsync(); await using var command = new SqlCommand(sql, connection); return AsText(await command.ExecuteScalarAsync()); } protected override async Task> PairsAsync(string cs, string sql) { await using var connection = new SqlConnection(cs); await connection.OpenAsync(); await using var command = new SqlCommand(sql, connection); await using var reader = await command.ExecuteReaderAsync(); var rows = new List<(string?, string?)>(); while (await reader.ReadAsync()) rows.Add((AsText(reader.GetValue(0)), AsText(reader.GetValue(1)))); return rows; } protected override Task ExecuteSqlAsync(string cs, string sql) => ExecuteAsync(cs, sql); private string Master() => new SqlConnectionStringBuilder(_server) { InitialCatalog = "master" }.ConnectionString; private static async Task ExecuteAsync(string cs, string sql) { await using var connection = new SqlConnection(cs); await connection.OpenAsync(); await using var command = new SqlCommand(sql, connection); await command.ExecuteNonQueryAsync(); } } Path: redb/redb.Tests.Integration/Tests/MsSql/MsSqlExportSchemaGateTests.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/MsSql/MsSqlExportSchemaGateTests.cs ---- using Microsoft.Data.SqlClient; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Core.Extensions; using redb.MSSql.Extensions; using redb.MSSql.Sql; using redb.Tests.Integration.Tests.Base; namespace redb.Tests.Integration.Tests.MsSql; /// on SQL Server, scratch databases dropped afterwards. public class MsSqlExportSchemaGateTests : ExportSchemaGateTestsBase, IAsyncLifetime { private string _server = null!; private readonly List _databases = []; private readonly List _files = []; protected override string ProviderName => "mssql"; protected override bool SupportsParallel => true; protected override string OutdatedRemedy => "`redb schema --upgrade --provider mssql`"; protected override string SchemaVersionSql => "SELECT dbo.pvt_module_version()"; public Task InitializeAsync() { var config = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build(); _server = config.GetConnectionString("MSSql")!; return Task.CompletedTask; } public async Task DisposeAsync() { SqlConnection.ClearAllPools(); foreach (var database in _databases) await ExecuteAsync(Master(), $"IF DB_ID('{database}') IS NOT NULL BEGIN ALTER DATABASE [{database}] SET SINGLE_USER WITH ROLLBACK IMMEDIATE; DROP DATABASE [{database}] END"); foreach (var file in _files) File.Delete(file); } protected override async Task NewDatabaseAsync(string suffix) { var name = $"redb_export_gate_{Guid.NewGuid().ToString("N")[..12]}_{suffix}"; _databases.Add(name); await ExecuteAsync(Master(), $"CREATE DATABASE [{name}]"); return new SqlConnectionStringBuilder(_server) { InitialCatalog = name }.ConnectionString; } protected override ServiceProvider Build(string cs) { var services = new ServiceCollection(); services.AddLogging(b => b.SetMinimumLevel(LogLevel.Warning)); services.AddRedb(options => options .UseMsSql(cs) .Configure(c => c.CacheDomain = $"export-gate-{Guid.NewGuid():N}")); return services.BuildServiceProvider(); } protected override string NewFile() { var file = Path.Combine(Path.GetTempPath(), $"redb-export-gate-{Guid.NewGuid():N}.redb"); _files.Add(file); return file; } protected override async Task StageOlderAsync(string cs) { await ExecuteAsync(cs, "ALTER TABLE _schemes DROP COLUMN _renamed_from; ALTER TABLE _structures DROP COLUMN _renamed_from;"); await ExecuteAsync(cs, """ ALTER FUNCTION dbo.pvt_module_version() RETURNS nvarchar(50) WITH SCHEMABINDING AS BEGIN RETURN N'0.0.1'; END """); } protected override async Task StageNewerAsync(string cs, bool servesThisBuild) { var compat = servesThisBuild ? $"{new MsSqlDialect().Query_PvtRequiredVersion()}|4.8.0" : "99.0.0|99.0.0"; await ExecuteAsync(cs, """ ALTER FUNCTION dbo.pvt_module_version() RETURNS nvarchar(50) WITH SCHEMABINDING AS BEGIN RETURN N'99.0.0'; END """); await ExecuteAsync(cs, $""" CREATE OR ALTER FUNCTION dbo.pvt_module_compat() RETURNS nvarchar(50) WITH SCHEMABINDING AS BEGIN RETURN N'{compat}'; END """); } protected override async Task ScalarAsync(string cs, string sql) { await using var connection = new SqlConnection(cs); await connection.OpenAsync(); await using var command = new SqlCommand(sql, connection); return Convert.ToString(await command.ExecuteScalarAsync()); } protected override async Task> ProviderStateAsync(string cs) { var lines = new List(); await using var connection = new SqlConnection(cs); await connection.OpenAsync(); foreach (var sql in new[] { """ SELECT 'index ' + t.name + '.' + i.name + ' disabled=' + CAST(i.is_disabled AS varchar(1)) FROM sys.indexes i JOIN sys.tables t ON t.object_id = i.object_id WHERE i.name IS NOT NULL ORDER BY 1 """, """ SELECT 'fk ' + name + ' disabled=' + CAST(is_disabled AS varchar(1)) + ' untrusted=' + CAST(is_not_trusted AS varchar(1)) FROM sys.foreign_keys ORDER BY 1 """, }) { await using var command = new SqlCommand(sql, connection); await using var reader = await command.ExecuteReaderAsync(); while (await reader.ReadAsync()) lines.Add(reader.GetString(0)); } return lines; } private string Master() => new SqlConnectionStringBuilder(_server) { InitialCatalog = "master" }.ConnectionString; protected override Task ExecuteSqlAsync(string cs, string sql) => ExecuteAsync(cs, sql); private static async Task ExecuteAsync(string cs, string sql) { await using var connection = new SqlConnection(cs); await connection.OpenAsync(); await using var command = new SqlCommand(sql, connection); await command.ExecuteNonQueryAsync(); } } Path: redb/redb.Tests.Integration/Tests/MsSql/MsSqlExportSequenceTests.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/MsSql/MsSqlExportSequenceTests.cs ---- using Microsoft.Data.SqlClient; using Microsoft.Extensions.Configuration; using redb.Export.Providers; namespace redb.Tests.Integration.Tests.MsSql; /// /// redb.Export on SQL Server restores the id sequence so that the next id is new. The exporter reads the last id /// handed out (current_value), and RESTART WITH names the NEXT value, so restarting at the value read /// handed out an id that an imported row already had (review 2026-09-24). Runs on a scratch database of its own: /// rewinding the shared test database's sequence would break every other test. /// public class MsSqlExportSequenceTests : IAsyncLifetime { private string _server = null!; private string _database = null!; public async Task InitializeAsync() { var config = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build(); _server = config.GetConnectionString("MSSql")!; _database = "redb_export_seq_" + Guid.NewGuid().ToString("N")[..12]; await ExecuteAsync(Master(), $"CREATE DATABASE [{_database}]"); await ExecuteAsync(Scratch(), "CREATE SEQUENCE global_identity AS BIGINT START WITH 1000 INCREMENT BY 1"); } public async Task DisposeAsync() { SqlConnection.ClearAllPools(); await ExecuteAsync(Master(), $"ALTER DATABASE [{_database}] SET SINGLE_USER WITH ROLLBACK IMMEDIATE; DROP DATABASE [{_database}]"); } [Fact] public async Task AfterAnImport_TheNextIdIsNotOneAlreadyHandedOut() { // Three ids handed out: 1000, 1001, 1002 - the last one belongs to some exported row. for (var i = 0; i < 3; i++) await ScalarAsync(Scratch(), "SELECT NEXT VALUE FOR global_identity"); await using var provider = ProviderFactory.Create("mssql"); await provider.OpenAsync(Scratch()); var lastHandedOut = await provider.GetSequenceValueAsync(); lastHandedOut.Should().Be(1002, "precondition: the exporter reads the last id handed out"); // What an import does with the value it carried over. await provider.BeginImportAsync(); await provider.SetSequenceValueAsync(lastHandedOut); await provider.CommitImportAsync(); (await ScalarAsync(Scratch(), "SELECT NEXT VALUE FOR global_identity")).Should().Be(1003, "the next object saved after the import must not take the id of the last imported row"); } private string Master() => new SqlConnectionStringBuilder(_server) { InitialCatalog = "master" }.ConnectionString; private string Scratch() => new SqlConnectionStringBuilder(_server) { InitialCatalog = _database }.ConnectionString; private static async Task ExecuteAsync(string cs, string sql) { await using var connection = new SqlConnection(cs); await connection.OpenAsync(); await using var command = new SqlCommand(sql, connection); await command.ExecuteNonQueryAsync(); } private static async Task ScalarAsync(string cs, string sql) { await using var connection = new SqlConnection(cs); await connection.OpenAsync(); await using var command = new SqlCommand(sql, connection); return Convert.ToInt64(await command.ExecuteScalarAsync()); } } Path: redb/redb.Tests.Integration/Tests/MsSql/MsSqlFieldNamedLikeAFunctionTests.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/MsSql/MsSqlFieldNamedLikeAFunctionTests.cs ---- using redb.Tests.Integration.Fixtures; using redb.Tests.Integration.Tests.Base; namespace redb.Tests.Integration.Tests.MsSql; [Collection("MsSql")] public class MsSqlFieldNamedLikeAFunctionTests : FieldNamedLikeAFunctionTestsBase { public MsSqlFieldNamedLikeAFunctionTests(MsSqlFixture fixture) : base(fixture.Redb) { } } Path: redb/redb.Tests.Integration/Tests/MsSql/MsSqlFieldPathResolverTests.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/MsSql/MsSqlFieldPathResolverTests.cs ---- using redb.Core; using redb.Tests.Integration.Fixtures; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.MsSql; /// /// dbo.pvt_resolve_field_path on SQL Server Free. T-SQL keeps a variable's old value when /// SELECT @v = ... finds no row, so a nested child the scheme does not have resolved to its parent: /// Contacts[].NoSuchField came back as the Contacts array itself, and whatever read it - a filter, a sort, /// a grouping - silently used the wrong structure. /// [Collection("MsSql")] public class MsSqlFieldPathResolverTests { private readonly IRedbService _redb; public MsSqlFieldPathResolverTests(MsSqlFixture fixture) => _redb = fixture.Redb; private async Task ResolveAsync(string path) { var scheme = await _redb.SyncSchemeAsync(); return await _redb.Context.ExecuteScalarAsync( "SELECT dbo.pvt_resolve_field_path(" + scheme.Id + ", $1)", new object[] { path }); } [Fact] public async Task ANestedChildTheSchemeDoesNotHave_IsNotResolved() { (await ResolveAsync("Contacts[].NoSuchField")).Should().BeNull(); } [Fact] public async Task ANestedChildTheSchemeHas_IsResolved() { var parent = await ResolveAsync("Contacts[]"); var child = await ResolveAsync("Contacts[].Type"); child.Should().NotBeNull().And.Contain("\"db_type\":\"String\""); child.Should().NotBe(parent); } } Path: redb/redb.Tests.Integration/Tests/MsSql/MsSqlFilterFieldPathTests.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/MsSql/MsSqlFilterFieldPathTests.cs ---- using redb.Tests.Integration.Fixtures; using redb.Tests.Integration.Tests.Base; namespace redb.Tests.Integration.Tests.MsSql; [Collection("MsSql")] public class MsSqlFilterFieldPathTests : FilterFieldPathTestsBase { public MsSqlFilterFieldPathTests(MsSqlFixture fixture) : base(fixture.Redb) { } } Path: redb/redb.Tests.Integration/Tests/MsSql/MsSqlFilterRefusalTests.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/MsSql/MsSqlFilterRefusalTests.cs ---- using redb.Core; using redb.Tests.Integration.Fixtures; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.MsSql; /// /// The SQL Server Free filter and aggregate builders (review SQ-5). Where PostgreSQL raises, SQL Server /// substituted: an operator it did not know became 1=1 (the condition vanished) or 1=0 (no rows, and /// every row under $not); an unknown comparison became =; a value that was not a number became 0; an /// aggregate it could not compile became a NULL column. Each case now fails through dbo.pvt_fail with a /// message that starts with "redb:". The core does not write most of these shapes, so the functions are called /// directly - they are the public surface for callers that submit the JSON themselves. /// [Collection("MsSql")] public class MsSqlFilterRefusalTests { private readonly IRedbService _redb; public MsSqlFilterRefusalTests(MsSqlFixture fixture) => _redb = fixture.Redb; private async Task BuildQueryAsync(string filterJson) { var scheme = await _redb.SyncSchemeAsync(); return await _redb.Context.ExecuteScalarAsync( "SELECT dbo.pvt_build_query_sql(" + scheme.Id + ", $1, NULL, 0, NULL, 10, 0, N'flat', NULL, 1, 1, NULL)", new object[] { filterJson }); } private async Task BuildAggregateAsync(string aggregationsJson) { var scheme = await _redb.SyncSchemeAsync(); return await _redb.Context.ExecuteScalarAsync( "SELECT dbo.pvt_build_aggregate_sql(" + scheme.Id + ", NULL, $1, N'flat')", new object[] { aggregationsJson }); } [Theory] [InlineData("{\"$foo\":1}")] // unknown top-level operator: was 1=1 [InlineData("{\"Department\":{\"$foo\":\"x\"}}")] // unknown field operator: was 1=0 [InlineData("{\"Department\":{\"$in\":\"x\"}}")] // $in without a list: was 1=0 [InlineData("{\"0$:name\":{\"$arrayContains\":\"x\"}}")] // array operator on a base field: was 1=0 [InlineData("{\"$level\":\"abc\"}")] // level that is not a number: was 0 [InlineData("{\"Department.$length\":{\"$foo\":3}}")] // unknown comparison: was = [InlineData("{\"Department.$length\":{\"$eq\":\"abc\"}}")] // length that is not a number: was 0 public async Task AFilterItCannotRead_IsRefused(string filterJson) { var build = async () => await BuildQueryAsync(filterJson); await build.Should().ThrowAsync().WithMessage("*redb:*"); } [Theory] [InlineData("{\"Department\":{\"$eq\":\"x\"}}")] [InlineData("{\"$and\":[]}")] [InlineData("{\"Department\":{\"$eq\":null}}")] [InlineData("{\"$level\":1}")] public async Task AFilterItReads_IsBuilt(string filterJson) { (await BuildQueryAsync(filterJson)).Should().NotBeNullOrEmpty(); } [Fact] public async Task AnAggregateOnAFieldTheSchemeDoesNotHave_IsRefused() { var build = async () => await BuildAggregateAsync("[{\"alias\":\"s\",\"$sum\":{\"$field\":\"NoSuchField\"}}]"); await build.Should().ThrowAsync().WithMessage("*redb:*"); } [Fact] public async Task AnAggregateItReads_IsBuilt() { (await BuildAggregateAsync("[{\"alias\":\"s\",\"$sum\":{\"$field\":\"Salary\"}}]")).Should().Contain("SUM("); } } Path: redb/redb.Tests.Integration/Tests/MsSql/MsSqlFreeListItemJsonTests.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/MsSql/MsSqlFreeListItemJsonTests.cs ---- using Microsoft.Extensions.Configuration; using redb.Core.Extensions; using redb.MSSql.Extensions; using redb.Tests.Integration.Tests.Base; namespace redb.Tests.Integration.Tests.MsSql; public class MsSqlFreeListItemJsonTests : FreeListItemJsonTestsBase { protected override void UseProvider(RedbOptionsBuilder options) { var cs = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build().GetConnectionString("MSSql")!; options.UseMsSql(cs); } } Path: redb/redb.Tests.Integration/Tests/MsSql/MsSqlGroupByHavingTests.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/MsSql/MsSqlGroupByHavingTests.cs ---- using redb.Tests.Integration.Fixtures; using redb.Tests.Integration.Tests.Base; namespace redb.Tests.Integration.Tests.MsSql; [Collection("MsSql")] public class MsSqlGroupByHavingTests : GroupByHavingTestsBase { public MsSqlGroupByHavingTests(MsSqlFixture fixture) : base(fixture.Redb) { } } Path: redb/redb.Tests.Integration/Tests/MsSql/MsSqlGroupBySelectShapesTests.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/MsSql/MsSqlGroupBySelectShapesTests.cs ---- using redb.Tests.Integration.Fixtures; using redb.Tests.Integration.Tests.Base; namespace redb.Tests.Integration.Tests.MsSql; [Collection("MsSql")] public class MsSqlGroupBySelectShapesTests : GroupBySelectShapesTestsBase { public MsSqlGroupBySelectShapesTests(MsSqlFixture fixture) : base(fixture.Redb) { } } Path: redb/redb.Tests.Integration/Tests/MsSql/MsSqlGroupByTests.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/MsSql/MsSqlGroupByTests.cs ---- using redb.Tests.Integration.Fixtures; using redb.Tests.Integration.Tests.Base; namespace redb.Tests.Integration.Tests.MsSql; [Collection("MsSql")] public class MsSqlGroupByTests : GroupByTestsBase { public MsSqlGroupByTests(MsSqlFixture fixture) : base(fixture.Redb) { } } Path: redb/redb.Tests.Integration/Tests/MsSql/MsSqlIgnoredPropertyWalkTests.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/MsSql/MsSqlIgnoredPropertyWalkTests.cs ---- using Microsoft.Extensions.Configuration; using redb.Core.Extensions; using redb.MSSql.Extensions; using redb.Tests.Integration.Tests.Base; namespace redb.Tests.Integration.Tests.MsSql; public class MsSqlIgnoredPropertyWalkTests : IgnoredPropertyWalkTestsBase { protected override void UseProvider(RedbOptionsBuilder options) { var cs = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build().GetConnectionString("MSSql")!; options.UseMsSql(cs); } } Path: redb/redb.Tests.Integration/Tests/MsSql/MsSqlImportTriggerStateTests.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/MsSql/MsSqlImportTriggerStateTests.cs ---- using Microsoft.Data.SqlClient; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Core; using redb.Core.Data; using redb.Core.Extensions; using redb.Core.Models.Entities; using redb.Export.Providers; using redb.Export.Services; using redb.MSSql.Extensions; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.MsSql; /// /// An import into SQL Server turns off the table triggers for the load and turns on afterwards exactly the ones that were /// on. It ran ENABLE TRIGGER ALL, which also switched on tr_auto_create_node_permissions, a trigger the schema keeps off /// (as on PostgreSQL): after any import every new object got permission rows the application does not write. The /// triggers turned off are kept in a table of the database, so a parallel load that dies leaves the next run the list. /// public class MsSqlImportTriggerStateTests : IAsyncLifetime { private string _server = null!; private readonly List _databases = []; private readonly List _files = []; public Task InitializeAsync() { _server = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build().GetConnectionString("MSSql")!; return Task.CompletedTask; } public async Task DisposeAsync() { SqlConnection.ClearAllPools(); foreach (var database in _databases) await ExecuteAsync(Master(), $"IF DB_ID('{database}') IS NOT NULL BEGIN ALTER DATABASE [{database}] SET SINGLE_USER WITH ROLLBACK IMMEDIATE; DROP DATABASE [{database}] END"); foreach (var file in _files) File.Delete(file); } [Theory] [InlineData(1)] [InlineData(2)] public async Task AnImport_LeavesEveryTriggerAsItFoundIt(int parallelism) { var file = await ExportOfSeededAsync(); var target = await SeededAsync("dst"); var before = await TriggersAsync(target); before.Should().Contain("tr_auto_create_node_permissions disabled=1", "precondition: the schema keeps it off"); await using (var provider = ProviderFactory.Create("mssql")) { await provider.OpenAsync(target); await new ImportService(provider, verbose: false, batchSize: 1000, parallelism: parallelism) .ImportAsync(file, clean: true, dryRun: false); } RedbKeyGeneratorBase.ClearAllCaches(); (await TriggersAsync(target)).Should().Equal(before); (await ScalarAsync(target, "SELECT COUNT(*) FROM sys.tables WHERE name = '_import_disabled_triggers'")).Should().Be("0"); } [Fact] public async Task TheTriggersADeadLoadTurnedOff_AreTurnedOnByTheNextRun_AndNoOthers() { var target = await SeededAsync("dead"); var before = await TriggersAsync(target); // A load that turned the triggers off and died. await using (var dead = ProviderFactory.Create("mssql")) { await dead.OpenAsync(target); await dead.DisableConstraintsAsync(); } (await TriggersAsync(target)).Should().OnlyContain(t => t.EndsWith("disabled=1", StringComparison.Ordinal)); // The next run turns off nothing more and turns on what the dead one turned off. await using (var next = ProviderFactory.Create("mssql")) { await next.OpenAsync(target); await next.DisableConstraintsAsync(); await next.EnableConstraintsAsync(); } (await TriggersAsync(target)).Should().Equal(before); } private async Task> TriggersAsync(string cs) { var lines = new List(); await using var connection = new SqlConnection(cs); await connection.OpenAsync(); await using var command = new SqlCommand( "SELECT name + ' disabled=' + CAST(is_disabled AS varchar(1)) FROM sys.triggers WHERE parent_class = 1 ORDER BY name", connection); await using var reader = await command.ExecuteReaderAsync(); while (await reader.ReadAsync()) lines.Add(reader.GetString(0)); return lines; } private async Task ExportOfSeededAsync() { var source = await SeededAsync("src"); var file = Path.Combine(Path.GetTempPath(), $"redb-export-trg-{Guid.NewGuid():N}.redb"); _files.Add(file); await using var provider = ProviderFactory.Create("mssql"); await provider.OpenAsync(source); await new ExportService(provider, verbose: false, batchSize: 1000).ExportAsync(file, null, compress: false, dryRun: false); return file; } private async Task SeededAsync(string suffix) { var name = $"redb_export_trg_{Guid.NewGuid().ToString("N")[..12]}_{suffix}"; _databases.Add(name); await ExecuteAsync(Master(), $"CREATE DATABASE [{name}]"); var cs = new SqlConnectionStringBuilder(_server) { InitialCatalog = name }.ConnectionString; var services = new ServiceCollection(); services.AddLogging(b => b.SetMinimumLevel(LogLevel.Warning)); services.AddRedb(options => options.UseMsSql(cs).Configure(c => c.CacheDomain = $"trg-{Guid.NewGuid():N}")); await using var provider = services.BuildServiceProvider(); var redb = provider.GetRequiredService(); await redb.InitializeAsync(ensureCreated: true, typeof(ExportService).Assembly); await redb.SyncSchemeAsync(); await redb.SaveAsync(new RedbObject { name = $"{suffix}-object", Props = new SimpleProps { Title = suffix } }); return cs; } private string Master() => new SqlConnectionStringBuilder(_server) { InitialCatalog = "master" }.ConnectionString; private static async Task ScalarAsync(string cs, string sql) { await using var connection = new SqlConnection(cs); await connection.OpenAsync(); await using var command = new SqlCommand(sql, connection); return Convert.ToString(await command.ExecuteScalarAsync()); } private static async Task ExecuteAsync(string cs, string sql) { await using var connection = new SqlConnection(cs); await connection.OpenAsync(); await using var command = new SqlCommand(sql, connection); await command.ExecuteNonQueryAsync(); } } Path: redb/redb.Tests.Integration/Tests/MsSql/MsSqlIndexCatalogTests.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/MsSql/MsSqlIndexCatalogTests.cs ---- using Microsoft.Data.SqlClient; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using redb.Core.Data; using redb.Core.Extensions; using redb.Core.Models; using redb.Core.Models.Configuration; using redb.MSSql.Extensions; using redb.MSSql.Sql; using redb.Tests.Integration.Tests.Base; namespace redb.Tests.Integration.Tests.MsSql; /// MsSqlIndexCatalog.Base against a fresh SQL Server database of this build (see ). public class MsSqlIndexCatalogTests : IndexCatalogTestsBase { internal static readonly string AdminBase = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build().GetConnectionString("MSSql")!; protected override async Task CreateDatabaseAsync(string name) { await ExecAdminAsync($"CREATE DATABASE [{name}]"); return new SqlConnectionStringBuilder(AdminBase) { InitialCatalog = name }.ConnectionString; } protected override async Task DropDatabaseAsync(string name) { SqlConnection.ClearAllPools(); await ExecAdminAsync($"IF DB_ID(N'{name}') IS NOT NULL BEGIN ALTER DATABASE [{name}] SET SINGLE_USER WITH ROLLBACK IMMEDIATE; DROP DATABASE [{name}]; END"); } internal static async Task ExecAdminAsync(string sql) { var cs = new SqlConnectionStringBuilder(AdminBase) { InitialCatalog = "master", Pooling = false }.ConnectionString; await using var connection = new SqlConnection(cs); await connection.OpenAsync(); await using var command = new SqlCommand(sql, connection) { CommandTimeout = 300 }; await command.ExecuteNonQueryAsync(); } protected override void AddRedb(IServiceCollection services, string connectionString, Action configure) => services.AddRedb(o => o.UseMsSql(connectionString).Configure(configure)); // SQL Server keeps no statement: it is written from the catalog, keys in order with their direction, the INCLUDE list, // the filter. The repair appends WITH (ONLINE = ON) where the edition has it. protected override async Task> ReadCreateStatementsAsync(IRedbContext context) { var rows = await context.QueryAsync( """ SELECT i.name AS [Name], 'CREATE ' + CASE WHEN i.is_unique = 1 THEN 'UNIQUE ' ELSE '' END + 'NONCLUSTERED INDEX [' + i.name + '] ON [dbo].[' + t.name + '] (' + (SELECT STRING_AGG('[' + c.name + ']' + CASE WHEN ic.is_descending_key = 1 THEN ' DESC' ELSE '' END, ', ') WITHIN GROUP (ORDER BY ic.key_ordinal) FROM sys.index_columns ic JOIN sys.columns c ON c.object_id = ic.object_id AND c.column_id = ic.column_id WHERE ic.object_id = i.object_id AND ic.index_id = i.index_id AND ic.is_included_column = 0 AND ic.key_ordinal > 0) + ')' + ISNULL(' INCLUDE (' + (SELECT STRING_AGG('[' + c.name + ']', ', ') WITHIN GROUP (ORDER BY ic.index_column_id) FROM sys.index_columns ic JOIN sys.columns c ON c.object_id = ic.object_id AND c.column_id = ic.column_id WHERE ic.object_id = i.object_id AND ic.index_id = i.index_id AND ic.is_included_column = 1) + ')', '') + CASE WHEN i.has_filter = 1 THEN ' WHERE ' + i.filter_definition ELSE '' END AS [Sql] FROM sys.indexes i JOIN sys.tables t ON t.object_id = i.object_id WHERE SCHEMA_NAME(t.schema_id) = 'dbo' AND i.type > 0 AND i.name IS NOT NULL """); return rows.ToDictionary(r => r.Name!, r => r.Sql!, StringComparer.OrdinalIgnoreCase); } protected override IReadOnlyList Catalog => MsSqlIndexCatalog.Base; protected override (string File, string Namespace, string Class, string Member, RedbIndexOrigin Origin) Target => ("redb.MSSql/sql/MsSqlIndexCatalog.g.cs", "redb.MSSql.Sql", "MsSqlIndexCatalog", "Base", RedbIndexOrigin.Base); protected sealed class SqlRow { public string? Name { get; set; } public string? Sql { get; set; } } } /// The index check and its repair on SQL Server (ONLINE where the edition has it), see . public class MsSqlIndexRepairTests : IndexRepairTestsBase { protected override async Task CreateDatabaseAsync(string name) { await MsSqlIndexCatalogTests.ExecAdminAsync($"CREATE DATABASE [{name}]"); return new SqlConnectionStringBuilder(MsSqlIndexCatalogTests.AdminBase) { InitialCatalog = name }.ConnectionString; } protected override async Task DropDatabaseAsync(string name) { SqlConnection.ClearAllPools(); await MsSqlIndexCatalogTests.ExecAdminAsync( $"IF DB_ID(N'{name}') IS NOT NULL BEGIN ALTER DATABASE [{name}] SET SINGLE_USER WITH ROLLBACK IMMEDIATE; DROP DATABASE [{name}]; END"); } protected override void AddRedb(IServiceCollection services, string connectionString, Action configure) => services.AddRedb(o => o.UseMsSql(connectionString).Configure(configure)); protected override string DropIndexSql(string table, string index) => $"DROP INDEX [{index}] ON [dbo].[{table}]"; protected override string CreateOtherIndexSql(string index) => $"CREATE INDEX [{index}] ON [dbo].[_objects] ([_date_create])"; } Path: redb/redb.Tests.Integration/Tests/MsSql/MsSqlInjectionHardeningTests.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/MsSql/MsSqlInjectionHardeningTests.cs ---- using AwesomeAssertions; using Microsoft.Data.SqlClient; using Microsoft.Extensions.DependencyInjection; using redb.Core.Data; using redb.Core.Models.Users; using redb.Core.Query.Aggregation; using redb.Core.Serialization; using redb.MSSql.Query; using redb.Tests.Integration.Fixtures; using redb.Tests.Integration.Models; using Xunit; namespace redb.Tests.Integration.Tests.MsSql; /// /// Fail-closed checks for the Free SQL Server module (SQLI-PoC, MSSQL half). The two builders used /// to echo a caller-supplied name inside a comment, where a crafted name closed the comment and the /// remainder became live T-SQL; both now call dbo.pvt_fail. The LIKE check covers the bracket that /// SQL Server reads as a character-class opener while PostgreSQL and SQLite read it literally. /// [Collection("MsSql")] public class MsSqlInjectionHardeningTests(MsSqlFixture fixture) { private MssqlQueryProvider Provider => new( fixture.ServiceProvider.GetRequiredService(), fixture.ServiceProvider.GetRequiredService(), schemeSync: fixture.Redb); private IRedbContext Ctx => fixture.ServiceProvider.GetRequiredService(); private async Task EmployeeSchemeIdAsync() => (await fixture.Redb.LoadSchemeByTypeAsync()).Id; [Fact] public async Task UnknownFieldInExprFilter_FailsClosed() { var schemeId = await EmployeeSchemeIdAsync(); // The control run proves the filter shape itself is fine: a legitimate bound, no rows. var control = async () => await Provider.ExecuteAggregateAsync( schemeId, "Age", AggregateFunction.Sum, """{"$expr":{"$gt":[{"$field":"Age"},{"$const":9999}]}}"""); await control.Should().NotThrowAsync(); // The payload closes the comment the builder used to emit around the unknown field name. var act = async () => await Provider.ExecuteAggregateAsync( schemeId, "Age", AggregateFunction.Sum, """{"$expr":{"$gt":[{"$field":"x*/ 1 = 1 OR /*"},{"$const":0}]}}"""); var ex = (await act.Should().ThrowAsync()).Which; ex.Message.Should().Contain("unknown props field"); } [Fact] public async Task UnknownWindowFunction_FailsClosedInSql() { // pvt_build_window_expr(node, fields, base_prefix): an unsupported function name must not // travel into the returned SQL. Called straight at the module, since the C# layer refuses // such a name even earlier. var act = async () => await Ctx.ExecuteScalarAsync( "SELECT dbo.pvt_build_window_expr($1, $2, $3)", new object[] { """{"func":"x*/ as [i],(select count(*) from sys.objects)/*"}""", "{}", "" }); var ex = (await act.Should().ThrowAsync()).Which; ex.Message.Should().Contain("unsupported window function"); } [Fact] public async Task WindowFunctionName_FromCSharp_IsRefused() { var schemeId = await EmployeeSchemeIdAsync(); var act = async () => await Provider.ExecuteWindowQueryAsync( schemeId, selectFields: [], windowFuncs: [new redb.Core.Query.Window.WindowFuncRequest { Func = "ROW_NUMBER) OVER (ORDER BY 1)--", Alias = "v" }], partitionBy: [], orderBy: []); // Two layers can refuse it: the C# gate (ArgumentException from WindowFunctionName) and the // T-SQL module (SqlException from dbo.pvt_fail). Either is fail-closed, which is the point. var ex = await act.Should().ThrowAsync(); ex.Which.Message.Should().MatchRegex("(?i)unsupported window function|plain identifier"); } [Fact] public async Task ExactEmailSearch_DoesNotTreatBracketAsCharacterClass() { var suffix = Guid.NewGuid().ToString("N")[..8]; var email = $"poc.user{suffix}@example.com"; await fixture.Redb.UserProvider.CreateUserAsync(new CreateUserRequest { Login = $"poc_like_{suffix}", Password = "Poc!12345", Name = "POC Like User", Email = email }); // Control: the plain address matches, a different one does not. var exact = await fixture.Redb.UserProvider.GetUsersAsync(new UserSearchCriteria { EmailExact = email }); exact.Should().ContainSingle(u => u.Email == email); var miss = await fixture.Redb.UserProvider.GetUsersAsync( new UserSearchCriteria { EmailExact = $"poc.userz{suffix}@example.com" }); miss.Should().BeEmpty(); // The payload used to act as a character class and match a different address. var evil = $"poc.user[{suffix[0]}]{suffix[1..]}@example.com"; var byEvil = await fixture.Redb.UserProvider.GetUsersAsync(new UserSearchCriteria { EmailExact = evil }); byEvil.Should().BeEmpty("'[' must be searched literally, not as a LIKE character class"); } } Path: redb/redb.Tests.Integration/Tests/MsSql/MsSqlIntegerAverageTests.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/MsSql/MsSqlIntegerAverageTests.cs ---- using redb.Tests.Integration.Fixtures; using redb.Tests.Integration.Tests.Base; namespace redb.Tests.Integration.Tests.MsSql; [Collection("MsSql")] public class MsSqlIntegerAverageTests : IntegerAverageTestsBase { public MsSqlIntegerAverageTests(MsSqlFixture fixture) : base(fixture.Redb) { } } Path: redb/redb.Tests.Integration/Tests/MsSql/MsSqlLazyHostTests.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/MsSql/MsSqlLazyHostTests.cs ---- using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using redb.Core.Extensions; using redb.MSSql.Extensions; using redb.Tests.Integration.Tests.Base; namespace redb.Tests.Integration.Tests.MsSql; public class MsSqlLazyHostTests : LazyHostTestsBase { protected override void UseProvider(RedbOptionsBuilder options) { var cs = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build().GetConnectionString("MSSql")!; options.UseMsSql(cs); } protected override string ReadFlagSql => "SELECT CAST(SESSION_CONTEXT(N'redb.lazy_refs') AS NVARCHAR(10))"; } Path: redb/redb.Tests.Integration/Tests/MsSql/MsSqlLazyReferenceTests.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/MsSql/MsSqlLazyReferenceTests.cs ---- using redb.Tests.Integration.Fixtures; using redb.Tests.Integration.Tests.Base; namespace redb.Tests.Integration.Tests.MsSql; [Collection("MsSql")] public class MsSqlLazyReferenceTests : LazyReferenceTestsBase { public MsSqlLazyReferenceTests(MsSqlFixture fixture) : base(fixture.Redb) { } } Path: redb/redb.Tests.Integration/Tests/MsSql/MsSqlLazyReferencesOptionTests.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/MsSql/MsSqlLazyReferencesOptionTests.cs ---- using redb.Tests.Integration.Fixtures; using redb.Tests.Integration.Tests.Base; namespace redb.Tests.Integration.Tests.MsSql; [Collection("MsSql")] public class MsSqlLazyReferencesOptionTests : LazyReferencesOptionTestsBase { public MsSqlLazyReferencesOptionTests(MsSqlFixture fixture) : base(fixture.Redb) { } } Path: redb/redb.Tests.Integration/Tests/MsSql/MsSqlLikeEscapingTests.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/MsSql/MsSqlLikeEscapingTests.cs ---- using redb.Tests.Integration.Fixtures; using redb.Tests.Integration.Tests.Base; namespace redb.Tests.Integration.Tests.MsSql; [Collection("MsSql")] public class MsSqlLikeEscapingTests : LikeEscapingTestsBase { public MsSqlLikeEscapingTests(MsSqlFixture fixture) : base(fixture.Redb) { } } Path: redb/redb.Tests.Integration/Tests/MsSql/MsSqlListItemArrayAnyTests.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/MsSql/MsSqlListItemArrayAnyTests.cs ---- using redb.Tests.Integration.Fixtures; using redb.Tests.Integration.Tests.Base; namespace redb.Tests.Integration.Tests.MsSql; [Collection("MsSql")] public class MsSqlListItemArrayAnyTests : ListItemArrayAnyTestsBase { public MsSqlListItemArrayAnyTests(MsSqlFixture fixture) : base(fixture.Redb) { } } Path: redb/redb.Tests.Integration/Tests/MsSql/MsSqlListItemObjectWalkTests.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/MsSql/MsSqlListItemObjectWalkTests.cs ---- using Microsoft.Extensions.Configuration; using redb.Core.Extensions; using redb.MSSql.Extensions; using redb.Tests.Integration.Tests.Base; namespace redb.Tests.Integration.Tests.MsSql; public class MsSqlListItemObjectWalkTests : ListItemObjectWalkTestsBase { protected override void UseProvider(RedbOptionsBuilder options) { var cs = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build().GetConnectionString("MSSql")!; options.UseMsSql(cs); } } Path: redb/redb.Tests.Integration/Tests/MsSql/MsSqlListReadPropsOnceTests.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/MsSql/MsSqlListReadPropsOnceTests.cs ---- using Microsoft.Extensions.Configuration; using redb.Core.Extensions; using redb.MSSql.Extensions; using redb.Tests.Integration.Tests.Base; namespace redb.Tests.Integration.Tests.MsSql; public class MsSqlListReadPropsOnceTests : ListReadPropsOnceTestsBase { protected override void UseProvider(RedbOptionsBuilder options) { var cs = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build().GetConnectionString("MSSql")!; options.UseMsSql(cs); } } Path: redb/redb.Tests.Integration/Tests/MsSql/MsSqlListTests.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/MsSql/MsSqlListTests.cs ---- using redb.Tests.Integration.Fixtures; using redb.Tests.Integration.Tests.Base; namespace redb.Tests.Integration.Tests.MsSql; [Collection("MsSql")] public class MsSqlListTests : ListTestsBase { public MsSqlListTests(MsSqlFixture fixture) : base(fixture.Redb) { } } Path: redb/redb.Tests.Integration/Tests/MsSql/MsSqlLockForUpdateTests.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/MsSql/MsSqlLockForUpdateTests.cs ---- using redb.Tests.Integration.Fixtures; using redb.Tests.Integration.Tests.Base; namespace redb.Tests.Integration.Tests.MsSql; [Collection("MsSql")] public class MsSqlLockForUpdateTests : LockForUpdateTestsBase { public MsSqlLockForUpdateTests(MsSqlFixture fixture) : base(fixture.Redb) { } } Path: redb/redb.Tests.Integration/Tests/MsSql/MsSqlLongBaseFilterTests.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/MsSql/MsSqlLongBaseFilterTests.cs ---- using redb.Tests.Integration.Fixtures; using redb.Tests.Integration.Tests.Base; namespace redb.Tests.Integration.Tests.MsSql; [Collection("MsSql")] public class MsSqlLongBaseFilterTests : LongBaseFilterTestsBase { public MsSqlLongBaseFilterTests(MsSqlFixture fixture) : base(fixture.Redb) { } } Path: redb/redb.Tests.Integration/Tests/MsSql/MsSqlMaintenanceTests.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/MsSql/MsSqlMaintenanceTests.cs ---- using Microsoft.Data.SqlClient; using Microsoft.Extensions.DependencyInjection; using redb.Core.Data; using redb.MSSql.Data; using redb.MSSql.Providers; using redb.Tests.Integration.Fixtures; using redb.Tests.Integration.Tests.Base; namespace redb.Tests.Integration.Tests.MsSql; [Collection("MsSql")] public class MsSqlMaintenanceTests : MaintenanceTestsBase { private readonly MsSqlFixture _fixture; public MsSqlMaintenanceTests(MsSqlFixture fixture) : base(fixture.Redb) => _fixture = fixture; [Fact] public async Task StatisticsWindow_WithoutServerStateRight_HasNoStart() { // A database owner without VIEW SERVER STATE: a temporary login, db_owner of the test // database and nothing at server level. Pooling is off so the login can be dropped at once. var adminCs = ((SqlRedbContext)_fixture.ServiceProvider.GetRequiredService()).ConnectionString; const string login = "redb_test_no_server_state"; var password = "Rt1!" + Guid.NewGuid().ToString("N"); var ownerCs = new SqlConnectionStringBuilder(adminCs) { UserID = login, Password = password, Pooling = false } .ConnectionString; await using var admin = new SqlRedbContext(adminCs); await DropLoginAsync(admin, login); await admin.ExecuteAsync($"CREATE LOGIN [{login}] WITH PASSWORD = '{password}', CHECK_POLICY = OFF"); try { await admin.ExecuteAsync($"CREATE USER [{login}] FOR LOGIN [{login}]"); await admin.ExecuteAsync($"ALTER ROLE db_owner ADD MEMBER [{login}]"); await using var owner = new SqlRedbContext(ownerCs); var maintenance = new MssqlMaintenanceProvider(owner, 1000); var window = await maintenance.GetStatisticsWindowAsync(); window.CountersSince.Should().BeNull("the instance start time needs a server-level right"); (await maintenance.GetTableStatsAsync()).Should().Contain(t => t.Table == "_values"); // The usage counters come from a server-level DMV as well: without the right the // indexes and their sizes are still listed, the counters are null. var indexes = await maintenance.GetIndexStatsAsync(); indexes.Should().Contain(s => s.Table == "_values" && s.SizeBytes > 0); indexes.Should().OnlyContain(s => s.Seeks == null && s.Scans == null && s.Updates == null); } finally { await DropLoginAsync(admin, login); } } private static async Task DropLoginAsync(IRedbContext admin, string login) { await admin.ExecuteAsync($"DROP USER IF EXISTS [{login}]"); await admin.ExecuteAsync( $"IF SUSER_ID('{login}') IS NOT NULL DROP LOGIN [{login}]"); } }