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; } }