Path: redb/redb.Core/Providers/Base/SchemeSyncProviderBase.cs
Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the 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/Providers/Base/SchemeSyncProviderBase.cs
----
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
using redb.Core.Attributes;
using redb.Core.Caching;
using redb.Core.Data;
using redb.Core.Exceptions;
using redb.Core.Models.Configuration;
using redb.Core.Models.Contracts;
using redb.Core.Models.Entities;
using redb.Core.Query;
using redb.Core.Utils;
using Microsoft.Extensions.Logging;
namespace redb.Core.Providers.Base;
///
/// Base class for scheme synchronization provider.
/// Contains all reflection logic and type mapping which is database-agnostic.
/// SQL queries are delegated to ISqlDialect.
///
public abstract partial class SchemeSyncProviderBase : ISchemeSyncProvider, ISchemeCacheProvider
{
protected readonly IRedbContext Context;
protected readonly RedbServiceConfiguration Configuration;
protected readonly ISqlDialect Sql;
protected readonly ILogger? Logger;
///
/// Cache domain identifier for isolating caches between different database connections.
///
protected readonly string CacheDomain;
///
/// Domain-bound metadata cache for this provider.
///
public GlobalMetadataCache Cache { get; }
///
/// Domain-bound list cache for this provider.
///
public GlobalListCache ListCache { get; }
///
/// Domain-bound props/object cache for this provider.
///
public GlobalPropsCache PropsCache { get; }
// The structure trees are cached with the schemes, per cache domain, in Cache (GlobalMetadataCache): scheme ids are
// per-database facts and collide across databases (review B-10), and every invalidation of a scheme drops its trees.
/// No longer used: the structure trees live in the scheme cache () and are dropped with
/// their scheme. Always empty; removed in the next major version.
[Obsolete("The structure trees live in the scheme cache (Cache) and are dropped with their scheme; this field is no longer filled or read and is removed in the next major version.")]
protected static readonly ConcurrentDictionary<(string Domain, long SchemeId), List> StructureTreeCache = new();
/// No longer used: the structure subtrees live in the scheme cache () and are dropped
/// with their scheme. Always empty; removed in the next major version.
[Obsolete("The structure subtrees live in the scheme cache (Cache) and are dropped with their scheme; this field is no longer filled or read and is removed in the next major version.")]
protected static readonly ConcurrentDictionary<(string Domain, long SchemeId, long? ParentId), List> SubtreeCache = new();
// C# type to REDB type mapping cache. Non-concurrent Dictionary, so it is built in a
// local and published atomically; the lock serializes builders. Parallel scheme syncs
// (e.g. Postgres + MSSql fixtures initializing at once) would otherwise read the cache
// while another thread is still populating it and corrupt its internal state.
private static Dictionary? _csharpToRedbTypeCache;
private static readonly SemaphoreSlim _csharpToRedbTypeCacheLock = new(1, 1);
protected SchemeSyncProviderBase(
IRedbContext context,
ISqlDialect sql,
RedbServiceConfiguration? configuration = null,
string? cacheDomain = null,
ILogger? logger = null)
{
Context = context ?? throw new ArgumentNullException(nameof(context));
Sql = sql ?? throw new ArgumentNullException(nameof(sql));
Configuration = configuration ?? new RedbServiceConfiguration();
CacheDomain = cacheDomain ?? Configuration.GetEffectiveCacheDomain();
// Initialize domain-bound caches
Cache = new GlobalMetadataCache(CacheDomain);
Cache.Initialize(Configuration);
ListCache = new GlobalListCache(CacheDomain, Configuration.EnableListCache);
ListCache.SetTtl(Configuration.ListCacheTtl);
PropsCache = new GlobalPropsCache(CacheDomain);
Logger = logger;
}
// ============================================================
// === MAIN SYNC METHODS ===
// ============================================================
public Task EnsureSchemeFromTypeAsync(CancellationToken cancellationToken = default) where TProps : class
=> GuardSchemeSyncAsync(() => EnsureSchemeFromTypeCoreAsync(cancellationToken), cancellationToken);
private async Task EnsureSchemeFromTypeCoreAsync(CancellationToken cancellationToken) where TProps : class
{
var scheme = await EnsureSchemeFromTypeInternalAsync(typeof(TProps), GetSchemeAliasForType());
// Same authoritative binding as SyncSchemeAsync, so the idempotent "ensure" path (which may
// early-return an already-existing scheme) also makes the type polymorphically loadable.
Cache.RegisterClrType(scheme.Name, scheme.Id, typeof(TProps));
return scheme;
}
///
/// Ensures a scheme exists for the given type and carries its name to the target.
///
/// The target name is the explicit [RedbScheme(Name = "...")] when declared, otherwise
/// FullName. The scheme is looked up along a three-step chain — target name, FullName, short type
/// name — and the first match is renamed in place. Renaming is a single-row UPDATE of
/// _schemes._name: the id is preserved, so objects, structures and values are untouched.
///
///
/// With no explicit name the target equals FullName, the first two steps collapse into one, and the
/// behaviour is byte-for-byte the legacy one: FullName, then migrate from the short name, then create.
///
///
private async Task EnsureSchemeFromTypeInternalAsync(Type type, string? alias = null, CancellationToken cancellationToken = default)
{
var fullName = type.FullName ?? type.Name;
var shortName = type.Name;
var explicitName = GetExplicitSchemeName(type);
var targetName = explicitName ?? fullName;
// V4 (К7): the CLR namespace is the ownership mark of a scheme. Written on every sync,
// it gates short-name adoption below — see RedbSchemeNamespaceMismatchException.
var nameSpace = type.Namespace;
if (explicitName != null)
{
// Fail before touching the database, naming the type — a raw constraint violation from the
// driver would say nothing about which class is at fault.
SchemeNameValidator.Validate(explicitName, type);
ClrSchemeTypeIndex.ThrowIfNameConflict(explicitName, type);
}
// RedbScheme.RenamedFrom: the previous names the class declares, newest first.
var declaredPrevious = GetDeclaredPreviousSchemeNames(type, targetName);
// 1. Try the target name first.
var existingScheme = await Context.QueryFirstOrDefaultAsync(
Sql.Schemes_SelectByName(), new object[] { targetName }, cancellationToken);
if (existingScheme != null)
{
// A declared previous name still stored next to the scheme: each may hold objects.
foreach (var previousName in declaredPrevious)
{
var strayId = await Context.ExecuteScalarAsync(Sql.Schemes_ExistsByName(), new object[] { previousName }, cancellationToken);
if (strayId.HasValue)
throw RedbRenameConflictException.SchemeBothStored(type, targetName, previousName, existingScheme.Id, strayId.Value);
}
// The rename already happened, so nothing should still sit under a previous name. If
// something does, the type maps to two schemes at once — an older binary re-created the
// old one after the rename — and objects are quietly being split between them. Fail loudly;
// silently picking one would hide real data loss.
//
// Only checked for explicitly named types: without an explicit name this is the untouched
// legacy path, and tightening it would break projects that never opted in.
if (explicitName != null)
{
foreach (var previousName in new[] { fullName, shortName })
{
if (previousName == targetName)
continue;
var strayId = await Context.ExecuteScalarAsync(Sql.Schemes_ExistsByName(), new object[] { previousName }, cancellationToken);
if (strayId.HasValue)
{
throw new RedbSchemeNameTakenException(
type, targetName, existingScheme.Id, previousName, strayId.Value);
}
}
}
await SyncSchemeNameSpaceAsync(type, existingScheme, nameSpace);
await SyncSchemeAliasAsync(existingScheme, alias);
return existingScheme;
}
// 2. The previous names the class declares: the one stored is renamed in place.
var declaredStored = new List<(string Name, RedbScheme Scheme)>();
foreach (var previousName in declaredPrevious)
{
var stored = await Context.QueryFirstOrDefaultAsync(
Sql.Schemes_SelectByName(), new object[] { previousName }, cancellationToken);
if (stored != null)
declaredStored.Add((previousName, stored));
}
if (declaredStored.Count > 1)
throw RedbRenameConflictException.SchemeSeveralStored(type, targetName,
declaredStored.Select(s => (s.Name, s.Scheme.Id)).ToList());
if (declaredStored.Count == 1)
{
var (previousName, renamedScheme) = declaredStored[0];
await RenameSchemeAsync(renamedScheme, previousName, targetName, type, cancellationToken);
await SyncSchemeNameSpaceAsync(type, renamedScheme, nameSpace);
await SyncSchemeAliasAsync(renamedScheme, alias);
return renamedScheme;
}
// 3. Fallback: find the scheme under a previous name and rename it in place.
// FullName covers "type used to live by its CLR name"; the short name covers schemes
// created by redb versions that predate FullName naming. Dropping the short-name step
// would silently orphan those old databases.
foreach (var previousName in explicitName != null
? new[] { fullName, shortName }
: new[] { shortName })
{
if (previousName == targetName)
continue;
var legacyScheme = await Context.QueryFirstOrDefaultAsync(
Sql.Schemes_SelectByName(), new object[] { previousName }, cancellationToken);
if (legacyScheme == null)
continue;
if (previousName == shortName)
{
// V4 (К7): a short name proves nothing — two unrelated projects both have an
// `Order`. The recorded namespace decides: a foreign one is a hard stop before
// anything is renamed; NULL is a pre-namespace database and is adopted the legacy
// way, but no longer silently.
if (legacyScheme.NameSpace == null)
{
Logger?.LogWarning(
"Scheme '{SchemeName}' (ID: {SchemeId}) is adopted by type {Type} via its short " +
"name with no recorded namespace (a pre-namespace database). The namespace is " +
"written now; if this scheme actually belongs to another project, restore its " +
"_name_space and rename the scheme back.",
previousName, legacyScheme.Id, type.FullName);
}
else if (!string.Equals(legacyScheme.NameSpace, nameSpace, StringComparison.Ordinal))
{
throw new RedbSchemeNamespaceMismatchException(
type, previousName, legacyScheme.Id, legacyScheme.NameSpace, nameSpace);
}
}
await RenameSchemeAsync(legacyScheme, previousName, targetName, type, cancellationToken);
await SyncSchemeNameSpaceAsync(type, legacyScheme, nameSpace);
await SyncSchemeAliasAsync(legacyScheme, alias);
return legacyScheme;
}
// 4. Nothing to rename — create the scheme, unless the name is one a stored scheme was renamed from and this
// application has no class of that scheme: then the class predates the rename.
await CheckSchemeRenamedAwayAsync(type, targetName, cancellationToken);
BeforeSchemeWrite();
var newId = await Context.NextObjectIdAsync();
var newScheme = new RedbScheme
{
Id = newId,
Name = targetName,
Alias = alias,
NameSpace = nameSpace,
Type = RedbTypeIds.Class
};
// Conflict-safe INSERT: several nodes starting at once all miss the lookups above and all
// reach this line. A plain INSERT would let all but one fail on UNIQUE(_name) — and inside a
// transaction on PostgreSQL that error also poisons the transaction, so catching it and
// re-reading is not an option. The dialect suppresses the conflict instead, and the loser
// simply reads back the winner's row.
var inserted = await Context.ExecuteAsync(
Sql.Schemes_InsertIfAbsent(), new object[] { newScheme.Id, newScheme.Name, newScheme.Alias, newScheme.Type,
newScheme.NameSpace }, cancellationToken);
if (inserted == 0)
{
var winner = await Context.QueryFirstOrDefaultAsync(
Sql.Schemes_SelectByName(), new object[] { targetName }, cancellationToken);
if (winner == null)
{
throw new InvalidOperationException(
$"Scheme '{targetName}' was not inserted (conflict) but cannot be read back. " +
"The scheme was likely removed concurrently.");
}
Logger?.LogInformation(
"Lost the creation race for scheme '{SchemeName}'; using the existing scheme (ID: {SchemeId})",
targetName, winner.Id);
await SyncSchemeNameSpaceAsync(type, winner, nameSpace);
await SyncSchemeAliasAsync(winner, alias);
return winner;
}
if (explicitName != null)
ClrSchemeTypeIndex.Register(targetName, type);
return newScheme;
}
///
/// Brings _schemes._alias in line with the attribute. The attribute is the source of truth,
/// mirroring how structure aliases already behave — a value edited by hand in the database is
/// overwritten, and removing the attribute resets the alias to NULL.
///
private async Task SyncSchemeAliasAsync(RedbScheme scheme, string? alias, CancellationToken cancellationToken = default)
{
if (scheme.Alias == alias)
return;
BeforeSchemeWrite();
await Context.ExecuteAsync(Sql.Schemes_UpdateAlias(), new object[] { (object?)alias ?? DBNull.Value, scheme.Id }, cancellationToken);
scheme.Alias = alias;
Cache.InvalidateScheme(scheme.Id);
Cache.InvalidateScheme(scheme.Name);
}
///
/// Brings _schemes._name_space in line with the CLR type (V4, К7). The namespace is the
/// ownership mark of a scheme: a scheme from a pre-namespace database (NULL) acquires its owner
/// on the first synchronisation; a scheme owned by ANOTHER namespace is never taken over on any
/// path - the typed names the way out (move the
/// mark when the type moved, or rename one of the two). Owner decision 2026-09-01.
///
private async Task SyncSchemeNameSpaceAsync(Type type, RedbScheme scheme, string? nameSpace, CancellationToken cancellationToken = default)
{
if (scheme.NameSpace == nameSpace)
return;
if (scheme.NameSpace != null)
{
// К7 (owner decision 2026-09-01): a scheme has ONE owner, on every adoption path - the
// explicit name, the FullName match and the creation-race loser included, not only the
// short-name fallback. A type moved to another namespace or a second project reusing
// the name gets a typed stop with the way out in the message, never a silent takeover.
throw new RedbSchemeNamespaceMismatchException(type, scheme.Name, scheme.Id, scheme.NameSpace, nameSpace);
}
BeforeSchemeWrite();
await Context.ExecuteAsync(Sql.Schemes_UpdateNameSpace(), new object[] { (object?)nameSpace ?? DBNull.Value, scheme.Id }, cancellationToken);
scheme.NameSpace = nameSpace;
Cache.InvalidateScheme(scheme.Id);
Cache.InvalidateScheme(scheme.Name);
}
public Task> SyncStructuresFromTypeAsync(IRedbScheme scheme, bool strictDeleteExtra = true, CancellationToken cancellationToken = default) where TProps : class
=> GuardSchemeSyncAsync(() => SyncStructuresFromTypeCoreAsync(scheme, strictDeleteExtra, cancellationToken), cancellationToken);
private async Task> SyncStructuresFromTypeCoreAsync(IRedbScheme scheme, bool strictDeleteExtra, CancellationToken cancellationToken) where TProps : class
{
RefuseNestedCollections(typeof(TProps));
var existingStructures = await Context.QueryAsync(Sql.Structures_SelectByScheme(), new object[] { scheme.Id }, cancellationToken);
var structuresToKeep = new List();
// The version rule (RedbSchemeAttribute.Version): only a class of a higher version than the one the database
// recorded deletes structures or changes their type; the same version adds what it lacks; a lower version (an
// older build next to a newer one) changes nothing. The stored row is read here, not from the cache: another
// node may have raised it since.
var classVersion = GetRedbSchemeAttribute()?.Version ?? 0;
var storedVersion = (await Context.QueryFirstOrDefaultAsync(
Sql.Schemes_SelectById(), new object[] { scheme.Id }, cancellationToken))?.Version ?? 0;
if (classVersion < storedVersion)
{
Logger?.LogWarning(
"REDB schema sync: scheme '{SchemeName}' (id={SchemeId}) was synchronised by version {StoredVersion} of its " +
"Props class; this process runs version {ClassVersion} ({ClassType}) and changes none of its structures. " +
"Upgrade this process; its saves keep the fields it does not know or refuse.",
scheme.Name, scheme.Id, storedVersion, classVersion, typeof(TProps).FullName);
return existingStructures.Cast().ToList();
}
var gate = new SyncGate
{
Destructive = classVersion > storedVersion || Configuration.DefaultDestructiveSyncAtEqualVersion
};
await SyncStructuresRecursively(typeof(TProps), scheme.Id, scheme.Name, null, existingStructures, structuresToKeep, gate: gate);
// A second copy of a kept field (a duplicate root structure left by nodes that synced before the schema lock) is
// not an extra field: which copy holds an object's value depends on the node that saved it. Deleting it would
// drop those values; the duplicates, with their subtrees, are reported and left to RootStructureKey and the
// hand fix of UPGRADING.md.
var kept = existingStructures.Where(s => structuresToKeep.Contains(s.Id)).ToList();
var duplicates = existingStructures
.Where(s => !structuresToKeep.Contains(s.Id) && kept.Any(k => k.Name == s.Name && k.IdParent == s.IdParent))
.Select(s => s.Id)
.ToHashSet();
for (var grew = duplicates.Count > 0; grew;)
{
var below = existingStructures
.Where(s => s.IdParent.HasValue && duplicates.Contains(s.IdParent.Value) && !duplicates.Contains(s.Id))
.Select(s => s.Id)
.ToList();
duplicates.UnionWith(below);
grew = below.Count > 0;
}
// Reported per field: the copies at the top of each duplicated subtree, with the copy kept by the sync.
foreach (var field in existingStructures
.Where(s => duplicates.Contains(s.Id) && !(s.IdParent.HasValue && duplicates.Contains(s.IdParent.Value)))
.GroupBy(s => (s.Name, s.IdParent)))
{
var ids = kept.Where(k => k.Name == field.Key.Name && k.IdParent == field.Key.IdParent).Select(k => k.Id)
.Concat(field.Select(s => s.Id)).ToList();
ReportSchemaProblem(Data.RootStructureKey.DuplicateProblem(scheme.Id, scheme.Name, field.Key.Name, ids));
}
int deletedCount = 0;
if (strictDeleteExtra && !gate.Destructive)
{
gate.Held.AddRange(existingStructures
.Where(s => !structuresToKeep.Contains(s.Id) && !duplicates.Contains(s.Id))
.Select(s => $"'{s.Name}' (structure {s.Id}) kept with its values, the class does not declare it"));
}
else if (strictDeleteExtra)
{
var idsToDelete = existingStructures
.Where(s => !structuresToKeep.Contains(s.Id) && !duplicates.Contains(s.Id))
.Select(s => s.Id)
.ToList();
if (idsToDelete.Count > 0)
{
BeforeSchemeWrite();
if (Logger != null)
{
var namesToDelete = existingStructures
.Where(s => idsToDelete.Contains(s.Id))
.Select(s => $"{s.Id}:{s.Name}")
.ToList();
Logger.LogWarning(
"REDB schema sync: removing {Count} structure(s) from scheme '{SchemeName}' (id={SchemeId}): [{Items}]. " +
"This is a destructive DDL operation. On PostgreSQL the FK `_values._id_structure -> _structures._id` " +
"is ON DELETE CASCADE; on MSSQL the equivalent effect is produced by the INSTEAD OF DELETE trigger " +
"TR__structures__cascade_values. In both backends every `_values` row referencing these structures " +
"will be silently deleted. " +
"Set RedbServiceConfiguration.DefaultStrictDeleteExtra=false (or pass strictDeleteExtra:false) " +
"to skip destructive sync \u2014 recommended for rolling/blue-green deployments.",
idsToDelete.Count, scheme.Name, scheme.Id, string.Join(", ", namesToDelete));
}
deletedCount = await Context.ExecuteAsync(Sql.Structures_DeleteByIds(idsToDelete), System.Array.Empty