Path: redb/redb.Core/Models/RedbIndexCheck.cs
Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the 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/Models/RedbIndexCheck.cs
----
using System;
using System.Collections.Generic;
using System.Linq;
namespace redb.Core.Models
{
/// Where an expected index comes from.
public enum RedbIndexOrigin
{
/// The base schema every redb database has.
Base = 1,
/// A Pro module (the indexes of the streams query form), built once at the module step that brings it.
ProModule = 2,
}
/// What the check found about one expected index.
public enum RedbIndexState
{
/// No index of that name.
Missing = 1,
/// PostgreSQL: the index exists but is INVALID, left by an interrupted CREATE INDEX CONCURRENTLY.
Invalid = 2,
/// An index of that name exists with other key columns, included columns or uniqueness. Never changed by the repair.
Differs = 3,
}
/// One index the database is expected to have, as a fresh database of this build has it.
public sealed class RedbExpectedIndex
{
public RedbExpectedIndex(string name, string table, bool isUnique, IReadOnlyList keyColumns,
IReadOnlyList includedColumns, string createSql, RedbIndexOrigin origin = RedbIndexOrigin.Base)
{
Name = name;
Table = table;
IsUnique = isUnique;
KeyColumns = keyColumns;
IncludedColumns = includedColumns;
CreateSql = createSql;
Origin = origin;
}
/// Index name.
public string Name { get; }
/// Table of the index.
public string Table { get; }
/// Whether it is unique.
public bool IsUnique { get; }
/// Key columns in index order, lower case.
public IReadOnlyList KeyColumns { get; }
/// Included (covered, not keyed) columns, lower case, in no particular order.
public IReadOnlyList IncludedColumns { get; }
/// The statement that creates it on this provider, as a fresh database of this build has it.
public string CreateSql { get; }
/// Base schema or a Pro module.
public RedbIndexOrigin Origin { get; }
/// The same index with another origin.
public RedbExpectedIndex WithOrigin(RedbIndexOrigin origin)
=> new(Name, Table, IsUnique, KeyColumns, IncludedColumns, CreateSql, origin);
///
/// A statement on one line: every run of whitespace outside quoted text ('...', "...", [...]) becomes one space.
/// The tables keep their statements this way, so line endings of a checkout cannot change them.
///
public static string OneLine(string sql)
{
var sb = new System.Text.StringBuilder(sql.Length);
char quote = '\0';
var space = false;
foreach (var ch in sql.Trim())
{
if (quote != '\0')
{
sb.Append(ch);
if (ch == quote) quote = '\0';
continue;
}
if (char.IsWhiteSpace(ch))
{
space = true;
continue;
}
if (space) { sb.Append(' '); space = false; }
sb.Append(ch);
if (ch == '\'' || ch == '"') quote = ch;
else if (ch == '[') quote = ']';
}
return sb.ToString();
}
}
/// One index as the database has it, read from its catalog for the check.
public sealed class RedbIndexShape
{
/// Index name.
public string Name { get; set; } = string.Empty;
/// Table of the index.
public string Table { get; set; } = string.Empty;
/// Whether it is unique.
public bool IsUnique { get; set; }
/// Key columns in index order.
public IReadOnlyList KeyColumns { get; set; } = Array.Empty();
/// Included columns.
public IReadOnlyList IncludedColumns { get; set; } = Array.Empty();
/// False only for a PostgreSQL index left INVALID by an interrupted concurrent build.
public bool IsValid { get; set; } = true;
}
/// An expected index that is missing, INVALID, or defined otherwise.
public sealed class RedbIndexFinding
{
public RedbIndexFinding(RedbExpectedIndex expected, RedbIndexState state, RedbIndexShape? actual, string serves)
{
Expected = expected;
State = state;
Actual = actual;
Serves = serves;
}
/// The index as this build expects it.
public RedbExpectedIndex Expected { get; }
/// Missing, Invalid or Differs.
public RedbIndexState State { get; }
/// The index of that name the database has; null when it is missing.
public RedbIndexShape? Actual { get; }
/// What the index serves, in a few words: an operator who dropped it on purpose can judge from this.
public string Serves { get; }
/// Index name.
public string Name => Expected.Name;
/// One line for a log or a console.
public override string ToString()
{
var origin = Expected.Origin == RedbIndexOrigin.Base ? "base" : "Pro module";
var text = $"{Name} on {Expected.Table} ({origin}): {State}";
if (State == RedbIndexState.Differs && Actual != null)
text += $" - expected ({string.Join(", ", Expected.KeyColumns)})"
+ (Expected.IncludedColumns.Count > 0 ? $" INCLUDE ({string.Join(", ", Expected.IncludedColumns)})" : "")
+ (Expected.IsUnique ? " UNIQUE" : "")
+ $", found ({string.Join(", ", Actual.KeyColumns)})"
+ (Actual.IncludedColumns.Count > 0 ? $" INCLUDE ({string.Join(", ", Actual.IncludedColumns)})" : "")
+ (Actual.IsUnique ? " UNIQUE" : "");
if (Serves.Length > 0)
text += $"; serves {Serves}";
return text;
}
}
///
/// What found: the expected indexes of the base schema and of the Pro
/// modules in use that are missing, INVALID or defined otherwise. Indexes the database has beyond these are not
/// reported: an operator may add his own.
///
public sealed class RedbIndexReport
{
public RedbIndexReport(IReadOnlyList findings, int expectedCount)
{
Findings = findings;
ExpectedCount = expectedCount;
}
/// The findings, base indexes first.
public IReadOnlyList Findings { get; }
/// How many indexes were expected.
public int ExpectedCount { get; }
/// True when every expected index is there as expected.
public bool IsClean => Findings.Count == 0;
/// The findings the repair acts on: Missing and Invalid.
public IEnumerable Repairable => Findings.Where(f => f.State != RedbIndexState.Differs);
}
///
/// A place in _values that holds more than one row where a unique index allows one: the index, the object, the
/// structure and how many rows. Found by before it builds.
///
public sealed record RedbIndexDuplicate(string Index, long ObjectId, long StructureId, long Rows)
{
public override string ToString() => $"{Index}: object {ObjectId}, structure {StructureId}, {Rows} rows";
}
/// What did.
public sealed class RedbIndexRepairResult
{
/// A result with no duplicate rows found (the constructor of 4.8.0).
public RedbIndexRepairResult(IReadOnlyList built, IReadOnlyList notBuilt,
IReadOnlyList statements, string? reason)
: this(built, notBuilt, statements, reason, null)
{
}
public RedbIndexRepairResult(IReadOnlyList built, IReadOnlyList notBuilt,
IReadOnlyList statements, string? reason, IReadOnlyList? duplicates)
{
Built = built;
NotBuilt = notBuilt;
Statements = statements;
Reason = reason;
Duplicates = duplicates ?? Array.Empty();
}
///
/// The rows that kept a unique index from being built: for each such index, the places that hold more than one
/// row (at most 100 per index). The repair deletes nothing; those indexes are in .
///
public IReadOnlyList Duplicates { get; }
/// Names of the indexes built (an INVALID one dropped and built again).
public IReadOnlyList Built { get; }
/// Repairable findings left as they are (see ), and every Differs finding.
public IReadOnlyList NotBuilt { get; }
///
/// The statements for the indexes not built when the engine cannot build them online (SQL Server editions without
/// ONLINE index operations): to run in a maintenance window, or again with offline building allowed.
///
public IReadOnlyList Statements { get; }
/// Why repairable findings were not built; null when all were.
public string? Reason { get; }
}
/// The comparison of expected indexes with the catalog, shared by every provider.
public static class RedbIndexComparer
{
///
/// Findings for against : by name, case-insensitive; column
/// lists compared case-insensitively, key columns in order, included columns as a set.
///
public static RedbIndexReport Compare(IReadOnlyList expected, IReadOnlyList actual)
{
var byName = new Dictionary(StringComparer.OrdinalIgnoreCase);
foreach (var index in actual)
byName.TryAdd(index.Name, index);
var findings = new List();
foreach (var index in expected.OrderBy(e => e.Origin).ThenBy(e => e.Table, StringComparer.Ordinal)
.ThenBy(e => e.Name, StringComparer.Ordinal))
{
var serves = RedbIndexPurpose.Of(index.Name);
if (!byName.TryGetValue(index.Name, out var found))
findings.Add(new RedbIndexFinding(index, RedbIndexState.Missing, null, serves));
else if (!found.IsValid)
findings.Add(new RedbIndexFinding(index, RedbIndexState.Invalid, found, serves));
else if (!SameShape(index, found))
findings.Add(new RedbIndexFinding(index, RedbIndexState.Differs, found, serves));
}
return new RedbIndexReport(findings, expected.Count);
}
private static bool SameShape(RedbExpectedIndex expected, RedbIndexShape actual)
=> expected.IsUnique == actual.IsUnique
&& string.Equals(expected.Table, actual.Table, StringComparison.OrdinalIgnoreCase)
&& expected.KeyColumns.Select(Norm).SequenceEqual(actual.KeyColumns.Select(Norm))
&& expected.IncludedColumns.Select(Norm).OrderBy(c => c, StringComparer.Ordinal)
.SequenceEqual(actual.IncludedColumns.Select(Norm).OrderBy(c => c, StringComparer.Ordinal));
private static string Norm(string column) => column.Trim().Trim('"', '[', ']').ToLowerInvariant();
}
}