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(), cancellationToken); } } // The version the class synchronised with; never lowered (the statement compares). if (classVersion > storedVersion) { BeforeSchemeWrite(); await Context.ExecuteAsync(Sql.Schemes_UpdateVersion(), new object[] { classVersion, scheme.Id }, cancellationToken); Cache.InvalidateScheme(scheme.Id); } if (deletedCount > 0 || structuresToKeep.Count > 0) { // A check pass got here without a write: the structures are in step, and the cache only needs a rebuild // when its rows are gone (a change of _types empties the whole cache). A writing pass rebuilds it always. if (!IsCheckPass || await CountMetadataCacheRowsAsync(scheme.Id, cancellationToken) != existingStructures.Count) { BeforeSchemeWrite(); await Context.ExecuteAsync(Sql.Schemes_SyncMetadataCache(), new object[] { scheme.Id }, cancellationToken); } } var allStructures = await Context.QueryAsync(Sql.Structures_SelectBySchemeShort(), new object[] { scheme.Id }, cancellationToken); if (allStructures.Any()) { var schemeEntity = await Context.QueryFirstOrDefaultAsync(Sql.Schemes_SelectById(), new object[] { scheme.Id }, cancellationToken); if (schemeEntity != null) { var newSchemeHash = SchemeHashCalculator.ComputeSchemeStructureHash(allStructures); if (schemeEntity.StructureHash != newSchemeHash) { BeforeSchemeWrite(); await Context.ExecuteAsync(Sql.Schemes_UpdateHash(), new object[] { newSchemeHash, scheme.Id }, cancellationToken); Cache.InvalidateScheme(scheme.Id); } } } var updatedStructures = await Context.QueryAsync(Sql.Structures_SelectByScheme(), new object[] { scheme.Id }, cancellationToken); // V4: keys of a [RedbUnique] structure must be trustworthy before the scheme is handed out - // recompute where the attribute just appeared, the encoder version moved, or a SQL-side // writer left rows unhashed (see SchemeSyncProviderBase.Unique.cs). await EnsureUniqueKeysAsync(scheme, updatedStructures); // Logged last, once per sync of the scheme: a check pass that still has a write ahead leaves before this line and // the writing pass logs it, so a start logs one line per scheme. Saves and queries do not sync, so they never log it. if (gate.Held.Count > 0) { Logger?.LogWarning( "REDB schema sync: scheme '{SchemeName}' (id={SchemeId}), Props class {ClassType} version {ClassVersion}, " + "database version {StoredVersion}: {Count} change(s) that take data away were not applied: [{Items}]. " + "Raise RedbScheme.Version on the class to apply them, or call DropUnknownStructuresAsync for the fields it no " + "longer declares.", scheme.Name, scheme.Id, typeof(TProps).FullName, classVersion, storedVersion, gate.Held.Count, string.Join("; ", gate.Held)); } return updatedStructures.Cast().ToList(); } public Task SyncSchemeAsync(CancellationToken cancellationToken = default) where TProps : class => GuardSchemeSyncAsync(() => SyncSchemeCoreAsync(cancellationToken), cancellationToken); private async Task SyncSchemeCoreAsync(CancellationToken cancellationToken) where TProps : class { // Before the scheme row: a class with a collection directly inside a collection is refused with nothing written. RefuseNestedCollections(typeof(TProps)); var attr = GetRedbSchemeAttribute(); var alias = attr?.Alias; var scheme = await EnsureSchemeFromTypeInternalAsync(typeof(TProps), alias); // V4: [RedbTags] on the Props class writes the scheme's free-form marker. WITHOUT the // attribute the column is left untouched - direct writes survive synchronisation. var schemeTags = typeof(TProps).GetCustomAttribute(); if (schemeTags != null) { if (schemeTags.Tags is { Length: > 450 }) throw new InvalidOperationException( $"[RedbTags] on '{typeof(TProps).Name}' is {schemeTags.Tags.Length} characters, the limit is 450"); // A check pass with the marker already in place writes nothing; a writing pass writes it as before. if (!IsCheckPass || scheme.Tags != schemeTags.Tags) { BeforeSchemeWrite(); await Context.ExecuteAsync(Sql.Schemes_UpdateTags(), new object[] { schemeTags.Tags, scheme.Id }, cancellationToken); } } // Honor the configured policy. Default value of DefaultStrictDeleteExtra is true, // so behavior is unchanged for users on the default config. Users who explicitly // set the flag to false (or pick the Development/HighPerformance/Migration presets) // now actually get the non-destructive sync they asked for \u2014 required for safe // rolling/blue-green deployments where old and new app versions share a database. var structures = await SyncStructuresFromTypeAsync( scheme, strictDeleteExtra: Configuration.DefaultStrictDeleteExtra); // Authoritatively bind scheme_id → TProps for polymorphic loads. This is the canonical write // of the per-domain projection: Type and the freshly-synced scheme_id co-exist here, so the // registry cannot drift from the DB regardless of assembly/ALC timing or which node synced. // (Global, db-independent name↔Type lands in ClrSchemeTypeIndex.) Cache.RegisterClrType(scheme.Name, scheme.Id, typeof(TProps)); // Reload scheme from DB to get current state (including updated hash), // attach structures, and cache for subsequent queries var freshScheme = await Context.QueryFirstOrDefaultAsync(Sql.Schemes_SelectById(), new object[] { scheme.Id }, cancellationToken); if (freshScheme != null) { freshScheme.SetStructures(structures.Cast().ToList()); Cache.CacheScheme(freshScheme); return freshScheme; } return scheme; } // ============================================================ // === RECURSIVE STRUCTURE SYNC (platform-agnostic) === // ============================================================ private async Task SyncStructuresRecursively( Type type, long schemeId, string schemeName, long? parentId, List existingStructures, List structuresToKeep, HashSet? visitedTypes = null, bool pathHasCollection = false, SyncGate? gate = null) { visitedTypes ??= []; if (visitedTypes.Contains(type)) return; visitedTypes.Add(type); var properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance) .Where(p => !ShouldIgnoreProperty(p)) .ToArray(); var nullabilityContext = new NullabilityInfoContext(); // [RedbRename]: a class older than a rename stored at this level stops here, before anything is written. CheckRenamedAway(schemeName, type, properties, parentId, existingStructures); foreach (var property in properties) { var nullabilityInfo = nullabilityContext.Create(property); // V4 (Б1, решение владельца 2026-08-31): byte[] - скаляр в _values._ByteArray, не массив // байтов по строке на элемент. IsArrayType(byte[]) даёт true из-за type.IsArray - исключаем. var isArray = IsArrayType(property.PropertyType) && property.PropertyType != typeof(byte[]); var isDictionary = IsDictionaryType(property.PropertyType); Type baseType; Type? keyType = null; if (isDictionary) { var (dictKeyType, dictValueType) = GetDictionaryKeyValueTypes(property.PropertyType); baseType = dictValueType; keyType = dictKeyType; } else if (isArray) { baseType = GetArrayElementType(property.PropertyType); } else { baseType = property.PropertyType; } var isRequired = nullabilityInfo.WriteState != NullabilityState.Nullable && Nullable.GetUnderlyingType(baseType) == null; var typeId = await GetTypeIdForTypeAsync(baseType); var structureName = property.Name; var typeName = await MapCSharpTypeToRedbTypeAsync(baseType); long? keyTypeId = null; if (isDictionary && keyType != null) { keyTypeId = RedbKeySerializer.GetKeyTypeId(keyType); } var aliasAttr = property.GetCustomAttribute(); var structureAlias = aliasAttr?.Alias; // V4 (Л2, L.6): the `virtual` marker (LAZY plan §3.2-3.3). Only a reference - // RedbObject or a collection of them - can be lazy; `virtual` on a scalar or a // nested class means nothing to the builders and is deliberately not recorded. var lazyGetter = property.GetGetMethod(); var isReferenceShaped = baseType.IsGenericType && baseType.GetGenericTypeDefinition() == typeof(Models.Entities.RedbObject<>); var isLazy = isReferenceShaped && lazyGetter is { IsVirtual: true, IsFinal: false }; // [RedbRename] first: the stored structure of a previous name is renamed in place, and the type, alias and // flag updates below apply to it as to any structure found under its name. var existingStructure = await MatchStructureAsync(schemeName, type, property, properties, parentId, existingStructures); var shapeApplied = true; if (existingStructure != null) { shapeApplied = await UpdateExistingStructure(existingStructure, typeId, typeName, isDictionary, isArray, keyTypeId, structureAlias, isRequired, isLazy, gate, schemeName, keyClrType: keyType); structuresToKeep.Add(existingStructure.Id); } else { var newStructure = await CreateNewStructure(schemeId, parentId, structureName, structureAlias, typeId, isRequired, isDictionary, isArray, keyTypeId, properties.ToList().IndexOf(property), isLazy); existingStructures.Add(newStructure); structuresToKeep.Add(newStructure.Id); } // V4: [RedbUnique] - validate placement and keep _structures._unique in step (rejection // happens here, at synchronisation, not at insert). var uniqueTarget = existingStructure ?? existingStructures.Last(s => s.Name == structureName && s.IdParent == parentId); await SyncUniqueFlagAsync(type, property, uniqueTarget, isArray, isDictionary, baseType, pathHasCollection); // V4: [RedbTags] writes the free-form marker. WITHOUT the attribute the column is // left untouched, so values written directly by applications survive every sync. var tagsAttribute = property.GetCustomAttribute(); if (tagsAttribute != null && uniqueTarget.Tags != tagsAttribute.Tags) { if (tagsAttribute.Tags is { Length: > 450 }) throw new InvalidOperationException( $"[RedbTags] on '{type.Name}.{property.Name}' is {tagsAttribute.Tags.Length} characters, the limit is 450"); BeforeSchemeWrite(); await Context.ExecuteAsync(Sql.Structures_UpdateTags(), new object[] { tagsAttribute.Tags, uniqueTarget.Id }); uniqueTarget.Tags = tagsAttribute.Tags; } if (IsBusinessClass(baseType) && shapeApplied) { var currentStructureId = existingStructure?.Id ?? existingStructures.Last(s => s.Name == structureName && s.IdParent == parentId).Id; // S2: a collection anywhere on the path poisons uniqueness for everything below - // the elements of every object share one structure, so a key there would mean one // value across all elements of all objects. Thread the mark down the descent. await SyncStructuresRecursively(baseType, schemeId, schemeName, currentStructureId, existingStructures, structuresToKeep, visitedTypes, pathHasCollection || isArray || isDictionary, gate); } } visitedTypes.Remove(type); } /// /// What one sync of a scheme may do under the version rule (): whether it /// may delete structures and change their type or collection kind, and what it held back, for the warning. /// private sealed class SyncGate { public bool Destructive { get; init; } public List Held { get; } = []; } /// False when the version rule held a change of type or collection kind back: the stored structure keeps /// its shape, and the sync does not descend into it with the class's shape. private async Task UpdateExistingStructure( RedbStructure structure, long typeId, string typeName, bool isDictionary, bool isArray, long? keyTypeId, string? alias, bool isRequired, bool isLazy, SyncGate? gate = null, string? schemeName = null, CancellationToken cancellationToken = default, Type? keyClrType = null) { var newCollectionKind = isDictionary ? RedbTypeIds.Dictionary : (isArray ? RedbTypeIds.Array : (long?)null); if (gate is { Destructive: false } && ShapeDiffers(structure, typeId, isDictionary, isArray)) { // The version rule: the type a newer build (or a class of the same version) left stays as it is. gate.Held.Add($"'{structure.Name}' (structure {structure.Id}) keeps its stored type, the class declares {typeName}" + (structure.CollectionType != newCollectionKind ? " with another collection kind" : "")); return false; } // A change of the collection kind (single value, array, dictionary) is never converted: the rows keep the shape // of the old kind, and the new class would read them wrong (a single value as an empty array, an array as null, // array positions as dictionary keys) until a save drops them. With values stored the sync stops here, before // anything of this property is written; without values the kind just changes below. The pre-V4 byte[] layout is // the one kind change that is converted (ConvertByteArrayStorageAsync). if (structure.CollectionType != newCollectionKind && !IsLegacyByteArrayShape(structure, typeId, isArray) && await Context.ExecuteScalarAsync(Sql.Values_ExistsByStructure(), new object[] { structure.Id }, cancellationToken) == 1) { throw new RedbCollectionKindChangeException(schemeName ?? $"#{structure.IdScheme}", structure.Name, structure.Id, KindName(structure.CollectionType), KindName(newCollectionKind)); } if (IsLegacyByteArrayShape(structure, typeId, isArray)) { // V4 (Б1): the pre-V4 Array-of-Byte layout of a byte[] property. Assemble the bytes into // the scalar _ByteArray on the base row, drop the element rows, then flip the type - the // generic migration below has no Byte->ByteArray path and must not see this shape. BeforeSchemeWrite(); await ConvertByteArrayStorageAsync(structure); await Context.ExecuteAsync(Sql.Structures_UpdateType(), new object[] { typeId, structure.Id }, cancellationToken); structure.IdType = typeId; } else if (structure.IdType != typeId) { // Order matters and is load-bearing: the migration either moves the values or throws, and // only a completed migration is allowed to reach Structures_UpdateType. Switching the type // on a failed migration is what turned a bad type change into silently missing values. await RefuseTicksDateChangeAsync(structure, typeId, typeName); BeforeSchemeWrite(); await MigrateStructureTypeInternalAsync( structure.Id, structure.IdType, typeName, structure.Name, structure.IdScheme); await Context.ExecuteAsync(Sql.Structures_UpdateType(), new object[] { typeId, structure.Id }, cancellationToken); structure.IdType = typeId; } var newCollectionType = isDictionary ? RedbTypeIds.Dictionary : (isArray ? RedbTypeIds.Array : (long?)null); if (structure.CollectionType != newCollectionType) { BeforeSchemeWrite(); await Context.ExecuteAsync(Sql.Structures_UpdateCollectionType(), new object[] { (object?)newCollectionType ?? DBNull.Value, structure.Id }, cancellationToken); structure.CollectionType = newCollectionType; } if (structure.KeyType != keyTypeId) { if (structure.KeyType.HasValue && keyTypeId.HasValue && keyClrType != null) await RefuseUnreadableKeysAsync(structure, keyTypeId.Value, keyClrType, cancellationToken); BeforeSchemeWrite(); await Context.ExecuteAsync(Sql.Structures_UpdateKeyType(), new object[] { (object?)keyTypeId ?? DBNull.Value, structure.Id }, cancellationToken); structure.KeyType = keyTypeId; } if (structure.Alias != alias) { BeforeSchemeWrite(); await Context.ExecuteAsync(Sql.Structures_UpdateAlias(), new object[] { (object?)alias ?? DBNull.Value, structure.Id }, cancellationToken); structure.Alias = alias; } if (structure.AllowNotNull != isRequired) { BeforeSchemeWrite(); await Context.ExecuteAsync(Sql.Structures_UpdateAllowNotNull(), new object[] { isRequired, structure.Id }, cancellationToken); structure.AllowNotNull = isRequired; } // V4 (Л2): the code is the source of truth for the marker, like every structure flag here. if ((structure.Lazy ?? false) != isLazy) { BeforeSchemeWrite(); await Context.ExecuteAsync(Sql.Structures_UpdateLazy(), new object[] { isLazy, structure.Id }, cancellationToken); structure.Lazy = isLazy; // The metadata cache mirrors the marker and the hash-diff path will not fire for a // flag restored over a manual edit - resync the scheme cache right here. await Context.ExecuteAsync(Sql.Schemes_SyncMetadataCache(), new object[] { structure.IdScheme }, cancellationToken); Cache.InvalidateScheme(structure.IdScheme); } return true; } private async Task CreateNewStructure( long schemeId, long? parentId, string name, string? alias, long typeId, bool isRequired, bool isDictionary, bool isArray, long? keyTypeId, int order, bool isLazy, CancellationToken cancellationToken = default) { BeforeSchemeWrite(); var newId = await Context.NextObjectIdAsync(); var structure = new RedbStructure { Id = newId, IdScheme = schemeId, IdParent = parentId, Name = name, Alias = alias, IdType = typeId, AllowNotNull = isRequired, CollectionType = isDictionary ? RedbTypeIds.Dictionary : (isArray ? RedbTypeIds.Array : null), KeyType = keyTypeId, Order = order, Lazy = isLazy }; await Context.ExecuteAsync(Sql.Structures_Insert(), new object[] { structure.Id, structure.IdScheme, structure.IdParent, structure.Name, structure.Alias, structure.IdType, structure.AllowNotNull, structure.CollectionType, structure.KeyType, structure.Order, structure.Lazy }, cancellationToken); return structure; } /// /// Moves a structure's stored values to the column the new type reads from, during scheme sync. /// Throws when it cannot, so the caller never switches /// _id_type on values that stayed behind. /// /// /// and only enrich the error message and /// are optional so that the pre-existing signature keeps compiling for anyone who overrode it. /// /// protected virtual async Task MigrateStructureTypeInternalAsync( long structureId, long oldTypeId, string newTypeName, string? propertyName = null, long? schemeId = null, CancellationToken cancellationToken = default) { // Resolve by ID. Passing the id into a lookup keyed by NAME is what used to happen here: it // matched nothing, fell back to the literal "unknown", and every provider then reported an // unknown source type — an error nobody read, because the result was discarded. var oldTypeName = await ResolveTypeNameByIdAsync(oldTypeId); var result = await MigrateStructureTypeAsync(structureId, oldTypeName, newTypeName, false); // Providers report failure as data, not as an exception: an `errors` string when the migration // never ran, a non-zero error count when it ran and left rows behind. Both are failures here. var failed = !string.IsNullOrWhiteSpace(result.Errors) || result.ErrorCount > 0; if (!failed) return; // A structure with no stored values has nothing to strand. This is the ordinary case for a type // with no scalar storage column of its own (a nested class), where every provider reports an // unknown source type and there is genuinely nothing to move. Refusing here would break type // changes on empty schemes for no gain. var storedRows = await CountStructureValuesAsync(structureId); if (storedRows == 0) return; // A migration that never started reports zero affected rows even though the values are sitting // right there — it bailed out before counting anything. Reporting that zero would tell the // reader nothing is at stake, which is the opposite of the truth, so fall back to the rows we // just counted ourselves. var affected = result.AffectedRows > 0 ? result.AffectedRows : (int)storedRows; throw new RedbTypeMigrationException( structureId, propertyName ?? $"structure {structureId}", schemeId ?? 0, schemeId.HasValue ? await TryResolveSchemeNameAsync(schemeId.Value) : null, oldTypeName, newTypeName, affected, result.SuccessCount, affected - result.SuccessCount, result.Errors); } /// /// A dictionary key type changes only the structure: the stored keys stay as they are, and the load reads them with /// the new key type. A key that does not read under it, or reads but is written back as other text (another canon), /// would fail or be lost at read. The stored keys are read once here; any such key refuses the change with /// , naming a few of them. No key is converted. /// private async Task RefuseUnreadableKeysAsync(RedbStructure structure, long newKeyTypeId, Type newKeyType, CancellationToken cancellationToken) { var rows = await Context.QueryAsync(Sql.Values_SelectByStructure(), new object[] { structure.Id }, cancellationToken); // A key row hangs off a base row of the dictionary; deeper rows of the same structure (a list inside a dictionary // value) carry positions, not keys. A base row is the one whose parent is not a row of this structure (a // dictionary inside an array element carries a pseudo index), as ConvertByteArrayStorageAsync tells them apart. var ownIds = rows.Select(r => r.Id).ToHashSet(); var baseRowIds = rows.Where(r => r.ArrayParentId is not { } p || !ownIds.Contains(p)).Select(r => r.Id).ToHashSet(); var keys = rows.Where(r => r.ArrayIndex != null && r.ArrayParentId is { } parent && baseRowIds.Contains(parent)) .Select(r => r.ArrayIndex!).Distinct(StringComparer.Ordinal).ToList(); if (keys.Count == 0) return; var bad = new List(); foreach (var key in keys) { bool reads; try { var value = RedbKeySerializer.DeserializeObject(key, newKeyType); reads = value != null && RedbKeySerializer.SerializeObject(value, newKeyType) == key; } catch (Exception) { reads = false; } if (!reads) bad.Add(key); } if (bad.Count == 0) return; var oldKeyName = await ResolveTypeNameByIdAsync(structure.KeyType!.Value); var newKeyName = await ResolveTypeNameByIdAsync(newKeyTypeId); var shown = string.Join(", ", bad.Take(5).Select(k => $"'{k}'")); throw new RedbTypeMigrationException( structure.Id, structure.Name, structure.IdScheme, await TryResolveSchemeNameAsync(structure.IdScheme), $"{oldKeyName} key", $"{newKeyName} key", keys.Count, $"{bad.Count} of {keys.Count} stored dictionary key(s) do not read as {newKeyType.Name}" + $" ({shown}{(bad.Count > 5 ? ", ..." : "")}); keys are not converted."); } private static bool IsTicksType(long typeId) => typeId is RedbTypeIds.TimeSpan or RedbTypeIds.TimeOnly; private static bool IsDateType(long typeId) => typeId is RedbTypeIds.DateTime or RedbTypeIds.DateTimeOffset or RedbTypeIds.DateOnly; /// /// A time span or a time of day (ticks in _Long) and a date have no common meaning: the engine conversion /// between the long and the date column reads and writes Unix seconds, so it turned one hour into a date in the /// year 3110 and a date into a few minutes, and reported success. With stored values such a change is refused /// before the engine call, by the redb type ids; without values the type just changes. A plain long or int and a /// date keep the conversion (Unix seconds), which a consumer may rely on. /// private async Task RefuseTicksDateChangeAsync(RedbStructure structure, long newTypeId, string newTypeName) { var oldTypeId = structure.IdType; if (!(IsTicksType(oldTypeId) && IsDateType(newTypeId)) && !(IsDateType(oldTypeId) && IsTicksType(newTypeId))) return; var storedRows = await CountStructureValuesAsync(structure.Id); if (storedRows == 0) return; var oldTypeName = await ResolveTypeNameByIdAsync(oldTypeId); throw new RedbTypeMigrationException( structure.Id, structure.Name, structure.IdScheme, await TryResolveSchemeNameAsync(structure.IdScheme), oldTypeName, newTypeName, (int)storedRows, $"'{oldTypeName}' and '{newTypeName}' have no common meaning (a time span or a time of day is stored as " + "ticks, a date as a date), so no conversion keeps the stored values."); } /// /// REDB type name for a type id, from the by-id metadata cache and falling back to one query for /// the whole (tiny, seed-only) _types table. No new dialect method: the id-keyed cache and /// Types_SelectAll already exist. /// private async Task ResolveTypeNameByIdAsync(long typeId, CancellationToken cancellationToken = default) { var cached = Cache.GetTypeById(typeId); if (cached != null) return cached.Name; var allTypes = (await Context.QueryAsync(Sql.Types_SelectAll(), System.Array.Empty(), cancellationToken)).ToList(); Cache.CacheTypesById(allTypes); var found = allTypes.FirstOrDefault(t => t.Id == typeId); if (found == null) throw new InvalidOperationException( $"Type id={typeId} is referenced by a structure but is missing from the _types table. " + "The database schema is inconsistent."); return found.Name; } /// /// Rows in _values for a structure, regardless of which typed column holds them. Composed /// here rather than added to ISqlDialect: it is one portable statement and the parameter form is /// the only provider-specific part. COUNT(*) is cast because its natural width differs by engine. /// private async Task CountStructureValuesAsync(long structureId, CancellationToken cancellationToken = default) { var sql = $"SELECT CAST(COUNT(*) AS BIGINT) FROM _values WHERE _id_structure = {Sql.FormatParameter(1)}"; return await Context.ExecuteScalarAsync(sql, new object[] { structureId }, cancellationToken) ?? 0; } /// Rows of the metadata cache of a scheme: one per structure when the cache is in step. private async Task CountMetadataCacheRowsAsync(long schemeId, CancellationToken cancellationToken) => await Context.ExecuteScalarAsync(Sql.Schemes_CountMetadataCache(), new object[] { schemeId }, cancellationToken) ?? 0; /// Best-effort scheme name for an error message; never the reason a call fails. private async Task TryResolveSchemeNameAsync(long schemeId, CancellationToken cancellationToken = default) { try { var scheme = await Context.QueryFirstOrDefaultAsync(Sql.Schemes_SelectById(), new object[] { schemeId }, cancellationToken); return scheme?.Name; } catch { return null; } } /// public virtual async Task MigrateStructureTypeAsync(long structureId, string oldTypeName, string newTypeName, bool dryRun = false, CancellationToken cancellationToken = default) { var result = await Context.QueryFirstOrDefaultAsync( Sql.Schemes_MigrateStructureType(), new object[] { structureId, oldTypeName, newTypeName, dryRun }, cancellationToken); return result ?? new TypeMigrationResult(); } // ============================================================ // === TYPE MAPPING (platform-agnostic) === // ============================================================ private async Task GetTypeIdForTypeAsync(Type type, CancellationToken cancellationToken = default) { var underlyingType = Nullable.GetUnderlyingType(type) ?? type; var typeName = await MapCSharpTypeToRedbTypeAsync(underlyingType); var cachedId = Cache.GetTypeId(typeName); if (cachedId.HasValue) return cachedId.Value; var typeEntity = await Context.QueryFirstOrDefaultAsync(Sql.Types_SelectByName(), new object[] { typeName }, cancellationToken); if (typeEntity == null) throw new InvalidOperationException($"Type '{typeName}' not found in _types table. Check DB schema."); Cache.CacheType(typeName, typeEntity.Id); return typeEntity.Id; } private async Task MapCSharpTypeToRedbTypeAsync(Type csharpType) { if (_csharpToRedbTypeCache == null) await InitializeCSharpToRedbTypeMappingAsync(); if (csharpType.IsGenericType && csharpType.GetGenericTypeDefinition() == typeof(RedbObject<>)) return "Object"; // A bare (non-generic) RedbObject / IRedbObject field would fall through to the CLASS // branch and get reflected over its own properties - the framework's service fields in two // casings (id/Id, name/Name...). MSSQL's CI collation then hit UNIQUE IX__structures, // PostgreSQL the reserved-name trigger (23514), and the user saw a driver error naming // neither the field nor the cure (discussion #12, item 6). Refuse loudly instead: a // reference field is declared with its Props type. Generic implementations pass through // IRedbObject; this arm catches only the bare shapes. if (typeof(IRedbObject).IsAssignableFrom(csharpType) && !csharpType.GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IRedbObject<>))) throw new InvalidOperationException( $"A field of type '{csharpType.Name}' cannot be stored: a reference field must be " + "declared with its Props type - RedbObject. For raw binary payloads use a " + "byte[] property instead."); if (csharpType == typeof(IRedbListItem) || csharpType == typeof(RedbListItem)) return "ListItem"; var underlyingType = Nullable.GetUnderlyingType(csharpType); if (underlyingType != null && (underlyingType == typeof(IRedbListItem) || underlyingType == typeof(RedbListItem))) return "ListItem"; if (IsBusinessClass(csharpType)) return "Class"; if (_csharpToRedbTypeCache!.TryGetValue(csharpType, out var exactMatch)) return exactMatch; return "String"; } private async Task InitializeCSharpToRedbTypeMappingAsync(CancellationToken cancellationToken = default) { await _csharpToRedbTypeCacheLock.WaitAsync(); try { // Double-check: another thread may have finished building the cache while we waited. if (_csharpToRedbTypeCache != null) return; var allTypes = await Context.QueryAsync(Sql.Types_SelectAll(), System.Array.Empty(), cancellationToken); // Build into a LOCAL dictionary and publish it only once fully populated, so // concurrent readers in MapCSharpTypeToRedbTypeAsync never observe a half-filled // (and mid-mutation) instance. var cache = new Dictionary(); // Sort by ID to ensure base types (String, Long, etc.) are processed first // Base types have more negative IDs (e.g., String=-9223372036854775700) // Derived types like MimeType, FilePath have less negative IDs foreach (var dbType in allTypes.OrderBy(t => t.Id)) { var dotNetTypeName = dbType.Type1; if (string.IsNullOrEmpty(dotNetTypeName)) continue; var csharpType = MapStringToType(dotNetTypeName); // Don't overwrite base type mapping with derived types (e.g., String -> MimeType) if (csharpType != null && !cache.ContainsKey(csharpType)) { cache[csharpType] = dbType.Name; } } if (!cache.ContainsKey(typeof(DateTime))) { var dateTimeType = allTypes.FirstOrDefault(t => t.Name == "DateTime"); if (dateTimeType != null) { cache[typeof(DateTime)] = "DateTime"; } } var numericType = allTypes.FirstOrDefault(t => t.Name == "Numeric"); if (numericType != null) { cache[typeof(decimal)] = "Numeric"; } _csharpToRedbTypeCache = cache; // atomic publish — readers see null or a complete map } finally { _csharpToRedbTypeCacheLock.Release(); } } private static Type? MapStringToType(string typeName) => typeName switch { "string" => typeof(string), "int" => typeof(int), "long" => typeof(long), "short" => typeof(short), "byte" => typeof(byte), "double" => typeof(double), "float" => typeof(float), "decimal" => typeof(decimal), "Numeric" => typeof(decimal), "boolean" => typeof(bool), "DateTime" => typeof(DateTimeOffset), "DateTimeOffset" => typeof(DateTimeOffset), "Guid" => typeof(Guid), "byte[]" => typeof(byte[]), "char" => typeof(char), "TimeSpan" => typeof(TimeSpan), "DateOnly" => typeof(DateOnly), "TimeOnly" => typeof(TimeOnly), "RedbObjectRow" => typeof(RedbObject<>), "_RListItem" => null, "Enum" => typeof(Enum), _ => null }; // ============================================================ // === TYPE HELPERS (platform-agnostic) === // ============================================================ /// /// Whether a stored structure has another shape than the property the class declares for it: another REDB type or /// another collection kind. The pre-V4 byte-array layout is not a difference (the sync converts it in any case). /// The one comparison of the sync (which converts the shape, or holds it under the version rule) and of the save /// (which refuses a class whose shape the sync held). /// private static string KindName(long? collectionType) => collectionType == RedbTypeIds.Array ? "array" : collectionType == RedbTypeIds.Dictionary ? "dictionary" : "single value"; private static bool ShapeDiffers(IRedbStructure structure, long typeId, bool isDictionary, bool isArray) { var kind = isDictionary ? RedbTypeIds.Dictionary : (isArray ? RedbTypeIds.Array : (long?)null); return !IsLegacyByteArrayShape(structure, typeId, isArray) && (structure.IdType != typeId || structure.CollectionType != kind); } /// A property whose stored structure has another shape than the class declares (). public sealed record ShapeMismatch(string Path, string ClassType, string StoredType); /// /// The properties of whose stored structure has another shape, by the walk of /// : a type change the sync held under the version rule. Empty on the normal path. /// The type of a property is resolved through the type cache; the stored type's name is read only for a mismatch. /// internal async Task> ShapeMismatchesAsync(Type propsType, IReadOnlyCollection structures) { var found = new List(); var byParent = structures.ToLookup(s => s.IdParent); await WalkAsync(propsType, null, "", []); return found; async Task WalkAsync(Type type, long? parentId, string prefix, HashSet visited) { if (!visited.Add(type)) return; var children = byParent[parentId].ToList(); foreach (var property in type.GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(p => !ShouldIgnoreProperty(p))) { var structure = children.FirstOrDefault(s => s.Name == property.Name); if (structure == null) continue; var propertyType = property.PropertyType; var isDictionary = IsDictionaryType(propertyType); var isArray = IsArrayType(propertyType) && propertyType != typeof(byte[]); var baseType = isDictionary ? GetDictionaryKeyValueTypes(propertyType).ValueType : isArray ? GetArrayElementType(propertyType) : propertyType; var typeId = await GetTypeIdForTypeAsync(baseType); var path = prefix + property.Name; if (ShapeDiffers(structure, typeId, isDictionary, isArray)) { var storedName = await Context.ExecuteScalarAsync( $"SELECT _name FROM _types WHERE _id = {structure.IdType}", Array.Empty()) ?? structure.IdType.ToString(); var className = await MapCSharpTypeToRedbTypeAsync(Nullable.GetUnderlyingType(baseType) ?? baseType); found.Add(new ShapeMismatch(path, className + (isArray ? "[]" : isDictionary ? " (dictionary)" : ""), storedName + (structure.CollectionType == RedbTypeIds.Array ? "[]" : structure.CollectionType == RedbTypeIds.Dictionary ? " (dictionary)" : ""))); continue; } if (IsBusinessClass(baseType)) await WalkAsync(baseType, structure.Id, path + ".", visited); } visited.Remove(type); } } /// /// The structures of a scheme that a Props class knows: those matched by a property of the class, and below a /// nested class, an element class or a dictionary value class, those matched by its properties, the walk of /// SyncStructuresRecursively. A scheme read from the database can hold more: the fields a newer build of /// the class added. A save of this class writes and deletes only the values of the structures returned here. /// internal static HashSet ClassStructureIds(Type propsType, IReadOnlyCollection structures) { var known = new HashSet(); var byParent = structures.ToLookup(s => s.IdParent); Walk(propsType, null, []); return known; void Walk(Type type, long? parentId, HashSet visited) { if (!visited.Add(type)) return; var children = byParent[parentId].ToList(); foreach (var property in type.GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(p => !ShouldIgnoreProperty(p))) { var structure = children.FirstOrDefault(s => s.Name == property.Name); if (structure == null) continue; known.Add(structure.Id); var propertyType = property.PropertyType; var baseType = IsDictionaryType(propertyType) ? GetDictionaryKeyValueTypes(propertyType).ValueType : IsArrayType(propertyType) && propertyType != typeof(byte[]) ? GetArrayElementType(propertyType) : propertyType; if (IsBusinessClass(baseType)) Walk(baseType, structure.Id, visited); } visited.Remove(type); } } /// /// Refuses a Props class with a property that holds a collection directly inside a collection, a /// multi-dimensional array, or a collection type outside /// (HashSet<T>, Queue<T>, SortedDictionary<K, V>...), anywhere in the class tree /// the sync walks (). Called before the sync writes anything. Such a property /// was stored as the name of its type, and the object could not be loaded. A byte[] element or /// value is a single value; a collection inside a class element (List<Item> with a list in Item) is /// stored and stays allowed. /// internal static void RefuseNestedCollections(Type propsType) { Walk(propsType, []); static void Walk(Type type, HashSet visited) { if (!visited.Add(type)) return; foreach (var property in type.GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(p => !ShouldIgnoreProperty(p))) { var propertyType = property.PropertyType; if (propertyType.IsArray && propertyType.GetArrayRank() > 1) throw new RedbNestedCollectionException(type, property.Name, propertyType); var isDictionary = IsDictionaryType(propertyType); var isArray = IsArrayType(propertyType) && propertyType != typeof(byte[]); var baseType = isDictionary ? GetDictionaryKeyValueTypes(propertyType).ValueType : isArray ? GetArrayElementType(propertyType) : propertyType; if ((isDictionary || isArray) && IsCollectionValue(baseType)) throw new RedbNestedCollectionException(type, property.Name, propertyType); if (!isDictionary && !isArray && IsCollectionValue(propertyType)) throw new RedbUnsupportedCollectionException(type, property.Name, propertyType); if (IsBusinessClass(baseType)) Walk(baseType, visited); } visited.Remove(type); } } /// /// An element or dictionary value that is itself a collection: an array other than byte[], a list, a /// dictionary, or another framework collection. A class of the application that implements IEnumerable is a class /// and is not counted. /// private static bool IsCollectionValue(Type type) { type = Nullable.GetUnderlyingType(type) ?? type; if (type == typeof(string) || type == typeof(byte[])) return false; if (type.IsArray || IsArrayType(type) || IsDictionaryType(type)) return true; return typeof(System.Collections.IEnumerable).IsAssignableFrom(type) && !IsBusinessClass(type); } private static bool ShouldIgnoreProperty(PropertyInfo property) { // Only RedbIgnore affects DB schema. JsonIgnore is for JSON serialization (frontend). return property.GetCustomAttribute() != null; } private static bool IsArrayType(Type type) { if (IsDictionaryType(type)) return false; return type.IsArray || (type.IsGenericType && (type.GetGenericTypeDefinition() == typeof(List<>) || type.GetGenericTypeDefinition() == typeof(IList<>) || type.GetGenericTypeDefinition() == typeof(ICollection<>) || type.GetGenericTypeDefinition() == typeof(IEnumerable<>))); } private static bool IsDictionaryType(Type type) { if (!type.IsGenericType) return false; var genericDef = type.GetGenericTypeDefinition(); return genericDef == typeof(Dictionary<,>) || genericDef == typeof(IDictionary<,>); } private static (Type KeyType, Type ValueType) GetDictionaryKeyValueTypes(Type dictionaryType) { if (!dictionaryType.IsGenericType) throw new ArgumentException($"Type {dictionaryType} is not a generic Dictionary", nameof(dictionaryType)); var args = dictionaryType.GetGenericArguments(); if (args.Length != 2) throw new ArgumentException($"Type {dictionaryType} does not have 2 generic arguments", nameof(dictionaryType)); return (args[0], args[1]); } private static Type GetArrayElementType(Type arrayType) { if (arrayType.IsArray) return arrayType.GetElementType()!; if (arrayType.IsGenericType) return arrayType.GetGenericArguments()[0]; return arrayType; } private static bool IsBusinessClass(Type csharpType) { if (csharpType.IsPrimitive || csharpType == typeof(string) || csharpType == typeof(decimal)) return false; if (csharpType == typeof(DateTime) || csharpType == typeof(DateTimeOffset) || csharpType == typeof(DateOnly) || csharpType == typeof(TimeOnly) || csharpType == typeof(Guid) || csharpType == typeof(TimeSpan) || csharpType == typeof(byte[])) return false; if (Nullable.GetUnderlyingType(csharpType) != null) return false; if (csharpType.IsArray || IsArrayType(csharpType)) return false; if (csharpType.IsGenericType && csharpType.GetGenericTypeDefinition() == typeof(RedbObject<>)) return false; if (csharpType == typeof(IRedbListItem) || csharpType == typeof(RedbListItem)) return false; if (csharpType.IsEnum) return false; if (csharpType.Namespace?.StartsWith("System") == true) return false; return csharpType.IsClass; } private static RedbSchemeAttribute? GetRedbSchemeAttribute() where TProps : class => typeof(TProps).GetCustomAttribute(); private static RedbSchemeAttribute? GetRedbSchemeAttribute(Type type) => type.GetCustomAttribute(); // ============================================================ // === SCHEME LOOKUP METHODS === // ============================================================ public async Task GetSchemeByIdAsync(long schemeId, CancellationToken cancellationToken = default) { var cachedScheme = Cache.GetScheme(schemeId); if (cachedScheme != null) { var hashInDb = await Context.ExecuteScalarAsync(Sql.Schemes_SelectHashById(), new object[] { schemeId }, cancellationToken); if (cachedScheme.StructureHash == hashInDb) return cachedScheme; Cache.InvalidateScheme(schemeId); } var scheme = await Context.QueryFirstOrDefaultAsync(Sql.Schemes_SelectById(), new object[] { schemeId }, cancellationToken); if (scheme == null) return null; var structures = await Context.QueryAsync(Sql.Structures_SelectBySchemeCacheable(), new object[] { schemeId }, cancellationToken); scheme.SetStructures(structures); if (scheme.StructureHash == null && structures.Any()) { var newHash = SchemeHashCalculator.ComputeSchemeStructureHash(structures); await Context.ExecuteAsync(Sql.Schemes_UpdateHash(), new object[] { newHash, schemeId }, cancellationToken); scheme.StructureHash = newHash; } Cache.CacheScheme(scheme); return scheme; } /// public IRedbScheme? GetSchemeById(long schemeId) { // The sequence of GetSchemeByIdAsync, every call synchronous. var cachedScheme = Cache.GetScheme(schemeId); if (cachedScheme != null) { var hashInDb = Context.ExecuteScalar(Sql.Schemes_SelectHashById(), schemeId); if (cachedScheme.StructureHash == hashInDb) return cachedScheme; Cache.InvalidateScheme(schemeId); } var scheme = Context.QueryFirstOrDefault(Sql.Schemes_SelectById(), schemeId); if (scheme == null) return null; var structures = Context.Query(Sql.Structures_SelectBySchemeCacheable(), schemeId); scheme.SetStructures(structures); if (scheme.StructureHash == null && structures.Any()) { var newHash = SchemeHashCalculator.ComputeSchemeStructureHash(structures); Context.Execute(Sql.Schemes_UpdateHash(), newHash, schemeId); scheme.StructureHash = newHash; } Cache.CacheScheme(scheme); return scheme; } public async Task GetSchemeByNameAsync(string schemeName, CancellationToken cancellationToken = default) { var cachedScheme = Cache.GetScheme(schemeName); if (cachedScheme != null) return cachedScheme; var scheme = await Context.QueryFirstOrDefaultAsync(Sql.Schemes_SelectByName(), new object[] { schemeName }, cancellationToken); if (scheme == null) return null; var structures = await Context.QueryAsync(Sql.Structures_SelectBySchemeCacheable(), new object[] { scheme.Id }, cancellationToken); scheme.SetStructures(structures); Cache.CacheScheme(scheme); return scheme; } public async Task GetSchemeByTypeAsync(CancellationToken cancellationToken = default) where TProps : class { var schemeName = GetSchemeNameForType(); // Check cache first var cached = Cache.GetScheme(schemeName); if (cached != null) return cached; // Load from DB with structures and cache var scheme = await Context.QueryFirstOrDefaultAsync(Sql.Schemes_SelectByName(), new object[] { schemeName }, cancellationToken); if (scheme != null) { var structures = await Context.QueryAsync(Sql.Structures_SelectBySchemeCacheable(), new object[] { scheme.Id }, cancellationToken); scheme.SetStructures(structures); Cache.CacheScheme(scheme); } return scheme; } public async Task GetSchemeByTypeAsync(Type type, CancellationToken cancellationToken = default) { var schemeName = GetSchemeNameForType(type); // Check cache first var cached = Cache.GetScheme(schemeName); if (cached != null) return cached; // Load from DB with structures and cache var scheme = await Context.QueryFirstOrDefaultAsync(Sql.Schemes_SelectByName(), new object[] { schemeName }, cancellationToken); if (scheme != null) { var structures = await Context.QueryAsync(Sql.Structures_SelectBySchemeCacheable(), new object[] { scheme.Id }, cancellationToken); scheme.SetStructures(structures); Cache.CacheScheme(scheme); } return scheme; } /// /// Get scheme from cache synchronously (no DB call). /// Returns null if not in cache. /// public IRedbScheme? GetSchemeFromCache() where TProps : class { // Mirrors the three-step lookup chain used when syncing: the effective name first (an explicit // [RedbScheme(Name = "...")] or FullName), then FullName for the window where the type declares // an explicit name but the cache still holds the pre-rename entry, then the short type name for // backward compatibility with manually registered schemes. var t = typeof(TProps); return Cache.GetScheme(GetSchemeNameForType(t)) ?? Cache.GetScheme(t.FullName ?? t.Name) ?? Cache.GetScheme(t.Name); } /// /// Get scheme from cache synchronously (no DB call). /// Returns null if not in cache. /// public IRedbScheme? GetSchemeFromCache(string schemeName) { return Cache.GetScheme(schemeName); } public async Task LoadSchemeByTypeAsync(CancellationToken cancellationToken = default) where TProps : class { var scheme = await GetSchemeByTypeAsync(); return scheme ?? throw new ArgumentException($"Scheme for type '{typeof(TProps).Name}' not found"); } public async Task LoadSchemeByTypeAsync(Type type, CancellationToken cancellationToken = default) { var scheme = await GetSchemeByTypeAsync(type); return scheme ?? throw new ArgumentException($"Scheme for type '{type.Name}' not found"); } public async Task> GetSchemesAsync(CancellationToken cancellationToken = default) { var schemes = await Context.QueryAsync(Sql.Schemes_SelectAll(), System.Array.Empty(), cancellationToken); return schemes.Cast().ToList(); } public Task> GetStructuresAsync(IRedbScheme scheme, CancellationToken cancellationToken = default) => Task.FromResult(scheme.Structures.ToList()); public async Task> GetStructuresByTypeAsync(CancellationToken cancellationToken = default) where TProps : class { var scheme = await GetSchemeByTypeAsync(); if (scheme == null) return []; var structures = await Context.QueryAsync(Sql.Structures_SelectBySchemeShort(), new object[] { scheme.Id }, cancellationToken); return structures.Cast().ToList(); } public async Task> GetStructuresByTypeAsync(Type type, CancellationToken cancellationToken = default) { var scheme = await GetSchemeByTypeAsync(type); if (scheme == null) return []; var structures = await Context.QueryAsync(Sql.Structures_SelectBySchemeShort(), new object[] { scheme.Id }, cancellationToken); return structures.Cast().ToList(); } // ============================================================ // === SCHEME EXISTS METHODS === // ============================================================ public async Task SchemeExistsForTypeAsync(CancellationToken cancellationToken = default) where TProps : class { var schemeName = GetSchemeNameForType(); var result = await Context.ExecuteScalarAsync(Sql.Schemes_ExistsByName(), new object[] { schemeName }, cancellationToken); return result.HasValue; } public async Task SchemeExistsForTypeAsync(Type type, CancellationToken cancellationToken = default) { var schemeName = GetSchemeNameForType(type); var result = await Context.ExecuteScalarAsync(Sql.Schemes_ExistsByName(), new object[] { schemeName }, cancellationToken); return result.HasValue; } public async Task SchemeExistsByNameAsync(string schemeName, CancellationToken cancellationToken = default) { var result = await Context.ExecuteScalarAsync(Sql.Schemes_ExistsByName(), new object[] { schemeName }, cancellationToken); return result.HasValue; } // ============================================================ // === NAME/ALIAS HELPERS === // ============================================================ /// /// THE single place that turns a CLR type into a scheme name. Returns the explicit /// when the type declares one, otherwise FullName. /// /// Every lookup, existence check and creation path in this class must go through here. A path /// that computes type.FullName on its own does not fail loudly — it silently misses the /// lookup and ends up creating a second scheme for the same type. /// /// public string GetSchemeNameForType() where TProps : class => GetSchemeNameForType(typeof(TProps)); /// public string GetSchemeNameForType(Type type) => GetRedbSchemeAttribute(type)?.GetSchemeName(type) ?? type.FullName ?? type.Name; /// /// The explicit name declared by the type, or null when the type lives by FullName. /// Distinguishes "renaming requested" from "default naming" for the sync chain. /// private static string? GetExplicitSchemeName(Type type) { var name = GetRedbSchemeAttribute(type)?.Name; return string.IsNullOrWhiteSpace(name) ? null : name; } public string? GetSchemeAliasForType() where TProps : class => GetRedbSchemeAttribute()?.Alias; public string? GetSchemeAliasForType(Type type) => GetRedbSchemeAttribute(type)?.Alias; // ============================================================ // === OBJECT SCHEME (NON-GENERIC) === // ============================================================ public async Task EnsureObjectSchemeAsync(string name, CancellationToken cancellationToken = default) { var cached = Cache.GetScheme(name); if (cached != null) return cached; var existing = await Context.QueryFirstOrDefaultAsync( Sql.Schemes_SelectObjectByName(), new object[] { name, RedbTypeIds.Object }, cancellationToken); if (existing != null) { Cache.CacheScheme(existing); return existing; } var newId = await Context.NextObjectIdAsync(); var newScheme = new RedbScheme { Id = newId, Name = name, Type = RedbTypeIds.Object }; // Same creation race as the typed path — several nodes can reach this line for the same name. // The dialect suppresses the unique-name conflict so the transaction survives, and the loser // reads back the winner's row. var inserted = await Context.ExecuteAsync( Sql.Schemes_InsertObjectIfAbsent(), new object[] { newScheme.Id, newScheme.Name, newScheme.Type }, cancellationToken); if (inserted == 0) { var winner = await Context.QueryFirstOrDefaultAsync( Sql.Schemes_SelectObjectByName(), new object[] { name, RedbTypeIds.Object }, cancellationToken); if (winner == null) { throw new InvalidOperationException( $"Object scheme '{name}' was not inserted (conflict) but cannot be read back. " + "A non-Object scheme may already hold that name."); } Logger?.LogInformation( "Lost the creation race for object scheme '{SchemeName}'; using the existing scheme (ID: {SchemeId})", name, winner.Id); Cache.CacheScheme(winner); return winner; } Cache.CacheScheme(newScheme); return newScheme; } public async Task GetObjectSchemeAsync(string name, CancellationToken cancellationToken = default) { var cached = Cache.GetScheme(name); if (cached != null) return cached; var scheme = await Context.QueryFirstOrDefaultAsync( Sql.Schemes_SelectObjectByName(), new object[] { name, RedbTypeIds.Object }, cancellationToken); if (scheme == null) return null; Cache.CacheScheme(scheme); return scheme; } // ============================================================ // === ISchemeCacheProvider IMPLEMENTATION === // ============================================================ public void SetCacheEnabled(bool enabled) => Cache.SetEnabled(enabled); public bool IsCacheEnabled => Cache.IsEnabled; public void InvalidateCache() => Cache.Clear(); public void InvalidateSchemeCache() where TProps : class => Cache.InvalidateScheme(typeof(TProps).Name); public void InvalidateSchemeCache(long schemeId) => Cache.InvalidateScheme(schemeId); public void InvalidateSchemeCache(string schemeName) => Cache.InvalidateScheme(schemeName); public CacheStatistics GetCacheStatistics() => Cache.GetStatistics(); public void ResetCacheStatistics() => Cache.ResetStatistics(); public async Task WarmupCacheAsync(CancellationToken cancellationToken = default) where TProps : class { await GetSchemeByTypeAsync(); // Warmup by loading scheme } public async Task WarmupCacheAsync(Type[] types, CancellationToken cancellationToken = default) { foreach (var type in types) await GetSchemeByTypeAsync(type); // Warmup by loading schemes } public async Task WarmupAllSchemesAsync(CancellationToken cancellationToken = default) { var allSchemes = await Context.QueryAsync(Sql.Schemes_SelectAll(), System.Array.Empty(), cancellationToken); var allStructures = await Context.QueryAsync(Sql.Structures_SelectBySchemeCacheable(), System.Array.Empty(), cancellationToken); var structuresByScheme = allStructures.GroupBy(s => s.IdScheme).ToDictionary(g => g.Key, g => g.ToList()); foreach (var scheme in allSchemes) { if (structuresByScheme.TryGetValue(scheme.Id, out var structures)) { scheme.SetStructures(structures); } else { scheme.SetStructures(Array.Empty()); } if (scheme.StructureHash == null && scheme.Structures.Any()) { scheme.StructureHash = SchemeHashCalculator.ComputeSchemeStructureHash(scheme.StructuresInternal); await Context.ExecuteAsync(Sql.Schemes_UpdateHash(), new object[] { scheme.StructureHash, scheme.Id }, cancellationToken); } } foreach (var scheme in allSchemes) { Cache.CacheScheme(scheme); } } public CacheDiagnosticInfo GetCacheDiagnosticInfo() { var diagnosticText = Cache.GetDiagnosticInfo(); return new CacheDiagnosticInfo { Issues = [diagnosticText], Recommendations = [] }; } public long EstimateMemoryUsage() { var stats = Cache.GetStatistics(); var schemeCount = stats.SchemeHits + stats.SchemeMisses; var typeCount = stats.TypeHits + stats.TypeMisses; return schemeCount * 2048 + typeCount * 100; } // ============================================================ // === STRUCTURE TREE METHODS === // ============================================================ public async Task> GetStructureTreeAsync(long schemeId, CancellationToken cancellationToken = default) { if (Cache.GetStructureTree(schemeId) is { } cachedTree) return cachedTree; var scheme = await GetSchemeByIdAsync(schemeId); if (scheme == null) return []; var tree = StructureTreeBuilder.BuildFromFlat(scheme.Structures.ToList()); Cache.CacheStructureTree(schemeId, tree); return tree; } public async Task> GetSubtreeAsync(long schemeId, long? parentStructureId, CancellationToken cancellationToken = default) { if (Cache.GetSubtree(schemeId, parentStructureId) is { } cachedSubtree) return cachedSubtree; var fullTree = await GetStructureTreeAsync(schemeId); List subtree; if (parentStructureId == null) { subtree = fullTree.Where(n => n.IsRoot).ToList(); } else { var allNodes = StructureTreeBuilder.FlattenTree(fullTree); var parentNode = allNodes.FirstOrDefault(n => n.Structure.Id == parentStructureId); subtree = parentNode?.Children ?? []; } Cache.CacheSubtree(schemeId, parentStructureId, subtree); return subtree; } public async Task> GetChildrenStructuresAsync(long schemeId, long parentStructureId, CancellationToken cancellationToken = default) { var subtree = await GetSubtreeAsync(schemeId, parentStructureId); return subtree.Select(n => n.Structure).ToList(); } public async Task FindStructureNodeAsync(long schemeId, long structureId, CancellationToken cancellationToken = default) { var tree = await GetStructureTreeAsync(schemeId); var allNodes = StructureTreeBuilder.FlattenTree(tree); return allNodes.FirstOrDefault(n => n.Structure.Id == structureId); } public async Task FindStructureByPathAsync(long schemeId, string path, CancellationToken cancellationToken = default) { var tree = await GetStructureTreeAsync(schemeId); return StructureTreeBuilder.FindNodeByPath(tree, path); } public async Task GetStructureTreeJsonAsync(long schemeId, CancellationToken cancellationToken = default) { var result = await Context.ExecuteJsonAsync(Sql.Schemes_GetStructureTree(), new object[] { schemeId }, cancellationToken); return result ?? "[]"; } public async Task ValidateStructureTreeAsync(long schemeId, CancellationToken cancellationToken = default) where TProps : class { var tree = await GetStructureTreeAsync(schemeId); return StructureTreeBuilder.DiagnoseTree(tree, typeof(TProps)); } public void InvalidateStructureTreeCache(long schemeId) => Cache.InvalidateStructureTrees(schemeId); public (int TreesCount, int SubtreesCount, long MemoryEstimate) GetStructureTreeCacheStats() { var (treesCount, subtreesCount) = Cache.StructureTreeCounts(); var memoryEstimate = treesCount * 1024 + subtreesCount * 200; return (treesCount, subtreesCount, memoryEstimate); } public async Task HasChildrenStructuresAsync(long schemeId, long structureId, CancellationToken cancellationToken = default) { var children = await GetSubtreeAsync(schemeId, structureId); return children.Count > 0; } }