Path: redb/redb.Core/RedbServiceBase.Indexes.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Core/RedbServiceBase.Indexes.cs ---- using Microsoft.Extensions.Logging; using redb.Core.Models; namespace redb.Core; // The index check and the repair (CheckBaseIndexesAsync, RepairBaseIndexesAsync, CheckBaseIndexesOnStart). The expected // indexes are a table per provider, generated from a fresh database of this build and pinned by a test against one; the // actual ones come from the catalog in one read. Start-up only reports: an operator may have dropped an index on purpose. public abstract partial class RedbServiceBase { /// /// Whether this service moved the database to the module version of this build (created the schema, or applied the /// module bundle), and from which version: null for a database it created. A Pro module builds its indexes at such a /// step only, and only when the step comes from below the version that brought them; at any other start a missing /// one is reported by the index check, not built. /// protected (bool Applied, string? From) ModuleStep { get; private set; } /// /// Whether the module step of this start () is the one that brings a set of module indexes /// introduced at : a database created now, or one coming from a module older than that. /// protected bool ModuleStepBrings(string since) => ModuleStep.Applied && (string.IsNullOrEmpty(ModuleStep.From) || Data.ModuleCompatibility.IsNewer(since, ModuleStep.From)); /// /// The indexes a fresh database of this build has, for the provider (and with Pro, the module indexes in use). Empty /// where the provider has no table: the check then reports nothing. /// protected virtual IReadOnlyList ExpectedIndexes => Array.Empty(); /// /// Every index of the redb tables as the catalog has it: name, table, uniqueness, key and included columns, and /// whether it is valid. Read through . /// protected virtual async Task> ReadIndexShapesAsync(CancellationToken cancellationToken) { var sql = SqlDialect.Schema_SelectIndexShapes(); if (string.IsNullOrEmpty(sql)) return Array.Empty(); var rows = await _context.QueryAsync(sql, Array.Empty(), cancellationToken); return rows.Select(r => new RedbIndexShape { Name = r.Name ?? string.Empty, Table = r.Table ?? string.Empty, IsUnique = r.IsUnique, KeyColumns = Split(r.KeyColumnsCsv), IncludedColumns = Split(r.IncludedColumnsCsv), IsValid = r.IsValid, }).ToList(); static IReadOnlyList Split(string? csv) => string.IsNullOrWhiteSpace(csv) ? Array.Empty() : csv.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) .Select(c => c.ToLowerInvariant()).ToArray(); } /// public async Task CheckBaseIndexesAsync(CancellationToken cancellationToken = default) { var expected = ExpectedIndexes; if (expected.Count == 0) return new RedbIndexReport(Array.Empty(), 0); return RedbIndexComparer.Compare(expected, await ReadIndexShapesAsync(cancellationToken)); } /// public async Task RepairBaseIndexesAsync(IReadOnlyCollection? names = null, bool allowOffline = false, CancellationToken cancellationToken = default) { bool Wanted(RedbIndexFinding f) => names == null || names.Contains(f.Name, StringComparer.OrdinalIgnoreCase); await using (await AcquireSchemaLockAsync(cancellationToken)) { // Asked again under the lock: another process may have built some meanwhile. var report = await CheckBaseIndexesAsync(cancellationToken); var differs = report.Findings.Where(f => f.State == RedbIndexState.Differs && Wanted(f)).ToList(); var todo = report.Repairable.Where(Wanted).ToList(); if (todo.Count == 0) return new RedbIndexRepairResult(Array.Empty(), differs, Array.Empty(), null); var refusal = await RefuseIndexBuildAsync(allowOffline, cancellationToken); if (refusal != null) { var statements = todo.Select(f => IndexBuildStatement(f.Expected, online: false)).ToList(); _logger?.LogWarning("Indexes not built: {Reason} Statements: {Statements}", refusal, string.Join("; ", statements)); return new RedbIndexRepairResult(Array.Empty(), todo.Concat(differs).ToList(), statements, refusal); } var built = new List(); var blocked = new List(); var duplicates = new List(); foreach (var finding in todo) { cancellationToken.ThrowIfCancellationRequested(); var found = await FindValueIndexDuplicatesAsync(finding.Expected, cancellationToken); if (found.Count > 0) { _logger?.LogWarning("Index {Index} not built: {Count} places hold more than one row, first {First}.", finding.Name, found.Count, found[0]); blocked.Add(finding); duplicates.AddRange(found); continue; } if (finding.State == RedbIndexState.Invalid) await ExecuteIndexDdlAsync(IndexDropStatement(finding.Expected), cancellationToken); var statement = IndexBuildStatement(finding.Expected, online: !allowOffline || await CanBuildOnlineAsync(cancellationToken)); _logger?.LogInformation("Building index {Index}: {Statement}", finding.Name, statement); await ExecuteIndexDdlAsync(statement, cancellationToken); built.Add(finding.Name); } if (blocked.Count == 0) return new RedbIndexRepairResult(built, differs, Array.Empty(), null); var reason = $"Some places in _values hold more than one row where a unique index allows one, so " + $"{string.Join(", ", blocked.Select(f => f.Name))} not built; nothing was deleted. Duplicates lists the places."; return new RedbIndexRepairResult(built, blocked.Concat(differs).ToList(), Array.Empty(), reason, duplicates); } } /// /// The places a unique index of _values keyed on the object and the structure would refuse: read through /// with the index's own key and filter. Empty for /// any other index and where the provider does not look. /// private async Task> FindValueIndexDuplicatesAsync(RedbExpectedIndex index, CancellationToken cancellationToken) { if (!index.IsUnique || !string.Equals(index.Table, "_values", StringComparison.OrdinalIgnoreCase) || !index.KeyColumns.Contains("_id_object", StringComparer.OrdinalIgnoreCase) || !index.KeyColumns.Contains("_id_structure", StringComparer.OrdinalIgnoreCase)) return Array.Empty(); var where = index.CreateSql.LastIndexOf(" WHERE ", StringComparison.OrdinalIgnoreCase); var predicate = where < 0 ? null : index.CreateSql[(where + " WHERE ".Length)..]; var sql = SqlDialect.Schema_SelectValueIndexDuplicates(index.KeyColumns, predicate); if (string.IsNullOrEmpty(sql)) return Array.Empty(); var rows = await _context.QueryAsync(sql, Array.Empty(), cancellationToken); return rows.Select(r => new RedbIndexDuplicate(index.Name, r.ObjectId, r.StructureId, r.Rows)).ToList(); } /// /// Why the repair must not build here, or null when it may. The base answer is null; SQL Server refuses on an edition /// without ONLINE index operations unless is set. /// protected virtual Task RefuseIndexBuildAsync(bool allowOffline, CancellationToken cancellationToken) => Task.FromResult(null); /// Whether the engine builds an index online (SQL Server: the edition). True elsewhere. protected virtual Task CanBuildOnlineAsync(CancellationToken cancellationToken) => Task.FromResult(true); /// /// The statement that builds : the provider's own form of /// (PostgreSQL CONCURRENTLY, SQL Server ONLINE = ON when ). /// protected virtual string IndexBuildStatement(RedbExpectedIndex index, bool online) => index.CreateSql; /// The statement that drops an INVALID leftover of (PostgreSQL). protected virtual string IndexDropStatement(RedbExpectedIndex index) => $"DROP INDEX IF EXISTS \"{index.Name}\""; /// Runs an index statement; PostgreSQL runs it on a connection of its own, outside any transaction. protected virtual Task ExecuteIndexDdlAsync(string sql, CancellationToken cancellationToken) => _context.ExecuteAsync(sql); /// /// The start-up step of CheckBaseIndexesOnStart: one catalog read, one Warning naming what differs, nothing /// built. A failure of the read is logged and the start goes on. /// protected async Task ReportIndexesOnStartAsync() { if (!_configuration.CheckBaseIndexesOnStart || ExpectedIndexes.Count == 0) return; try { var report = await CheckBaseIndexesAsync(); if (report.IsClean) return; _logger?.LogWarning( "{Count} of {Expected} expected indexes are missing, INVALID or defined otherwise: {Findings}. " + "Nothing is built at start-up; RepairBaseIndexesAsync or 'redb indexes repair' builds the missing ones, " + "CheckBaseIndexesOnStart = false silences this line.", report.Findings.Count, report.ExpectedCount, string.Join("; ", report.Findings)); } catch (Exception ex) when (ex is not OperationCanceledException) { _logger?.LogWarning(ex, "The index check at start-up failed; the start goes on."); } } private sealed class IndexShapeRow { 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; } private sealed class DuplicateRow { public long ObjectId { get; set; } public long StructureId { get; set; } public long Rows { get; set; } } }