Bundle: redb / redb.Core (redb.Core.txt), 233 files Snapshot: 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 Index: https://redbase.app/src/dev-2026-12-06/redb/_index.txt ==== Path: redb/redb.Core/Attributes/RedbAliasAttribute.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/Attributes/RedbAliasAttribute.cs ---- using System; namespace redb.Core.Attributes { /// /// Attribute for specifying a human-readable alias /// Applied to enum values (ListItem.Alias) and Props properties (Structure.Alias) /// [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false)] public class RedbAliasAttribute : Attribute { public string Alias { get; } public RedbAliasAttribute(string alias) { Alias = alias ?? throw new ArgumentNullException(nameof(alias)); } } } Path: redb/redb.Core/Attributes/RedbIgnoreAttribute.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/Attributes/RedbIgnoreAttribute.cs ---- using System; namespace redb.Core.Attributes { /// /// Excludes a property from the REDB schema (but not from JSON serialization) /// [AttributeUsage(AttributeTargets.Property)] public class RedbIgnoreAttribute : Attribute { } } Path: redb/redb.Core/Attributes/RedbRenameAttribute.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/Attributes/RedbRenameAttribute.cs ---- using System; namespace redb.Core.Attributes { /// /// Declares a previous name of a Props property, so that the scheme sync renames the stored property instead of /// adding a new one and deleting the old one with its values. /// /// On the sync, a property whose name is not in the database but whose previous name is gets the stored structure /// renamed in place: the structure id stays, and with it every stored value. The next sync finds the property under /// its name and does nothing. When both the name and a previous name are in the database, the sync stops with /// and changes nothing: choosing one of them would lose the /// values of the other. /// /// /// The attribute is repeated for a chain of renames (A to B to C: two attributes on /// C), so that a database that missed a version is renamed too. The previous names are kept in the /// database (_structures._renamed_from): a node that still runs a class with the previous name stops at /// its sync with instead of adding the property again and /// deleting the renamed one. /// /// /// The attribute stays on the property for good, in the order of the chain, the first name first: the first name /// orders the property in the object hash, so the hashes stored before the rename stay valid after it. The sync /// checks the first attribute against the history the database keeps and stops with /// when they disagree or the attributes are gone. A database /// created directly with the renamed class has no history yet, so there the check cannot fire. /// /// /// A freed previous name may be taken by a new property of the same class once the rename is applied. While the /// database still stores the previous name and not the current one, the sync stops with an error: the stored /// structure could belong to either property. /// /// /// Two properties whose last attributes (the attribute declared last) name each other's current name swap the /// names in one step, which the sync refuses from the class alone: swap through a temporary name, one deployment /// per rename. /// /// [AttributeUsage(AttributeTargets.Property, AllowMultiple = true)] public sealed class RedbRenameAttribute : Attribute { /// The previous name of the property. public string OldName { get; } /// The previous name of the property. public RedbRenameAttribute(string oldName) { if (string.IsNullOrWhiteSpace(oldName)) throw new ArgumentException("The previous name of a property cannot be empty", nameof(oldName)); OldName = oldName; } } } Path: redb/redb.Core/Attributes/RedbSchemeAttribute.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/Attributes/RedbSchemeAttribute.cs ---- using System; namespace redb.Core.Attributes { /// /// Attribute for configuring the REDB schema for a properties class. /// /// By default the schema is named after the CLR type's . Set /// to pin an explicit name instead, decoupling the database identity of the /// schema from C# namespace/class refactoring. /// /// [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] public class RedbSchemeAttribute : Attribute { /// /// Explicit schema name in the database. When null or empty, the schema is named after the /// CLR type's — the legacy default. /// /// Setting this on an existing project renames the schema in the database on the next /// sync: the scheme row is looked up by the explicit name, then by FullName, then by the short /// type name, and the first match is renamed in place (the scheme id, and therefore all objects /// and structures, are untouched). Because an older binary would not find the scheme under its /// new name and would create a second one, every consumer of the database must be updated /// together. /// /// /// Must follow C# identifier rules — Latin letters, digits, _, . and +, /// no reserved words, 128 characters max. Validated before any SQL is issued; use /// for human-readable titles. /// /// /// Multi-node note. The name (and alias) live in this attribute — in code — so changing /// them means a redeploy, which restarts every node and rebuilds each process's static scheme /// caches fresh. Cross-node consistency is achieved by that restart; there is no online rename /// on live nodes without restart, and it is not supported. /// /// public string? Name { get; set; } /// /// Schema alias (human-readable name). Never used as the schema name — it is free-form and may /// contain spaces, punctuation and non-Latin letters. Synchronised from this attribute on every /// sync: changing it updates the database, removing it sets the alias back to null. /// public string? Alias { get; set; } /// /// Previous names of the schema, oldest first, so that the sync renames the stored schema instead of creating a /// new one and leaving every object under the old one. /// /// The sync looks the schema up by its name first; when it is not there, by these names, and renames the first /// one found in place (the schema id, and with it every object and structure, stays). Use it when an explicit /// changes (RenamedFrom = ["orders"]), or when a class without an explicit name is /// renamed or moved to another namespace (its previous FullName). When the schema name and a previous one are /// both stored, the sync stops with . /// /// /// The previous names are kept in the database (_schemes._renamed_from): a node that still runs a class /// with a previous name stops at its sync with instead of /// creating the old schema again. /// /// public string[]? RenamedFrom { get; set; } /// /// The version of this Props class, raised by the programmer with a change that takes data away: a property /// removed, or a property's type changed (and with a change inside a nested class of the scheme, which belongs /// to it). A class without the attribute, or without this value, has version 0. /// /// The sync records the version in the database (_schemes._version) and deletes a structure or /// changes its type only for a class whose version is higher than the recorded one. A class of the same /// version adds what it lacks and leaves the rest as it is, with a warning; a class of a lower version (an /// older build of the application next to a newer one) changes nothing. So a node that still runs an older /// build cannot take the fields or the types of a newer build away. The version recorded never goes down. /// /// /// Adding a property needs no new version. /// (on in the Development profile) lets a class of the same version delete and change too, for a local /// database during development. /// /// public int Version { get; set; } /// /// Parameterless constructor /// public RedbSchemeAttribute() { } /// /// Constructor with alias. The positional argument is always the alias, never the schema /// name — an explicit name can only be set through the named parameter, so /// existing declarations cannot change meaning by accident. /// /// Schema alias public RedbSchemeAttribute(string alias) { Alias = alias ?? throw new ArgumentNullException(nameof(alias)); } /// /// Get the schema name for the type: the explicit when set, otherwise the /// full class name (namespace.class). /// /// Class type /// Schema name /// /// Deliberately does no validation — this sits on hot paths (assembly rescan, cache warm-up, /// every sync). Explicit names are validated by /// at the points that write to the database. /// public string GetSchemeName(Type type) { return !string.IsNullOrWhiteSpace(Name) ? Name! : type.FullName ?? type.Name; } } } Path: redb/redb.Core/Attributes/RedbTagsAttribute.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/Attributes/RedbTagsAttribute.cs ---- using System; namespace redb.Core.Attributes { /// /// Writes the free-form _tags marker of a scheme (on the Props class) or of a /// structure (on a property) at synchronisation. The column is a reserved slot for future /// and custom extensions: 450 characters, indexed on _structures, no semantics /// imposed by redb. WITHOUT the attribute synchronisation leaves the column untouched, so /// values written directly by applications and extensions survive every sync. /// [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property, AllowMultiple = false, Inherited = true)] public sealed class RedbTagsAttribute : Attribute { /// The marker text, up to 450 characters (enforced in C# for provider parity). public string Tags { get; } public RedbTagsAttribute(string tags) => Tags = tags; } } Path: redb/redb.Core/Attributes/RedbUniqueAttribute.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/Attributes/RedbUniqueAttribute.cs ---- using System; namespace redb.Core.Attributes { /// /// Declares a Props property a unique key within its scheme: no two objects of the scheme may /// hold the same value in it. Enforced by the database — a unique index over /// _values (_id_structure, _unique), where _unique is the 128-bit hash of the /// value's canonical form () — and surfaced as /// . /// /// /// Allowed on: a scalar property — string, integers, Guid, bool, /// double/float, decimal, DateTime/DateTimeOffset/ /// DateOnly, byte[] and their nullable forms — of the Props class or of a nested /// class reached without crossing a collection (S2); and on a whole nested class, array or /// dictionary property, where the key is the SUBTREE content (S1). Not on enums (stored as their /// name in text, not a key type), single RedbObject references, or /// members of collection ELEMENTS — element rows share one structure across every element of /// every object. Scheme synchronisation rejects a misplaced attribute with /// . /// /// /// /// null never participates: any number of objects may leave the key empty. /// /// /// /// The value is compared exactly, after Unicode NFC normalisation for strings: no trimming, no /// case folding. A key is a notion of the application; an application that wants /// case-insensitive or trimmed keys normalises them before saving — the same contract as a unique /// index in any database, and what EF Core and Hibernate do. /// /// /// /// Putting the attribute on a property of a scheme that already has data recomputes the column /// for every existing object at the next synchronisation and reports duplicates /// () instead of failing start-up: duplicate rows stay /// outside the index until they are resolved. /// /// [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] public sealed class RedbUniqueAttribute : Attribute { /// /// On a COLLECTION property switches from the subtree-content key (the default) to /// ELEMENT keys: - no duplicate elements inside one /// collection; - element values unique across the whole /// scheme. Meaningless (and rejected at synchronisation) on scalars and nested classes, /// whose bare attribute already carries the strongest reading. /// public UniqueScope Scope { get; set; } = UniqueScope.Default; } } Path: redb/redb.Core/Attributes/SchemeNameValidator.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/Attributes/SchemeNameValidator.cs ---- using System; using System.Collections.Generic; using System.Text.RegularExpressions; using redb.Core.Exceptions; namespace redb.Core.Attributes { /// /// Single source of truth for explicit scheme name rules. /// /// The rules mirror the database-level triggers one-for-one (PostgreSQL /// validate_scheme_name, and the MSSql/SQLite equivalents). Validation lives here /// because it must behave identically on every provider and must fail before any SQL is /// issued — a raw 23505/2627 surfacing from the driver tells the developer nothing about /// which type is at fault. /// /// /// Only explicit names () are validated. Names /// derived from are valid by construction, and checking them /// would break existing projects that never asked for this feature. /// /// public static class SchemeNameValidator { /// Names starting with this prefix are reserved for internal schemes and skip validation. public const string SystemPrefix = "@@"; /// Maximum length accepted by the database triggers. public const int MaxLength = 128; private static readonly Regex AllowedShape = new(@"^[a-zA-Z_][a-zA-Z0-9_.+]*$", RegexOptions.Compiled | RegexOptions.CultureInvariant); private static readonly Regex ValidPart = new(@"^[a-zA-Z_][a-zA-Z0-9_]*$", RegexOptions.Compiled | RegexOptions.CultureInvariant); // Same list as the database triggers. Kept verbatim so the three providers and this // validator can never disagree about what a reserved word is. private static readonly HashSet ReservedWords = new(StringComparer.Ordinal) { "abstract", "as", "bool", "break", "byte", "case", "catch", "char", "checked", "class", "const", "continue", "decimal", "default", "delegate", "do", "double", "else", "enum", "event", "explicit", "extern", "false", "finally", "fixed", "float", "for", "foreach", "goto", "if", "implicit", "in", "int", "interface", "internal", "is", "lock", "long", "namespace", "new", "null", "object", "operator", "out", "override", "params", "private", "protected", "public", "readonly", "ref", "return", "sbyte", "sealed", "short", "sizeof", "stackalloc", "static", "string", "struct", "switch", "this", "throw", "true", "try", "typeof", "uint", "ulong", "unchecked", "unsafe", "ushort", "using", "virtual", "void", "volatile", "while" }; /// /// Validates an explicit scheme name and throws when it /// breaks a rule. The declaring type is carried into the message so the developer knows /// exactly which class to fix. /// public static void Validate(string? name, Type declaringType) { if (!IsValid(name, out var error)) throw new RedbSchemeNameException(declaringType, name, error!); } /// /// Non-throwing form. Returns false and fills with a /// human-readable reason. /// public static bool IsValid(string? name, out string? error) { error = null; // Rule 5: not empty / not whitespace-only. if (string.IsNullOrWhiteSpace(name)) { error = "the name is empty"; return false; } // Rule 0: system schemes bypass every other rule. if (name!.StartsWith(SystemPrefix, StringComparison.Ordinal)) return true; // Rule 6: length. if (name.Length > MaxLength) { error = $"the name is longer than {MaxLength} characters (got {name.Length})"; return false; } // Rule 1: must not start with a digit. Checked before the shape rule so the message is specific. if (name[0] >= '0' && name[0] <= '9') { error = "the name starts with a digit; it must start with a letter or underscore"; return false; } // Rule 2: allowed character set. if (!AllowedShape.IsMatch(name)) { error = "the name contains characters outside [a-zA-Z0-9_.+]; " + "spaces, punctuation and non-Latin letters are not allowed"; return false; } // Rule 3: must not end with a dot. if (name.EndsWith(".", StringComparison.Ordinal)) { error = "the name ends with a dot"; return false; } // Rule 4: no two consecutive dots. if (name.Contains("..")) { error = "the name contains two consecutive dots"; return false; } // Rules 7 and 8: every part between dots/pluses must be a valid identifier and // must not be a C# reserved word. foreach (var part in name.Split('.', '+')) { if (!ValidPart.IsMatch(part)) { error = $"namespace part '{part}' is not a valid identifier"; return false; } if (ReservedWords.Contains(part.ToLowerInvariant())) { error = $"namespace part '{part}' is a C# reserved word"; return false; } } return true; } } } Path: redb/redb.Core/Attributes/UniqueScope.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/Attributes/UniqueScope.cs ---- namespace redb.Core.Attributes; /// /// Scope of a key on a COLLECTION property (S3 of the /// subtree-unique plan). On scalars and nested classes the scope is not configurable - the /// bare attribute already means the strongest sensible reading (value unique per scheme, /// subtree content unique per scheme). /// public enum UniqueScope { /// /// The default reading of the bare attribute: for a scalar - the value canon; for a class, /// array or dictionary - the SUBTREE content key (no two objects hold this exact content). /// Default = 0, /// /// Element scope, scheme-wide: every ELEMENT value of the collection is unique across all /// objects of the scheme ("this email appears in one object only, whichever array it sits /// in"). References canonicalise by target id: "this object is attached at most once in /// the whole scheme". /// Scheme = 1, /// /// Element scope, per collection: no duplicate element values INSIDE one object's /// collection; different objects may repeat each other freely. The classic "unique set" - /// for references: "no duplicate links in this collection". /// Collection = 2, } Path: redb/redb.Core/Caching/CacheDelegates.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/Caching/CacheDelegates.cs ---- using System; using System.Linq.Expressions; using System.Reflection; using System.Runtime.CompilerServices; using redb.Core.Models.Contracts; using redb.Core.Utils; namespace redb.Core.Caching { /// /// Typed cache calls for an object type met at run time. A batch load and a graph write used to run /// GetMethod + MakeGenericMethod + Invoke on every object; here the call is built once per type /// and kept in a : a type unloaded with its collectible load context /// takes its delegate with it, so Tsak hot reload releases the assembly. /// internal static class CacheDelegates { private static readonly ConditionalWeakTable> _set = new(); private static readonly ConditionalWeakTable> _setGraph = new(); private static readonly ConditionalWeakTable> _get = new(); /// Write the object by its own id (the Set of the cache interface). A non-generic RedbObject carries /// no Props and was never an entry of its own. public static void Set(IRedbObjectCache cache, IRedbObject obj) { if (RedbObjectTypes.GenericOf(obj.GetType()) == null) return; _set.GetValue(obj.GetType(), CreateSet)(cache, obj); } /// Write the object and every loaded object under it in one walk. public static void SetGraph(GlobalPropsCache cache, IRedbObject obj) { if (RedbObjectTypes.GenericOf(obj.GetType()) == null) return; _setGraph.GetValue(obj.GetType(), CreateSetGraph)(cache, obj); } /// Read the object by id and hash; null when the cache has no current entry. public static IRedbObject? Get(GlobalPropsCache cache, Type propsType, long objectId, Guid hash) => _get.GetValue(propsType, CreateGet)(cache, objectId, hash); private static Action CreateSet(Type objectType) { var redbType = RedbObjectTypes.GenericOf(objectType)!; var set = typeof(IRedbObjectCache).GetMethod(nameof(IRedbObjectCache.Set))! .MakeGenericMethod(redbType.GetGenericArguments()[0]); var cache = Expression.Parameter(typeof(IRedbObjectCache), "cache"); var obj = Expression.Parameter(typeof(IRedbObject), "obj"); var call = Expression.Call(cache, set, Expression.Convert(obj, redbType)); return Expression.Lambda>(call, cache, obj).Compile(); } private static Action CreateSetGraph(Type objectType) { var redbType = RedbObjectTypes.GenericOf(objectType)!; var setGraph = typeof(GlobalPropsCache).GetMethod(nameof(GlobalPropsCache.SetGraph))! .MakeGenericMethod(redbType.GetGenericArguments()[0]); var cache = Expression.Parameter(typeof(GlobalPropsCache), "cache"); var obj = Expression.Parameter(typeof(IRedbObject), "obj"); var call = Expression.Call(cache, setGraph, Expression.Convert(obj, redbType)); return Expression.Lambda>(call, cache, obj).Compile(); } private static Func CreateGet(Type propsType) { var get = typeof(GlobalPropsCache).GetMethod(nameof(GlobalPropsCache.Get))! .MakeGenericMethod(propsType); var cache = Expression.Parameter(typeof(GlobalPropsCache), "cache"); var objectId = Expression.Parameter(typeof(long), "objectId"); var hash = Expression.Parameter(typeof(Guid), "hash"); var call = Expression.Call(cache, get, objectId, hash); var body = Expression.Convert(call, typeof(IRedbObject)); return Expression.Lambda>(body, cache, objectId, hash) .Compile(); } } } Path: redb/redb.Core/Caching/CacheDiagnosticInfo.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/Caching/CacheDiagnosticInfo.cs ---- using System.Collections.Generic; namespace redb.Core.Caching { /// /// Cache diagnostic information, returned by /// . /// /// /// These four types used to live in ICompositeMetadataCache.cs, alongside a layer of cache /// interfaces that was never implemented and never consumed. That layer was removed; these /// carried on being part of a live public contract, so they moved here unchanged. /// public class CacheDiagnosticInfo { /// /// Cache health status. /// public CacheHealthStatus HealthStatus { get; set; } /// /// Potential issues. /// public List Issues { get; set; } = new(); /// /// Optimization recommendations. /// public List Recommendations { get; set; } = new(); /// /// Memory information. /// public MemoryUsageInfo MemoryInfo { get; set; } = new(); /// /// Performance information. /// public PerformanceInfo PerformanceInfo { get; set; } = new(); } /// /// Cache health status enumeration. /// public enum CacheHealthStatus { /// Cache is healthy. Healthy, /// Cache has warnings. Warning, /// Cache is in critical state. Critical, /// Cache status is unknown. Unknown } /// /// Cache memory usage information. /// public class MemoryUsageInfo { /// /// Used memory in bytes. /// public long UsedBytes { get; set; } /// /// Maximum memory in bytes (if limited). /// public long? MaxBytes { get; set; } /// /// Memory usage percentage. /// public double UsagePercentage { get; set; } /// /// Memory fragmentation percentage (if available). /// public double? FragmentationPercentage { get; set; } } /// /// Cache performance information. /// public class PerformanceInfo { /// /// Average cache access time in milliseconds. /// public double AverageAccessTimeMs { get; set; } /// /// Average data source load time in milliseconds. /// public double AverageLoadTimeMs { get; set; } /// /// Operations per second. /// public double OperationsPerSecond { get; set; } /// /// Peak access time in milliseconds. /// public double PeakAccessTimeMs { get; set; } } } Path: redb/redb.Core/Caching/CachePublication.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/Caching/CachePublication.cs ---- using System; using redb.Core.Data; namespace redb.Core.Caching { /// /// The caches publish committed state only (review after 4.0.0). A cache Set marks the graph shared, and a shared /// instance does not keep what one transaction saw (owner decision 2026-09-15) - so a Set inside a transaction made /// the writer's own loaded object forget its lazy references: an edit of root.Props.Next.Props followed by a /// save of root.Props.Next saved a fresh reload, and every read of a list item's object was a query. A Set /// inside a transaction now waits for its commit; until then the instance is the reader's own, and what a /// rolled-back transaction loaded never reaches the cache. /// public static class CachePublication { /// /// Runs now, or once the transaction takes part in has /// committed - the explicit redb transaction of the context, else the ambient . /// public static void AfterCommit(IRedbContext context, Action publish) { ArgumentNullException.ThrowIfNull(context); ArgumentNullException.ThrowIfNull(publish); if (!TransactionHooks.OnCompleted(context, committed => { if (committed) publish(); })) publish(); } } } Path: redb/redb.Core/Caching/CacheStatistics.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/Caching/CacheStatistics.cs ---- namespace redb.Core.Caching; /// /// Cache statistics. /// public class CacheStatistics { public int SchemeHits { get; set; } public int SchemeMisses { get; set; } public int StructureHits { get; set; } public int StructureMisses { get; set; } public int TypeHits { get; set; } public int TypeMisses { get; set; } public double SchemeHitRatio => SchemeHits + SchemeMisses > 0 ? (double)SchemeHits / (SchemeHits + SchemeMisses) : 0; public double StructureHitRatio => StructureHits + StructureMisses > 0 ? (double)StructureHits / (StructureHits + StructureMisses) : 0; public double TypeHitRatio => TypeHits + TypeMisses > 0 ? (double)TypeHits / (TypeHits + TypeMisses) : 0; public double OverallHitRatio { get { var totalHits = SchemeHits + StructureHits + TypeHits; var totalRequests = SchemeHits + SchemeMisses + StructureHits + StructureMisses + TypeHits + TypeMisses; return totalRequests > 0 ? (double)totalHits / totalRequests : 0; } } } Path: redb/redb.Core/Caching/ClrSchemeTypeIndex.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/Caching/ClrSchemeTypeIndex.cs ---- using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Reflection; using System.Threading; using redb.Core.Attributes; using redb.Core.Exceptions; namespace redb.Core.Caching; /// /// Process-global registry of schemeName → CLR Type, derived from . /// /// This mapping is a database-independent fact: a type's scheme name comes from its attribute /// and is identical regardless of which database/connection it is used against. Therefore it lives /// once per process and is shared by every cache domain — unlike the per-domain /// scheme_id → Type projection in , where scheme_id is a /// per-database fact that must stay isolated per connection. /// /// It is self-healing: assembly loads (including into plugin AssemblyLoadContexts) bump a /// generation counter, and the index is rebuilt lazily on the next lookup. This removes the old /// one-shot, per-domain snapshot that went stale whenever modules loaded after initialization. /// /// /// Collectible ALC safety. Entries hold to , never /// a strong reference. A strong Type keeps its AssemblyLoadContext alive, so a static index /// that held one would pin every hot-reloaded plugin module in memory forever. Dead entries are pruned /// lazily on lookup. /// /// public static class ClrSchemeTypeIndex { private static readonly ConcurrentDictionary> _nameToType = new(); // Explicit [RedbScheme(Name = "...")] values claimed by more than one DISTINCT type (different // FullName). Two instances of the SAME FullName from different ALCs are a reload, not a conflict // (see Rescan). Recorded during the scan (best-effort, must not throw) and turned into a hard // failure by ThrowIfNameConflict at the deterministic point where the type is actually synced. private static readonly ConcurrentDictionary Existing, WeakReference Conflicting)> _nameConflicts = new(); private static readonly object _scanLock = new(); private static long _assemblyGeneration; // bumped on every assembly load in the process private static long _scannedGeneration = -1; // generation captured at the last completed scan static ClrSchemeTypeIndex() { // Fires for assemblies loaded into ANY load context (default + plugin ALCs) in .NET Core. AppDomain.CurrentDomain.AssemblyLoad += static (_, _) => Interlocked.Increment(ref _assemblyGeneration); } /// /// Resolve a scheme name (or alias) to its CLR type, or null if no /// type carries that name (a legitimately non-generic scheme). Prunes the entry if the type's ALC /// has been unloaded. /// public static Type? Resolve(string schemeName) { if (string.IsNullOrEmpty(schemeName)) return null; EnsureFresh(); var type = TryResolveLive(schemeName, out var dead); if (type != null || !dead) return type; // The entry pointed at a type whose ALC has unloaded. The same name may still belong to a live type: the // scan writes the last type that carries a name, and a module that loaded a copy of the host's own // assembly took the host's names; once it unloaded they resolved to null, and no assembly load came to // bring a rescan. Unloading is no load event, so the rescan is made here, once. lock (_scanLock) { var gen = Interlocked.Read(ref _assemblyGeneration); Rescan(); Volatile.Write(ref _scannedGeneration, gen); } return TryResolveLive(schemeName, out _); } private static Type? TryResolveLive(string schemeName, out bool dead) { dead = false; if (!_nameToType.TryGetValue(schemeName, out var weak)) return null; if (weak.TryGetTarget(out var type)) return type; // The type's ALC was unloaded — drop the dead entry (but only if it is still THIS weak ref; // a concurrent Register may have replaced it with a live one). ((System.Collections.Generic.ICollection>>)_nameToType) .Remove(new KeyValuePair>(schemeName, weak)); dead = true; return null; } /// /// Explicitly register a name → type mapping (e.g. from an authoritative scheme sync). Idempotent; /// last write wins. Lets types resolve even before/without an assembly scan. /// public static void Register(string schemeName, Type type) { if (!string.IsNullOrEmpty(schemeName) && type != null) _nameToType[schemeName] = new WeakReference(type); } /// Rescan loaded assemblies if any have loaded since the last scan. Cheap no-op when unchanged. public static void EnsureFresh() { if (Interlocked.Read(ref _scannedGeneration) == Interlocked.Read(ref _assemblyGeneration)) return; lock (_scanLock) { var gen = Interlocked.Read(ref _assemblyGeneration); if (_scannedGeneration == gen) return; // another thread already rescanned Rescan(); // If an assembly loaded mid-scan, gen < newest → next EnsureFresh rescans again (no lost update). Volatile.Write(ref _scannedGeneration, gen); } } private static void Rescan() { foreach (var type in EnumerateSchemeTypes()) { var attr = type.GetCustomAttribute(); if (attr == null) continue; var name = attr.GetSchemeName(type); if (!string.IsNullOrEmpty(name)) { // Only explicit names are policed. Alias collisions have always been last-write-wins // (e.g. "Product" is declared in two unrelated projects) and tightening them would // break projects that never opted into explicit naming. if (!string.IsNullOrWhiteSpace(attr.Name) && TryGetLiveOwner(name, out var owner) && owner != type) { // Same FullName from a different ALC = the SAME logical type reloaded (Tsak hot-swap), // NOT a name conflict. Only distinct FullNames sharing one explicit Name are a real clash. if (owner.FullName == type.FullName) { _nameConflicts.TryRemove(name, out _); // clear a stale conflict left by the old instance } else if (owner.GetCustomAttribute()?.Name == attr.Name) { _nameConflicts[name] = (new WeakReference(owner), new WeakReference(type)); } } _nameToType[name] = new WeakReference(type); // upsert; never Clear (readers stay safe) } if (!string.IsNullOrEmpty(attr.Alias)) _nameToType[attr.Alias!] = new WeakReference(type); } } private static bool TryGetLiveOwner(string name, out Type owner) { owner = null!; return _nameToType.TryGetValue(name, out var weak) && weak.TryGetTarget(out owner!); } /// /// Throws when another distinct type has claimed the same explicit scheme name. Called from /// the sync path rather than from the scan itself: the scan is a best-effort warm-up that must not /// throw, but a duplicate name is fatal and has to surface deterministically, before anything is /// written. A conflict whose other party has since been unloaded (dead weak ref) is not reported — /// there is nothing to clash with anymore. /// public static void ThrowIfNameConflict(string schemeName, Type type) { EnsureFresh(); if (!_nameConflicts.TryGetValue(schemeName, out var pair)) return; // Both parties must still be alive AND one of them must be the type being synced. if (!pair.Existing.TryGetTarget(out var existing) || !pair.Conflicting.TryGetTarget(out var conflicting)) { _nameConflicts.TryRemove(schemeName, out _); // one side unloaded → no live conflict return; } if (existing == type || conflicting == type) throw new RedbSchemeNameConflictException(schemeName, existing, conflicting); } /// /// Single source of truth for assembly enumeration: broad (every load context), reflection-load-safe. /// Used by the index and reusable by auto-sync so both see the same set. /// public static IEnumerable EnumerateSchemeTypes() { foreach (var asm in AppDomain.CurrentDomain.GetAssemblies()) { Type?[] types; try { types = asm.GetTypes(); } catch (ReflectionTypeLoadException ex) { types = ex.Types; } catch { continue; } foreach (var t in types) { if (t != null && t.GetCustomAttribute() != null) yield return t; } } } /// Diagnostics: number of live registered name keys (dead weak refs excluded). public static int Count { get { var n = 0; foreach (var weak in _nameToType.Values) if (weak.TryGetTarget(out _)) n++; return n; } } /// Test/reset hook — clears the index and forces a rescan on next lookup. public static void Clear() { lock (_scanLock) { _nameToType.Clear(); _nameConflicts.Clear(); Interlocked.Exchange(ref _scannedGeneration, -1); } } } Path: redb/redb.Core/Caching/CollectibleContextCleanup.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/Caching/CollectibleContextCleanup.cs ---- using System; using System.Reflection; using System.Reflection.Metadata; using System.Runtime.CompilerServices; using System.Runtime.Loader; using System.Threading; using Microsoft.Extensions.Logging; namespace redb.Core.Caching; /// /// Forgets a collectible when it unloads (a module of Tsak, for instance): the /// process-wide caches that hold INSTANCES of the module's types, or metadata built for them, drop those, so nothing /// keeps the context alive. Caches of redb keyed by type alone hold their key weakly instead and need nothing here. /// /// Every collectible context is watched from the moment one of its assemblies loads (and the ones that existed before /// this class first ran are picked up then), so the hot path pays nothing: the work happens once per unload, in /// , which Unload() raises before the context can be collected. /// /// internal static class CollectibleContextCleanup { private static readonly ConditionalWeakTable Watched = new(); private static readonly object Marker = new(); private static int _started; private static int _noHandlersReported; private static ILogger? _logger; /// /// Starts watching collectible contexts; called by every cache that can hold a module's instances and by every /// redb service. The first logger handed over reports the cleanup. /// public static void EnsureWatching(ILogger? logger = null) { if (logger != null) Interlocked.CompareExchange(ref _logger, logger, null); if (Interlocked.Exchange(ref _started, 1) == 1) return; AppDomain.CurrentDomain.AssemblyLoad += static (_, e) => Watch(e.LoadedAssembly); foreach (var context in AssemblyLoadContext.All) if (context.IsCollectible) Watch(context); } private static void Watch(Assembly assembly) { if (assembly.IsCollectible && AssemblyLoadContext.GetLoadContext(assembly) is { } context) Watch(context); } private static void Watch(AssemblyLoadContext context) { if (Watched.TryAdd(context, Marker)) context.Unloading += OnUnloading; } private static void OnUnloading(AssemblyLoadContext context) { context.Unloading -= OnUnloading; bool Unloading(Type type) => BelongsTo(type, context); GlobalPropsCache.RemoveObjectsOfTypes(Unloading); GlobalListCache.RemoveObjectsOfTypes(Unloading); ClearMetadataUpdateCaches(context); } /// /// The libraries of .NET keep process-wide caches built over the types they handled, and do not let a collectible /// context go while one of its types is in them: System.Text.Json above all (metadata in every options instance, /// the static SystemTextJsonRedbSerializer.Options of redb included, in contexts shared by equal options and /// in emitted member accessors), TypeDescriptor and others. They declare a handler for hot reload /// () whose ClearCache empties those caches; redb calls /// ClearCache(null) of every handler declared by a loaded assembly, as dotnet watch does, once per /// unload. The assemblies of the unloading context are left out. Unloadable assemblies are not supported by /// System.Text.Json otherwise: https://github.com/dotnet/runtime/issues/65323. Costs cold caches in those libraries /// for what follows, once per unload. /// private static void ClearMetadataUpdateCaches(AssemblyLoadContext unloading) { var found = 0; foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) { if (assembly.IsDynamic || AssemblyLoadContext.GetLoadContext(assembly) == unloading) continue; MetadataUpdateHandlerAttribute[] handlers; try { handlers = (MetadataUpdateHandlerAttribute[])assembly.GetCustomAttributes(typeof(MetadataUpdateHandlerAttribute), false); } catch (Exception ex) { _logger?.LogWarning(ex, "Unloading context {Context}: cannot read the hot reload handlers of {Assembly}", unloading.Name, assembly.FullName); continue; } foreach (var handler in handlers) { var clearCache = handler.HandlerType.GetMethod("ClearCache", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static, [typeof(Type[])]); if (clearCache == null) continue; found++; try { clearCache.Invoke(null, [null]); } catch (Exception ex) { _logger?.LogWarning(ex, "Unloading context {Context}: ClearCache of {Handler} failed, the other caches are cleared", unloading.Name, handler.HandlerType.FullName); } } } if (found == 0 && Interlocked.Exchange(ref _noHandlersReported, 1) == 0) _logger?.LogWarning( "Unloading context {Context}: no loaded assembly declares a hot reload cache handler; caches of the .NET " + "libraries (System.Text.Json among them) may keep the context alive", unloading.Name); } /// /// Whether needs : declared in one of its assemblies, or built /// over such a type (RedbObject<ModuleProps>, an array or list of one). /// internal static bool BelongsTo(Type type, AssemblyLoadContext context) { if (type.HasElementType) return BelongsTo(type.GetElementType()!, context); if (AssemblyLoadContext.GetLoadContext(type.Assembly) == context) return true; if (type.IsConstructedGenericType) foreach (var argument in type.GetGenericArguments()) if (BelongsTo(argument, context)) return true; return false; } } Path: redb/redb.Core/Caching/GlobalListCache.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/Caching/GlobalListCache.cs ---- using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; namespace redb.Core.Caching { /// /// Cache entry with TTL. /// internal class ListCacheEntry { public T Value { get; set; } = default!; public DateTime ExpiresAt { get; set; } public bool IsExpired => DateTime.UtcNow > ExpiresAt; } /// /// Domain-isolated cache data for lists. /// internal class ListCacheDomain { public bool Enabled = true; public TimeSpan Ttl = TimeSpan.FromMinutes(5); // Lists cache public readonly ConcurrentDictionary> ListsById = new(); public readonly ConcurrentDictionary> ListsByName = new(); // Items cache public readonly ConcurrentDictionary>> ItemsByListId = new(); public readonly ConcurrentDictionary> ItemsById = new(); public void Clear() { ListsById.Clear(); ListsByName.Clear(); ItemsByListId.Clear(); ItemsById.Clear(); } } /// /// Domain-isolated cache for lists and their items. /// Hybrid model: TTL for eventual consistency + local invalidation on changes. /// Instance is bound to specific domain, static data is shared. /// public sealed class GlobalListCache { private static readonly ConcurrentDictionary _domains = new(); private readonly string _domain; /// /// Domain identifier for this cache instance. /// public string Domain => _domain; /// /// Create cache instance for specific domain. /// public GlobalListCache(string? domain = null, bool? enabled = null) { CollectibleContextCleanup.EnsureWatching(); _domain = domain ?? "default"; var cache = GetCache(); if (enabled.HasValue) cache.Enabled = enabled.Value; } private ListCacheDomain GetCache() => _domains.GetOrAdd(_domain, _ => new ListCacheDomain()); /// /// Drops, in every domain, the cached items whose loaded object is of a type /// answers true for, and the item lists that hold one: the types of a collectible AssemblyLoadContext that /// unloads (). Such an item comes back from the database on next read. /// internal static void RemoveObjectsOfTypes(Func unloading) { bool Holds(RedbListItem item) => item.LoadedObject is { } loaded && unloading(loaded.GetType()); foreach (var domain in _domains.Values) { foreach (var entry in domain.ItemsById) if (Holds(entry.Value.Value)) domain.ItemsById.TryRemove(entry); foreach (var entry in domain.ItemsByListId) if (entry.Value.Value.Any(Holds)) domain.ItemsByListId.TryRemove(entry); } } /// /// Enable or disable cache for this domain. /// public void SetEnabled(bool enabled) { var cache = GetCache(); cache.Enabled = enabled; if (!enabled) cache.Clear(); } /// /// Check if cache is enabled. /// public bool IsEnabled => GetCache().Enabled; /// /// Set TTL for the cache. /// public void SetTtl(TimeSpan ttl) { if (ttl <= TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(ttl), "TTL must be greater than 0"); GetCache().Ttl = ttl; } // ===== LISTS ===== /// /// Get list by ID. /// public RedbList? GetList(long id) { var cache = GetCache(); if (!cache.Enabled) return null; if (cache.ListsById.TryGetValue(id, out var entry)) { if (!entry.IsExpired) return entry.Value; cache.ListsById.TryRemove(id, out _); } return null; } /// /// Get list by name. /// public RedbList? GetListByName(string name) { var cache = GetCache(); if (!cache.Enabled) return null; if (cache.ListsByName.TryGetValue(name, out var entry)) { if (!entry.IsExpired) return entry.Value; cache.ListsByName.TryRemove(name, out _); } return null; } /// /// Cache list. /// public void CacheList(RedbList list) { var cache = GetCache(); if (!cache.Enabled) return; var entry = new ListCacheEntry { Value = list, ExpiresAt = DateTime.UtcNow.Add(cache.Ttl) }; cache.ListsById[list.Id] = entry; cache.ListsByName[list.Name] = entry; } // ===== ITEMS ===== /// /// Get list items by list ID. /// public List? GetListItems(long listId) { var cache = GetCache(); if (!cache.Enabled) return null; if (cache.ItemsByListId.TryGetValue(listId, out var entry)) { if (!entry.IsExpired) return entry.Value; cache.ItemsByListId.TryRemove(listId, out _); } return null; } /// /// Get list item by ID. /// public RedbListItem? GetListItem(long itemId) { var cache = GetCache(); if (!cache.Enabled) return null; if (cache.ItemsById.TryGetValue(itemId, out var entry)) { if (!entry.IsExpired) return entry.Value; cache.ItemsById.TryRemove(itemId, out _); } return null; } /// /// Cache list items. /// public void CacheListItems(long listId, List items) { var cache = GetCache(); if (!cache.Enabled) return; var itemsEntry = new ListCacheEntry> { Value = items, ExpiresAt = DateTime.UtcNow.Add(cache.Ttl) }; cache.ItemsByListId[listId] = itemsEntry; foreach (var item in items) { // Shared by every scope from now on, with the object it may already carry: Object loads on the reader's // scope and, inside the reader's transaction, keeps nothing (owner decision 2026-09-15). Utils.LazyReferenceInstaller.MarkShared(item); item._cacheDomain ??= _domain; var itemEntry = new ListCacheEntry { Value = item, ExpiresAt = DateTime.UtcNow.Add(cache.Ttl) }; cache.ItemsById[item.Id] = itemEntry; } } // ===== INVALIDATION ===== /// /// Invalidate list and its items. /// public void InvalidateList(long listId) { var cache = GetCache(); if (cache.ListsById.TryRemove(listId, out var listEntry)) { cache.ListsByName.TryRemove(listEntry.Value.Name, out _); } InvalidateListItems(listId); } /// /// Invalidate list items. /// public void InvalidateListItems(long listId) { var cache = GetCache(); if (cache.ItemsByListId.TryRemove(listId, out var itemsEntry)) { foreach (var item in itemsEntry.Value) { cache.ItemsById.TryRemove(item.Id, out _); } } } /// /// Invalidate single list item. /// public void InvalidateListItem(long itemId) { GetCache().ItemsById.TryRemove(itemId, out _); } /// /// Clear cache for this domain. /// public void Clear() { GetCache().Clear(); } /// /// Get cache size statistics. /// public (int Lists, int Items) GetCacheSize() { var cache = GetCache(); return (cache.ListsById.Count, cache.ItemsById.Count); } } } Path: redb/redb.Core/Caching/GlobalMetadataCache.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/Caching/GlobalMetadataCache.cs ---- using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using redb.Core.Attributes; using redb.Core.Models.Contracts; using redb.Core.Models.Configuration; using redb.Core.Models.Entities; using redb.Core.Providers; namespace redb.Core.Caching; /// /// Type information for caching (DB types, not CLR types). /// public class RedbTypeInfo { public long Id { get; set; } public string Name { get; set; } = ""; public string? DbType { get; set; } public string? Type1 { get; set; } } /// /// Domain-isolated cache data. /// internal class DomainCache { // Cache enabled flag (per-domain) public bool Enabled = true; // Scheme caching public readonly ConcurrentDictionary SchemeByName = new(); public readonly ConcurrentDictionary SchemeById = new(); // Structure trees built from the cached schemes (whole tree, and the children of a parent structure; null parent = // the root nodes). They live and die with the scheme: every invalidation of a scheme drops its trees, so no caller // can read a scheme again and keep building rows from the tree of its previous version. public readonly ConcurrentDictionary> StructureTrees = new(); public readonly ConcurrentDictionary<(long SchemeId, long? ParentId), List> Subtrees = new(); public void ForgetTrees(long schemeId) { StructureTrees.TryRemove(schemeId, out _); foreach (var key in Subtrees.Keys) if (key.SchemeId == schemeId) Subtrees.TryRemove(key, out _); } // DB Type caching (redb types table) public readonly ConcurrentDictionary TypeCache = new(); public readonly ConcurrentDictionary TypeById = new(); // Per-domain CLR type projection. scheme_id is a per-database fact, so this must stay isolated // per connection/domain. The database-independent schemeName↔Type mapping lives process-globally // in ClrSchemeTypeIndex (one scan serves all domains; self-healing on assembly load). // Both directions hold the type weakly, as ClrSchemeTypeIndex does: the type of a module loaded into a // collectible AssemblyLoadContext must not keep that context alive. A dead entry reads as a miss and is // re-derived lazily; a type of the default context never dies, so its entry behaves as a strong one. public readonly ConcurrentDictionary> SchemeIdToClrType = new(); public readonly ConditionalWeakTable> ClrTypeToSchemeId = new(); public void MapClrType(long schemeId, Type type) { SchemeIdToClrType[schemeId] = new WeakReference(type); ClrTypeToSchemeId.AddOrUpdate(type, new StrongBox(schemeId)); } public bool TryGetClrType(long schemeId, [NotNullWhen(true)] out Type? type) { if (SchemeIdToClrType.TryGetValue(schemeId, out var weak)) { if (weak.TryGetTarget(out type)) return true; SchemeIdToClrType.TryRemove(new KeyValuePair>(schemeId, weak)); } type = null; return false; } public bool ClrTypeRegistryInitialized = false; // per-domain warm-up done (optimization only; resolution is lazy) // Statistics public long SchemeHits; public long SchemeMisses; public long TypeHits; public long TypeMisses; /// /// Clear scheme cache only (does NOT clear CLR Type Registry). /// Use this when disabling cache - system will work slower but correctly. /// public void Clear() { // Clear only scheme/type cache, NOT CLR Type Registry SchemeByName.Clear(); SchemeById.Clear(); StructureTrees.Clear(); Subtrees.Clear(); TypeCache.Clear(); TypeById.Clear(); // DO NOT clear CLR Type Registry - it's required for polymorphic deserialization // SchemeIdToClrType, ClrTypeToSchemeId stay intact (name↔Type lives in ClrSchemeTypeIndex) Interlocked.Exchange(ref SchemeHits, 0); Interlocked.Exchange(ref SchemeMisses, 0); Interlocked.Exchange(ref TypeHits, 0); Interlocked.Exchange(ref TypeMisses, 0); } /// /// Clear everything including CLR Type Registry (full reset). /// Use only for complete reinitialization or testing. /// public void ClearAll() { SchemeByName.Clear(); SchemeById.Clear(); StructureTrees.Clear(); Subtrees.Clear(); TypeCache.Clear(); TypeById.Clear(); SchemeIdToClrType.Clear(); ClrTypeToSchemeId.Clear(); ClrTypeRegistryInitialized = false; Interlocked.Exchange(ref SchemeHits, 0); Interlocked.Exchange(ref SchemeMisses, 0); Interlocked.Exchange(ref TypeHits, 0); Interlocked.Exchange(ref TypeMisses, 0); } public void ResetStatistics() { Interlocked.Exchange(ref SchemeHits, 0); Interlocked.Exchange(ref SchemeMisses, 0); Interlocked.Exchange(ref TypeHits, 0); Interlocked.Exchange(ref TypeMisses, 0); } } /// /// Metadata cache with domain isolation. /// Combines scheme caching and CLR type registry (former AutomaticTypeRegistry). /// Instance is bound to specific domain, static data is shared. /// Each domain (typically one per database connection) has isolated cache. /// public class GlobalMetadataCache { // ===== STATIC: shared data across all instances ===== private static readonly ConcurrentDictionary _domains = new(); private static readonly object _lock = new(); // ===== INSTANCE: domain binding ===== private readonly string _domain; /// /// Cache domain this instance is bound to. /// public string Domain => _domain; /// /// Creates cache instance bound to specific domain. /// public GlobalMetadataCache(string? domain = null) { _domain = domain ?? "default"; } /// /// Creates cache instance with domain from configuration. /// public GlobalMetadataCache(RedbServiceConfiguration configuration) { _domain = configuration?.GetEffectiveCacheDomain() ?? "default"; } private DomainCache GetCache() => _domains.GetOrAdd(_domain, _ => new DomainCache()); // ===== SCHEME CACHING ===== /// /// Get scheme by name from cache. /// public IRedbScheme? GetScheme(string schemeName) { if (!GetCache().Enabled) return null; var cache = GetCache(); if (cache.SchemeByName.TryGetValue(schemeName, out var scheme)) { Interlocked.Increment(ref cache.SchemeHits); return scheme; } Interlocked.Increment(ref cache.SchemeMisses); return null; } /// /// Get scheme by ID from cache. /// public IRedbScheme? GetScheme(long schemeId) { if (!GetCache().Enabled) return null; var cache = GetCache(); if (cache.SchemeById.TryGetValue(schemeId, out var scheme)) { Interlocked.Increment(ref cache.SchemeHits); return scheme; } Interlocked.Increment(ref cache.SchemeMisses); return null; } /// /// Cache scheme. /// public void CacheScheme(IRedbScheme scheme) { if (!GetCache().Enabled || scheme == null) return; var cache = GetCache(); // A scheme put over another version of itself (or over none) takes the place of the one its cached trees were // built from: they go. The same version cached again keeps them. if (!cache.SchemeById.TryGetValue(scheme.Id, out var previous) || previous.StructureHash != scheme.StructureHash) cache.ForgetTrees(scheme.Id); cache.SchemeByName[scheme.Name] = scheme; cache.SchemeById[scheme.Id] = scheme; } /// /// Invalidate scheme by ID, with its structure trees. /// public void InvalidateScheme(long schemeId) { var cache = GetCache(); // The trees go even when the scheme itself is no longer cached: a tree kept past its scheme is the stale // tree a save would build rows from after reading the scheme again. cache.ForgetTrees(schemeId); if (cache.SchemeById.TryGetValue(schemeId, out var scheme)) { cache.SchemeByName.TryRemove(scheme.Name, out _); cache.SchemeById.TryRemove(schemeId, out _); // Drop the per-domain scheme_id→Type projection (it can be lazily re-derived). The global // name↔Type (ClrSchemeTypeIndex) is a code fact and is NOT touched by per-domain invalidation. cache.SchemeIdToClrType.TryRemove(schemeId, out _); } } /// /// Invalidate scheme by name, with its structure trees. /// public void InvalidateScheme(string schemeName) { var cache = GetCache(); if (cache.SchemeByName.TryGetValue(schemeName, out var scheme)) { cache.ForgetTrees(scheme.Id); cache.SchemeByName.TryRemove(schemeName, out _); cache.SchemeById.TryRemove(scheme.Id, out _); // Drop the per-domain scheme_id→Type projection (lazily re-derivable). Global name↔Type // (ClrSchemeTypeIndex) is a code fact and is NOT touched by per-domain invalidation. cache.SchemeIdToClrType.TryRemove(scheme.Id, out _); } } // ===== STRUCTURE TREES ===== /// Cached structure tree of a scheme; null when absent or the cache is disabled. internal List? GetStructureTree(long schemeId) { var cache = GetCache(); return cache.Enabled && cache.StructureTrees.TryGetValue(schemeId, out var tree) ? tree : null; } internal void CacheStructureTree(long schemeId, List tree) { var cache = GetCache(); if (cache.Enabled) cache.StructureTrees.TryAdd(schemeId, tree); } /// Cached children of a parent structure (null parent = the root nodes); null when absent. internal List? GetSubtree(long schemeId, long? parentStructureId) { var cache = GetCache(); return cache.Enabled && cache.Subtrees.TryGetValue((schemeId, parentStructureId), out var subtree) ? subtree : null; } internal void CacheSubtree(long schemeId, long? parentStructureId, List subtree) { var cache = GetCache(); if (cache.Enabled) cache.Subtrees.TryAdd((schemeId, parentStructureId), subtree); } /// Drops the structure trees of a scheme and keeps the scheme. internal void InvalidateStructureTrees(long schemeId) => GetCache().ForgetTrees(schemeId); internal (int Trees, int Subtrees) StructureTreeCounts() { var cache = GetCache(); return (cache.StructureTrees.Count, cache.Subtrees.Count); } // ===== DB TYPE CACHING ===== /// /// Get type ID from cache. /// public long? GetTypeId(string typeName) { if (!GetCache().Enabled) return null; var cache = GetCache(); if (cache.TypeCache.TryGetValue(typeName, out var typeId)) { Interlocked.Increment(ref cache.TypeHits); return typeId; } Interlocked.Increment(ref cache.TypeMisses); return null; } /// /// Cache type ID. /// public void CacheType(string typeName, long typeId) { if (!GetCache().Enabled) return; GetCache().TypeCache[typeName] = typeId; } /// /// Get type info by ID. /// public RedbTypeInfo? GetTypeById(long typeId) { if (!GetCache().Enabled) return null; var cache = GetCache(); if (cache.TypeById.TryGetValue(typeId, out var typeInfo)) { Interlocked.Increment(ref cache.TypeHits); return typeInfo; } Interlocked.Increment(ref cache.TypeMisses); return null; } /// /// Bulk cache types by ID. /// public void CacheTypesById(IEnumerable types) { if (!GetCache().Enabled) return; var cache = GetCache(); foreach (var t in types) { cache.TypeById[t.Id] = t; } } /// /// Check if types by ID cache has data. /// public bool HasTypesByIdCache => !GetCache().TypeById.IsEmpty; /// /// The _types table of this domain by id, once has stored it (every caller /// stores the whole table), or null when nothing is cached or the cache is off. Cleared with the rest of the /// domain cache (). /// public IReadOnlyDictionary? GetTypesById() { var cache = GetCache(); if (!cache.Enabled || cache.TypeById.IsEmpty) return null; return cache.TypeById; } // ===== CLR TYPE REGISTRY (former AutomaticTypeRegistry) ===== /// /// Check if CLR type registry is initialized for this domain. /// public bool IsClrTypeRegistryInitialized => GetCache().ClrTypeRegistryInitialized; /// /// Best-effort warm-up of CLR type resolution for this domain: /// (1) refreshes the process-global schemeName↔Type index (), and /// (2) pre-populates this domain's scheme_id→Type projection for schemes already present in the DB. /// This is an OPTIMIZATION only — it is never a precondition for resolution, which is lazy and /// self-healing (see / ). The /// per-domain warm pass runs once; the global index stays self-healing regardless. /// /// Provider for scheme metadata /// Optional logger for diagnostics public async Task InitializeClrTypeRegistryAsync(ISchemeSyncProvider schemeProvider, ILogger? logger = null) { // Global, database-independent name↔Type layer — cheap no-op when no new assemblies loaded. ClrSchemeTypeIndex.EnsureFresh(); var cache = GetCache(); lock (_lock) { if (cache.ClrTypeRegistryInitialized) return; } // Pre-pop the per-domain scheme_id→Type for types whose scheme already exists in THIS domain's DB. foreach (var type in ClrSchemeTypeIndex.EnumerateSchemeTypes()) { try { var attr = type.GetCustomAttribute(); if (attr == null) continue; var schemeName = attr.GetSchemeName(type); ClrSchemeTypeIndex.Register(schemeName, type); if (!string.IsNullOrEmpty(attr.Alias)) ClrSchemeTypeIndex.Register(attr.Alias!, type); var scheme = await schemeProvider.GetSchemeByNameAsync(schemeName); if (scheme != null) cache.MapClrType(scheme.Id, type); } catch (Exception ex) { logger?.LogDebug(ex, "Skipping type {Type} during CLR registry warm-up", type.FullName); } } lock (_lock) { cache.ClrTypeRegistryInitialized = true; } logger?.LogInformation( "CLR type registry warmed for domain '{Domain}': {NameCount} global names, {SchemeIdCount} scheme_id mappings", _domain, ClrSchemeTypeIndex.Count, cache.SchemeIdToClrType.Count); } /// /// Get C# type by scheme ID (this domain). Fast path is the per-domain cache; on a miss it lazily /// self-heals by deriving the type from this domain's cached scheme name + the global /// , then backfills. Returns null if the scheme is not cached in this /// domain or genuinely has no CLR type. For the cold case (scheme not cached here) use /// , which can load the scheme by id. /// public Type? GetClrType(long schemeId) { var cache = GetCache(); if (cache.TryGetClrType(schemeId, out var type)) return type; // Lazy derive: scheme_id → (this domain's cached scheme name) → (global name↔Type). if (cache.SchemeById.TryGetValue(schemeId, out var scheme)) { var t = ClrSchemeTypeIndex.Resolve(scheme.Name); if (t != null) { cache.MapClrType(schemeId, t); return t; } } return null; } /// /// Get C# type by scheme name — served from the process-global /// (database-independent, self-healing on assembly load). /// public Type? GetClrType(string schemeName) => ClrSchemeTypeIndex.Resolve(schemeName); /// /// Resolve scheme_id → Type with a cold fallback. Tries the sync path first (per-domain cache + /// cached scheme); if the scheme is not cached in this domain, loads it by id and resolves via the /// global index, caching both for next time. Covers the cross-domain case (scheme synced under a /// different connection-hash domain, or created by another cluster node) with no per-call-site logic. /// Returns null only when the scheme genuinely has no CLR type (a legitimately non-generic scheme). /// public async Task ResolveClrTypeAsync(long schemeId, ISchemeSyncProvider schemeProvider) { var type = GetClrType(schemeId); if (type != null || IsSchemeKnown(schemeId)) return type; return RememberClrType(schemeId, await schemeProvider.GetSchemeByIdAsync(schemeId)); } /// /// Synchronous for the thread-pool-free load path: the cold lookup loads the /// scheme through on the calling thread. /// public Type? ResolveClrType(long schemeId, ISchemeSyncProvider schemeProvider) { var type = GetClrType(schemeId); if (type != null || IsSchemeKnown(schemeId)) return type; return RememberClrType(schemeId, schemeProvider.GetSchemeById(schemeId)); } // A scheme this domain holds and the type index does not answer to is a scheme with no CLR type: the index is // asked again on every lookup and heals itself when an assembly loads, so the provider is not asked again. // Asking it loaded the scheme on every read of a list item's object of such a scheme. private bool IsSchemeKnown(long schemeId) => GetCache().SchemeById.ContainsKey(schemeId); // The cold half of both forms: cache the loaded scheme in this domain and map its CLR type. private Type? RememberClrType(long schemeId, IRedbScheme? scheme) { if (scheme == null) return null; CacheScheme(scheme); // populate this domain's scheme cache so future sync lookups hit var type = ClrSchemeTypeIndex.Resolve(scheme.Name); if (type != null) GetCache().MapClrType(schemeId, type); return type; } /// /// Register CLR type mapping authoritatively: the database-independent name↔Type goes to the global /// , the per-database scheme_id↔Type goes to this domain. /// public void RegisterClrType(string schemeName, long schemeId, Type type) { ClrSchemeTypeIndex.Register(schemeName, type); // global (shared across domains/connections) GetCache().MapClrType(schemeId, type); // per-domain (scheme_id is per-database) } /// /// Get scheme_id by C# type. /// public long? GetSchemeIdByClrType(Type type) { return GetCache().ClrTypeToSchemeId.TryGetValue(type, out var schemeId) ? schemeId.Value : null; } /// /// Get CLR type registry statistics. /// public (int SchemeNames, int SchemeIds) GetClrTypeStatistics() { return (ClrSchemeTypeIndex.Count, GetCache().SchemeIdToClrType.Count); } // ===== STATISTICS & DIAGNOSTICS ===== /// /// Get cache statistics for this domain. /// public CacheStatistics GetStatistics() { var cache = GetCache(); return new CacheStatistics { SchemeHits = (int)cache.SchemeHits, SchemeMisses = (int)cache.SchemeMisses, TypeHits = (int)cache.TypeHits, TypeMisses = (int)cache.TypeMisses, StructureHits = 0, StructureMisses = 0 }; } /// /// Clear cache for this domain. /// public void Clear() { lock (_lock) { GetCache().Clear(); } } /// /// Clears this domain's schemes, types and scheme id to CLR type mappings: everything a scheme sync inside a /// transaction that rolled back may have cached from rows that no longer exist. Resolution refills it lazily. /// public void ClearDomainIncludingClrTypes() { lock (_lock) { GetCache().ClearAll(); } } /// /// Get diagnostic information. /// public string GetDiagnosticInfo() { var cache = GetCache(); var stats = GetStatistics(); return $"Domain: {_domain}, " + $"Schemes: {cache.SchemeByName.Count}, " + $"DbTypes: {cache.TypeCache.Count}, " + $"ClrTypes: {cache.SchemeIdToClrType.Count}, " + $"Hit Rate: {stats.OverallHitRatio:P1}, " + $"Total Domains: {_domains.Count}"; } // ===== STATIC METHODS: global operations ===== // ===== INSTANCE METHODS FOR CACHE CONTROL ===== /// /// Is caching enabled for this domain. /// public bool IsEnabled => GetCache().Enabled; /// /// Enable/disable caching for this domain. /// public void SetEnabled(bool enabled) { var cache = GetCache(); cache.Enabled = enabled; if (!enabled) cache.Clear(); } /// /// Initialize cache settings from configuration. /// public void Initialize(RedbServiceConfiguration configuration) { var cache = GetCache(); cache.Enabled = configuration.EnableMetadataCache; if (!cache.Enabled) cache.Clear(); } /// /// Reset statistics for this domain. /// public void ResetStatistics() { GetCache().ResetStatistics(); } // ===== STATIC UTILITY METHODS ===== /// /// Clear all domain caches. /// public static void ClearAll() { lock (_lock) { foreach (var cache in _domains.Values) { cache.Clear(); } _domains.Clear(); } } /// /// Clear cache for specific domain. /// public static void ClearDomain(string domain) { lock (_lock) { if (_domains.TryGetValue(domain, out var cache)) { cache.Clear(); } } } /// /// Get list of all registered domains. /// public static IReadOnlyCollection GetAllDomains() { return _domains.Keys.ToList(); } /// /// Reset statistics for all domains (static utility). /// public static void ResetAllStatistics() { lock (_lock) { foreach (var cache in _domains.Values) { Interlocked.Exchange(ref cache.SchemeHits, 0); Interlocked.Exchange(ref cache.SchemeMisses, 0); Interlocked.Exchange(ref cache.TypeHits, 0); Interlocked.Exchange(ref cache.TypeMisses, 0); } } } } Path: redb/redb.Core/Caching/GlobalPropsCache.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/Caching/GlobalPropsCache.cs ---- using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Reflection; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; namespace redb.Core.Caching { /// /// Domain-isolated cache data for props/objects. /// internal class PropsCacheDomain { public IRedbObjectCache? Cache { get; set; } } /// /// Domain-isolated cache for WHOLE RedbObject (not just Props!). /// Transparent to business code: if disabled (Cache == null), everything goes through DB. /// Instance is bound to specific domain, static data is shared. /// /// /// A cached graph is one instance shared by every scope. It carries nothing scope-bound, since a data object owns no /// connection: its reference stubs hold the scope-free loader of their database and load on the live scope of whoever /// reads them; only marks the graph shared, so a lazy load inside the reader's transaction /// keeps nothing. The detached loader swapped in on hand-out, and the dead-scope /// fallback installed on Set, are gone with the scope-bound loaders they compensated for. /// public sealed class GlobalPropsCache { private static readonly ConcurrentDictionary _domains = new(); private static readonly object _lock = new(); private readonly string _domain; /// /// Domain identifier for this cache instance. /// public string Domain => _domain; /// /// Create cache instance for specific domain. /// public GlobalPropsCache(string? domain = null) { _domain = domain ?? "default"; } private PropsCacheDomain GetCache() => _domains.GetOrAdd(_domain, _ => new PropsCacheDomain()); /// /// Get underlying cache instance for this domain. /// If null - cache is disabled, everything goes through DB. /// public IRedbObjectCache? Instance => GetCache().Cache; /// /// Initialize cache for this domain (called once at application startup per domain). /// public void Initialize(IRedbObjectCache cache) { CollectibleContextCleanup.EnsureWatching(); lock (_lock) { GetCache().Cache = cache; } } /// /// Get WHOLE RedbObject with hash validation. /// public RedbObject? Get(long objectId, Guid hash) where TProps : class, new() => Instance?.Get(objectId, hash); /// /// Get WHOLE RedbObject WITHOUT hash validation (for monolithic applications). /// public RedbObject? GetWithoutHashValidation(long objectId) where TProps : class, new() => Instance?.GetWithoutHashValidation(objectId); /// /// Save WHOLE RedbObject to cache. From here on the graph is shared by every scope. /// public void Set(RedbObject obj) where TProps : class, new() { var cache = Instance; if (cache == null || !obj.hash.HasValue) return; cache.Set(obj); Utils.LazyReferenceInstaller.MarkShared(obj); } /// /// Save WHOLE RedbObject and every loaded object under it. One walk marks the graph shared and collects the /// nested entries, where a Set followed by walked the same Props twice. /// public void SetGraph(RedbObject obj) where TProps : class, new() { var cache = Instance; if (cache == null || !obj.hash.HasValue) return; cache.Set(obj); foreach (var nested in Utils.LazyReferenceInstaller.MarkSharedAndCollect(obj)) { if (ReferenceEquals(nested, obj)) continue; CacheDelegates.Set(cache, nested); } } /// /// Caches every loaded RedbObject found under by its own id, so a nested object is /// served directly by id as well; the entries only (the Set of the root marked the graph shared already). /// Stubs are neither cached nor walked. /// public void SetNested(object props) { var cache = Instance; if (cache == null || props == null) return; CacheNestedObjectsInternal(cache, props, new HashSet(ReferenceEqualityComparer.Instance)); } /// /// Internal method for recursive caching with tracking of visited objects /// private static void CacheNestedObjectsInternal(IRedbObjectCache cache, object obj, HashSet visited) { if (obj == null) return; var objType = obj.GetType(); // CRITICAL: Check TYPE IMMEDIATELY before visited.Add()! // This prevents infinite boxing for value types (DateTime, int, etc.) if (objType.IsPrimitive || objType.IsValueType || objType.Namespace?.StartsWith("System") == true) { return; } // A list item is a leaf: reading its lazy Object property IS a database load, so the // reflective property walk below must never descend into one (stand, 2026-09-09). if (redb.Core.Utils.LazyReferenceInstaller.IsWalkLeaf(obj)) { return; } // Only AFTER type check add to visited (protection against circular references) if (!visited.Add(obj)) { return; } // If this is a RedbObject (or a TreeRedbObject) → cache it var genericObjType = Utils.RedbObjectTypes.GenericOf(objType); if (genericObjType != null) { var redbObj = obj as IRedbObject; // V4 (L.3): a reference stub is neither cached nor walked - reading its Props here // would BE the lazy load: synchronous, and for the whole reachable graph (review). if (redbObj != null && redbObj.Hash.HasValue && obj is RedbObject { IsPropsLoaded: true }) { // The entry only: the Set of the root marked the whole graph shared already, and a nested Set // through GlobalPropsCache walked the subtree again for every nested object (review after 4.0.0). var propsType = genericObjType.GetGenericArguments()[0]; var setMethod = typeof(IRedbObjectCache).GetMethod("Set")?.MakeGenericMethod(propsType); setMethod?.Invoke(cache, new[] { obj }); // Raw Props, never the getter var propsValue = objType.GetMethod("GetPropsDirectly")?.Invoke(obj, null); if (propsValue != null) { CacheNestedObjectsInternal(cache, propsValue, visited); } } return; } // Process arrays if (obj is Array array) { foreach (var item in array) { if (item != null) { CacheNestedObjectsInternal(cache, item, visited); } } return; } // Process collections (IEnumerable, except string) if (obj is System.Collections.IEnumerable enumerable && obj is not string) { foreach (var item in enumerable) { if (item != null) { CacheNestedObjectsInternal(cache, item, visited); } } return; } // Process business class properties (Address, Contact, Details, etc.) var properties = objType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (var prop in properties) { // The save's property set: not an indexer, not [RedbIgnore]. if (!Utils.LazyReferenceInstaller.IsWalkedProperty(prop)) continue; var propValue = prop.GetValue(obj); if (propValue != null) { CacheNestedObjectsInternal(cache, propValue, visited); } } } /// /// BULK: determine which objects need to be loaded from DB (set difference). /// Returns cached WHOLE RedbObject instances. /// public HashSet FilterNeedToLoad( List<(long objectId, Guid hash)> objects, out Dictionary> fromCache) where TProps : class, new() { if (Instance != null) return Instance.FilterNeedToLoad(objects, out fromCache); // Cache is disabled - load everything from DB fromCache = new Dictionary>(); return objects.Select(o => o.objectId).ToHashSet(); } /// /// Remove from cache. /// /// /// Drops, in every domain, the cached objects whose type answers true for: the /// types of a collectible AssemblyLoadContext that unloads (). /// internal static void RemoveObjectsOfTypes(Func unloading) { foreach (var domain in _domains.Values) domain.Cache?.RemoveObjectsOfTypes(unloading); } public void Remove(long objectId) { Instance?.Remove(objectId); } /// /// Clear cache for this domain. /// public void Clear() { Instance?.Clear(); } /// /// Get cache statistics for this domain. /// public PropsCacheStatistics GetStats() { return Instance?.GetStats() ?? new PropsCacheStatistics(); } } } Path: redb/redb.Core/Caching/IRedbObjectCache.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/Caching/IRedbObjectCache.cs ---- using System; using System.Collections.Generic; using redb.Core.Models.Entities; namespace redb.Core.Caching { /// /// Interface for caching WHOLE RedbObject objects (not just Props!) /// Cache key = objectId, Hash is used for validity validation /// Cache entire object with base fields + Props for: /// - 0 DB queries on Cache HIT (without SELECT base fields) /// - Reuse of nested RedbObject through references (memory savings) /// public interface IRedbObjectCache { /// /// Get WHOLE RedbObject from cache by objectId with hash validation /// /// Object ID /// Current object hash for validation /// RedbObject if found and hash matches, otherwise null RedbObject? Get(long objectId, Guid currentHash) where TProps : class, new(); /// /// Get WHOLE RedbObject from cache by objectId WITHOUT hash validation /// Used when SkipHashValidationOnCacheCheck = true (monolithic applications) /// /// Object ID /// RedbObject if found in cache, otherwise null (without actuality check) RedbObject? GetWithoutHashValidation(long objectId) where TProps : class, new(); /// /// Save WHOLE RedbObject to cache /// /// RedbObject for caching (with base fields + Props) void Set(RedbObject obj) where TProps : class, new(); /// /// BULK: determine which objects need to be loaded from DB (set difference) /// Returns cached WHOLE objects (not just Props) /// /// List of (objectId, hash) from DB /// OUT: RedbObject instances taken from cache /// HashSet of objectId that need to be loaded from DB HashSet FilterNeedToLoad( List<(long objectId, Guid hash)> objects, out Dictionary> fromCache) where TProps : class, new(); /// /// Remove object from cache /// /// Object ID void Remove(long objectId); /// /// Clear entire cache /// void Clear(); /// /// Get cache statistics /// PropsCacheStatistics GetStats(); /// /// Removes every cached object whose type answers true for. redb calls it when a /// collectible AssemblyLoadContext unloads (a module of Tsak, for instance), with a predicate that /// recognizes the types of that context: an object of such a type kept here would keep the context alive. /// The default implementation clears the whole cache, which is correct at the price of a cold cache. /// void RemoveObjectsOfTypes(Func unloading) => Clear(); // === LEGACY METHODS (COMMENTED OUT - use Get/Set for full RedbObject) === // /// // /// [LEGACY] Get only Props (for backward compatibility) // /// // [Obsolete("Use Get(objectId, hash) to get full RedbObject instead of only Props")] // TProps? GetProps(long objectId, Guid currentHash) where TProps : class, new(); // /// // /// [LEGACY] Save only Props (for backward compatibility) // /// // [Obsolete("Use Set(redbObject) to save full RedbObject instead of only Props")] // void SetProps(long objectId, Guid hash, TProps props) where TProps : class, new(); } } Path: redb/redb.Core/Caching/MemoryRedbObjectCache.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/Caching/MemoryRedbObjectCache.cs ---- using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading; using Microsoft.Extensions.Logging; using redb.Core.Models.Entities; namespace redb.Core.Caching { /// /// In-memory cache implementation for WHOLE RedbObject (not just Props!). /// Cache key = objectId, Hash is used for automatic invalidation. /// We cache entire object for 0 DB queries on Cache HIT and nested object reuse through references. /// /// /// Production under load (2026-09-15): hit validation - the object hash and the walk of its loaded graph - ran /// under one process-wide lock, and an insert into a full cache sorted every entry under the write lock, so /// readers queued behind each other with their connections open. The lock now guards the dictionary and the /// least-recently-used list only; validation runs outside it, and a full cache evicts a tenth of its limit at once. /// public class MemoryRedbObjectCache : IRedbObjectCache { private readonly object _sync = new(); private readonly Dictionary> _cache = new(); // Most recently used first. private readonly LinkedList _lru = new(); private readonly int _maxSize; private readonly int _evictionBatch; private readonly TimeSpan _ttl; private readonly ILogger? _logger; private long _hitCount; private long _missCount; // Diagnostics: every warning is written at most once per window. private static readonly TimeSpan DiagnosticWindow = TimeSpan.FromSeconds(10); private static readonly TimeSpan SlowValidation = TimeSpan.FromMilliseconds(50); private const int UnservedLookupThreshold = 100; private readonly Utils.RateWindow _evictionRate; private readonly Utils.RateWindow _slowValidationRate = new(DiagnosticWindow, 1); // The served/unserved window is lock-free like RateWindow: a hit ran under a second process-wide lock for // this bookkeeping alone. A race at a window boundary may lose a few counts; it is diagnostics. private long _servedWindowStartMs = Environment.TickCount64; private int _servedWindowLookups; private int _servedWindowHits; private int _servedWindowWarned; /// /// Constructor. /// /// Maximum number of objects in cache; a full cache evicts the least recently used tenth /// Cache entry time-to-live, counted from the last Set of the object /// Logger for the cache warnings: working set above the limit, slow hit validation, entries never served public MemoryRedbObjectCache(int maxSize = 10000, TimeSpan? ttl = null, ILogger? logger = null) { if (maxSize <= 0) throw new ArgumentOutOfRangeException(nameof(maxSize), "Must be greater than 0"); _maxSize = maxSize; _evictionBatch = Math.Max(1, maxSize / 10); _ttl = ttl ?? TimeSpan.FromMinutes(30); _logger = logger; // A fifth of the limit evicted within one window: the objects in use do not fit the cache. _evictionRate = new Utils.RateWindow(DiagnosticWindow, Math.Max(1, maxSize / 5)); } /// /// Get WHOLE RedbObject from cache with hash validation. /// public RedbObject? Get(long objectId, Guid currentHash) where TProps : class, new() => GetValidated(objectId, currentHash); /// /// Get WHOLE RedbObject from cache WITHOUT hash validation. /// Used for monolithic applications (SkipHashValidationOnCacheCheck = true). /// public RedbObject? GetWithoutHashValidation(long objectId) where TProps : class, new() => GetValidated(objectId, null); private RedbObject? GetValidated(long objectId, Guid? currentHash) where TProps : class, new() { Candidate candidate; bool found; lock (_sync) found = FindCurrentLocked(objectId, currentHash, out candidate); var served = found ? Validate(candidate) : null; Interlocked.Increment(ref served != null ? ref _hitCount : ref _missCount); return served; } /// /// Save WHOLE RedbObject to cache. /// public void Set(RedbObject obj) where TProps : class, new() { if (!obj.hash.HasValue) return; // Cannot cache without hash var evicted = 0; lock (_sync) { var now = DateTime.UtcNow; if (_cache.TryGetValue(obj.id, out var node)) { // A re-Set brings the object's current state and starts a new lifetime. Keeping the first // CreatedAt made an object that a periodic job re-caches on every pass miss for ever once // one TTL had passed. node.Value.Hash = obj.hash.Value; node.Value.RedbObject = obj; node.Value.CreatedAt = now; MoveToFrontLocked(node); return; } if (_cache.Count >= _maxSize) evicted = EvictLeastRecentlyUsedLocked(_evictionBatch); var entry = new CacheEntry { ObjectId = obj.id, Hash = obj.hash.Value, RedbObject = obj, CreatedAt = now }; _cache[obj.id] = _lru.AddFirst(entry); } if (evicted > 0) ReportEvictions(evicted); } /// /// BULK: determine which objects need to be loaded from DB. /// Returns cached WHOLE RedbObject instances. /// public HashSet FilterNeedToLoad( List<(long objectId, Guid hash)> objects, out Dictionary> fromCache) where TProps : class, new() { var needToLoad = new HashSet(); var candidates = new List(objects.Count); lock (_sync) { foreach (var (objectId, hash) in objects) { if (FindCurrentLocked(objectId, hash, out var candidate)) candidates.Add(candidate); else { needToLoad.Add(objectId); Interlocked.Increment(ref _missCount); } } } // Validated outside the lock, the same way as a single hit. fromCache = new Dictionary>(); foreach (var candidate in candidates) { var served = Validate(candidate); if (served != null) { fromCache[candidate.ObjectId] = served; Interlocked.Increment(ref _hitCount); } else { needToLoad.Add(candidate.ObjectId); Interlocked.Increment(ref _missCount); } } return needToLoad; } public void Remove(long objectId) { lock (_sync) { if (_cache.TryGetValue(objectId, out var node)) RemoveLocked(node); } } /// public void RemoveObjectsOfTypes(Func unloading) { lock (_sync) { var node = _lru.First; while (node != null) { var next = node.Next; if (unloading(node.Value.RedbObject.GetType())) RemoveLocked(node); node = next; } } } public void Clear() { lock (_sync) { _cache.Clear(); _lru.Clear(); } Interlocked.Exchange(ref _hitCount, 0); Interlocked.Exchange(ref _missCount, 0); } public PropsCacheStatistics GetStats() { int entries; lock (_sync) entries = _cache.Count; return new PropsCacheStatistics { TotalEntries = entries, HitCount = Interlocked.Read(ref _hitCount), MissCount = Interlocked.Read(ref _missCount) }; } /// /// The entry of if it is alive and, when is given, /// stored under that hash. An expired entry is dropped. Caller holds . /// private bool FindCurrentLocked(long objectId, Guid? currentHash, out Candidate candidate) { candidate = default; if (!_cache.TryGetValue(objectId, out var node)) return false; var entry = node.Value; if (DateTime.UtcNow - entry.CreatedAt > _ttl) { RemoveLocked(node); // Expired by time - free the slot return false; } // Hash check (against the DB hash the caller passed in) → a changed hash means outdated data. if (currentHash.HasValue && entry.Hash != currentHash.Value) return false; candidate = new Candidate(objectId, entry.RedbObject, entry.Hash); return true; } /// /// Checks a found entry against the live object, outside the cache lock: the object hash and the walk of /// the loaded graph read every stored property and must not hold other readers back. /// private RedbObject? Validate(Candidate candidate) where TProps : class, new() { // Same objectId, different TProps: the caller reloads instead of getting a mistyped object. if (candidate.RedbObject is not RedbObject typed) return null; // Never wake a stub: validating an unloaded instance would be a lazy load inside the cache probe - and a // deadlock with the load that probes. Nothing was stored for it to serve. if (!typed.IsPropsLoaded) return null; var started = Stopwatch.GetTimestamp(); // Dirty-snapshot check. The cache holds a REFERENCE to a shared object. If it was mutated // in place after Set (e.g. OpenIddict's SetStatus BEFORE Save), the stored hash is stale — it // reflects the state at Set, not the current Props. Recompute the live hash; if it drifted, // the cached object no longer matches its stored hash → MISS, so the caller reloads the // committed state from the DB instead of getting a stale ("already redeemed") snapshot. // V4 (review): the root's hash is id:hash of its references - an unsaved edit INSIDE // a loaded nested object does not move it. Ask the loaded part of the graph as well; // stubs are neither touched nor woken (raw Props access only). var served = typed.ComputeHash() == candidate.Hash && !Utils.LoadedGraphInspector.HasDirtyLoadedReference(typed.GetPropsDirectly()); ReportValidation(candidate.ObjectId, Stopwatch.GetElapsedTime(started), served); if (!served) return null; lock (_sync) { if (_cache.TryGetValue(candidate.ObjectId, out var node)) MoveToFrontLocked(node); } return typed; } private void MoveToFrontLocked(LinkedListNode node) { if (ReferenceEquals(_lru.First, node)) return; _lru.Remove(node); _lru.AddFirst(node); } private void RemoveLocked(LinkedListNode node) { _lru.Remove(node); _cache.Remove(node.Value.ObjectId); } private int EvictLeastRecentlyUsedLocked(int count) { var evicted = 0; while (evicted < count && _lru.Last is { } last) { RemoveLocked(last); evicted++; } return evicted; } private void ReportEvictions(int evicted) { var inWindow = _evictionRate.Add(evicted); if (inWindow > 0) _logger?.LogWarning( "Props cache is full: {Evicted} least recently used objects evicted within {Seconds}s " + "(PropsCacheMaxSize = {MaxSize}). The objects in use do not fit the cache, so loads keep missing " + "and caching them again; raise PropsCacheMaxSize above the working set.", inWindow, (int)DiagnosticWindow.TotalSeconds, _maxSize); } private void ReportValidation(long objectId, TimeSpan elapsed, bool served) { if (elapsed >= SlowValidation && _slowValidationRate.Add() > 0) _logger?.LogWarning( "Props cache hit validation of object {ObjectId} took {ElapsedMs} ms: the object hash and the check " + "of its loaded graph for unsaved edits read every stored property, so a getter that does work " + "(a lazy load, I/O) makes each cache hit of such an object that slow.", objectId, (long)elapsed.TotalMilliseconds); var now = Environment.TickCount64; var start = Interlocked.Read(ref _servedWindowStartMs); if (now - start > (long)DiagnosticWindow.TotalMilliseconds && Interlocked.CompareExchange(ref _servedWindowStartMs, now, start) == start) { Interlocked.Exchange(ref _servedWindowLookups, 0); Interlocked.Exchange(ref _servedWindowHits, 0); Interlocked.Exchange(ref _servedWindowWarned, 0); } var lookups = Interlocked.Increment(ref _servedWindowLookups); if (served) Interlocked.Increment(ref _servedWindowHits); var unserved = 0; if (lookups >= UnservedLookupThreshold && Volatile.Read(ref _servedWindowHits) == 0 && Interlocked.CompareExchange(ref _servedWindowWarned, 1, 0) == 0) unserved = lookups; if (unserved > 0) _logger?.LogWarning( "Props cache: {Lookups} lookups within {Seconds}s found a live cached entry and served none - the " + "cached objects no longer hash to what was stored. Typical causes: a read model that does not " + "reproduce the saved graph (a narrower class, a renamed or added property), or objects changed in " + "place after loading. The cache holds memory and gives no hits here.", unserved, (int)DiagnosticWindow.TotalSeconds); } private readonly struct Candidate { public Candidate(long objectId, object redbObject, Guid hash) { ObjectId = objectId; RedbObject = redbObject; Hash = hash; } public long ObjectId { get; } public object RedbObject { get; } public Guid Hash { get; } } /// /// Cache entry - stores WHOLE RedbObject. /// private sealed class CacheEntry { public long ObjectId { get; init; } public Guid Hash { get; set; } public object RedbObject { get; set; } = null!; public DateTime CreatedAt { get; set; } } } } Path: redb/redb.Core/Caching/PropsCacheStatistics.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/Caching/PropsCacheStatistics.cs ---- namespace redb.Core.Caching { /// /// Props object cache statistics. /// public class PropsCacheStatistics { /// /// Total cache entries. /// public int TotalEntries { get; set; } /// /// Cache hit count. /// public long HitCount { get; set; } /// /// Cache miss count. /// public long MissCount { get; set; } /// /// Cache hit rate (0.0 - 1.0). /// public double HitRate => HitCount + MissCount > 0 ? HitCount / (double)(HitCount + MissCount) : 0; } } Path: redb/redb.Core/Configuration/ConfigurationExtensions.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/Configuration/ConfigurationExtensions.cs ---- #pragma warning disable CS0618 // implements or uses the deprecated object permissions and roles (RedbDeprecation) using System; using System.Text.Json; using Microsoft.Extensions.Configuration; using redb.Core.Models.Configuration; namespace redb.Core.Configuration { /// /// Extension methods for integrating RedbServiceConfiguration with IConfiguration /// public static class ConfigurationExtensions { /// /// Get RedbService configuration from IConfiguration /// /// Application configuration /// Configuration section name (default "RedbService") /// Configured RedbService configuration public static RedbServiceConfiguration GetRedbServiceConfiguration( this IConfiguration configuration, string sectionName = "RedbService") { var section = configuration.GetSection(sectionName); if (!section.Exists()) { // If section doesn't exist, return default configuration return new RedbServiceConfiguration(); } // Profile support var profileName = section["Profile"]; var baseConfig = GetBaseConfigurationFromProfile(profileName); // Apply main settings from configuration ApplyConfigurationSettings(section, baseConfig); // Apply overrides var overridesSection = section.GetSection("Overrides"); if (overridesSection.Exists()) { ApplyConfigurationSettings(overridesSection, baseConfig); } return baseConfig; } /// /// Get RedbService configuration with validation /// /// Application configuration /// Configuration section name /// Throw exception on validation errors /// Validated RedbService configuration public static RedbServiceConfiguration GetValidatedRedbServiceConfiguration( this IConfiguration configuration, string sectionName = "RedbService", bool throwOnValidationError = true) { var config = configuration.GetRedbServiceConfiguration(sectionName); var validationResult = ConfigurationValidator.Validate(config); if (!validationResult.IsValid) { if (throwOnValidationError) { var errors = string.Join(Environment.NewLine, validationResult.GetAllMessages()); throw new InvalidOperationException($"Invalid RedbService configuration:{Environment.NewLine}{errors}"); } // Automatic fixing of critical errors config = ConfigurationValidator.FixCriticalErrors(config); } return config; } /// /// Check if RedbService configuration section exists /// /// Application configuration /// Configuration section name /// true if section exists public static bool HasRedbServiceConfiguration( this IConfiguration configuration, string sectionName = "RedbService") { return configuration.GetSection(sectionName).Exists(); } /// /// Get configuration description from IConfiguration /// /// Application configuration /// Configuration section name /// Configuration description public static string GetRedbServiceConfigurationDescription( this IConfiguration configuration, string sectionName = "RedbService") { var config = configuration.GetRedbServiceConfiguration(sectionName); return config.GetDescription(); } /// /// Create builder based on configuration from IConfiguration /// /// Application configuration /// Configuration section name /// Builder for further configuration public static RedbServiceConfigurationBuilder CreateRedbServiceBuilder( this IConfiguration configuration, string sectionName = "RedbService") { var baseConfig = configuration.GetRedbServiceConfiguration(sectionName); return new RedbServiceConfigurationBuilder(baseConfig); } // === PRIVATE METHODS === /// /// Get base configuration from profile /// private static RedbServiceConfiguration GetBaseConfigurationFromProfile(string? profileName) { if (string.IsNullOrEmpty(profileName)) { return new RedbServiceConfiguration(); } try { return PredefinedConfigurations.GetByName(profileName); } catch (ArgumentException) { // If profile not found, use default configuration return new RedbServiceConfiguration(); } } /// /// Apply settings from configuration section /// private static void ApplyConfigurationSettings(IConfigurationSection section, RedbServiceConfiguration config) { // Object deletion settings if (section["IdResetStrategy"] != null) { if (Enum.TryParse(section["IdResetStrategy"], true, out var idResetStrategy)) { config.IdResetStrategy = idResetStrategy; } } if (section["MissingObjectStrategy"] != null) { if (Enum.TryParse(section["MissingObjectStrategy"], true, out var missingObjectStrategy)) { config.MissingObjectStrategy = missingObjectStrategy; } } // Security settings if (section["DefaultCheckPermissionsOnLoad"] != null) { config.DefaultCheckPermissionsOnLoad = section.GetValue("DefaultCheckPermissionsOnLoad"); } if (section["DefaultCheckPermissionsOnSave"] != null) { config.DefaultCheckPermissionsOnSave = section.GetValue("DefaultCheckPermissionsOnSave"); } if (section["DefaultCheckPermissionsOnDelete"] != null) { config.DefaultCheckPermissionsOnDelete = section.GetValue("DefaultCheckPermissionsOnDelete"); } // Schema settings if (section["DefaultStrictDeleteExtra"] != null) { config.DefaultStrictDeleteExtra = section.GetValue("DefaultStrictDeleteExtra"); } if (section["AutoSyncSchemesOnSave"] != null) { config.AutoSyncSchemesOnSave = section.GetValue("AutoSyncSchemesOnSave"); } // Loading settings if (section["DefaultLoadDepth"] != null) { config.DefaultLoadDepth = section.GetValue("DefaultLoadDepth"); } if (section["DefaultMaxTreeDepth"] != null) { config.DefaultMaxTreeDepth = section.GetValue("DefaultMaxTreeDepth"); } // Performance settings if (section["EnableMetadataCache"] != null) { config.EnableMetadataCache = section.GetValue("EnableMetadataCache"); } if (section["MetadataCacheLifetimeMinutes"] != null) { config.MetadataCacheLifetimeMinutes = section.GetValue("MetadataCacheLifetimeMinutes"); } // Validation settings if (section["EnableSchemaValidation"] != null) { config.EnableSchemaValidation = section.GetValue("EnableSchemaValidation"); } if (section["EnableDataValidation"] != null) { config.EnableDataValidation = section.GetValue("EnableDataValidation"); } // Audit settings if (section["AutoSetModifyDate"] != null) { config.AutoSetModifyDate = section.GetValue("AutoSetModifyDate"); } if (section["AutoRecomputeHash"] != null) { config.AutoRecomputeHash = section.GetValue("AutoRecomputeHash"); } // Security context settings if (section["DefaultSecurityPriority"] != null) { // DefaultSecurityPriority removed - simple GetEffectiveUser() logic is used } if (section["SystemUserId"] != null) { config.SystemUserId = section.GetValue("SystemUserId"); } // JSON settings var jsonSection = section.GetSection("JsonOptions"); if (jsonSection.Exists()) { if (jsonSection["WriteIndented"] != null) { config.JsonOptions.WriteIndented = jsonSection.GetValue("WriteIndented"); } if (jsonSection["UseUnsafeRelaxedJsonEscaping"] != null) { config.JsonOptions.UseUnsafeRelaxedJsonEscaping = jsonSection.GetValue("UseUnsafeRelaxedJsonEscaping"); } } } } } Path: redb/redb.Core/Configuration/DefaultUserConfigurationInitializer.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/Configuration/DefaultUserConfigurationInitializer.cs ---- using System; using System.Threading.Tasks; using redb.Core.Models.Configuration; using redb.Core.Models.Entities; namespace redb.Core.Configuration { /// /// Default user configuration initializer. /// Creates basic configuration with reasonable values on first run. /// public class DefaultUserConfigurationInitializer { /// /// Fixed ID for default user configuration. /// public const long DefaultConfigId = -100; private readonly IRedbService _redbService; public DefaultUserConfigurationInitializer(IRedbService redbService) { _redbService = redbService ?? throw new ArgumentNullException(nameof(redbService)); } /// /// Initialize default configuration for users. /// Creates object with ID=-100 if it doesn't exist. /// public async Task InitializeAsync() { // Check if already exists var existing = await _redbService.LoadAsync(DefaultConfigId); if (existing != null) return; // Create default configuration with fixed ID var defaultConfig = new RedbObject { Id = DefaultConfigId, name = "Default User Config", Props = new UserConfigurationProps { // Cache quotas (smaller than system) ListCacheSize = 500, PropsCacheTtlMinutes = 30, ListCacheTtlMinutes = 5, // Loading limits (smaller than system) MaxLoadDepth = 10, MaxTreeDepth = 50, // Security (more checks for regular users) AlwaysCheckPermissionsOnLoad = false, AlwaysCheckPermissionsOnSave = false, // API quotas MaxRequestsPerMinute = 100, MaxBatchSize = 100, // Strategy (simpler for regular users) PropsSaveStrategy = PropsSaveStrategy.DeleteInsert, // Metadata Description = "Default configuration for regular users. " + "Applied if user or their roles don't have personal configuration.", Priority = 0 } }; await _redbService.SaveAsync(defaultConfig); } } } Path: redb/redb.Core/Configuration/IUserConfigurationService.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/Configuration/IUserConfigurationService.cs ---- using System.Threading.Tasks; using redb.Core.Models.Configuration; using redb.Core.Models.Entities; namespace redb.Core.Configuration { /// /// Service for managing user configurations /// Provides merging of configurations from the chain: /// RedbServiceConfiguration -> Default User Config -> Role Config -> User Config /// public interface IUserConfigurationService { /// /// Get effective user configuration /// (taking into account the entire inheritance chain and overrides) /// /// User ID /// Effective configuration with resolved values Task GetEffectiveConfigurationAsync(long userId); /// /// Get default configuration for regular users /// (not for sys, but for new users) /// /// RedbObject with default configuration or null if not created Task?> GetDefaultConfigurationAsync(); /// /// Set configuration for user /// /// User ID /// Configuration object ID (RedbObject<UserConfigurationProps>) or null to reset Task SetUserConfigurationAsync(long userId, long? configId); /// /// Set configuration for role /// /// Role ID /// Configuration object ID (RedbObject<UserConfigurationProps>) or null to reset Task SetRoleConfigurationAsync(long roleId, long? configId); /// /// Create new configuration /// /// Configuration name (e.g., "VIP Config") /// Configuration properties /// Configuration description (optional) /// Created configuration RedbObject Task> CreateConfigurationAsync( string name, UserConfigurationProps props, string? description = null); /// /// Invalidate user configuration cache /// Called after changing user configuration or their roles /// /// User ID void InvalidateCache(long userId); /// /// Clear entire configuration cache /// Called after global changes /// void ClearCache(); } } Path: redb/redb.Core/Configuration/JsonConverters.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/Configuration/JsonConverters.cs ---- using System; using System.Text.Json; using System.Text.Json.Serialization; using redb.Core.Models.Configuration; namespace redb.Core.Configuration { /// /// JsonConverter for ObjectIdResetStrategy /// public class ObjectIdResetStrategyJsonConverter : JsonConverter { public override ObjectIdResetStrategy Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { var value = reader.GetString(); return value?.ToLowerInvariant() switch { "manual" => ObjectIdResetStrategy.Manual, "autoresetondelete" => ObjectIdResetStrategy.AutoResetOnDelete, "autocreatenewonsave" => ObjectIdResetStrategy.AutoCreateNewOnSave, _ => throw new JsonException($"Unknown ObjectIdResetStrategy value: {value}") }; } public override void Write(Utf8JsonWriter writer, ObjectIdResetStrategy value, JsonSerializerOptions options) { var stringValue = value switch { ObjectIdResetStrategy.Manual => "Manual", ObjectIdResetStrategy.AutoResetOnDelete => "AutoResetOnDelete", ObjectIdResetStrategy.AutoCreateNewOnSave => "AutoCreateNewOnSave", _ => throw new JsonException($"Unknown ObjectIdResetStrategy value: {value}") }; writer.WriteStringValue(stringValue); } } /// /// JsonConverter for MissingObjectStrategy /// public class MissingObjectStrategyJsonConverter : JsonConverter { public override MissingObjectStrategy Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { var value = reader.GetString(); return value?.ToLowerInvariant() switch { "throwexception" => MissingObjectStrategy.ThrowException, "autoswitchtoinsert" => MissingObjectStrategy.AutoSwitchToInsert, "returnnull" => MissingObjectStrategy.ReturnNull, _ => throw new JsonException($"Unknown MissingObjectStrategy value: {value}") }; } public override void Write(Utf8JsonWriter writer, MissingObjectStrategy value, JsonSerializerOptions options) { var stringValue = value switch { MissingObjectStrategy.ThrowException => "ThrowException", MissingObjectStrategy.AutoSwitchToInsert => "AutoSwitchToInsert", MissingObjectStrategy.ReturnNull => "ReturnNull", _ => throw new JsonException($"Unknown MissingObjectStrategy value: {value}") }; writer.WriteStringValue(stringValue); } } /// /// JsonConverter for PropsSaveStrategy /// public class PropsSaveStrategyJsonConverter : JsonConverter { public override PropsSaveStrategy Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { var value = reader.GetString(); return value?.ToLowerInvariant() switch { "deleteinsert" => PropsSaveStrategy.DeleteInsert, "changetracking" => PropsSaveStrategy.ChangeTracking, _ => throw new JsonException($"Unknown PropsSaveStrategy value: {value}") }; } public override void Write(Utf8JsonWriter writer, PropsSaveStrategy value, JsonSerializerOptions options) { var stringValue = value switch { PropsSaveStrategy.DeleteInsert => "DeleteInsert", PropsSaveStrategy.ChangeTracking => "ChangeTracking", _ => throw new JsonException($"Unknown PropsSaveStrategy value: {value}") }; writer.WriteStringValue(stringValue); } } // SecurityContextPriorityJsonConverter removed - priorities are no longer used /// /// JsonSerializer settings for RedbService configuration /// public static class RedbConfigurationJsonOptions { /// /// Get JsonSerializer settings with all converters support /// public static JsonSerializerOptions GetJsonSerializerOptions() { var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true, PropertyNamingPolicy = JsonNamingPolicy.CamelCase, WriteIndented = true, AllowTrailingCommas = true, ReadCommentHandling = JsonCommentHandling.Skip }; // Add converters for enums options.Converters.Add(new ObjectIdResetStrategyJsonConverter()); options.Converters.Add(new MissingObjectStrategyJsonConverter()); options.Converters.Add(new PropsSaveStrategyJsonConverter()); // options.Converters.Add(new SecurityContextPriorityJsonConverter()); // Removed options.Converters.Add(new JsonStringEnumConverter(JsonNamingPolicy.CamelCase)); return options; } } } Path: redb/redb.Core/Configuration/README.md 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/Configuration/README.md ---- # 🔧 RedbService Configuration via IConfiguration Complete integration of the RedbService configuration system with Microsoft.Extensions.Configuration to support `appsettings.json`, environment variables, and other configuration sources. ## 🚀 Quick Start ### 1. Basic setup in Program.cs ```csharp var builder = WebApplication.CreateBuilder(args); // Automatic loading from appsettings.json builder.Services.AddRedbServiceConfiguration(builder.Configuration); var app = builder.Build(); ``` ### 2. Basic appsettings.json ```json { "RedbService": { "DefaultCheckPermissionsOnLoad": false, "DefaultCheckPermissionsOnSave": false, "DefaultCheckPermissionsOnDelete": true, "DefaultLoadDepth": 10, "EnableSchemaMetadataCache": true } } ``` ## 📋 Configuration Methods ### 1. Using predefined profiles ```json { "RedbService": { "Profile": "Development", "Overrides": { "DefaultLoadDepth": 15, "EnableSchemaMetadataCache": false } } } ``` **Available profiles:** - `Development` - for development - `Production` - for production - `HighPerformance` - for high performance - `BulkOperations` - for bulk operations - `Debug` - for debugging - `IntegrationTesting` - for integration testing - `DataMigration` - for data migration ### 2. Full configuration ```json { "RedbService": { "IdResetStrategy": "AutoCreateNewOnSave", "MissingObjectStrategy": "AutoSwitchToInsert", "DefaultCheckPermissionsOnLoad": false, "DefaultCheckPermissionsOnSave": false, "DefaultCheckPermissionsOnDelete": true, "DefaultLoadDepth": 10, "DefaultMaxTreeDepth": 50, "EnableSchemaMetadataCache": true, "SchemaMetadataCacheLifetimeMinutes": 30, "EnableSchemaValidation": true, "EnableDataValidation": true, "AutoSetModifyDate": true, "AutoRecomputeHash": true, "DefaultSecurityPriority": "Context", "SystemUserId": 0, "JsonOptions": { "WriteIndented": false, "UseUnsafeRelaxedJsonEscaping": true } } } ``` ### 3. Environment variables ```bash # Override via environment variables REDBSERVICE__DEFAULTCHECKPERMISSIONSONLOAD=true REDBSERVICE__DEFAULTLOADDEPTH=5 REDBSERVICE__ENABLESCHEMAMETADATACACHE=false REDBSERVICE__JSONOPTIONS__WRITEINDENTED=true ``` ## 🛠️ Registration methods in DI ### 1. Basic registration ```csharp // Load from appsettings.json services.AddRedbServiceConfiguration(configuration); // With validation services.AddValidatedRedbServiceConfiguration(configuration); ``` ### 2. Combined setup ```csharp // appsettings.json + programmatic setup services.AddRedbServiceConfiguration(configuration, builder => { builder.WithLoadDepth(5) .WithStrictSecurity(); }); ``` ### 3. Predefined profiles ```csharp // Using a profile services.AddRedbServiceConfiguration("Production"); // Profile + additional setup services.AddRedbServiceConfiguration("Development", builder => { builder.WithoutCache() .WithPrettyJson(); }); ``` ### 4. Programmatic configuration ```csharp // Via builder only services.AddRedbServiceConfiguration(builder => { builder.ForProduction() .WithLoadDepth(3) .WithMetadataCache(enabled: true, lifetimeMinutes: 120); }); ``` ### 5. Change monitoring ```csharp // Hot-reload configuration services.AddRedbServiceConfigurationMonitoring(configuration); // Usage in a service public class MyService { private readonly IRedbServiceConfigurationMonitor _configMonitor; public MyService(IRedbServiceConfigurationMonitor configMonitor) { _configMonitor = configMonitor; _configMonitor.ConfigurationChanged += OnConfigChanged; } private void OnConfigChanged(RedbServiceConfiguration newConfig) { // React to configuration changes } } ``` ## 🔍 Configuration validation ### 1. Automatic validation ```csharp // Validation during registration services.AddValidatedRedbServiceConfiguration(configuration, throwOnValidationError: true); ``` ### 2. Validation for specific scenarios ```csharp // Validation for production services.AddSingleton>( new ScenarioBasedConfigurationValidator(ConfigurationScenario.Production)); ``` ### 3. Validation with auto-fix ```csharp // Automatic correction of critical errors services.AddSingleton>( new RedbServiceConfigurationValidatorWithAutoFix(autoFixCriticalErrors: true)); ``` ## 🌍 Configuration for different environments ### appsettings.json (base) ```json { "RedbService": { "Profile": "Development" } } ``` ### appsettings.Production.json ```json { "RedbService": { "Profile": "Production", "Overrides": { "DefaultLoadDepth": 3, "SchemaMetadataCacheLifetimeMinutes": 120 } } } ``` ### appsettings.Development.json ```json { "RedbService": { "Profile": "Development", "Overrides": { "EnableSchemaMetadataCache": false, "JsonOptions": { "WriteIndented": true } } } } ``` ## 📊 Usage in code ### 1. Via IOptions ```csharp public class MyService { private readonly RedbServiceConfiguration _config; public MyService(IOptions options) { _config = options.Value; } } ``` ### 2. Via IOptionsMonitor (with hot-reload) ```csharp public class MyService { private readonly IOptionsMonitor _configMonitor; public MyService(IOptionsMonitor configMonitor) { _configMonitor = configMonitor; } public void DoSomething() { var currentConfig = _configMonitor.CurrentValue; // Use current configuration } } ``` ### 3. Direct injection ```csharp public class MyService { private readonly RedbServiceConfiguration _config; public MyService(RedbServiceConfiguration config) { _config = config; } } ``` ## ⚙️ Configuration settings ### Object processing strategies | Parameter | Values | Description | |----------|----------|----------| | `IdResetStrategy` | `Manual`, `AutoResetOnDelete`, `AutoCreateNewOnSave` | ID reset strategy after deletion | | `MissingObjectStrategy` | `ThrowException`, `AutoSwitchToInsert`, `ReturnNull` | Handling non-existent objects | ### Security settings | Parameter | Type | Description | |----------|-----|----------| | `DefaultCheckPermissionsOnLoad` | `bool` | Check permissions on load | | `DefaultCheckPermissionsOnSave` | `bool` | Check permissions on save | | `DefaultCheckPermissionsOnDelete` | `bool` | Check permissions on delete | | `DefaultSecurityPriority` | `System`, `Explicit`, `Context` | Security context priority | | `SystemUserId` | `long` | System user ID | ### Performance settings | Parameter | Type | Description | |----------|-----|----------| | `DefaultLoadDepth` | `int` | Object loading depth | | `DefaultMaxTreeDepth` | `int` | Maximum tree depth | | `EnableSchemaMetadataCache` | `bool` | Enable metadata caching | | `SchemaMetadataCacheLifetimeMinutes` | `int` | Cache lifetime in minutes | ### Validation settings | Parameter | Type | Description | |----------|-----|----------| | `EnableSchemaValidation` | `bool` | Schema validation | | `EnableDataValidation` | `bool` | Data validation | ### JSON settings | Parameter | Type | Description | |----------|-----|----------| | `JsonOptions.WriteIndented` | `bool` | Formatted JSON | | `JsonOptions.UseUnsafeRelaxedJsonEscaping` | `bool` | Simplified JSON escaping | ## 🎯 Examples for different scenarios See the `appsettings.examples.json` file for detailed configuration examples for various usage scenarios. ## 🚨 Solving the deleted objects problem ```json { "RedbService": { "IdResetStrategy": "AutoResetOnDelete", "MissingObjectStrategy": "AutoSwitchToInsert" } } ``` This configuration automatically solves the problem when attempting to resave an object after it has been deleted from the database causes an error. ## 🔧 Debugging configuration ```csharp // Get description of current configuration var description = configuration.GetRedbServiceConfigurationDescription(); Console.WriteLine($"RedbService configuration: {description}"); // Check validity var config = configuration.GetRedbServiceConfiguration(); var validation = ConfigurationValidator.Validate(config); if (!validation.IsValid) { foreach (var message in validation.GetAllMessages()) { Console.WriteLine(message); } } ``` Integration with `IConfiguration` makes RedbService much more flexible and convenient for enterprise use! 🚀 Path: redb/redb.Core/Configuration/RedbServiceConfigurationValidator.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/Configuration/RedbServiceConfigurationValidator.cs ---- #pragma warning disable CS0618 // implements or uses the deprecated object permissions and roles (RedbDeprecation) using System; using System.Linq; using Microsoft.Extensions.Options; using redb.Core.Models.Configuration; namespace redb.Core.Configuration { /// /// RedbService configuration validator for integration with Options pattern /// public class RedbServiceConfigurationValidator : IValidateOptions { /// /// Validate configuration /// /// Configuration name (usually null for default) /// Configuration to validate /// Validation result public ValidateOptionsResult Validate(string? name, RedbServiceConfiguration options) { if (options == null) { return ValidateOptionsResult.Fail("RedbServiceConfiguration cannot be null"); } var validationResult = ConfigurationValidator.Validate(options); if (validationResult.IsValid) { // If there are only warnings, consider configuration valid return ValidateOptionsResult.Success; } // Collect all errors var errorMessages = validationResult.Errors .Select(e => $"{e.PropertyName}: {e.Message}") .ToList(); // Add warnings as informational messages var warningMessages = validationResult.Warnings .Select(w => $"WARNING - {w.PropertyName}: {w.Message}") .ToList(); var allMessages = errorMessages.Concat(warningMessages); return ValidateOptionsResult.Fail(allMessages); } } /// /// Extended validator with auto-fix support /// public class RedbServiceConfigurationValidatorWithAutoFix : IValidateOptions { private readonly bool _autoFixCriticalErrors; /// /// Create validator with auto-fix capability /// /// Automatically fix critical errors public RedbServiceConfigurationValidatorWithAutoFix(bool autoFixCriticalErrors = true) { _autoFixCriticalErrors = autoFixCriticalErrors; } public ValidateOptionsResult Validate(string? name, RedbServiceConfiguration options) { if (options == null) { return ValidateOptionsResult.Fail("RedbServiceConfiguration cannot be null"); } var validationResult = ConfigurationValidator.Validate(options); // If there are critical errors and auto-fix is enabled if (validationResult.HasCriticalErrors && _autoFixCriticalErrors) { // Fix critical errors in-place var fixedConfig = ConfigurationValidator.FixCriticalErrors(options); CopyFixedValues(fixedConfig, options); // Re-validate the fixed configuration validationResult = ConfigurationValidator.Validate(options); } if (validationResult.IsValid) { return ValidateOptionsResult.Success; } // If errors remain after auto-fix var errorMessages = validationResult.Errors .Where(e => e.Severity != ConfigurationValidationSeverity.Warning) .Select(e => $"{e.PropertyName}: {e.Message} (Current: {e.CurrentValue})") .ToList(); if (errorMessages.Any()) { return ValidateOptionsResult.Fail(errorMessages); } // Only warnings - consider valid return ValidateOptionsResult.Success; } /// /// Copy fixed values /// // The fixed configuration is a full copy (CFG-1), so everything is taken back: a list of the fields // FixCriticalErrors happens to touch today goes stale the day it touches another. private static void CopyFixedValues(RedbServiceConfiguration source, RedbServiceConfiguration target) => target.CopyFrom(source); } /// /// Validator for specific usage scenarios /// public class ScenarioBasedConfigurationValidator : IValidateOptions { private readonly ConfigurationScenario _expectedScenario; /// /// Create validator for specific scenario /// /// Expected usage scenario public ScenarioBasedConfigurationValidator(ConfigurationScenario expectedScenario) { _expectedScenario = expectedScenario; } public ValidateOptionsResult Validate(string? name, RedbServiceConfiguration options) { if (options == null) { return ValidateOptionsResult.Fail("RedbServiceConfiguration cannot be null"); } // Base validation var baseValidation = ConfigurationValidator.Validate(options); if (baseValidation.HasCriticalErrors) { var criticalErrors = baseValidation.Errors .Where(e => e.Severity == ConfigurationValidationSeverity.Critical) .Select(e => e.Message); return ValidateOptionsResult.Fail(criticalErrors); } // Validation for specific scenario var scenarioErrors = ValidateForScenario(options, _expectedScenario); if (scenarioErrors.Any()) { return ValidateOptionsResult.Fail(scenarioErrors); } return ValidateOptionsResult.Success; } /// /// Validation for specific scenario /// private static string[] ValidateForScenario(RedbServiceConfiguration config, ConfigurationScenario scenario) { var errors = new System.Collections.Generic.List(); switch (scenario) { case ConfigurationScenario.Production: if (!config.IsProductionSafe()) { errors.Add("Configuration is not safe for production environment"); } if (config.JsonOptions.WriteIndented) { errors.Add("WriteIndented should be false in production for performance"); } break; case ConfigurationScenario.Development: if (config.DefaultCheckPermissionsOnLoad || config.DefaultCheckPermissionsOnSave || config.DefaultCheckPermissionsOnDelete) { errors.Add("Permission checks should typically be disabled in development"); } break; case ConfigurationScenario.HighPerformance: if (!config.IsPerformanceOptimized()) { errors.Add("Configuration is not optimized for high performance"); } if (config.DefaultLoadDepth > 5) { errors.Add("DefaultLoadDepth should be <= 5 for high performance scenarios"); } break; case ConfigurationScenario.BulkOperations: if (config.EnableDataValidation) { errors.Add("Data validation should be disabled for bulk operations"); } if (config.DefaultLoadDepth > 1) { errors.Add("DefaultLoadDepth should be 1 for bulk operations"); } break; } return errors.ToArray(); } } /// /// Configuration usage scenarios /// public enum ConfigurationScenario { /// /// Production environment /// Production, /// /// Development environment /// Development, /// /// High performance /// HighPerformance, /// /// Bulk operations /// BulkOperations, /// /// Integration testing /// IntegrationTesting, /// /// Debug /// Debug } } Path: redb/redb.Core/Configuration/ServiceCollectionExtensions.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/Configuration/ServiceCollectionExtensions.cs ---- #pragma warning disable CS0618 // implements or uses the deprecated object permissions and roles (RedbDeprecation) using System; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using redb.Core.Models.Configuration; namespace redb.Core.Configuration { /// /// Extension methods for registering RedbService in DI container. /// public static class ServiceCollectionExtensions { /// /// Add RedbService configuration from IConfiguration. /// /// Service collection /// Application configuration /// Configuration section name /// Service collection for chaining [Obsolete("Use services.AddRedb(configuration) directly")] public static IServiceCollection AddRedbServiceConfiguration( this IServiceCollection services, IConfiguration configuration, string sectionName = "RedbService") { // Register configuration through Options pattern services.Configure( configuration.GetSection(sectionName)); // Add configuration validation services.AddSingleton, RedbServiceConfigurationValidator>(); // Register direct access to configuration services.AddSingleton(provider => { var options = provider.GetRequiredService>(); return options.CurrentValue; }); return services; } /// /// Add RedbService configuration with validation. /// /// Service collection /// Application configuration /// Configuration section name /// Throw exception on validation errors /// Service collection for chaining [Obsolete("Use services.AddRedb(configuration) - validation is built into properties")] public static IServiceCollection AddValidatedRedbServiceConfiguration( this IServiceCollection services, IConfiguration configuration, string sectionName = "RedbService", bool throwOnValidationError = true) { // Get and validate configuration during registration var config = configuration.GetValidatedRedbServiceConfiguration(sectionName, throwOnValidationError); // Register validated configuration services.AddSingleton(config); // Also register through Options pattern for compatibility services.Configure(options => { // Copy all properties from validated configuration CopyConfigurationProperties(config, options); }); return services; } /// /// Add RedbService configuration via builder. /// /// Service collection /// Delegate for builder configuration /// Service collection for chaining [Obsolete("Use services.AddRedb(options => { ... }) directly")] public static IServiceCollection AddRedbServiceConfiguration( this IServiceCollection services, Action configureBuilder) { var builder = new RedbServiceConfigurationBuilder(); configureBuilder(builder); var config = builder.Build(); services.AddSingleton(config); return services; } /// /// Add RedbService configuration combining IConfiguration and builder. /// /// Service collection /// Application configuration /// Delegate for additional configuration /// Configuration section name /// Service collection for chaining [Obsolete("Use services.AddRedb(configuration) directly")] public static IServiceCollection AddRedbServiceConfiguration( this IServiceCollection services, IConfiguration configuration, Action configureBuilder, string sectionName = "RedbService") { // Create builder based on configuration var builder = configuration.CreateRedbServiceBuilder(sectionName); // Apply additional settings configureBuilder(builder); var config = builder.Build(); services.AddSingleton(config); return services; } /// /// Add predefined RedbService configuration. /// /// Service collection /// Predefined configuration /// Service collection for chaining [Obsolete("Use services.AddRedb(config) directly")] public static IServiceCollection AddRedbServiceConfiguration( this IServiceCollection services, RedbServiceConfiguration predefinedConfig) { services.AddSingleton(predefinedConfig); return services; } /// /// Add RedbService configuration by profile name. /// /// Service collection /// Configuration profile name /// Optional additional configuration /// Service collection for chaining [Obsolete("Use services.AddRedb(PredefinedConfigurations.GetByName(profile)) directly")] public static IServiceCollection AddRedbServiceConfiguration( this IServiceCollection services, string profileName, Action? configureBuilder = null) { var config = PredefinedConfigurations.GetByName(profileName); if (configureBuilder != null) { var builder = new RedbServiceConfigurationBuilder(config); configureBuilder(builder); config = builder.Build(); } services.AddSingleton(config); return services; } /// /// Add RedbService configuration change monitoring. /// /// Service collection /// Application configuration /// Configuration section name /// Service collection for chaining [Obsolete("Use services.AddRedb(configuration) - configuration changes via direct property modification")] public static IServiceCollection AddRedbServiceConfigurationMonitoring( this IServiceCollection services, IConfiguration configuration, string sectionName = "RedbService") { // Register change monitoring through IOptionsMonitor services.Configure( configuration.GetSection(sectionName)); // Add validation on changes services.AddSingleton, RedbServiceConfigurationValidator>(); // Register service for tracking changes services.AddSingleton(); return services; } // === PRIVATE METHODS === /// /// Copy configuration properties. /// private static void CopyConfigurationProperties(RedbServiceConfiguration source, RedbServiceConfiguration target) { target.IdResetStrategy = source.IdResetStrategy; target.MissingObjectStrategy = source.MissingObjectStrategy; target.DefaultCheckPermissionsOnLoad = source.DefaultCheckPermissionsOnLoad; target.DefaultCheckPermissionsOnSave = source.DefaultCheckPermissionsOnSave; target.DefaultCheckPermissionsOnDelete = source.DefaultCheckPermissionsOnDelete; target.DefaultStrictDeleteExtra = source.DefaultStrictDeleteExtra; target.AutoSyncSchemesOnSave = source.AutoSyncSchemesOnSave; target.DefaultLoadDepth = source.DefaultLoadDepth; target.DefaultMaxTreeDepth = source.DefaultMaxTreeDepth; target.EnableMetadataCache = source.EnableMetadataCache; target.MetadataCacheLifetimeMinutes = source.MetadataCacheLifetimeMinutes; target.EnableSchemaValidation = source.EnableSchemaValidation; target.EnableDataValidation = source.EnableDataValidation; target.AutoSetModifyDate = source.AutoSetModifyDate; target.AutoRecomputeHash = source.AutoRecomputeHash; // target.DefaultSecurityPriority = source.DefaultSecurityPriority; // Removed target.SystemUserId = source.SystemUserId; target.JsonOptions.WriteIndented = source.JsonOptions.WriteIndented; target.JsonOptions.UseUnsafeRelaxedJsonEscaping = source.JsonOptions.UseUnsafeRelaxedJsonEscaping; } } /// /// Interface for configuration change monitoring. /// public interface IRedbServiceConfigurationMonitor { /// /// Current configuration. /// RedbServiceConfiguration CurrentConfiguration { get; } /// /// Configuration changed event. /// event Action ConfigurationChanged; } /// /// Configuration change monitoring implementation. /// internal class RedbServiceConfigurationMonitor : IRedbServiceConfigurationMonitor, IDisposable { private readonly IOptionsMonitor _optionsMonitor; private readonly IDisposable? _changeSubscription; public RedbServiceConfigurationMonitor(IOptionsMonitor optionsMonitor) { _optionsMonitor = optionsMonitor; _changeSubscription = _optionsMonitor.OnChange(OnConfigurationChanged); } public RedbServiceConfiguration CurrentConfiguration => _optionsMonitor.CurrentValue; public event Action? ConfigurationChanged; private void OnConfigurationChanged(RedbServiceConfiguration configuration) { var validationResult = ConfigurationValidator.Validate(configuration); if (validationResult.HasCriticalErrors) { throw new InvalidOperationException( $"Critical configuration errors: {string.Join(", ", validationResult.GetAllMessages())}"); } ConfigurationChanged?.Invoke(configuration); } public void Dispose() { _changeSubscription?.Dispose(); } } } Path: redb/redb.Core/Configuration/UserConfigurationService.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/Configuration/UserConfigurationService.cs ---- #pragma warning disable CS0618 // implements or uses the deprecated object permissions and roles (RedbDeprecation) using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using redb.Core.Data; using redb.Core.Models.Configuration; using redb.Core.Models.Entities; using redb.Core.Query; namespace redb.Core.Configuration; /// /// The user configuration service of every provider: the statements come from the dialect. PostgreSQL and SQLite used /// to carry copies of this class with the same SQL written into them. /// public class UserConfigurationService : IUserConfigurationService { private readonly IRedbService _redbService; private readonly IRedbContext _context; private readonly RedbServiceConfiguration _baseConfiguration; private readonly ISqlDialect _sql; // Cache for effective configurations (userId -> (config, expireTime)) private readonly ConcurrentDictionary _configCache = new(); private readonly TimeSpan _cacheTtl = TimeSpan.FromMinutes(5); private class CachedConfiguration { public EffectiveUserConfiguration Configuration { get; set; } = null!; public DateTime ExpiresAt { get; set; } } public UserConfigurationService( IRedbService redbService, IRedbContext context, RedbServiceConfiguration baseConfiguration, ISqlDialect sql) { _redbService = redbService ?? throw new ArgumentNullException(nameof(redbService)); _context = context ?? throw new ArgumentNullException(nameof(context)); _baseConfiguration = baseConfiguration ?? throw new ArgumentNullException(nameof(baseConfiguration)); _sql = sql ?? throw new ArgumentNullException(nameof(sql)); } /// /// Get effective configuration for user. /// public async Task GetEffectiveConfigurationAsync(long userId) { // Check cache if (_configCache.TryGetValue(userId, out var cached)) { if (DateTime.UtcNow < cached.ExpiresAt) { return cached.Configuration; } // Expired - remove _configCache.TryRemove(userId, out _); } // Build configuration var effective = await BuildEffectiveConfigurationAsync(userId); // Cache it _configCache[userId] = new CachedConfiguration { Configuration = effective, ExpiresAt = DateTime.UtcNow.Add(_cacheTtl) }; return effective; } /// /// Build effective configuration for user. /// private async Task BuildEffectiveConfigurationAsync(long userId) { var effective = new EffectiveUserConfiguration { UserId = userId, CreatedAt = DateTime.UtcNow }; // Step 1: Base values from RedbServiceConfiguration ApplyBaseConfiguration(effective); // Step 2: For sys (userId=0) return base values (no limits) if (userId == 0) { effective.ListCacheSize = null; // Unlimited return effective; } // Step 3: Load Default User Configuration var defaultConfig = await GetDefaultConfigurationAsync(); if (defaultConfig != null) { ApplyOverride(effective, defaultConfig.Props, "Default User Config", 10); } // Step 4: Load the configurations of the user's roles (their id, name and configuration in one statement) var roles = await _context.QueryAsync(_sql.UsersRoles_SelectRolesByUser(), userId); var roleConfigs = new List<(RedbObject config, string roleName)>(); foreach (var role in roles) { if (role.IdConfiguration == null) continue; var roleConfig = await _redbService.LoadAsync(role.IdConfiguration.Value); if (roleConfig != null) roleConfigs.Add((roleConfig, role.Name)); } // Sort by priority and apply foreach (var (config, roleName) in roleConfigs.OrderBy(rc => rc.config.Props.Priority)) { ApplyOverride(effective, config.Props, $"Role:{roleName}", 20 + config.Props.Priority); } // Step 5: Load personal user configuration var userConfigId = await _context.ExecuteScalarAsync(_sql.Users_SelectConfigurationId(), userId); if (userConfigId.HasValue) { var userConfig = await _redbService.LoadAsync(userConfigId.Value); if (userConfig != null) { ApplyOverride(effective, userConfig.Props, "User", 100); } } return effective; } /// /// Apply base values from RedbServiceConfiguration. /// private void ApplyBaseConfiguration(EffectiveUserConfiguration effective) { effective.PropsCacheSize = _baseConfiguration.PropsCacheMaxSize; effective.ListCacheSize = 5000; effective.PropsCacheTtl = _baseConfiguration.PropsCacheTtl; effective.ListCacheTtl = _baseConfiguration.ListCacheTtl; effective.MaxLoadDepth = _baseConfiguration.DefaultLoadDepth; effective.MaxTreeDepth = _baseConfiguration.DefaultMaxTreeDepth; effective.AlwaysCheckPermissionsOnLoad = _baseConfiguration.DefaultCheckPermissionsOnLoad; effective.AlwaysCheckPermissionsOnSave = _baseConfiguration.DefaultCheckPermissionsOnSave; effective.MaxRequestsPerMinute = null; effective.MaxBatchSize = 1000; effective.PropsSaveStrategy = _baseConfiguration.PropsSaveStrategy; // Sources effective.Sources.Add(new ConfigurationSource { ParameterName = "All", Source = "RedbServiceConfiguration", Priority = 0, Value = "Base values" }); } /// /// Apply override from configuration (only non-null values). /// private void ApplyOverride( EffectiveUserConfiguration target, UserConfigurationProps source, string sourceName, int priority) { // PropsCacheSize is not merged: the props cache has one process-wide limit (obsolete on the props). if (source.ListCacheSize.HasValue) { target.ListCacheSize = source.ListCacheSize.Value; target.Sources.Add(new ConfigurationSource { ParameterName = nameof(source.ListCacheSize), Source = sourceName, Priority = priority, Value = source.ListCacheSize.Value.ToString() }); } if (source.PropsCacheTtlMinutes.HasValue) { target.PropsCacheTtl = TimeSpan.FromMinutes(source.PropsCacheTtlMinutes.Value); target.Sources.Add(new ConfigurationSource { ParameterName = nameof(source.PropsCacheTtlMinutes), Source = sourceName, Priority = priority, Value = source.PropsCacheTtlMinutes.Value.ToString() }); } if (source.ListCacheTtlMinutes.HasValue) { target.ListCacheTtl = TimeSpan.FromMinutes(source.ListCacheTtlMinutes.Value); target.Sources.Add(new ConfigurationSource { ParameterName = nameof(source.ListCacheTtlMinutes), Source = sourceName, Priority = priority, Value = source.ListCacheTtlMinutes.Value.ToString() }); } if (source.MaxLoadDepth.HasValue) { target.MaxLoadDepth = source.MaxLoadDepth.Value; target.Sources.Add(new ConfigurationSource { ParameterName = nameof(source.MaxLoadDepth), Source = sourceName, Priority = priority, Value = source.MaxLoadDepth.Value.ToString() }); } if (source.MaxTreeDepth.HasValue) { target.MaxTreeDepth = source.MaxTreeDepth.Value; target.Sources.Add(new ConfigurationSource { ParameterName = nameof(source.MaxTreeDepth), Source = sourceName, Priority = priority, Value = source.MaxTreeDepth.Value.ToString() }); } if (source.AlwaysCheckPermissionsOnLoad.HasValue) { target.AlwaysCheckPermissionsOnLoad = source.AlwaysCheckPermissionsOnLoad.Value; target.Sources.Add(new ConfigurationSource { ParameterName = nameof(source.AlwaysCheckPermissionsOnLoad), Source = sourceName, Priority = priority, Value = source.AlwaysCheckPermissionsOnLoad.Value.ToString() }); } if (source.AlwaysCheckPermissionsOnSave.HasValue) { target.AlwaysCheckPermissionsOnSave = source.AlwaysCheckPermissionsOnSave.Value; target.Sources.Add(new ConfigurationSource { ParameterName = nameof(source.AlwaysCheckPermissionsOnSave), Source = sourceName, Priority = priority, Value = source.AlwaysCheckPermissionsOnSave.Value.ToString() }); } if (source.MaxRequestsPerMinute.HasValue) { target.MaxRequestsPerMinute = source.MaxRequestsPerMinute.Value; target.Sources.Add(new ConfigurationSource { ParameterName = nameof(source.MaxRequestsPerMinute), Source = sourceName, Priority = priority, Value = source.MaxRequestsPerMinute.Value.ToString() }); } if (source.MaxBatchSize.HasValue) { target.MaxBatchSize = source.MaxBatchSize.Value; target.Sources.Add(new ConfigurationSource { ParameterName = nameof(source.MaxBatchSize), Source = sourceName, Priority = priority, Value = source.MaxBatchSize.Value.ToString() }); } if (source.PropsSaveStrategy.HasValue) { target.PropsSaveStrategy = source.PropsSaveStrategy.Value; target.Sources.Add(new ConfigurationSource { ParameterName = nameof(source.PropsSaveStrategy), Source = sourceName, Priority = priority, Value = source.PropsSaveStrategy.Value.ToString() }); } } /// /// Get default user configuration (ID=-100). /// public Task?> GetDefaultConfigurationAsync() { return _redbService.LoadAsync(DefaultUserConfigurationInitializer.DefaultConfigId); } /// /// Set user configuration. /// public async Task SetUserConfigurationAsync(long userId, long? configId) { var exists = await _context.ExecuteScalarAsync(_sql.Users_ExistsById(), userId); if (!exists.HasValue) throw new ArgumentException($"User with ID {userId} not found"); await _context.ExecuteAsync(_sql.Users_UpdateConfiguration(), (object?)configId ?? DBNull.Value, userId); // Invalidate cache InvalidateCache(userId); } /// /// Set role configuration. /// public async Task SetRoleConfigurationAsync(long roleId, long? configId) { var exists = await _context.ExecuteScalarAsync(_sql.Roles_ExistsById(), roleId); if (!exists.HasValue) throw new ArgumentException($"Role with ID {roleId} not found"); await _context.ExecuteAsync(_sql.Roles_UpdateConfiguration(), (object?)configId ?? DBNull.Value, roleId); // Invalidate cache for all users with this role var users = await _context.QueryAsync(_sql.UsersRoles_SelectUsersByRole(), roleId); foreach (var user in users) { InvalidateCache(user.Id); } } /// /// Create new configuration. /// public async Task> CreateConfigurationAsync( string name, UserConfigurationProps props, string? description = null) { if (string.IsNullOrWhiteSpace(name)) throw new ArgumentException("Configuration name cannot be empty", nameof(name)); if (props == null) throw new ArgumentNullException(nameof(props)); // Set description if (!string.IsNullOrWhiteSpace(description)) { props.Description = description; } // Create RedbObject var config = new RedbObject { name = name, Props = props }; // Save via IRedbService await _redbService.SaveAsync(config); return config; } /// /// Invalidate cache for user configuration. /// public void InvalidateCache(long userId) { _configCache.TryRemove(userId, out _); } /// /// Clear all configuration cache. /// public void ClearCache() { _configCache.Clear(); } } Path: redb/redb.Core/Configuration/appsettings.examples.json 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/Configuration/appsettings.examples.json ---- { // ===== ПРИМЕР 1: Базовая конфигурация ===== "RedbService_Basic": { "DefaultCheckPermissionsOnLoad": false, "DefaultCheckPermissionsOnSave": false, "DefaultCheckPermissionsOnDelete": true, "DefaultLoadDepth": 10, "EnableSchemaMetadataCache": true, "SchemaMetadataCacheLifetimeMinutes": 30, "JsonOptions": { "WriteIndented": false, "UseUnsafeRelaxedJsonEscaping": true } }, // ===== ПРИМЕР 2: Использование профиля ===== "RedbService_WithProfile": { "Profile": "Development", "Overrides": { "DefaultLoadDepth": 15, "EnableSchemaMetadataCache": false, "JsonOptions": { "WriteIndented": true } } }, // ===== ПРИМЕР 3: Продакшн конфигурация ===== "RedbService_Production": { "Profile": "Production", "Overrides": { "DefaultLoadDepth": 3, "SchemaMetadataCacheLifetimeMinutes": 120, "SystemUserId": 1 } }, // ===== ПРИМЕР 4: Полная конфигурация ===== "RedbService_Full": { // Стратегии обработки объектов "IdResetStrategy": "AutoCreateNewOnSave", "MissingObjectStrategy": "AutoSwitchToInsert", // Настройки безопасности "DefaultCheckPermissionsOnLoad": false, "DefaultCheckPermissionsOnSave": false, "DefaultCheckPermissionsOnDelete": true, "DefaultSecurityPriority": "Context", "SystemUserId": 0, // Настройки схем "DefaultStrictDeleteExtra": true, "AutoSyncSchemesOnSave": true, // Настройки загрузки "DefaultLoadDepth": 10, "DefaultMaxTreeDepth": 50, // Настройки производительности "EnableSchemaMetadataCache": true, "SchemaMetadataCacheLifetimeMinutes": 30, // Настройки валидации "EnableSchemaValidation": true, "EnableDataValidation": true, // Настройки аудита "AutoSetModifyDate": true, "AutoRecomputeHash": true, // Настройки JSON "JsonOptions": { "WriteIndented": false, "UseUnsafeRelaxedJsonEscaping": true } }, // ===== ПРИМЕР 5: Конфигурация для разработки ===== "RedbService_Development": { "Profile": "Development", "Overrides": { // Отключаем кеш для актуальности данных "EnableSchemaMetadataCache": false, // Подробное JSON для отладки "JsonOptions": { "WriteIndented": true }, // Больше глубины для полной картины "DefaultLoadDepth": 20, "DefaultMaxTreeDepth": 100 } }, // ===== ПРИМЕР 6: Конфигурация для высокой производительности ===== "RedbService_HighPerformance": { "Profile": "HighPerformance", "Overrides": { // Минимальная глубина "DefaultLoadDepth": 2, "DefaultMaxTreeDepth": 5, // Агрессивное кеширование "SchemaMetadataCacheLifetimeMinutes": 180, // Отключаем тяжелые операции "AutoRecomputeHash": false } }, // ===== ПРИМЕР 7: Конфигурация для массовых операций ===== "RedbService_BulkOperations": { "Profile": "BulkOperations", "Overrides": { // Минимальные настройки для максимальной скорости "DefaultLoadDepth": 1, "DefaultMaxTreeDepth": 1, "EnableSchemaValidation": false, "EnableDataValidation": false, "AutoSetModifyDate": false, "AutoRecomputeHash": false } }, // ===== ПРИМЕР 8: Конфигурация для тестирования ===== "RedbService_Testing": { "Profile": "IntegrationTesting", "Overrides": { // Отключаем кеш для изоляции тестов "EnableSchemaMetadataCache": false, // Подробное JSON для анализа "JsonOptions": { "WriteIndented": true }, // Строгая обработка ошибок "IdResetStrategy": "Manual", "MissingObjectStrategy": "ThrowException" } }, // ===== ПРИМЕР 9: Конфигурация для миграции данных ===== "RedbService_DataMigration": { "Profile": "DataMigration", "Overrides": { // Максимальная толерантность к ошибкам "IdResetStrategy": "AutoCreateNewOnSave", "MissingObjectStrategy": "AutoSwitchToInsert", // Отключаем валидацию данных (могут быть некорректные) "EnableDataValidation": false, // Не удаляем поля при миграции "DefaultStrictDeleteExtra": false, // Системный приоритет "DefaultSecurityPriority": "System" } }, // ===== ПРИМЕР 10: Конфигурация с переменными окружения ===== // Эти значения можно переопределить через environment variables: // REDBSERVICE__DEFAULTCHECKPERMISSIONSONLOAD=true // REDBSERVICE__DEFAULTLOADDEPTH=5 // REDBSERVICE__ENABLESCHEMAMETADATACACHE=false "RedbService_WithEnvOverrides": { "DefaultCheckPermissionsOnLoad": false, // Можно переопределить через REDBSERVICE__DEFAULTCHECKPERMISSIONSONLOAD "DefaultLoadDepth": 10, // Можно переопределить через REDBSERVICE__DEFAULTLOADDEPTH "EnableSchemaMetadataCache": true // Можно переопределить через REDBSERVICE__ENABLESCHEMAMETADATACACHE } } Path: redb/redb.Core/Data/AmbientConnectionRegistry.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/Data/AmbientConnectionRegistry.cs ---- using System; using System.Collections.Concurrent; using System.Data.Common; using System.Threading; using System.Threading.Tasks; using System.Transactions; namespace redb.Core.Data { /// /// One physical connection per database per ambient . /// /// A redb.Route .Transacted() block is a , and everything it writes - /// redb objects, raw SQL through redb.Context, a store resolving a scope of its own, the key /// generator - must land in that one transaction. Two connections open at the same time inside it turn /// it into a distributed transaction: SQL Server refuses it, PostgreSQL aborts at commit, and SQLite /// never takes part in System.Transactions at all. So the TRANSACTION holds the connection: every redb /// connection wrapper of the same database asks this registry for it while the transaction is ambient. /// /// /// The connection is opened inside the transaction on first use, so SqlClient and Npgsql enlist /// it themselves. /// A provider whose driver cannot enlist (SQLite) begins its own transaction on it; the entry /// enlists as a volatile resource and commits or rolls that transaction back with the scope. /// The entry is released when the transaction completes. /// Dependent clones share the transaction and therefore the entry: two commands at the same time /// are refused (owner decision: parallel branches in one transaction are not supported). /// /// public static class AmbientConnectionRegistry { private const string ConcurrentUseMessage = "The connection of an ambient transaction was used from two threads at the same time. One transaction " + "has one connection per database, and a connection runs one command at a time: parallel branches " + "cannot share a transaction. Run the branches sequentially, or give each branch its own transaction " + "(a sub-route with its own Transacted(), the parent route without one)."; private const string TransactionEndedMessage = "The ambient transaction of this connection has already ended (committed, rolled back - for example " + "because a parallel branch failed - or timed out). Commands after its end are refused: they would " + "run outside the transaction."; private const string SessionSettingsMismatchMessage = "Two redb configurations of the same database that differ in their connection parameters or session settings " + "are used inside one transaction. The transaction holds one connection per database, set up by the " + "configuration that opened it, and a command of the other configuration would run on it with settings that " + "are not its own. Inside one transaction, reach this database through one configuration, or give each " + "configuration its own transaction."; private static readonly ConcurrentDictionary Entries = new(StringComparer.Ordinal); // One open at a time per transaction and database. One process-wide lock held every other transaction's first // open behind a SQLite BEGIN IMMEDIATE waiting for its write lock (review after 4.0.0). private static readonly ConcurrentDictionary Opening = new(StringComparer.Ordinal); /// Number of live entries (diagnostics and tests). public static int Count => Entries.Count; /// /// The connection of for , opened on first /// use, with its command gate entered. Dispose the lease when the command is done. /// /// The ambient transaction (). /// Provider-qualified identity of the database (server, database, user). /// The caller's configuration: the cache domain of its connection string /// () plus the session /// settings redb applies on open. A different signature on a connection the transaction already holds is /// refused: that connection carries the settings of the configuration that opened it. /// Opens a new connection with the provider's session settings applied. /// For a driver that cannot enlist: begins the provider transaction /// the entry commits or rolls back with the scope. Null for drivers that enlist. /// Cancels opening the connection. public static async Task AcquireAsync( Transaction transaction, string databaseKey, string sessionSignature, Func> openAsync, Func? beginOwnTransaction, CancellationToken cancellationToken = default) { var entry = await GetOrOpenAsync(transaction, databaseKey, sessionSignature, openAsync, beginOwnTransaction, cancellationToken) .ConfigureAwait(false); return new AmbientLease(entry, entry.Gate.Enter()); } /// Synchronous for the thread-pool-free paths. public static AmbientLease Acquire( Transaction transaction, string databaseKey, string sessionSignature, Func open, Func? beginOwnTransaction) { var entry = GetOrOpen(transaction, databaseKey, sessionSignature, open, beginOwnTransaction); return new AmbientLease(entry, entry.Gate.Enter()); } /// /// The entry without entering its gate - for work that runs between commands of the same flow /// (bulk copy, key generation) and must use the transaction's connection. /// public static async Task GetOrOpenAsync( Transaction transaction, string databaseKey, string sessionSignature, Func> openAsync, Func? beginOwnTransaction, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(transaction); ArgumentNullException.ThrowIfNull(sessionSignature); var key = KeyFor(transaction, databaseKey); if (Entries.TryGetValue(key, out var existing)) return Matching(existing, sessionSignature); var opening = Opening.GetOrAdd(key, static _ => new SemaphoreSlim(1, 1)); await opening.WaitAsync(cancellationToken).ConfigureAwait(false); try { if (Entries.TryGetValue(key, out existing)) return Matching(existing, sessionSignature); var connection = await openAsync(cancellationToken).ConfigureAwait(false); return Register(transaction, key, sessionSignature, connection, beginOwnTransaction); } finally { opening.Release(); } } /// Synchronous . public static AmbientConnection GetOrOpen( Transaction transaction, string databaseKey, string sessionSignature, Func open, Func? beginOwnTransaction) { ArgumentNullException.ThrowIfNull(transaction); ArgumentNullException.ThrowIfNull(sessionSignature); var key = KeyFor(transaction, databaseKey); if (Entries.TryGetValue(key, out var existing)) return Matching(existing, sessionSignature); var opening = Opening.GetOrAdd(key, static _ => new SemaphoreSlim(1, 1)); opening.Wait(); try { if (Entries.TryGetValue(key, out existing)) return Matching(existing, sessionSignature); return Register(transaction, key, sessionSignature, open(), beginOwnTransaction); } finally { opening.Release(); } } /// The live entry of for the database, or null when none was opened. public static AmbientConnection? TryGet(Transaction transaction, string databaseKey) { ArgumentNullException.ThrowIfNull(transaction); return Entries.TryGetValue(KeyFor(transaction, databaseKey), out var entry) ? entry : null; } // Dependent clones report the local identifier of the transaction they depend on, so every branch of // one transaction resolves the same entry; RequiresNew gets an identifier of its own. private static string KeyFor(Transaction transaction, string databaseKey) => transaction.TransactionInformation.LocalIdentifier + "|" + databaseKey; private static AmbientConnection Matching(AmbientConnection entry, string sessionSignature) => string.Equals(entry.SessionSignature, sessionSignature, StringComparison.Ordinal) ? entry : throw new InvalidOperationException(SessionSettingsMismatchMessage); private static AmbientConnection Register( Transaction transaction, string key, string sessionSignature, DbConnection connection, Func? beginOwnTransaction) { DbTransaction? own = null; AmbientConnection? entry = null; try { // A connection opened for a transaction that already ended would run its commands outside it. var status = transaction.TransactionInformation.Status; if (status == TransactionStatus.Aborted) throw new TransactionAbortedException(TransactionEndedMessage); if (status != TransactionStatus.Active) throw new TransactionException(TransactionEndedMessage); if (beginOwnTransaction != null) own = beginOwnTransaction(connection); // A command may legally run up to the connection's own command timeout; the end of the // transaction waits that long for the in-flight one. TimeSpan budget; using (var probe = connection.CreateCommand()) budget = CommandGate.BudgetFrom(probe.CommandTimeout); entry = new AmbientConnection(key, sessionSignature, connection, own, budget, new CommandGate("ambient transaction connection", ConcurrentUseMessage, TransactionEndedMessage)); // Reachable before the completion handler is attached: on a transaction that ends in between, // the handler runs at once and must find the entry to remove. Entries[key] = entry; if (own != null) transaction.EnlistVolatile(entry, EnlistmentOptions.None); transaction.TransactionCompleted += (_, _) => Release(entry); return entry; } catch { // Nothing else will end this transaction or close the connection. if (entry != null) Entries.TryRemove(new System.Collections.Generic.KeyValuePair(key, entry)); Opening.TryRemove(key, out _); try { own?.Dispose(); } finally { connection.Dispose(); } throw; } } private static void Release(AmbientConnection entry) { Entries.TryRemove(new System.Collections.Generic.KeyValuePair(entry.Key, entry)); // The transaction ended: a later caller of this key opens nothing (Register refuses), so its gate is done. Opening.TryRemove(entry.Key, out _); entry.Close(); } } /// /// The connection an ambient transaction holds for one database. See . /// public sealed class AmbientConnection : ISinglePhaseNotification { private readonly TimeSpan _teardownBudget; internal AmbientConnection( string key, string sessionSignature, DbConnection connection, DbTransaction? ownTransaction, TimeSpan teardownBudget, CommandGate gate) { Key = key; SessionSignature = sessionSignature; Connection = connection; OwnTransaction = ownTransaction; _teardownBudget = teardownBudget; Gate = gate; } internal string Key { get; } /// Connection parameters and session settings of the configuration that opened the connection. public string SessionSignature { get; } internal CommandGate Gate { get; } /// The open connection. MSSQL and PostgreSQL enlisted it in the transaction when it opened. public DbConnection Connection { get; } /// /// The provider transaction a driver that cannot enlist runs under (SQLite); commands must be bound to /// it. Null for drivers that enlist. /// public DbTransaction? OwnTransaction { get; } /// /// Refuses new commands and waits for the in-flight one. The transaction can end while a branch still /// runs a command - a failed dependent clone rolls the whole transaction back at once, and so does the /// scope timeout. Ending the provider transaction under that command races a non-thread-safe /// connection, and on SQLite a command that slips in after ROLLBACK runs in autocommit and stays. /// private void EndCommands() => Gate.DisposeAndWaitAsync(_teardownBudget).AsTask().GetAwaiter().GetResult(); void IEnlistmentNotification.Prepare(PreparingEnlistment preparingEnlistment) { EndCommands(); preparingEnlistment.Prepared(); } void IEnlistmentNotification.Commit(Enlistment enlistment) { try { EndCommands(); OwnTransaction?.Commit(); } finally { enlistment.Done(); } } void IEnlistmentNotification.Rollback(Enlistment enlistment) { try { EndCommands(); OwnTransaction?.Rollback(); } finally { enlistment.Done(); } } void IEnlistmentNotification.InDoubt(Enlistment enlistment) { try { EndCommands(); OwnTransaction?.Rollback(); } finally { enlistment.Done(); } } void ISinglePhaseNotification.SinglePhaseCommit(SinglePhaseEnlistment singlePhaseEnlistment) { try { EndCommands(); OwnTransaction?.Commit(); } catch (Exception commitFailure) { // The transaction manager reports the abort to the scope's owner; this is not a swallow. singlePhaseEnlistment.Aborted(commitFailure); return; } singlePhaseEnlistment.Committed(); } internal void Close() { // MSSQL and PostgreSQL end the transaction in the driver, not through this entry: the wait for a // branch's in-flight command happens here, before the connection is disposed under it. EndCommands(); try { OwnTransaction?.Dispose(); } finally { Connection.Dispose(); } } } /// One command's hold on an : releases the connection's gate on dispose. public sealed class AmbientLease : IDisposable { private readonly CommandGate.Releaser _releaser; private int _disposed; internal AmbientLease(AmbientConnection entry, CommandGate.Releaser releaser) { Entry = entry; _releaser = releaser; } /// The transaction's connection for this database. public AmbientConnection Entry { get; } public void Dispose() { if (Interlocked.Exchange(ref _disposed, 1) == 0) _releaser.Dispose(); } } } Path: redb/redb.Core/Data/AssignedIdRollback.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/Data/AssignedIdRollback.cs ---- using System.Collections.Generic; using redb.Core.Models.Contracts; namespace redb.Core.Data { /// /// Ids a save assigns to the caller's objects inside a transaction that rolls back go back to 0 on those objects, /// so saving them again inserts new rows instead of addressing rows that were never committed. Only ids the save /// assigned: an object that had its id before keeps it. Only the object's own id: a copy the application made /// elsewhere (another object's property, a variable) is not reset. /// internal static class AssignedIdRollback { /// /// Registers the reset for , whose ids the save has just assigned. Outside a /// transaction nothing is registered: the ids then come from committed ranges and the save owns its own rollback. /// public static void ResetOnRollback(IRedbContext context, IReadOnlyList objects) { if (objects.Count == 0) return; var assigned = new (IRedbObject Obj, long Id)[objects.Count]; for (var i = 0; i < objects.Count; i++) assigned[i] = (objects[i], objects[i].Id); TransactionHooks.OnCompleted(context, committed => { if (committed) return; foreach (var (obj, id) in assigned) { // An id the application changed since is its own: left alone. if (obj.Id == id) obj.Id = 0; } }); } } } Path: redb/redb.Core/Data/CommandGate.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/Data/CommandGate.cs ---- using System; using System.Threading; using System.Threading.Tasks; namespace redb.Core.Data { /// /// Mutual exclusion between the commands and the teardown of ONE physical connection /// (a production report, 2026-09-11). A redb connection wrapper is single-command by /// design and always carried a fail-fast guard against two concurrent commands - but /// teardown was exempt from it, so an HTTP scope's dispose could run under a lazy /// loader's in-flight SELECT: NpgsqlOperationInProgressException on Reset, or (timing /// depending) an outright hang of scope disposal. /// /// The gate closes both holes and is SHARED by all three providers so the contract /// cannot drift: /// - a command entered after teardown began is refused with /// - the lazy loader's cue to fall back to a /// detached (fresh-scope) load; /// - teardown waits for the in-flight command before touching the physical connection; /// new entrants bounce the moment the flag is set, so the wait is bounded by one /// command. /// public sealed class CommandGate { private readonly string _owner; private readonly string? _concurrentUseMessage; private readonly string? _disposedMessage; private int _inUse; private volatile bool _disposed; public CommandGate(string ownerName) => _owner = ownerName; /// /// A gate whose refusals carry their own explanation - the connection of an ambient transaction is /// shared by every scope of that transaction and ends with the transaction, so "resolve your own /// IRedbService" and "the scope has ended" are the wrong advice there. /// public CommandGate(string ownerName, string concurrentUseMessage, string disposedMessage) { _owner = ownerName; _concurrentUseMessage = concurrentUseMessage; _disposedMessage = disposedMessage; } /// Teardown has begun (or completed); new commands are refused. public bool IsDisposed => _disposed; /// /// Enters a command. Throws on CONCURRENT use /// (one scoped service shared across exchanges) and /// on entry after teardown began. /// public Releaser Enter() { ThrowIfDisposed(); if (Interlocked.CompareExchange(ref _inUse, 1, 0) != 0) throw new InvalidOperationException(_concurrentUseMessage ?? $"IRedbService used concurrently: the same {_owner} was entered from two threads. " + "Each exchange/request must resolve its OWN scoped IRedbService (ProcessWithRedb / controller.Redb()) — " + "one instance is a single, non-thread-safe DB connection."); if (_disposed) { // Teardown began between the flag check and the CAS: hand the slot back so the // waiting dispose proceeds, and refuse exactly like the early check does. Interlocked.Exchange(ref _inUse, 0); ThrowIfDisposed(); } return new Releaser(this); } private void ThrowIfDisposed() { if (_disposed) throw new ObjectDisposedException(_owner, _disposedMessage ?? "The scope that owned this connection has ended; load through a fresh scope instead."); } /// /// The teardown wait budget derived from the connection's OWN command timeout: a /// command may legally run right up to it, so teardown waits that long plus a little /// slack for the driver to surface its own timeout first. Zero or negative means the /// driver allows infinite commands - teardown still must end, so a generous fixed /// budget applies; the command's own fault stays observable on its side either way. /// public static TimeSpan BudgetFrom(int commandTimeoutSeconds) => commandTimeoutSeconds > 0 ? TimeSpan.FromSeconds(commandTimeoutSeconds + 5) : TimeSpan.FromMinutes(10); /// /// Marks the gate disposed and WAITS until the in-flight command (if any) releases /// the slot. The budget is deliberately REQUIRED - derive it from the connection's own /// command timeout via ; there is no magic default. It is a /// last-resort escape for a command stuck beyond its own timeout: teardown then /// proceeds rather than hang forever. /// public async ValueTask DisposeAndWaitAsync(TimeSpan budget) { _disposed = true; var clock = System.Diagnostics.Stopwatch.StartNew(); while (Volatile.Read(ref _inUse) != 0 && clock.Elapsed < budget) await Task.Delay(10).ConfigureAwait(false); } public readonly struct Releaser : IDisposable { private readonly CommandGate _gate; public Releaser(CommandGate gate) => _gate = gate; public void Dispose() => Interlocked.Exchange(ref _gate._inUse, 0); } } } Path: redb/redb.Core/Data/DbErrorClassifier.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/Data/DbErrorClassifier.cs ---- using redb.Core.Exceptions; namespace redb.Core.Data; /// /// Classifies provider exceptions by their native error code without referencing the drivers. /// /// /// One place for every duck-typed code check. Before this type there were two independent copies of /// the same reflection walk — DeadlockRetryHelper.IsDeadlock and /// RedbServiceBase.IsUndefinedFunctionError — and V4 needed a third (insufficient privilege) /// and a fourth (unique violation). Four copies of "walk the inner-exception chain, read /// SqlState or Number by reflection" is how one of them ends up subtly different. /// /// /// /// Reflection rather than a driver reference on purpose: redb.Core must not depend on Npgsql, /// Microsoft.Data.SqlClient or Microsoft.Data.Sqlite. The property names (SqlState, /// Number, SqliteErrorCode, SqliteExtendedErrorCode) are the drivers' public /// API and have been stable for years. /// /// public static class DbErrorClassifier { /// SQL Server 1205, PostgreSQL 40P01. The retry helper's condition. public static bool IsDeadlock(Exception ex) => Any(ex, pgState: s => s == "40P01", mssqlNumber: n => n == 1205, sqlite: null); /// /// PostgreSQL 40001 (serialization_failure), SQL Server 3960/3961 (snapshot update conflict). /// BR-1: under elevated isolation the database aborts the loser; the WHOLE transaction must be /// retried by its owner - retrying one statement inside the aborted transaction is useless. /// SQLite never raises it (a single serial writer). Exposed so callers classify without /// provider-specific code. /// public static bool IsSerializationFailure(Exception ex) => Any(ex, pgState: s => s == "40001", mssqlNumber: n => n == 3960 || n == 3961, sqlite: null); /// /// The function or procedure named in the statement does not exist: PostgreSQL 42883, SQL Server /// 195 ("not a recognized built-in function name") or 4121 ("Cannot find either column ... or /// the user-defined function"). Used to recognise a database that has never had the PVT module. /// public static bool IsUndefinedFunction(Exception ex) => Any(ex, pgState: s => s == "42883", mssqlNumber: n => n is 195 or 4121, sqlite: null); /// /// The connected role is not allowed to do what the statement does: PostgreSQL 42501 /// (insufficient_privilege), SQL Server 229 (permission denied on object), 262 (permission /// denied for CREATE/ALTER), 297 (user does not have permission), 3701 ("cannot drop ... because /// it does not exist or you do not have permission" — the module redeploy drops functions it has /// just read the version from, so in that context the second reading is the only one possible), /// 15247 (permission denied on server). This is what an application without owner rights gets /// when it tries to apply a schema upgrade — and what turns into /// instead of a raw driver error. /// public static bool IsInsufficientPrivilege(Exception ex) => Any(ex, pgState: s => s == "42501", mssqlNumber: n => n is 229 or 262 or 297 or 3701 or 15247, sqlite: null); /// /// A unique index or constraint rejected the row: PostgreSQL 23505, SQL Server 2601 (unique /// index) or 2627 (unique constraint), SQLite extended code 2067 (SQLITE_CONSTRAINT_UNIQUE). /// A primary key is not one of them: PostgreSQL and SQL Server report its clash with the same /// codes, and it is told apart by name - every primary key of the redb schema is named /// PK__<table> (PostgreSQL folds it to pk__). SQLite reports it with its own /// extended code (1555), which never matched. /// public static bool IsUniqueViolation(Exception ex) => Any(ex, pgState: s => s == "23505", mssqlNumber: n => n is 2601 or 2627, sqlite: c => c == 2067) && DescribeUniqueViolation(ex).ConstraintName?.StartsWith("PK__", StringComparison.OrdinalIgnoreCase) != true; /// /// The primary key of _objects or _values rejected the row: an id given to a new row is already /// taken. PostgreSQL 23505 and SQL Server 2627 name the key (PK__objects, PK__values); SQLite /// reports extended code 1555 with the column (_objects._id, _values._id). /// internal static bool IsObjectOrValueKeyViolation(Exception ex) { if (Any(ex, pgState: s => s == "23505", mssqlNumber: n => n == 2627, sqlite: c => c == 1555)) { var text = DescribeUniqueViolation(ex).ConstraintName; return text != null && (text.Contains("PK__objects", StringComparison.OrdinalIgnoreCase) || text.Contains("PK__values", StringComparison.OrdinalIgnoreCase) || text.Contains("_objects._id", StringComparison.OrdinalIgnoreCase) || text.Contains("_values._id", StringComparison.OrdinalIgnoreCase)); } return false; } /// /// What the driver said about a unique violation: the constraint or index name, its own detail /// line, and — when the message carries the key tuple of a _values index — the structure id /// (the first component of UIX__values__structure_unique). All best-effort: SQLite names only /// the columns, and a message format is not a contract. /// public static (string? ConstraintName, string? Detail, long? StructureId, RedbUniqueViolationKind Kind) DescribeUniqueViolation(Exception ex) { for (var cur = ex; cur != null; cur = cur.InnerException) { var type = cur.GetType(); switch (type.Name) { case "PostgresException": { var constraint = type.GetProperty("ConstraintName")?.GetValue(cur) as string; var detail = type.GetProperty("Detail")?.GetValue(cur) as string; long? structureId = null; if (constraint != null && constraint.Contains("values") && detail != null) { var m = System.Text.RegularExpressions.Regex.Match(detail, @"=\((\d+),"); if (m.Success && long.TryParse(m.Groups[1].Value, out var id)) structureId = id; } return (constraint, detail, structureId, ClassifyUniqueIndex(constraint)); } case "SqlException": { var message = cur.Message; var cm = System.Text.RegularExpressions.Regex.Match(message, @"(?:index|constraint) '([^']+)'"); var constraint = cm.Success ? cm.Groups[1].Value : null; long? structureId = null; if (constraint != null && constraint.Contains("values")) { var m = System.Text.RegularExpressions.Regex.Match(message, @"duplicate key value is \((\d+),"); if (m.Success && long.TryParse(m.Groups[1].Value, out var id)) structureId = id; } return (constraint, message, structureId, ClassifyUniqueIndex(constraint)); } case "SqliteException": // "UNIQUE constraint failed: _values._id_structure, _values._unique" - columns only: // no key tuple, so no structure id - but the columns still classify the index. return (cur.Message, cur.Message, null, ClassifyUniqueIndex(cur.Message)); } } return (null, null, null, RedbUniqueViolationKind.Unknown); } /// /// Classifies which unique index the driver named (BR-8, 2026-09-02). PostgreSQL and MSSQL /// report the index name (UIX__objects__scheme_unique / UIX__values__structure_unique); /// SQLite reports column names ("_objects._id_scheme, _objects._value_unique"). Both /// spellings match, so callers branch on the enum instead of provider-specific strings. /// private static RedbUniqueViolationKind ClassifyUniqueIndex(string? text) { if (string.IsNullOrEmpty(text)) return RedbUniqueViolationKind.Unknown; if (text.Contains("objects", StringComparison.OrdinalIgnoreCase) && (text.Contains("scheme_unique", StringComparison.OrdinalIgnoreCase) || text.Contains("_value_unique", StringComparison.OrdinalIgnoreCase))) return RedbUniqueViolationKind.ObjectKey; if (text.Contains("values", StringComparison.OrdinalIgnoreCase) && text.Contains("unique", StringComparison.OrdinalIgnoreCase)) return RedbUniqueViolationKind.Property; return RedbUniqueViolationKind.Unknown; } private static bool Any( Exception ex, Func pgState, Func mssqlNumber, Func? sqlite) { for (var cur = ex; cur != null; cur = cur.InnerException) { var type = cur.GetType(); switch (type.Name) { case "PostgresException": if (type.GetProperty("SqlState")?.GetValue(cur) is string state && pgState(state)) return true; break; case "SqlException": if (type.GetProperty("Number")?.GetValue(cur) is int number && mssqlNumber(number)) return true; break; case "SqliteException": if (sqlite is null) break; // The extended code carries the CONSTRAINT sub-kind; the plain code is the family. if (type.GetProperty("SqliteExtendedErrorCode")?.GetValue(cur) is int ext && sqlite(ext)) return true; if (type.GetProperty("SqliteErrorCode")?.GetValue(cur) is int code && sqlite(code)) return true; break; } } return false; } } Path: redb/redb.Core/Data/DeadlockRetryHelper.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/Data/DeadlockRetryHelper.cs ---- namespace redb.Core.Data; /// /// Retries an async operation on SQL deadlock (MsSql error 1205, Postgres state 40P01). /// Cluster-safe: each connection independently detects and retries. /// /// The unit that owns the transaction retries it, and only that unit: the server has already rolled the deadlock /// victim's transaction back, so a command run again inside it fails with a second error (PostgreSQL 25P02, an aborted /// transaction on SQL Server) that replaces the deadlock. So the helper never retries inside an ambient /// , and the overloads taking an never retry /// when that context is already in a transaction (an explicit one or ExecuteAtomicAsync's) when the operation /// starts. The original exception then leaves at once, for the owner of the transaction to run its unit again. /// /// /// The operation is run again as a whole, so it must open its own transaction (or run as single statements) and be /// safe to repeat: wrap the unit that owns the transaction, for example a whole ExecuteAtomicAsync call made /// outside any transaction. After the last attempt the deadlock leaves unchanged. /// /// public static class DeadlockRetryHelper { private const int DefaultMaxRetries = 3; private const int DefaultBaseDelayMs = 50; public static Task ExecuteWithRetryAsync(Func operation, int maxRetries = DefaultMaxRetries, int baseDelayMs = DefaultBaseDelayMs, System.Threading.CancellationToken cancellationToken = default) { return ExecuteWithRetryInternalAsync(operation, owned: true, maxRetries, baseDelayMs, cancellationToken); } public static Task ExecuteWithRetryAsync(Func> operation, int maxRetries = DefaultMaxRetries, int baseDelayMs = DefaultBaseDelayMs, System.Threading.CancellationToken cancellationToken = default) { return ExecuteWithRetryInternalAsync(operation, owned: true, maxRetries, baseDelayMs, cancellationToken); } /// /// Retries on a deadlock unless is in a transaction when it /// starts: then the transaction belongs to the caller, and the deadlock leaves at once. /// public static Task ExecuteWithRetryAsync(IRedbContext context, Func operation, int maxRetries = DefaultMaxRetries, int baseDelayMs = DefaultBaseDelayMs, System.Threading.CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(context); return ExecuteWithRetryInternalAsync(operation, owned: !context.IsInTransaction, maxRetries, baseDelayMs, cancellationToken); } /// /// Retries on a deadlock unless is in a transaction when it /// starts: then the transaction belongs to the caller, and the deadlock leaves at once. /// public static Task ExecuteWithRetryAsync(IRedbContext context, Func> operation, int maxRetries = DefaultMaxRetries, int baseDelayMs = DefaultBaseDelayMs, System.Threading.CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(context); return ExecuteWithRetryInternalAsync(operation, owned: !context.IsInTransaction, maxRetries, baseDelayMs, cancellationToken); } private static async Task ExecuteWithRetryInternalAsync(Func operation, bool owned, int maxRetries, int baseDelayMs, System.Threading.CancellationToken cancellationToken) { for (int attempt = 0; ; attempt++) { // Cancellation checks before each attempt and inside the backoff delay (never // mid-transaction: the operation itself owns its rollback path). cancellationToken.ThrowIfCancellationRequested(); try { await operation(); return; } catch (Exception ex) when (owned && attempt < maxRetries && IsDeadlock(ex) && !InAmbientTransaction()) { var delay = baseDelayMs * (1 << attempt); var jitter = Random.Shared.Next(delay); await Task.Delay(delay + jitter, cancellationToken); } } } private static async Task ExecuteWithRetryInternalAsync(Func> operation, bool owned, int maxRetries, int baseDelayMs, System.Threading.CancellationToken cancellationToken) { for (int attempt = 0; ; attempt++) { cancellationToken.ThrowIfCancellationRequested(); try { return await operation(); } catch (Exception ex) when (owned && attempt < maxRetries && IsDeadlock(ex) && !InAmbientTransaction()) { var delay = baseDelayMs * (1 << attempt); var jitter = Random.Shared.Next(delay); await Task.Delay(delay + jitter, cancellationToken); } } } /// /// Deadlock detection lives in with every other code check; /// this is kept as the name the retry loop and its tests use. /// internal static bool IsDeadlock(Exception ex) => DbErrorClassifier.IsDeadlock(ex); // Read only after a deadlock, inside the exception filter: between TransactionScope.Complete() and Dispose() the // getter throws, and a throwing filter counts as "no match", so the original deadlock still leaves unretried. private static bool InAmbientTransaction() => System.Transactions.Transaction.Current != null; } Path: redb/redb.Core/Data/IBulkOperations.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/Data/IBulkOperations.cs ---- using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using redb.Core.Models.Entities; namespace redb.Core.Data { /// /// Bulk operations abstraction for high-performance data operations. /// Replaces EFCore.BulkExtensions with pure ADO.NET COPY protocol. /// public interface IBulkOperations { /// /// Bulk insert objects using COPY protocol. /// Much faster than individual INSERTs for large datasets. /// /// Objects to insert. /// Cancels the operation; see the cancellation contract in the plan (OCE only, rollback always completes). Task BulkInsertObjectsAsync(IEnumerable objects, CancellationToken cancellationToken = default); /// /// Bulk insert values using COPY protocol. /// /// Values to insert. /// Cancels the operation; see the cancellation contract in the plan (OCE only, rollback always completes). Task BulkInsertValuesAsync(IEnumerable values, CancellationToken cancellationToken = default); /// /// Bulk update objects. /// Uses temp table + UPDATE FROM pattern for efficiency. /// /// Objects to update. /// Cancels the operation; see the cancellation contract in the plan (OCE only, rollback always completes). Task BulkUpdateObjectsAsync(IEnumerable objects, CancellationToken cancellationToken = default); /// /// Bulk update values. /// Uses temp table + UPDATE FROM pattern for efficiency. /// /// Values to update. /// Cancels the operation; see the cancellation contract in the plan (OCE only, rollback always completes). Task BulkUpdateValuesAsync(IEnumerable values, CancellationToken cancellationToken = default); /// /// Bulk delete objects by IDs. /// Uses ANY() with array for efficiency. /// /// Object IDs to delete. /// Cancels the operation; see the cancellation contract in the plan (OCE only, rollback always completes). Task BulkDeleteObjectsAsync(IEnumerable objectIds, CancellationToken cancellationToken = default); /// /// Bulk delete values by IDs. /// /// Value IDs to delete. /// Cancels the operation; see the cancellation contract in the plan (OCE only, rollback always completes). Task BulkDeleteValuesAsync(IEnumerable valueIds, CancellationToken cancellationToken = default); /// /// Bulk delete values by object IDs. /// Commonly used before re-inserting all values for object. /// /// Object IDs whose values to delete. /// Cancels the operation; see the cancellation contract in the plan (OCE only, rollback always completes). Task BulkDeleteValuesByObjectIdsAsync(IEnumerable objectIds, CancellationToken cancellationToken = default); /// /// Bulk delete values by ListItem IDs. /// Used when deleting list items that are referenced by values. /// /// ListItem IDs whose referencing values to delete. /// Cancels the operation; see the cancellation contract in the plan (OCE only, rollback always completes). Task BulkDeleteValuesByListItemIdsAsync(IEnumerable listItemIds, CancellationToken cancellationToken = default); } } Path: redb/redb.Core/Data/IKeyGenerator.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/Data/IKeyGenerator.cs ---- using System.Threading.Tasks; using System.Threading; namespace redb.Core.Data { /// /// Key generator abstraction for generating unique IDs. /// Replaces EF Core's automatic ID generation. /// public interface IKeyGenerator { /// /// Generate next unique ID for objects. /// Uses database sequence or other mechanism. /// /// Next unique ID. Task NextObjectIdAsync(CancellationToken cancellationToken = default); /// /// Generate next unique ID for values. /// Uses database sequence or other mechanism. /// /// Next unique ID. Task NextValueIdAsync(CancellationToken cancellationToken = default); /// /// Generate batch of object IDs for bulk operations. /// More efficient than calling NextObjectIdAsync multiple times. /// /// Number of IDs to generate. /// Array of unique IDs. /// Cancels the operation; see the cancellation contract in the plan (OCE only, rollback always completes). Task NextObjectIdBatchAsync(int count, CancellationToken cancellationToken = default); /// /// Generate batch of value IDs for bulk operations. /// More efficient than calling NextValueIdAsync multiple times. /// /// Number of IDs to generate. /// Array of unique IDs. /// Cancels the operation; see the cancellation contract in the plan (OCE only, rollback always completes). Task NextValueIdBatchAsync(int count, CancellationToken cancellationToken = default); } } Path: redb/redb.Core/Data/IRedbConnection.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/Data/IRedbConnection.cs ---- using System; using System.Collections.Generic; using System.Data.Common; using System.Threading; using System.Threading.Tasks; namespace redb.Core.Data { /// /// Database connection abstraction for REDB. /// Replaces DbContext with pure ADO.NET approach. /// All methods automatically use CurrentTransaction if active. /// public interface IRedbConnection : IAsyncDisposable, IDisposable { /// True once the connection has been disposed - its scope has ended (V4, review). bool IsDisposed { get; } /// /// Connection string used for this connection. /// string ConnectionString { get; } /// /// Currently active transaction (null if no transaction). /// All operations automatically use this transaction. /// IRedbTransaction? CurrentTransaction { get; } /// /// Whether any transaction is active — explicit (CurrentTransaction) or ambient (TransactionScope). /// Use this instead of checking CurrentTransaction directly. /// EF Core pattern: checks both CurrentTransaction and Transaction.Current. /// bool IsInTransaction { get; } /// /// Get underlying DbConnection for advanced operations (e.g., COPY protocol). /// This ensures all operations use the same connection and transaction. /// Task GetUnderlyingConnectionAsync(CancellationToken cancellationToken = default); /// /// Lends the connection this redb connection works on for the caller's own commands, in the transaction /// redb's commands run in: redb's explicit transaction (, /// ), else the ambient /// (its one connection per database), else no transaction. /// Build the commands with : it binds the transaction the /// driver requires (SQLite always, SQL Server in an explicit transaction). /// /// The lease enters the same command gates a redb command enters, so it is one command's hold: release it /// with await using as soon as the commands are done. While it is held, redb on this connection or in /// the same ambient transaction is refused at once. What the holder must never do is listed on /// . /// /// /// The lease is on this connection only, so on the connection of the redb service the caller resolved. A named /// redb service has a connection of its own; an explicit transaction belongs to the DI scope that began it, and a /// connection of another scope lends its own connection outside that transaction. Inside a /// every scope of the same database lends the scope's /// connection. /// /// /// For a long-lived owner of the connection (EF Core, PostgreSQL COPY, SqlBulkCopy) use /// instead: it holds no gate, so its work and redb's must run /// strictly one after the other. /// /// /// The default body throws : a connection outside the redb providers /// has to lend its connection itself. /// /// /// Cancels opening the connection. Task LeaseAsync(CancellationToken cancellationToken = default) => throw new NotSupportedException( $"{GetType().FullName} does not lend its connection: implement IRedbConnection.LeaseAsync."); // === QUERY METHODS === /// /// Execute SQL query and return list of mapped objects. /// /// Result type (must have parameterless constructor). /// SQL query with parameters ($1, $2, etc.). /// Query parameters. /// List of mapped objects. Task> QueryAsync(string sql, params object[] parameters) where T : new(); /// Cancellable form: parameters as an explicit array (params cannot precede ct). Task> QueryAsync(string sql, object[] parameters, CancellationToken cancellationToken) where T : new(); /// /// Execute SQL query and return first result or null. /// /// Result type. /// SQL query with parameters. /// Query parameters. /// First result or null. Task QueryFirstOrDefaultAsync(string sql, params object[] parameters) where T : class, new(); /// Cancellable form. Task QueryFirstOrDefaultAsync(string sql, object[] parameters, CancellationToken cancellationToken) where T : class, new(); /// /// Execute SQL query and return scalar value. /// /// Scalar type. /// SQL query with parameters. /// Query parameters. /// Scalar value or default. Task ExecuteScalarAsync(string sql, params object[] parameters); /// Cancellable form. Task ExecuteScalarAsync(string sql, object[] parameters, CancellationToken cancellationToken); // === SYNCHRONOUS COUNTERPARTS (thread-pool-free lazy path) === // The sync getter of RedbListItem.Object must reach the database without a single // thread-pool continuation: on a saturated pool a blocked thread waiting for pool-scheduled // continuations degrades (or, pre-2026-09 fixes, deadlocks). These run the whole call on // the calling thread down to ADO.NET. The defaults fall back to blocking on the async // form, so third-party implementations keep compiling - but the fallback is pool-coupled; // the in-tree providers override with true sync ADO calls. /// Synchronous : runs on the calling thread down to ADO.NET. T? QueryFirstOrDefault(string sql, params object[] parameters) where T : class, new() => QueryFirstOrDefaultAsync(sql, parameters).ConfigureAwait(false).GetAwaiter().GetResult(); /// Synchronous : runs on the calling thread down to ADO.NET. T? ExecuteScalar(string sql, params object[] parameters) => ExecuteScalarAsync(sql, parameters).ConfigureAwait(false).GetAwaiter().GetResult(); /// Synchronous : runs on the calling thread down to ADO.NET. string? ExecuteJson(string sql, params object[] parameters) => ExecuteJsonAsync(sql, parameters).ConfigureAwait(false).GetAwaiter().GetResult(); /// Synchronous : runs on the calling thread down to ADO.NET. List Query(string sql, params object[] parameters) where T : new() => QueryAsync(sql, parameters).ConfigureAwait(false).GetAwaiter().GetResult(); /// Synchronous : runs on the calling thread down to ADO.NET. int Execute(string sql, params object[] parameters) => ExecuteAsync(sql, parameters).ConfigureAwait(false).GetAwaiter().GetResult(); /// /// Execute SQL query and return list of scalar values (first column only). /// Use for simple queries like SELECT _id FROM ... that return single column. /// /// Scalar type (long, int, string, etc.). /// SQL query with parameters. /// Query parameters. /// List of scalar values. Task> QueryScalarListAsync(string sql, params object[] parameters); /// Cancellable form. Task> QueryScalarListAsync(string sql, object[] parameters, CancellationToken cancellationToken); /// /// Execute SQL command (INSERT, UPDATE, DELETE) and return affected rows count. /// /// SQL command with parameters. /// Command parameters. /// Number of affected rows. Task ExecuteAsync(string sql, params object[] parameters); /// Cancellable form. Task ExecuteAsync(string sql, object[] parameters, CancellationToken cancellationToken); // === TRANSACTION METHODS === /// /// Begin new transaction. /// Sets CurrentTransaction property. /// All subsequent operations will use this transaction. /// /// Transaction object. /// /// BR-1 (owner decision 2026-09-02): optional isolation level for THIS transaction. Null keeps /// each provider's default, exactly as before. PostgreSQL/MSSQL apply it to the opened /// transaction; SQLite accepts it for portability and stays a single serial writer. Under /// elevated levels the database may abort the loser (PG 40001, MSSQL 3960): retry the WHOLE /// transaction - see DbErrorClassifier.IsSerializationFailure. /// Task BeginTransactionAsync(System.Data.IsolationLevel? isolationLevel = null, CancellationToken cancellationToken = default); // === ATOMIC OPERATIONS (SaveChanges replacement) === /// /// Execute multiple operations atomically (all-or-nothing). /// If no transaction is active, creates one automatically. /// Ensures atomicity like EF SaveChanges(). /// /// Operations to execute atomically. /// Cancels the operation; see the cancellation contract in the plan (OCE only, rollback always completes). Task ExecuteAtomicAsync(Func operations, CancellationToken cancellationToken = default); /// /// Atomic execution under an explicit isolation level (BR-1). An active or ambient transaction /// wins: operations join it and its level is NOT changed. /// Task ExecuteAtomicAsync(System.Data.IsolationLevel isolationLevel, Func operations, CancellationToken cancellationToken = default); /// /// Execute multiple operations atomically and return result. /// If no transaction is active, creates one automatically. /// /// Result type. /// Operations to execute atomically. /// Operation result. /// Cancels the operation; see the cancellation contract in the plan (OCE only, rollback always completes). Task ExecuteAtomicAsync(Func> operations, CancellationToken cancellationToken = default); /// Result-returning form of the isolation-level overload (BR-1). Task ExecuteAtomicAsync(System.Data.IsolationLevel isolationLevel, Func> operations, CancellationToken cancellationToken = default); // === RAW SQL === /// /// Execute raw SQL function returning JSON. /// Commonly used for PostgreSQL functions like get_object_json(). /// /// SQL query returning JSON. /// Query parameters. /// JSON string or null. Task ExecuteJsonAsync(string sql, params object[] parameters); /// Cancellable form. Task ExecuteJsonAsync(string sql, object[] parameters, CancellationToken cancellationToken); /// /// Execute raw SQL function returning multiple JSON rows. /// /// SQL query returning JSON rows. /// Query parameters. /// List of JSON strings. Task> ExecuteJsonListAsync(string sql, params object[] parameters); /// Cancellable form. Task> ExecuteJsonListAsync(string sql, object[] parameters, CancellationToken cancellationToken); } } Path: redb/redb.Core/Data/IRedbContext.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/Data/IRedbContext.cs ---- using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace redb.Core.Data { /// /// Main database context interface for REDB. /// Facade over connection, key generator, and bulk operations. /// Replaces EF Core DbContext. /// public interface IRedbContext : IAsyncDisposable, IDisposable { /// True once the context has been disposed - the scope that owned it has ended (V4, review). bool IsDisposed { get; } // === COMPONENTS === /// /// Database connection for queries and commands. /// IRedbConnection Db { get; } /// /// Key generator with caching. /// IKeyGenerator Keys { get; } /// /// Bulk operations (COPY protocol). /// IBulkOperations Bulk { get; } // === CONNECTION SHORTCUTS === /// /// Execute SQL query and return list of mapped objects. /// Task> QueryAsync(string sql, params object[] parameters) where T : new(); /// Cancellable form: parameters as an explicit array (params cannot precede ct). Task> QueryAsync(string sql, object[] parameters, CancellationToken cancellationToken) where T : new(); /// /// Execute SQL query and return first result or null. /// Task QueryFirstOrDefaultAsync(string sql, params object[] parameters) where T : class, new(); /// Cancellable form. Task QueryFirstOrDefaultAsync(string sql, object[] parameters, CancellationToken cancellationToken) where T : class, new(); /// /// Execute SQL query and return scalar value. /// Task ExecuteScalarAsync(string sql, params object[] parameters); /// Cancellable form. Task ExecuteScalarAsync(string sql, object[] parameters, CancellationToken cancellationToken); // === SYNCHRONOUS COUNTERPARTS (thread-pool-free lazy path) === // See IRedbConnection: these forward to the connection, which runs the call on the // calling thread down to ADO.NET (no thread-pool continuations). Used by the sync // getter of RedbListItem.Object. /// Synchronous on the calling thread. T? QueryFirstOrDefault(string sql, params object[] parameters) where T : class, new() => Db.QueryFirstOrDefault(sql, parameters); /// Synchronous on the calling thread. T? ExecuteScalar(string sql, params object[] parameters) => Db.ExecuteScalar(sql, parameters); /// Synchronous on the calling thread. string? ExecuteJson(string sql, params object[] parameters) => Db.ExecuteJson(sql, parameters); /// Synchronous on the calling thread. List Query(string sql, params object[] parameters) where T : new() => Db.Query(sql, parameters); /// Synchronous on the calling thread. int Execute(string sql, params object[] parameters) => Db.Execute(sql, parameters); /// /// Execute SQL query and return list of scalar values (first column only). /// Task> QueryScalarListAsync(string sql, params object[] parameters); /// Cancellable form. Task> QueryScalarListAsync(string sql, object[] parameters, CancellationToken cancellationToken); /// /// Execute SQL command (INSERT, UPDATE, DELETE). /// Task ExecuteAsync(string sql, params object[] parameters); /// Cancellable form. Task ExecuteAsync(string sql, object[] parameters, CancellationToken cancellationToken); /// /// Execute SQL returning JSON. /// Task ExecuteJsonAsync(string sql, params object[] parameters); /// Cancellable form. Task ExecuteJsonAsync(string sql, object[] parameters, CancellationToken cancellationToken); /// /// Execute SQL returning multiple JSON rows. /// Task> ExecuteJsonListAsync(string sql, params object[] parameters); /// Cancellable form. Task> ExecuteJsonListAsync(string sql, object[] parameters, CancellationToken cancellationToken); /// /// The rows of as a JSON array of objects keyed by column name, NULL values included; /// "[]" when there are none. For statements whose columns are known only at run time (analytics of a provider /// without row_to_json); one command, as every other method here. /// Task QueryRowsAsJsonAsync(string sql, object[] parameters, CancellationToken cancellationToken = default); // === TRANSACTION SHORTCUTS === /// /// Current active transaction (null if none). /// IRedbTransaction? CurrentTransaction { get; } /// /// Whether any transaction is active — explicit (CurrentTransaction) or ambient (TransactionScope). /// EF Core pattern: checks both CurrentTransaction and Transaction.Current. /// bool IsInTransaction { get; } /// /// Begin new transaction. /// /// /// BR-1 (owner decision 2026-09-02): optional isolation level for THIS transaction. Null keeps /// each provider's default, exactly as before. PostgreSQL/MSSQL apply it to the opened /// transaction; SQLite accepts it for portability and stays a single serial writer. Under /// elevated levels the database may abort the loser (PG 40001, MSSQL 3960): retry the WHOLE /// transaction - see DbErrorClassifier.IsSerializationFailure. /// Task BeginTransactionAsync(System.Data.IsolationLevel? isolationLevel = null, CancellationToken cancellationToken = default); /// /// Execute operations atomically (all-or-nothing). /// Like EF SaveChanges() but explicit. /// Task ExecuteAtomicAsync(Func operations, CancellationToken cancellationToken = default); /// /// Atomic execution under an explicit isolation level (BR-1). An active or ambient transaction /// wins: operations join it and its level is NOT changed. /// Task ExecuteAtomicAsync(System.Data.IsolationLevel isolationLevel, Func operations, CancellationToken cancellationToken = default); /// /// Execute operations atomically and return result. /// Task ExecuteAtomicAsync(Func> operations, CancellationToken cancellationToken = default); /// Result-returning form of the isolation-level overload (BR-1). Task ExecuteAtomicAsync(System.Data.IsolationLevel isolationLevel, Func> operations, CancellationToken cancellationToken = default); // === KEY GENERATION SHORTCUTS === /// /// Get next object ID. /// Task NextObjectIdAsync(CancellationToken cancellationToken = default); /// /// Get next value ID. /// Task NextValueIdAsync(CancellationToken cancellationToken = default); /// /// Get batch of object IDs. /// Task NextObjectIdBatchAsync(int count, CancellationToken cancellationToken = default); /// /// Get batch of value IDs. /// Task NextValueIdBatchAsync(int count, CancellationToken cancellationToken = default); } } Path: redb/redb.Core/Data/IRedbTransaction.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/Data/IRedbTransaction.cs ---- using System; using System.Threading.Tasks; namespace redb.Core.Data { /// /// Database transaction abstraction for REDB. /// Connection-scoped: all operations through parent connection /// automatically participate in this transaction. /// public interface IRedbTransaction : IAsyncDisposable { /// /// Transaction unique identifier (for diagnostics). /// Guid TransactionId { get; } /// /// Whether transaction is still active (not committed or rolled back). /// bool IsActive { get; } /// /// Transaction start time. /// DateTimeOffset StartedAt { get; } /// /// Commit all changes in transaction. /// After commit, transaction becomes inactive. /// Task CommitAsync(); /// /// Rollback all changes in transaction. /// After rollback, transaction becomes inactive. /// Task RollbackAsync(); } } Path: redb/redb.Core/Data/ModuleCompatibility.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/Data/ModuleCompatibility.cs ---- namespace redb.Core.Data; /// /// The rule of a database module newer than the package: never replaced, used when it serves the package. Shared by /// the module check of PostgreSQL and SQL Server (versions such as "0.7.24", the compatibility function's /// "<oldest module served>|<package version>") and the file check of SQLite (whole numbers). /// public static class ModuleCompatibility { /// /// Whether is a newer version than . A version that does not /// read as numbers (a hand-set marker such as "0.0.0-test" reads as 0.0.0, anything else not at all) is not newer: /// such a module is replaced as an older one is. /// public static bool IsNewer(string? deployed, string required) => TryParse(deployed, out var d) && TryParse(required, out var r) && d > r; /// /// Whether a module that reports (the value of its compatibility function, null when it /// has none) serves a package whose own module is : the first part of the value is not /// above it. Also returns the package version the module names, null when it names none. /// public static bool Serves(string? compat, string required, out string? fromPackage) { fromPackage = null; if (string.IsNullOrWhiteSpace(compat)) return false; var parts = compat.Split('|'); if (parts.Length == 2 && !string.IsNullOrWhiteSpace(parts[1])) fromPackage = parts[1].Trim(); return TryParse(parts[0], out var oldest) && TryParse(required, out var own) && oldest <= own; } private static bool TryParse(string? text, out Version version) { version = new Version(0, 0); if (string.IsNullOrWhiteSpace(text)) return false; var dash = text.IndexOf('-'); var core = (dash >= 0 ? text[..dash] : text).Trim(); if (!Version.TryParse(core, out var parsed)) return false; version = parsed; return true; } } Path: redb/redb.Core/Data/RedbConnectionLease.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/Data/RedbConnectionLease.cs ---- using System; using System.Data; using System.Data.Common; using System.Threading; using System.Threading.Tasks; namespace redb.Core.Data { /// /// The connection a redb connection works on, lent for the caller's own commands: the open connection, the /// transaction the commands must run in, and a command factory bound to both. Taken by /// , given back by . /// /// The connection and the transaction stay redb's (or the ambient transaction's). While the lease is held the /// holder must never: commit, roll back or dispose the transaction, or begin one of its own; close, dispose or /// reopen the connection, or change its database; change session settings (SET, PRAGMA, isolation level); /// leave a data reader open past the release; call redb on the same connection or in the same ambient /// transaction (the call is refused at once); swallow a failure of its own command and go on with the /// transaction (on PostgreSQL a failed command aborts the transaction for every later command). /// /// public sealed class RedbConnectionLease : IAsyncDisposable { private const string NotOpenMessage = "The connection of a redb lease was not open when the lease was released: the holder closed it, or it " + "broke under the holder's command. The connection belongs to redb or to the ambient transaction; the " + "holder must not close, dispose or reopen it."; private readonly Action _release; private int _released; /// /// A lease over . gives the connection back (leaves /// the command gates the lease entered); it runs once and must not close the connection. /// /// The open connection the commands run on. /// The transaction the commands must be bound to, or null when the driver runs /// them in the connection's transaction by itself (an enlisted connection, or no transaction). /// Gives the connection back; called once by . public RedbConnectionLease(DbConnection connection, DbTransaction? transaction, Action release) { Connection = connection ?? throw new ArgumentNullException(nameof(connection)); Transaction = transaction; _release = release ?? throw new ArgumentNullException(nameof(release)); } /// The open connection. Not the holder's: never close, dispose or reopen it. public DbConnection Connection { get; } /// /// The transaction every command of the holder must be bound to: redb's explicit transaction, or on SQLite /// inside a the transaction redb runs on the scope's /// connection. Null when the connection was enlisted in the ambient transaction by its driver (PostgreSQL, /// SQL Server) or when no transaction is active: commands then need none. /// binds it already. /// public DbTransaction? Transaction { get; } /// A command on , bound to . The holder disposes it. public DbCommand CreateCommand() { if (Volatile.Read(ref _released) != 0) throw new ObjectDisposedException(nameof(RedbConnectionLease), "The lease was already released."); var command = Connection.CreateCommand(); command.Transaction = Transaction; return command; } /// /// Gives the connection back. The second call does nothing. Throws /// after the release when the connection is no longer open: the holder closed it, or it broke. /// public ValueTask DisposeAsync() { if (Interlocked.Exchange(ref _released, 1) != 0) return default; var open = Connection.State == ConnectionState.Open; _release(); if (!open) throw new InvalidOperationException(NotOpenMessage); return default; } } } Path: redb/redb.Core/Data/RedbContextBase.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/Data/RedbContextBase.cs ---- using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using redb.Core.Diagnostics; namespace redb.Core.Data { /// /// Base class for REDB context. /// Provides common logic and shortcuts. /// DB-specific implementations inherit from this. /// public abstract class RedbContextBase : IRedbContext { // === ABSTRACT COMPONENTS (set by derived class) === /// /// Database connection. /// public abstract IRedbConnection Db { get; } /// public bool IsDisposed => Db.IsDisposed; /// /// Key generator. /// public abstract IKeyGenerator Keys { get; } /// /// Bulk operations. /// // Reached to write (COPY protocol): the transaction has written. public IBulkOperations Bulk { get { TransactionWrites.Mark(this); return BulkOperations; } } /// The provider's bulk operations. protected abstract IBulkOperations BulkOperations { get; } /// /// How long one bulk load of may run (SqlBulkCopy on SQL Server, binary COPY on /// PostgreSQL); null keeps the driver's value, means no limit. SQLite has no /// bulk protocol and ignores it. The registrations of the providers set it from /// . /// public TimeSpan? BulkInsertTimeout { get; set; } // === CONNECTION SHORTCUTS === // // Every command runs inside a telemetry span on RedbActivitySource (see RedbTelemetry), so the time // an ORM call spends in the database is a span of its own rather than an empty gap - including when // the call comes from a bean inside a route. With no OpenTelemetry subscriber the source has no // listeners and the connection is called directly: no span and no extra allocation. /// /// Execute SQL query and return list of mapped objects. /// public Task> QueryAsync(string sql, params object[] parameters) where T : new() => RedbTelemetry.Enabled ? RedbTelemetry.RunAsync(RedbTelemetry.Query, () => Db.QueryAsync(sql, parameters)) : Db.QueryAsync(sql, parameters); /// public Task> QueryAsync(string sql, object[] parameters, CancellationToken cancellationToken) where T : new() => RedbTelemetry.Enabled ? RedbTelemetry.RunAsync(RedbTelemetry.Query, () => Db.QueryAsync(sql, parameters, cancellationToken)) : Db.QueryAsync(sql, parameters, cancellationToken); /// /// Execute SQL query and return first result or null. /// public Task QueryFirstOrDefaultAsync(string sql, params object[] parameters) where T : class, new() => RedbTelemetry.Enabled ? RedbTelemetry.RunAsync(RedbTelemetry.Query, () => Db.QueryFirstOrDefaultAsync(sql, parameters)) : Db.QueryFirstOrDefaultAsync(sql, parameters); /// public Task QueryFirstOrDefaultAsync(string sql, object[] parameters, CancellationToken cancellationToken) where T : class, new() => RedbTelemetry.Enabled ? RedbTelemetry.RunAsync(RedbTelemetry.Query, () => Db.QueryFirstOrDefaultAsync(sql, parameters, cancellationToken)) : Db.QueryFirstOrDefaultAsync(sql, parameters, cancellationToken); /// /// Execute SQL query and return scalar value. /// public Task ExecuteScalarAsync(string sql, params object[] parameters) => RedbTelemetry.Enabled ? RedbTelemetry.RunAsync(RedbTelemetry.Scalar, () => Db.ExecuteScalarAsync(sql, parameters)) : Db.ExecuteScalarAsync(sql, parameters); /// public Task ExecuteScalarAsync(string sql, object[] parameters, CancellationToken cancellationToken) => RedbTelemetry.Enabled ? RedbTelemetry.RunAsync(RedbTelemetry.Scalar, () => Db.ExecuteScalarAsync(sql, parameters, cancellationToken)) : Db.ExecuteScalarAsync(sql, parameters, cancellationToken); /// /// Execute SQL query and return list of scalar values (first column only). /// public Task> QueryScalarListAsync(string sql, params object[] parameters) => RedbTelemetry.Enabled ? RedbTelemetry.RunAsync(RedbTelemetry.Query, () => Db.QueryScalarListAsync(sql, parameters)) : Db.QueryScalarListAsync(sql, parameters); /// public Task> QueryScalarListAsync(string sql, object[] parameters, CancellationToken cancellationToken) => RedbTelemetry.Enabled ? RedbTelemetry.RunAsync(RedbTelemetry.Query, () => Db.QueryScalarListAsync(sql, parameters, cancellationToken)) : Db.QueryScalarListAsync(sql, parameters, cancellationToken); /// /// Execute SQL command (INSERT, UPDATE, DELETE). /// public Task ExecuteAsync(string sql, params object[] parameters) { TransactionWrites.Mark(this); return RedbTelemetry.Enabled ? RedbTelemetry.RunAsync(RedbTelemetry.Execute, () => Db.ExecuteAsync(sql, parameters)) : Db.ExecuteAsync(sql, parameters); } /// public Task ExecuteAsync(string sql, object[] parameters, CancellationToken cancellationToken) { TransactionWrites.Mark(this); return RedbTelemetry.Enabled ? RedbTelemetry.RunAsync(RedbTelemetry.Execute, () => Db.ExecuteAsync(sql, parameters, cancellationToken)) : Db.ExecuteAsync(sql, parameters, cancellationToken); } /// /// Execute SQL returning JSON. /// public Task ExecuteJsonAsync(string sql, params object[] parameters) => RedbTelemetry.Enabled ? RedbTelemetry.RunAsync(RedbTelemetry.Json, () => Db.ExecuteJsonAsync(sql, parameters)) : Db.ExecuteJsonAsync(sql, parameters); /// public Task ExecuteJsonAsync(string sql, object[] parameters, CancellationToken cancellationToken) => RedbTelemetry.Enabled ? RedbTelemetry.RunAsync(RedbTelemetry.Json, () => Db.ExecuteJsonAsync(sql, parameters, cancellationToken)) : Db.ExecuteJsonAsync(sql, parameters, cancellationToken); /// /// Execute SQL returning multiple JSON rows. /// public Task> ExecuteJsonListAsync(string sql, params object[] parameters) => RedbTelemetry.Enabled ? RedbTelemetry.RunAsync(RedbTelemetry.Json, () => Db.ExecuteJsonListAsync(sql, parameters)) : Db.ExecuteJsonListAsync(sql, parameters); /// public Task> ExecuteJsonListAsync(string sql, object[] parameters, CancellationToken cancellationToken) => RedbTelemetry.Enabled ? RedbTelemetry.RunAsync(RedbTelemetry.Json, () => Db.ExecuteJsonListAsync(sql, parameters, cancellationToken)) : Db.ExecuteJsonListAsync(sql, parameters, cancellationToken); /// public Task QueryRowsAsJsonAsync(string sql, object[] parameters, CancellationToken cancellationToken = default) => RedbTelemetry.Enabled ? RedbTelemetry.RunAsync(RedbTelemetry.Json, () => QueryRowsAsJsonCoreAsync(sql, parameters, cancellationToken)) : QueryRowsAsJsonCoreAsync(sql, parameters, cancellationToken); /// /// The provider's row-to-JSON read behind , run on : every /// row of as an object keyed by column name, NULL values included; "[]" for none. /// protected abstract Task QueryRowsAsJsonCoreAsync(string sql, object[] parameters, CancellationToken cancellationToken); // === TRANSACTION SHORTCUTS === /// /// Current active transaction. /// public IRedbTransaction? CurrentTransaction => Db.CurrentTransaction; /// /// Whether any transaction is active — explicit or ambient TransactionScope. /// public bool IsInTransaction => Db.IsInTransaction; /// /// Begin new transaction. /// public Task BeginTransactionAsync(System.Data.IsolationLevel? isolationLevel = null, CancellationToken cancellationToken = default) => Db.BeginTransactionAsync(isolationLevel, cancellationToken); /// /// Execute operations atomically. /// public Task ExecuteAtomicAsync(Func operations, CancellationToken cancellationToken = default) => Db.ExecuteAtomicAsync(operations, cancellationToken); /// /// Execute operations atomically and return result. /// public Task ExecuteAtomicAsync(Func> operations, CancellationToken cancellationToken = default) => Db.ExecuteAtomicAsync(operations, cancellationToken); /// public Task ExecuteAtomicAsync(System.Data.IsolationLevel isolationLevel, Func operations, CancellationToken cancellationToken = default) => Db.ExecuteAtomicAsync(isolationLevel, operations, cancellationToken); /// public Task ExecuteAtomicAsync(System.Data.IsolationLevel isolationLevel, Func> operations, CancellationToken cancellationToken = default) => Db.ExecuteAtomicAsync(isolationLevel, operations, cancellationToken); // === KEY GENERATION SHORTCUTS === /// /// Get next object ID. /// public Task NextObjectIdAsync(CancellationToken cancellationToken = default) => Keys.NextObjectIdAsync(cancellationToken); /// /// Get next value ID. /// public Task NextValueIdAsync(CancellationToken cancellationToken = default) => Keys.NextValueIdAsync(cancellationToken); /// /// Get batch of object IDs. /// public Task NextObjectIdBatchAsync(int count, CancellationToken cancellationToken = default) => Keys.NextObjectIdBatchAsync(count, cancellationToken); /// /// Get batch of value IDs. /// public Task NextValueIdBatchAsync(int count, CancellationToken cancellationToken = default) => Keys.NextValueIdBatchAsync(count, cancellationToken); // === DISPOSE === /// /// Dispose context and all components asynchronously. /// public virtual async ValueTask DisposeAsync() { await Db.DisposeAsync(); } /// /// Dispose context and all components synchronously. /// Required for DI container compatibility. /// public virtual void Dispose() { // Synchronous dispose - call async version and wait Db.DisposeAsync().AsTask().GetAwaiter().GetResult(); } } } Path: redb/redb.Core/Data/RedbKeyGeneratorBase.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/Data/RedbKeyGeneratorBase.cs ---- using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace redb.Core.Data { /// /// Domain-isolated key cache data. /// internal class KeyCacheDomain { public readonly ConcurrentQueue Keys = new(); public readonly SemaphoreSlim Lock = new(1, 1); public volatile bool IsRefilling = false; // The highest id this process has handed out for the domain, whatever the outcome of the transaction that // took it. A provider whose sequence rolls back with the caller's transaction (SQLite) never hands out an id // at or below it again. public long IssuedHighWater; } /// /// Base class for key generation with domain-isolated caching. /// Each domain (typically one per database connection) has isolated cache. /// Instance is bound to specific domain, static data is shared. /// public abstract class RedbKeyGeneratorBase : IKeyGenerator { // === STATIC: shared data across all instances, isolated by domain === private static readonly ConcurrentDictionary _domains = new(); private static int _cacheSize = 10000; private const double REFILL_THRESHOLD = 0.1; // 10% of cache size // === INSTANCE: domain binding === private readonly string _domain; /// /// Cache domain this instance is bound to. /// public string Domain => _domain; protected RedbKeyGeneratorBase(string? domain = null) { _domain = domain ?? "default"; } private KeyCacheDomain GetCache() => _domains.GetOrAdd(_domain, _ => new KeyCacheDomain()); // === ABSTRACT METHODS (DB-specific) === /// /// Generate batch of keys from database sequence. /// Only batch generation - no single key methods! /// protected abstract Task> GenerateKeysAsync(int count); /// /// Provider hook for a refill that must not use a SEPARATE connection, bypassing the shared cache: /// /// SQLite single-writer trap: when the calling scope already holds a write transaction /// (BEGIN IMMEDIATE), a refill on another connection waits for the file's only write lock while /// the lock holder waits for the refill. Keys come from the scope's transaction instead; a /// rollback takes the sequence bump back, while the application may still hold the ids, so the /// provider takes every later range above . /// MSSQL and PostgreSQL inside a TransactionScope: another connection would be a second /// connection in the transaction (a distributed transaction). Keys come through the scope's /// wrapper on the transaction's connection; sequences are not transactional, so a rollback leaves /// a gap, never a duplicate. /// /// Default: null - the refill uses its own connection. /// protected virtual Task?> TryGenerateKeysInAmbientTransactionAsync(int count) => Task.FromResult?>(null); /// /// The highest id this process has handed out for this domain (), 0 before the first. /// A provider whose sequence bump can roll back with the caller's transaction takes every next range above it: /// an id a rolled-back transaction handed out may still be held by the application, and a second owner of the /// same id would overwrite the first one's row. /// protected long IssuedHighWater => Interlocked.Read(ref GetCache().IssuedHighWater); /// Raises to , the highest id of a range just handed out. protected void RecordIssued(long top) { var cache = GetCache(); var current = Interlocked.Read(ref cache.IssuedHighWater); while (top > current) { var seen = Interlocked.CompareExchange(ref cache.IssuedHighWater, top, current); if (seen == current) return; current = seen; } } // === PUBLIC API === /// /// Get next object ID (uses shared static cache). /// // ct is honoured at the entry only: the refill below feeds a SHARED static cache, and a // caller's token must not abort a refill other callers are waiting on. The refill query // itself is a single short statement. public async Task NextObjectIdAsync(CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); return await GetNextKeyAsync(); } /// /// Get next value ID (uses shared static cache). /// public async Task NextValueIdAsync(CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); return await GetNextKeyAsync(); } /// /// Get batch of object IDs. /// public async Task NextObjectIdBatchAsync(int count, CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); return await GetNextKeyBatchAsync(count); } /// /// Get batch of value IDs. /// public async Task NextValueIdBatchAsync(int count, CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); return await GetNextKeyBatchAsync(count); } // === CORE CACHE LOGIC === private async Task GetNextKeyAsync() { var cache = GetCache(); // Try to get from cache if (cache.Keys.TryDequeue(out long key)) { // Check if background refill needed (< threshold) int currentCount = cache.Keys.Count; int threshold = (int)(_cacheSize * REFILL_THRESHOLD); if (currentCount <= threshold && !cache.IsRefilling) { // Fire-and-forget: background thread with separate connection StartBackgroundRefill(); } return key; } // Cache empty. If this scope sits inside its own write transaction, a refill on a // separate connection would self-deadlock (SQLite single writer) - take the key // through the ambient transaction instead, bypassing the shared cache. var ambient = await TryGenerateKeysInAmbientTransactionAsync(1); if (ambient is { Count: > 0 }) return ambient[0]; // Cache empty - WAIT until fully refilled await RefillCacheBlockingAsync(); // Must have keys now cache.Keys.TryDequeue(out key); return key; } private async Task GetNextKeyBatchAsync(int count) { if (count <= 0) return Array.Empty(); var cache = GetCache(); var result = new long[count]; int collected = 0; while (collected < count) { // Try to get from cache if (cache.Keys.TryDequeue(out long key)) { result[collected++] = key; // Check if background refill needed int currentCount = cache.Keys.Count; int threshold = (int)(_cacheSize * REFILL_THRESHOLD); if (currentCount <= threshold && !cache.IsRefilling) { StartBackgroundRefill(); } } else { // Same single-writer trap as in GetNextKeyAsync: inside the scope's own // transaction the remainder comes through it, bypassing the shared cache. var ambient = await TryGenerateKeysInAmbientTransactionAsync(count - collected); if (ambient is { Count: > 0 }) { foreach (var ambientKey in ambient) result[collected++] = ambientKey; continue; } // Cache empty - wait for refill await RefillCacheBlockingAsync(); } } return result; } // === CACHE REFILL === /// /// Starts the background refill WITHOUT the caller's ExecutionContext. An ambient TransactionScope of the /// caller would otherwise flow into it: the refill would open its connection inside the caller's /// transaction (a second connection - a distributed transaction) or after that scope completed. /// private void StartBackgroundRefill() { using (System.Threading.ExecutionContext.SuppressFlow()) { _ = Task.Run(async () => await RefillCacheBackgroundAsync()); } } /// /// Background refill - runs in separate thread with separate DB connection. /// Called when cache is below threshold but not empty. /// private async Task RefillCacheBackgroundAsync() { var cache = GetCache(); // Non-blocking check if (cache.IsRefilling) return; if (!await cache.Lock.WaitAsync(0)) return; try { cache.IsRefilling = true; int currentCount = cache.Keys.Count; int keysToGenerate = _cacheSize - currentCount; if (keysToGenerate <= 0) return; // Separate DB connection in background thread var keys = await GenerateKeysAsync(keysToGenerate); foreach (var newKey in keys) { cache.Keys.Enqueue(newKey); } } finally { cache.IsRefilling = false; cache.Lock.Release(); } } /// /// Blocking refill - waits until cache is fully filled. /// Called when cache is EMPTY - must wait for keys. /// private async Task RefillCacheBlockingAsync() { var cache = GetCache(); // Wait for semaphore (blocks until we can refill) await cache.Lock.WaitAsync(); try { // Double-check if another thread filled while we waited if (cache.Keys.Count > 0) return; cache.IsRefilling = true; // Generate full batch var keys = await GenerateKeysAsync(_cacheSize); foreach (var newKey in keys) { cache.Keys.Enqueue(newKey); } } finally { cache.IsRefilling = false; cache.Lock.Release(); } } // === CONFIGURATION === /// /// Set cache size (default 10000). /// public static void SetCacheSize(int size) { _cacheSize = size; } /// /// Clear cache for this domain. /// public void ClearCache() { var cache = GetCache(); while (cache.Keys.TryDequeue(out _)) { } } /// /// Clear cache for all domains (for testing/reset). /// public static void ClearAllCaches() { foreach (var domain in _domains.Values) { while (domain.Keys.TryDequeue(out _)) { } } } } } Path: redb/redb.Core/Data/RedbRowMapping.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/Data/RedbRowMapping.cs ---- using System; using System.Collections.Generic; using System.Data; using System.Linq.Expressions; using System.Reflection; using System.Text.Json.Serialization; namespace redb.Core.Data { /// /// What the row mappers of the providers (RedbRowMapper, SqlRowMapper) know about a type, built once per type: /// which column names reach which property, and a compiled setter per property. Each provider keeps its own /// conversions; this only replaces the per-cell work around them. A page of 100 objects of 86 values each read /// 8 600 rows of 15 columns, and per cell the mapper looked the column name up again, and set the property by /// reflection: about 50 of the 98 ms of the page. /// /// /// Immutable once built (static readonly, initialised by the type initializer): safe to share between threads. /// Nothing is keyed by SQL text: the columns are bound to properties once per result set by . /// internal static class RedbRowMapping { /// /// Column name -> property, case-insensitive, the rules of the mappers as they were: for every writable public /// instance property its JsonPropertyName (or snake_case name), the same with a leading underscore, the /// property name, its lowercase form, and the lowercase form with a leading underscore. A later property /// claiming a name already taken replaces the earlier one, as the dictionary assignment did before. /// public static readonly Dictionary PropertyMap = BuildMap(); private static readonly Dictionary Slots = BuildSlots(); /// The property of each column of by ordinal, null where no property takes it. public static Slot?[] Bind(IDataRecord record) { var slots = new Slot?[record.FieldCount]; for (var i = 0; i < slots.Length; i++) if (PropertyMap.TryGetValue(record.GetName(i), out var property)) slots[i] = Slots[property]; return slots; } private static Dictionary BuildMap() { var map = new Dictionary(StringComparer.OrdinalIgnoreCase); foreach (var prop in typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance)) { if (!prop.CanWrite) continue; var jsonName = prop.GetCustomAttribute()?.Name ?? ToSnakeCase(prop.Name); map[jsonName] = prop; map["_" + jsonName] = prop; map[prop.Name] = prop; map[prop.Name.ToLowerInvariant()] = prop; map["_" + prop.Name.ToLowerInvariant()] = prop; } return map; } private static Dictionary BuildSlots() { var slots = new Dictionary(); foreach (var property in PropertyMap.Values) if (!slots.ContainsKey(property)) slots[property] = new Slot(property, CompileSetter(property)); return slots; } /// /// (obj, value) => obj.Property = (PropertyType)value, or null where that cannot be compiled (an indexer, a /// setter the compiler refuses): such a property keeps the reflection setter. /// private static Action? CompileSetter(PropertyInfo property) { var setter = property.GetSetMethod(nonPublic: true); if (setter == null || property.GetIndexParameters().Length > 0 || typeof(T).IsValueType) return null; try { var obj = Expression.Parameter(typeof(T), "obj"); var value = Expression.Parameter(typeof(object), "value"); var call = Expression.Call(obj, setter, Expression.Convert(value, property.PropertyType)); return Expression.Lambda>(call, obj, value).Compile(); } catch (Exception ex) when (ex is ArgumentException or InvalidOperationException or NotSupportedException) { return null; } } private static string ToSnakeCase(string pascalCase) { if (string.IsNullOrEmpty(pascalCase)) return pascalCase; var result = new System.Text.StringBuilder(); for (var i = 0; i < pascalCase.Length; i++) { var c = pascalCase[i]; if (char.IsUpper(c) && i > 0) result.Append('_'); result.Append(char.ToLowerInvariant(c)); } return result.ToString(); } /// One property of as a column reaches it. internal sealed class Slot { private readonly Action? _setter; internal Slot(PropertyInfo property, Action? setter) { Property = property; TargetType = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType; _setter = setter; } /// The property. public PropertyInfo Property { get; } /// The property type, or the underlying type of a Nullable property. public Type TargetType { get; } /// /// Sets the property. A value of exactly goes through the compiled setter; any other /// value through as before, which keeps the conversions /// reflection makes on its own (a widening of a primitive, an enum from its underlying value) and its errors. /// public void Assign(T obj, object value) { if (_setter != null && value.GetType() == TargetType) _setter(obj, value); else Property.SetValue(obj, value); } } } } Path: redb/redb.Core/Data/RollbackAfterFailure.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/Data/RollbackAfterFailure.cs ---- using System; using System.Threading.Tasks; namespace redb.Core.Data { /// /// Rolls back a transaction after the work in it failed, without letting a failed rollback replace the failure. /// /// SQL Server ends the transaction itself on a command timeout, on a deadlock victim (1205) and on any error that /// dooms it; the client's rollback then throws "This SqlTransaction has completed". Rethrown from the catch, that /// error hid the SqlException the caller needs: its message, its Number and the deadlock retry that looks for 1205. /// The rollback error is kept on the original exception under . /// /// internal static class RollbackAfterFailure { /// Key in of the original exception that holds the rollback error. internal const string DataKey = "redb:RollbackFailure"; /// /// Rolls back; an exception of the rollback is attached to /// and swallowed, so the caller rethrows the original as it was. /// internal static async Task RollbackAsync(IRedbTransaction transaction, Exception original) { try { await transaction.RollbackAsync(); } catch (Exception rollbackFailure) { try { original.Data[DataKey] = rollbackFailure; } catch (Exception) { /* an exception type with a read-only Data keeps only the original */ } } } } } Path: redb/redb.Core/Data/RootStructureKey.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/Data/RootStructureKey.cs ---- using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using redb.Core.Models.Entities; using redb.Core.Query; using redb.Core.Utils; namespace redb.Core.Data { /// /// The unique key of the root structures of a scheme: one field name once per scheme. The key of /// _structures (_id_scheme, _name, _id_parent) lets a root field in twice on PostgreSQL and SQLite, where two /// NULL parents are distinct, and nodes syncing one scheme at once used to do exactly that (SQL Server counts NULLs /// as equal and refused it). The SQL is the dialect's (the "root structure key" group of ); /// this class decides. /// /// /// A database written before the schema lock may hold such duplicates already, and the key cannot be built over /// them. A duplicate nothing points to (no value, no child with a value, no structure overriding it, no migration /// record) is removed with its subtree; one with values is left alone, and the key waits until the duplicates are /// resolved by hand (UPGRADING.md, "Duplicate root structures"). Run under the schema lock, in one transaction. /// /// public static class RootStructureKey { /// Name of the unique key, as the dialects create it. public const string IndexName = "UX__structures__root"; /// /// Removes the empty root duplicates and builds the key when none with values remain. Called only for a dialect /// whose is not null. /// /// The context of the service; joins its transaction or opens one. /// The dialect. /// Whether _migrations exists; its rows point to structures. /// Where removals are reported. /// Cancellation. /// True when the key exists afterwards. public static async Task EnsureAsync( IRedbContext context, ISqlDialect sql, bool hasMigrationsTable, ILogger? logger, CancellationToken cancellationToken = default) { IRedbTransaction? own = context.IsInTransaction ? null : await context.BeginTransactionAsync(cancellationToken: cancellationToken); try { var created = await EnsureInTransactionAsync(context, sql, hasMigrationsTable, logger, cancellationToken); if (own != null) await own.CommitAsync(); return created; } catch (Exception failure) { if (own != null) await RollbackAfterFailure.RollbackAsync(own, failure); throw; } finally { if (own != null) await own.DisposeAsync(); } } private static async Task EnsureInTransactionAsync( IRedbContext context, ISqlDialect sql, bool hasMigrationsTable, ILogger? logger, CancellationToken cancellationToken) { var roots = await context.QueryAsync( sql.Structures_SelectRootDuplicates(), Array.Empty(), cancellationToken); // PostgreSQL: the foreign key of _values cascades on delete, so a node of the previous version writing into // a duplicate between the look and the delete would lose its value. Locked first, its insert waits and then // fails on the key. SQLite: no lock statement, the schema lock is the only writer. var lockSubtree = sql.Structures_LockSubtree(); var unresolved = new List(); var touchedSchemes = new HashSet(); foreach (var group in roots.GroupBy(r => (r.IdScheme, r.Name))) { var used = new List(); var empty = new List(); foreach (var root in group) { if (lockSubtree != null) await context.ExecuteAsync(lockSubtree, new object[] { root.Id }, cancellationToken); // Asked after the lock, in a statement of its own: it sees every value committed before the lock. var referenced = await context.ExecuteScalarAsync( sql.Structures_SubtreeIsReferenced(hasMigrationsTable), new object[] { root.Id }, cancellationToken); (referenced == 1 ? used : empty).Add(root); } // One copy stays: the one with values, or the first one when none has any. var keep = used.Count > 0 ? used : new List { empty[0] }; var remove = empty.Where(e => !keep.Contains(e)).ToList(); var schemeName = await SchemeNameAsync(context, sql, group.Key.IdScheme, cancellationToken); foreach (var duplicate in remove) { await context.ExecuteAsync(sql.Structures_DeleteSubtreeMetadataCache(), new object[] { duplicate.Id }, cancellationToken); // The children go with it (ON DELETE CASCADE of _id_parent); none of them holds a value. await context.ExecuteAsync(sql.Structures_DeleteById(), new object[] { duplicate.Id }, cancellationToken); touchedSchemes.Add(group.Key.IdScheme); } if (remove.Count > 0) logger?.LogInformation( "REDB schema upgrade: removed {Count} empty duplicate(s) of root field '{Field}' of scheme '{Scheme}' " + "(id {SchemeId}): structure id(s) {Ids}; kept {Kept}.", remove.Count, group.Key.Name, schemeName, group.Key.IdScheme, string.Join(", ", remove.Select(r => r.Id)), string.Join(", ", keep.Select(k => k.Id))); if (used.Count > 1) unresolved.Add($"'{schemeName}' (id {group.Key.IdScheme}) field '{group.Key.Name}': structures " + string.Join(", ", used.Select(u => u.Id))); } foreach (var schemeId in touchedSchemes) { // The nodes compare the hash with their cached structure tree: a new one makes them reload it. var structures = await context.QueryAsync( sql.Structures_SelectBySchemeShort(), new object[] { schemeId }, cancellationToken); await context.ExecuteAsync(sql.Schemes_UpdateHash(), new object[] { SchemeHashCalculator.ComputeSchemeStructureHash(structures), schemeId }, cancellationToken); await context.ExecuteAsync(sql.Schemes_SyncMetadataCache(), new object[] { schemeId }, cancellationToken); } if (unresolved.Count > 0) { // Each remaining duplicate is logged as an error by the schema check of the start that follows // (FindDuplicatesAsync), at every start until resolved. logger?.LogInformation( "REDB schema upgrade: the unique key of root structures ({Index}) is not built while duplicates holding " + "values remain: {Duplicates}.", IndexName, string.Join("; ", unresolved)); return false; } await context.ExecuteAsync(sql.Structures_CreateRootKey(), Array.Empty(), cancellationToken); logger?.LogInformation("REDB schema upgrade: the unique key of root structures ({Index}) is built.", IndexName); return true; } /// /// The root duplicates in the database, one problem per field (read only). Asked only while the key is missing: /// with it, there can be none. /// public static async Task> FindDuplicatesAsync( IRedbContext context, ISqlDialect sql, CancellationToken cancellationToken = default) { var roots = await context.QueryAsync( sql.Structures_SelectRootDuplicates(), Array.Empty(), cancellationToken); var problems = new List(); foreach (var group in roots.GroupBy(r => (r.IdScheme, r.Name))) { var schemeName = await SchemeNameAsync(context, sql, group.Key.IdScheme, cancellationToken); problems.Add(DuplicateProblem(group.Key.IdScheme, schemeName, group.Key.Name, group.Select(r => r.Id).ToList())); } return problems; } /// The problem, and its logged text, for one root field found more than once. public static Models.RedbSchemaProblem DuplicateProblem(long schemeId, string schemeName, string field, IReadOnlyList ids) => new(Models.RedbSchemaProblemKind.DuplicateRootStructure, schemeId, schemeName, field, ids, $"REDB schema problem: root field '{field}' of scheme '{schemeName}' (id {schemeId}) exists {ids.Count} times " + $"(structures {string.Join(", ", ids)}), and objects may hold values on more than one copy. The unique key " + $"of root structures ({IndexName}) is not built until it is resolved. Resolve it by hand as described in " + "UPGRADING.md, section \"Duplicate root structures\"; this error repeats at every start until then."); private static async Task SchemeNameAsync(IRedbContext context, ISqlDialect sql, long schemeId, CancellationToken cancellationToken) => (await context.QueryFirstOrDefaultAsync(sql.Schemes_SelectById(), new object[] { schemeId }, cancellationToken)) ?.Name ?? ""; } } Path: redb/redb.Core/Data/SchemaLockHandle.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/Data/SchemaLockHandle.cs ---- using System; using System.Threading; using System.Threading.Tasks; namespace redb.Core.Data { /// /// The lock that serializes the schema work of processes starting against one database: creating the schema, /// deploying the SQL module, building the indexes of the streams form, upgrading a SQLite file, synchronizing the /// schemes. Two nodes of a cluster that met an old database used to run the same upgrade at once, and the second /// failed on what the first had just created ("index already exists", "tuple concurrently updated"). /// /// /// A provider hands one per database: a server-side named lock on a connection of its own (PostgreSQL advisory /// lock, SQL Server application lock) or the single write lock of the file (SQLite). The attempt never blocks, /// so the wait, its log and its time-out live once, in . Disposing releases the lock /// when it was taken and frees the connection. /// /// public abstract class SchemaLockHandle : IAsyncDisposable { /// One attempt to take the lock: true when it is now held, false when another process holds it. public abstract Task TryAcquireAsync(CancellationToken cancellationToken); /// What the lock is called on the server, for the log of a waiting node. public abstract string Name { get; } /// public abstract ValueTask DisposeAsync(); /// A lock that is always granted: for a context the provider cannot lock (a custom one). public static SchemaLockHandle None { get; } = new NoLock(); private sealed class NoLock : SchemaLockHandle { public override string Name => "none"; public override Task TryAcquireAsync(CancellationToken cancellationToken) => Task.FromResult(true); public override ValueTask DisposeAsync() => ValueTask.CompletedTask; } } } Path: redb/redb.Core/Data/TransactionCompletion.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/Data/TransactionCompletion.cs ---- using System; using System.Collections.Generic; using System.Runtime.CompilerServices; namespace redb.Core.Data { /// /// Callbacks that run when an explicit redb transaction () ends, with whether it /// committed. The provider transaction classes report the outcome once; the props and list caches use it to /// publish what a transaction loaded only after its commit (). Entries are /// held weakly by the transaction: a transaction nobody completes leaves nothing behind. /// public static class TransactionCompletion { private static readonly ConditionalWeakTable>> Pending = new(); /// Runs with true when the transaction commits, false when it ends any other way. public static void Register(IRedbTransaction transaction, Action onCompleted) { ArgumentNullException.ThrowIfNull(transaction); ArgumentNullException.ThrowIfNull(onCompleted); var callbacks = Pending.GetOrCreateValue(transaction); lock (callbacks) callbacks.Add(onCompleted); } /// Called by the transaction once, after it committed or rolled back. public static void Completed(IRedbTransaction transaction, bool committed) { ArgumentNullException.ThrowIfNull(transaction); if (!Pending.TryGetValue(transaction, out var callbacks)) return; Pending.Remove(transaction); Action[] snapshot; lock (callbacks) snapshot = callbacks.ToArray(); foreach (var callback in snapshot) callback(committed); } } } Path: redb/redb.Core/Data/TransactionHooks.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/Data/TransactionHooks.cs ---- using System; using System.Transactions; namespace redb.Core.Data { /// /// The transaction a context takes part in - its explicit redb transaction, else the ambient /// - and a callback for its end. One place for what the cache publication and the /// lazy-load rule both need (review after 4.0.0). /// public static class TransactionHooks { /// The transaction object the context takes part in, or null outside any transaction. public static object? TransactionOf(IRedbContext context) { ArgumentNullException.ThrowIfNull(context); if (context.CurrentTransaction is { IsActive: true } explicitTransaction) return explicitTransaction; return Transaction.Current; } /// /// Runs with whether the transaction committed once the context's transaction /// ends. Returns false, running nothing, when the context is in no transaction. /// public static bool OnCompleted(IRedbContext context, Action onCompleted) { ArgumentNullException.ThrowIfNull(onCompleted); switch (TransactionOf(context)) { case IRedbTransaction explicitTransaction: TransactionCompletion.Register(explicitTransaction, onCompleted); return true; case Transaction ambient: ambient.TransactionCompleted += (_, e) => onCompleted(e.Transaction.TransactionInformation.Status == TransactionStatus.Committed); return true; default: return false; } } } } Path: redb/redb.Core/Data/TransactionWrites.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/Data/TransactionWrites.cs ---- using System; using System.Runtime.CompilerServices; namespace redb.Core.Data { /// /// Whether a transaction has written anything yet. Inside a transaction that has written nothing, what its /// connection reads is committed state, so a shared instance may keep it (the lazy-load rule, owner decision /// 2026-09-17); once the transaction has written, what it reads may be its own uncommitted work, and a shared /// instance keeps nothing of it (owner decision 2026-09-15). redb writes in few known places, which mark /// here: every non-query command and every bulk operation (), and the provider /// methods that write behind a query (soft delete, purge). Kept per transaction object, weakly. /// public static class TransactionWrites { private static readonly ConditionalWeakTable> Written = new(); /// The context's transaction has written. public static void Mark(IRedbContext context) { if (TransactionHooks.TransactionOf(context) is { } transaction) Written.GetOrCreateValue(transaction).Value = true; } /// Whether the context's transaction has written anything; false outside a transaction. public static bool Any(IRedbContext context) => TransactionHooks.TransactionOf(context) is { } transaction && Written.TryGetValue(transaction, out var box) && box.Value; /// /// Whether a load made now on the context's connection reads committed state: outside a transaction, or /// inside one that has written nothing yet. /// public static bool ReadsCommitted(IRedbContext context) => !Any(context); } } Path: redb/redb.Core/Diagnostics/RedbActivitySource.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/Diagnostics/RedbActivitySource.cs ---- using System.Diagnostics; namespace redb.Core.Diagnostics; /// /// Centralized telemetry identity for REDB. The engine declares each database command on an /// named ; an OpenTelemetry consumer subscribes /// with .AddSource(RedbActivitySource.SourceName) and a span per command appears. /// /// The source is inert until something subscribes: with no listener nothing is emitted and a command /// is run straight through, so REDB adds no trace by itself and no statement text or parameters ever /// leave the process in a span. This is the shape EF Core uses for its own /// Microsoft.EntityFrameworkCore source: the engine owns the source, the application opts in /// by name. /// /// public static class RedbActivitySource { /// Canonical source name used for OpenTelemetry tracing instrumentation. public const string SourceName = "redb.Core"; /// The shared activity source instance. public static readonly ActivitySource Source = new(SourceName, GetVersion()); private static string GetVersion() => typeof(RedbActivitySource).Assembly.GetName().Version?.ToString() ?? "0.0.0"; } Path: redb/redb.Core/Diagnostics/RedbTelemetry.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/Diagnostics/RedbTelemetry.cs ---- using System; using System.Diagnostics; using System.Threading.Tasks; namespace redb.Core.Diagnostics; /// /// Wraps one database command in an on . /// The span carries the operation name and the database system only, never the statement text or the /// parameters (they may hold secrets or personal data). A command that throws marks the span an error, /// a caller's cancellation does not; either way the exception is rethrown unchanged. When nothing /// subscribes, the caller runs the connection directly: no span, no extra allocation. /// internal static class RedbTelemetry { /// Value of the db.system tag on every REDB span. public const string System = "redb"; /// A read returning rows or scalars. public const string Query = "query"; /// A single scalar read. public const string Scalar = "scalar"; /// A write (INSERT, UPDATE, DELETE). public const string Execute = "execute"; /// A raw call returning JSON. public const string Json = "json"; /// Whether anything subscribes to the source; when false a wrapper is a no-op and skipped. public static bool Enabled => RedbActivitySource.Source.HasListeners(); /// Runs inside a span named for . public static async Task RunAsync(string operation, Func> action) { using var activity = Start(operation); try { return await action().ConfigureAwait(false); } catch (Exception ex) { Fail(activity, ex); throw; } } /// Runs inside a span named for . public static async Task RunAsync(string operation, Func action) { using var activity = Start(operation); try { await action().ConfigureAwait(false); } catch (Exception ex) { Fail(activity, ex); throw; } } private static Activity? Start(string operation) { var activity = RedbActivitySource.Source.StartActivity($"redb.{operation}", ActivityKind.Internal); if (activity is { IsAllDataRequested: true }) { activity.SetTag("db.system", System); activity.SetTag("db.operation", operation); } return activity; } private static void Fail(Activity? activity, Exception ex) { if (activity is null) return; // The exception is always recorded; only the error status is withheld for a caller's // cancellation, which is not a failure of the database. activity.AddException(ex); if (ex is not OperationCanceledException) activity.SetStatus(ActivityStatusCode.Error, ex.Message); } } Path: redb/redb.Core/Exceptions/RedbCollectionKindChangeException.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/Exceptions/RedbCollectionKindChangeException.cs ---- using System; namespace redb.Core.Exceptions; /// /// A scheme sync refused because a property changed its collection kind (a single value, an array or a dictionary) while /// the structure still holds values. The stored rows have the shape of the old kind and the new class would read them /// wrong: a single value would come back as an empty array, an array as null, the positions of an array as dictionary /// keys. The values would then be lost at the next save. Nothing is converted. The sync stops at this property; the /// properties synced before it are complete, and the scheme keeps its stored version, so the next start tries again. /// public class RedbCollectionKindChangeException : Exception { /// The scheme of the property. public string SchemeName { get; } /// The property as its structure names it. public string PropertyName { get; } /// The structure that holds the values. public long StructureId { get; } /// The kind stored for the structure: "single value", "array" or "dictionary". public string StoredKind { get; } /// The kind the class declares. public string DeclaredKind { get; } public RedbCollectionKindChangeException(string schemeName, string propertyName, long structureId, string storedKind, string declaredKind) : base($"The sync of scheme '{schemeName}' is refused: the property '{propertyName}' (structure {structureId}) is stored " + $"as {Article(storedKind)} and the class declares {Article(declaredKind)}, while the database holds values of it. " + "redb does not convert values between collection kinds, and the new class would read the stored ones wrong. " + "Give the new shape a new property name (the old one keeps its values until it is removed), or move the " + "values by hand before the upgrade and remove the old ones.") { SchemeName = schemeName; PropertyName = propertyName; StructureId = structureId; StoredKind = storedKind; DeclaredKind = declaredKind; } private static string Article(string kind) => kind == "array" ? "an array" : "a " + kind; } Path: redb/redb.Core/Exceptions/RedbDictionaryKeyException.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/Exceptions/RedbDictionaryKeyException.cs ---- using System; namespace redb.Core.Exceptions; /// /// A load stopped because a stored dictionary key does not read as the key type of the class: most often an enum member /// renamed or removed after the object was saved (an enum key is stored by its member name, so renumbering is harmless /// but renaming is not). No entry is skipped: the object is not returned with an entry missing. Restore the member, or /// rewrite the stored keys of the old name (_values._array_index of the dictionary's structure). /// public class RedbDictionaryKeyException : Exception { /// The name of the dictionary property. public string Field { get; } /// The key as it is stored. public string StoredKey { get; } /// The key type the class declares. public Type KeyType { get; } public RedbDictionaryKeyException(string field, string storedKey, Type keyType, Exception inner) : base($"The stored key '{storedKey}' of the dictionary '{field}' does not read as {keyType.Name}: {inner.Message} " + "A member renamed or removed after the object was saved leaves keys of the old name; restore the member or " + "rewrite those stored keys.", inner) { Field = field; StoredKey = storedKey; KeyType = keyType; } } Path: redb/redb.Core/Exceptions/RedbDictionaryKeyTooLongException.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/Exceptions/RedbDictionaryKeyTooLongException.cs ---- using System; namespace redb.Core.Exceptions; /// /// A dictionary key is longer than the provider's _array_index column holds. SQL Server declares the column /// NVARCHAR(430) (the index key width); PostgreSQL and SQLite have no bound and never raise this. The save /// refuses before any row is written, so nothing stored changes. /// public class RedbDictionaryKeyTooLongException : InvalidOperationException { /// Id of the object whose dictionary was rejected (0 or a temporary id for a new object). public long ObjectId { get; } /// Name of the dictionary property. public string Property { get; } /// Length of the serialized key, in UTF-16 code units. public int Length { get; } /// The provider's bound, in UTF-16 code units. public int Limit { get; } public RedbDictionaryKeyTooLongException(long objectId, string property, int length, int limit) : base($"object id={objectId}: a key of dictionary '{property}' is {length} characters, " + $"the limit on this provider is {limit}. Use a shorter key.") { ObjectId = objectId; Property = property; Length = length; Limit = limit; } } Path: redb/redb.Core/Exceptions/RedbLazyLoadScopeEndedException.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/Exceptions/RedbLazyLoadScopeEndedException.cs ---- using System; namespace redb.Core.Exceptions; /// /// Thrown when a lazy load - the Props of an unloaded reference, RedbListItem.Object - finds no live redb /// scope to run on. A data object owns no connection: the load runs on the scope of whoever reads it (owner decision /// 2026-09-15). Here none reads: the scope that loaded the object has ended, or the code runs outside any scope - a /// background task, a static cache, a UI event handler. Before, the load quietly took a fresh scope and pooled connection /// per read. /// public class RedbLazyLoadScopeEndedException : InvalidOperationException { private const string WaysOut = " Read it inside a live scope: resolve IRedbService from a scope, or wrap the block in " + "using (redb.BeginAccess()) { ... } (UI event handlers, background work). Or load it explicitly while a scope " + "is alive - redb.LoadAsync(id), redb.LoadReferencesAsync(parent, p => p.Reference), redb.LoadLinkedObjectsAsync(items), " + "a larger depth - or set RedbServiceConfiguration.LazyLoadWithoutScope = FreshScope to open a scope per load."; /// Id of the object whose Props (or which, behind a list item) were asked for. public long ObjectId { get; } /// Scheme of that object; 0 when the load came from a list item and the scheme is not known yet. public long SchemeId { get; } public RedbLazyLoadScopeEndedException(long objectId, long schemeId) : base($"Object {objectId} (scheme {schemeId}) is an unloaded reference and no live redb scope reads it here." + WaysOut) { ObjectId = objectId; SchemeId = schemeId; } private RedbLazyLoadScopeEndedException(string message, long objectId) : base(message) { ObjectId = objectId; } /// A list item's linked object asked for with no live redb scope. public static RedbLazyLoadScopeEndedException ForListItem(long listItemId, long objectId) => new($"The object {objectId} linked to list item {listItemId} is loaded lazily and no live redb scope reads it here." + WaysOut, objectId); } Path: redb/redb.Core/Exceptions/RedbLockNotAcquiredException.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/Exceptions/RedbLockNotAcquiredException.cs ---- using System; using System.Collections.Generic; using System.Linq; namespace redb.Core.Exceptions; /// /// The strict row lock (LockForUpdateRequiredAsync) found fewer rows than it was asked to /// lock: the missing ids have no row in _objects - deleted, or never created. A CAS pattern /// (lock -> re-read -> save) must not proceed on an unlocked row: with the default /// MissingObjectStrategy.AutoSwitchToInsert the save would silently resurrect the deleted /// object (BR-9, 2026-09-02). Catch this to abort the CAS, or to recreate the object deliberately. /// The lenient LockForUpdateAsync reports a count instead of throwing. /// public class RedbLockNotAcquiredException : Exception { /// The distinct ids the caller asked to lock. public IReadOnlyList RequestedIds { get; } /// The ids that have no row in _objects, ascending. public IReadOnlyList MissingIds { get; } public RedbLockNotAcquiredException(IReadOnlyList requestedIds, IReadOnlyList missingIds) : base(BuildMessage(requestedIds, missingIds)) { RequestedIds = requestedIds; MissingIds = missingIds; } private static string BuildMessage(IReadOnlyList requested, IReadOnlyList missing) => $"Could not lock {missing.Count} of {requested.Count} requested objects: " + $"ids [{string.Join(", ", missing)}] have no row in _objects (deleted, or never created). " + "A CAS must not proceed on an unlocked row - abort, or recreate the object deliberately."; } Path: redb/redb.Core/Exceptions/RedbNestedCollectionException.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/Exceptions/RedbNestedCollectionException.cs ---- using System; using System.Linq; namespace redb.Core.Exceptions; /// /// A property holds a collection directly inside a collection (List<List<T>>, T[][], /// List<T[]>, List<Dictionary<K, V>>, Dictionary<K, List<V>>, /// Dictionary<K, Dictionary<K2, V>>, Dictionary<K, V>[]) or is a multi-dimensional array /// (T[,]). redb stores neither: before, each inner collection was written as the name of its type, a /// multi-dimensional array as a flat one, and the object could not be loaded afterwards. The scheme sync refuses such a /// property before it writes anything; a save that meets one (a scheme synced before the refusal existed) refuses /// before any row is deleted or written. A byte[] element or value is a single value and is not refused. /// Wrap the inner collection in a class: List<Group> with class Group { List<T> Items }. /// public class RedbNestedCollectionException : Exception { /// The class (or scheme) that declares the property. public string OwnerName { get; } /// The property. public string PropertyName { get; } /// The declared type of the property, or what the save met in it, in C# notation. public string PropertyTypeName { get; } /// Refusal of a declared property type, at the scheme sync. public RedbNestedCollectionException(Type ownerType, string propertyName, Type propertyType) : this(Display(ownerType), propertyName, Display(propertyType), atSave: false) { } /// Refusal at a save: says what the save met in the property. public RedbNestedCollectionException(string ownerName, string propertyName, string found) : this(ownerName, propertyName, found, atSave: true) { } private RedbNestedCollectionException(string ownerName, string propertyName, string typeName, bool atSave) : base((atSave ? $"The save is refused: the property '{ownerName}.{propertyName}' holds {typeName}. " : $"The property '{ownerName}.{propertyName}' of type '{typeName}' is refused. ") + "redb does not store a collection directly inside a collection, nor a multi-dimensional array: the inner " + "collections would be written as the name of their type and the object could not be loaded. Wrap the " + "inner collection in a class, for example List with class Group { List Items { get; set; } }, " + "or use a jagged layout of such classes for a multi-dimensional array.") { OwnerName = ownerName; PropertyName = propertyName; PropertyTypeName = typeName; } /// A type in C# notation: List<List<int>>, int[,]. public static string Display(Type type) { if (type.IsArray) return Display(type.GetElementType()!) + "[" + new string(',', type.GetArrayRank() - 1) + "]"; if (Nullable.GetUnderlyingType(type) is { } underlying) return Display(underlying) + "?"; if (!type.IsGenericType) return type.Name; var name = type.Name; var tick = name.IndexOf('`'); if (tick >= 0) name = name[..tick]; return name + "<" + string.Join(", ", type.GetGenericArguments().Select(Display)) + ">"; } } Path: redb/redb.Core/Exceptions/RedbObjectReferencedException.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/Exceptions/RedbObjectReferencedException.cs ---- namespace redb.Core.Exceptions; /// /// Objects of a trash container are still referenced by live objects - a RedbObject<T> /// reference in their Props points at them - so they cannot be physically deleted without breaking /// those references. /// /// redb never repairs this on its own: nulling the references would hide the caller's mistake inside /// other objects' data. The purge removes everything else of the container, marks the container /// failed (the background worker no longer retries it) and names both sides here, so the /// references can be removed or re-pointed deliberately. Purging the container again afterwards /// finishes it. /// /// public class RedbObjectReferencedException : Exception { /// The trash container that could not be purged completely. public long TrashId { get; } /// Objects still left in the container. public long RemainingCount { get; } /// Objects that live objects still reference (the first pairs found, at most 100). public IReadOnlyList ReferencedObjectIds { get; } /// Live objects holding those references. public IReadOnlyList ReferencingObjectIds { get; } public RedbObjectReferencedException( long trashId, long remainingCount, IReadOnlyList referencedObjectIds, IReadOnlyList referencingObjectIds) : base(BuildMessage(trashId, remainingCount, referencedObjectIds, referencingObjectIds)) { TrashId = trashId; RemainingCount = remainingCount; ReferencedObjectIds = referencedObjectIds; ReferencingObjectIds = referencingObjectIds; } private static string BuildMessage(long trashId, long remaining, IReadOnlyList referenced, IReadOnlyList referencing) => $"Trash container {trashId} cannot be purged completely: {remaining} object(s) are still referenced by " + $"live objects (referenced: {Ids(referenced)}; referencing: {Ids(referencing)}). Everything else was purged. " + "The container is marked 'failed' and is no longer retried automatically; remove or re-point those " + "references, then purge the container again."; private static string Ids(IReadOnlyList ids) => ids.Count <= 20 ? string.Join(", ", ids) : string.Join(", ", ids.Take(20)) + $" and {ids.Count - 20} more"; } Path: redb/redb.Core/Exceptions/RedbProRequiredException.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/Exceptions/RedbProRequiredException.cs ---- namespace redb.Core.Exceptions; /// /// Thrown when a Pro-only feature is invoked on a Free edition instance. /// public class RedbProRequiredException : Exception { public string Feature { get; } public RedbProRequiredException(string feature) : base($"Feature '{feature}' requires redb Pro edition.") { Feature = feature; } } Path: redb/redb.Core/Exceptions/RedbPropertyTypeHeldException.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/Exceptions/RedbPropertyTypeHeldException.cs ---- using System; using System.Collections.Generic; using System.Linq; using redb.Core.Providers.Base; namespace redb.Core.Exceptions; /// /// A save refused because a property of the Props class has another type (or collection kind) than the structure stored /// for it, and the sync did not convert it: the class's is not higher /// than the version the database recorded. Writing the property into the stored structure would put its value in the /// wrong column, where it is lost. Nothing was written. Reads are not refused: they go through the stored type. /// public class RedbPropertyTypeHeldException : Exception { /// The scheme of the objects. public string SchemeName { get; } /// The CLR type of the Props class. public Type PropsType { get; } /// Each property whose stored shape differs: its path, the type the class declares, the type stored. public IReadOnlyList Properties { get; } public RedbPropertyTypeHeldException(string schemeName, Type propsType, IReadOnlyList properties) : base($"Saving objects of scheme '{schemeName}' with the class '{propsType.FullName}' is refused: " + string.Join("; ", properties.Select(p => $"'{p.Path}' is declared {p.ClassType} and stored as {p.StoredType}")) + ". The sync did not convert the stored values because the class's RedbScheme.Version is not higher than the " + "database's. Raise RedbScheme.Version so the sync converts them, or set DefaultDestructiveSyncAtEqualVersion " + "on a development database.") { SchemeName = schemeName; PropsType = propsType; Properties = properties; } } Path: redb/redb.Core/Exceptions/RedbPropsClassOlderException.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/Exceptions/RedbPropsClassOlderException.cs ---- using System; using System.Collections.Generic; namespace redb.Core.Exceptions; /// /// A save refused because the Props class of this process is older than the scheme in the database: the stored /// objects have values of fields a newer build of the class added under a nested class, an array or a dictionary /// this class knows. Saving would replace that nested class or collection and delete those values. Nothing was /// written. /// /// /// A field a newer build added at the top level of the class is kept by the save and needs no refusal. The way out is /// upgrading this process, or not saving these objects from it while old and new builds run side by side. /// /// public class RedbPropsClassOlderException : Exception { /// The scheme of the objects. public string SchemeName { get; } /// The CLR type of the Props class this process saved with. public Type PropsType { get; } /// The fields the database has and the class lacks, as paths (HomeAddress.Country). public IReadOnlyList UnknownFields { get; } /// The version of the class this process saved with (). public int ClassVersion { get; } /// The version of the class the scheme was last synchronised with, as the database records it. public int StoredVersion { get; } public RedbPropsClassOlderException(string schemeName, Type propsType, IReadOnlyList unknownFields) : base($"Saving objects of scheme '{schemeName}' with the class '{propsType.FullName}' would delete the values of " + $"fields this class does not know: {string.Join(", ", unknownFields)}. A newer build of the class wrote them. " + "Upgrade this process, or do not save these objects from it while old and new builds run side by side.") { SchemeName = schemeName; PropsType = propsType; UnknownFields = unknownFields; } /// /// The scheme was synchronised by a newer version of the class (), /// which may have removed fields or changed their types: a save with this older class would write the old shape over /// the new one, so it is refused as a whole. /// public RedbPropsClassOlderException(string schemeName, Type propsType, int classVersion, int storedVersion) : base($"Saving objects of scheme '{schemeName}' with the class '{propsType.FullName}' version {classVersion} is refused: " + $"the scheme was synchronised by version {storedVersion} of the class, which may have removed fields or changed " + "their types. Upgrade this process, or do not save these objects from it while old and new builds run side by side.") { SchemeName = schemeName; PropsType = propsType; UnknownFields = []; ClassVersion = classVersion; StoredVersion = storedVersion; } } Path: redb/redb.Core/Exceptions/RedbRenameConflictException.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/Exceptions/RedbRenameConflictException.cs ---- namespace redb.Core.Exceptions; /// /// Thrown by the scheme sync when a rename cannot be applied without losing stored values, or when the class being /// synchronised predates a rename the database has already seen. Thrown before anything is written for the field; /// the sync of the scheme stops. /// public class RedbRenameConflictException : Exception { /// The scheme the conflict is in. public string SchemeName { get; } /// The name the class declares: a property name, or the scheme name for a scheme rename. public string Name { get; } /// The other stored names involved in the conflict. public IReadOnlyList StoredNames { get; } private RedbRenameConflictException(string message, string schemeName, string name, IReadOnlyList storedNames) : base(message) { SchemeName = schemeName; Name = name; StoredNames = storedNames; } /// The property and one of its previous names are both stored: each may hold values. internal static RedbRenameConflictException BothStored(string schemeName, string propertyPath, string oldName, long id, long oldId) => new($"Scheme '{schemeName}': property '{propertyPath}' declares [RedbRename(\"{oldName}\")], but the " + $"database stores both '{propertyPath}' (structure {id}) and '{oldName}' (structure {oldId}). " + "Renaming would lose the values of one of them. Move the values to one structure and delete the " + "other by hand, then start again.", schemeName, propertyPath, [oldName]); /// More than one stored property matches the previous names of one property. internal static RedbRenameConflictException SeveralStored(string schemeName, string propertyPath, IReadOnlyList<(string Name, long Id)> stored) => new($"Scheme '{schemeName}': property '{propertyPath}' has more than one stored previous name: " + string.Join(", ", stored.Select(s => $"'{s.Name}' (structure {s.Id})")) + ". Renaming one of them would leave the others to the sync. Keep one structure and delete the " + "others by hand, then start again.", schemeName, propertyPath, stored.Select(s => s.Name).Distinct().ToList()); /// The scheme name and one of its previous names (RedbScheme.RenamedFrom) are both stored. internal static RedbRenameConflictException SchemeBothStored(Type type, string schemeName, string previousName, long id, long previousId) => new($"Type '{type.FullName ?? type.Name}' declares scheme '{schemeName}' renamed from '{previousName}', but " + $"the database stores both '{schemeName}' (scheme {id}) and '{previousName}' (scheme {previousId}). " + "Renaming would leave the objects of one of them behind. Move the objects to one scheme and delete the " + "other by hand, then start again.", schemeName, schemeName, [previousName]); /// More than one stored scheme matches the previous names of one class. internal static RedbRenameConflictException SchemeSeveralStored(Type type, string schemeName, IReadOnlyList<(string Name, long Id)> stored) => new($"Type '{type.FullName ?? type.Name}' declares scheme '{schemeName}', and more than one of its previous " + "names is stored: " + string.Join(", ", stored.Select(s => $"'{s.Name}' (scheme {s.Id})")) + ". Keep one scheme and delete the others by hand, then start again.", schemeName, schemeName, stored.Select(s => s.Name).ToList()); /// /// The class declares a scheme name that the database records as renamed, and no class of this application declares /// the scheme under its current name: the class is older than the rename. /// internal static RedbRenameConflictException SchemeRenamedAway(Type type, string schemeName, string currentName, long id) => new($"Type '{type.FullName ?? type.Name}' declares scheme '{schemeName}', but the database records that " + $"'{schemeName}' was renamed to '{currentName}' (scheme {id}). This application runs a class older than " + $"the rename. Update it to the class of '{currentName}'; nothing was changed. If a class of this " + $"application does declare '{currentName}' in a module not loaded yet, load that module before this one.", currentName, schemeName, [currentName]); /// /// The database records a rename history for the property, and the first /// of the property is not the first name of that history, or the property has none. The first name orders the /// property in the object hash, so the class would compute the hashes in another order than they were stored. /// internal static RedbRenameConflictException FirstNameMismatch(string schemeName, string propertyPath, long id, IReadOnlyList history, string? declaredFirst) => new($"Scheme '{schemeName}': the database records that property '{propertyPath}' (structure {id}) was " + $"renamed from {string.Join(", ", history.Select(n => $"'{n}'"))}, so its first [RedbRename] must be " + $"[RedbRename(\"{history[0]}\")]; " + (declaredFirst == null ? "the property declares none. " : $"the property declares [RedbRename(\"{declaredFirst}\")] first. ") + "[RedbRename] stays on a renamed property for good: its first name orders the property in the object " + "hash. Restore the attributes, the first name first; nothing was changed.", schemeName, propertyPath, history.ToList()); /// /// The class declares a property under a name that the database records as renamed: the class is older than the /// rename, and adding the property again would split the values and, under the strict sync, delete the renamed one. /// internal static RedbRenameConflictException RenamedAway(string schemeName, string propertyPath, string currentName, long id) => new($"Scheme '{schemeName}': the class declares property '{propertyPath}', but the database records that " + $"'{propertyPath}' was renamed to '{currentName}' (structure {id}). This application runs a class " + $"older than the rename. Update it to the class with '{currentName}'; nothing was changed.", schemeName, propertyPath, [currentName]); } Path: redb/redb.Core/Exceptions/RedbSchemaLockTimeoutException.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/Exceptions/RedbSchemaLockTimeoutException.cs ---- using System; namespace redb.Core.Exceptions; /// /// Start-up waited for the schema lock longer than : /// another process holds it, most likely while it upgrades the same database. Building the indexes of a large table /// takes minutes, so the usual remedies are a longer time-out or starting the nodes one after another. /// /// /// A distinct type: a hosting layer that restarts the process on failure can tell "another node is still upgrading" /// from a defect without parsing text. /// /// public class RedbSchemaLockTimeoutException : Exception { /// Provider name as the dialect reports it. public string Provider { get; } /// The lock as the server knows it. public string LockName { get; } /// How long start-up waited. public TimeSpan Waited { get; } public RedbSchemaLockTimeoutException(string provider, string lockName, TimeSpan waited) : base($"{provider}: the schema lock '{lockName}' was not released within {waited}. Another process holds it, " + "most likely upgrading this database (the indexes of a large table take minutes to build). Raise " + "RedbServiceConfiguration.SchemaLockTimeout, or start the nodes one after another.") { Provider = provider; LockName = lockName; Waited = waited; } } Path: redb/redb.Core/Exceptions/RedbSchemaMissingException.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/Exceptions/RedbSchemaMissingException.cs ---- namespace redb.Core.Exceptions; /// /// The database has no redb schema at all - the core table _schemes is missing - and /// initialization was asked not to create it (InitializeAsync() without /// ensureCreated: true). /// /// /// Schema creation is opt-in on purpose: the application role usually may not run DDL, and an /// unexpected empty database more often means a connection string pointing at the wrong one than /// a fresh installation. Before this type the first start-up step - the module version probe or /// the scheme sync - surfaced a raw driver error ("relation _schemes does not exist") that said /// nothing about how to proceed. Now the failure names the situation and the two ways out. /// /// public class RedbSchemaMissingException : Exception { /// Provider name as the service reports it, for the operator's convenience. public string Provider { get; } public RedbSchemaMissingException(string provider) : base(BuildMessage(provider)) { Provider = provider; } private static string BuildMessage(string provider) => $"The {provider} database has no redb schema (table _schemes not found) and initialization " + "was asked not to create it. Create it with InitializeAsync(ensureCreated: true) " + "(RedbServiceConfiguration.EnsureCreated = true for the hosted-service start-up), or have the " + "schema owner run the script from IRedbService.GetSchemaScript(). If this database was not " + "expected to be empty, check the connection string first."; } Path: redb/redb.Core/Exceptions/RedbSchemaNewerException.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/Exceptions/RedbSchemaNewerException.cs ---- namespace redb.Core.Exceptions; /// /// The database carries a redb module (or, on SQLite, a file schema) newer than this package's, and that newer module /// does not serve this package. Start-up stops and leaves the database as it is. /// /// /// A package never puts its own, older module over a newer one: a node of the previous version in a cluster that is /// being upgraded would otherwise take the database back for every node. When the newer module still serves this /// package (it says so itself: pvt_module_compat() on PostgreSQL and SQL Server, the _schema_compat row /// of a SQLite file) the start goes on with a warning; when it does not, this exception is thrown. The way out is /// upgrading the redb packages of this application. /// /// /// /// A sibling of , not a case of it: that one asks for the database to be /// upgraded, this one for the application. /// /// public class RedbSchemaNewerException : Exception { /// Module version (SQLite: file schema version) the database reports. public string DeployedVersion { get; } /// Module version (SQLite: file schema version) this package ships. public string PackageVersion { get; } /// /// The redb package version from which on the database is served, as the database itself states it; null /// when the database states nothing (a module without the compatibility function, a file without the row). /// public string? RequiredPackageVersion { get; } /// Provider name as the dialect reports it. public string Provider { get; } public RedbSchemaNewerException(string provider, string deployedVersion, string packageVersion, string? requiredPackageVersion) : base(BuildMessage(provider, deployedVersion, packageVersion, requiredPackageVersion)) { Provider = provider; DeployedVersion = deployedVersion; PackageVersion = packageVersion; RequiredPackageVersion = requiredPackageVersion; } /// /// For a caller outside the service start, such as a tool, that reads the version and judges it itself: the same /// first sentence, then the caller's own way out instead of upgrading the application's packages. /// /// Provider name as the dialect reports it. /// Module version (SQLite: file schema version) the database reports. /// Module version (SQLite: file schema version) this package ships. /// The package version the database names as served from, null when it names none. /// What the operator does about it: the closing sentence of the message. public RedbSchemaNewerException( string provider, string deployedVersion, string packageVersion, string? requiredPackageVersion, string remedy) : base($"{Newer(provider, deployedVersion, packageVersion, requiredPackageVersion)} The database was left unchanged. {remedy}") { Provider = provider; DeployedVersion = deployedVersion; PackageVersion = packageVersion; RequiredPackageVersion = requiredPackageVersion; } private static string BuildMessage(string provider, string deployed, string package, string? requiredPackage) => $"{Newer(provider, deployed, package, requiredPackage)} " + "Upgrade the redb packages of this application; the database was left unchanged."; /// The first sentence of every message: what is deployed, what this package ships, what the database asks for. private static string Newer(string provider, string deployed, string package, string? requiredPackage) { var needs = requiredPackage is null ? "it does not state which packages it serves" : $"it needs redb packages from {requiredPackage} on"; return $"The {provider} database carries the redb module {deployed}, newer than {package} of this package, and {needs}."; } } Path: redb/redb.Core/Exceptions/RedbSchemaOutdatedException.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/Exceptions/RedbSchemaOutdatedException.cs ---- namespace redb.Core.Exceptions; /// /// The database schema is behind the version this build requires, and the application could not /// bring it up to date itself. /// /// /// Start-up applies the versioned SQL module automatically when the connected role is allowed to. /// It often is not: the DBA grants owner rights for the initial installation and revokes them /// afterwards, so ALTER TABLE and CREATE OR REPLACE FUNCTION from the application /// fail with a privilege error. Before this type that surfaced as a raw driver exception with no /// indication of what to do. Now it says what is deployed, what is required, what could not be /// applied, and how to get the script for the DBA — the same text the application would have run. /// /// /// /// A distinct type, not InvalidOperationException: a hosting layer has to be able to tell /// "someone must run the upgrade script" from every other start-up failure without parsing text. /// /// public class RedbSchemaOutdatedException : Exception { /// Module version the database reports, or null when the module is absent. public string? DeployedVersion { get; } /// Module version this build ships and requires. public string RequiredVersion { get; } /// Provider name as the dialect reports it, for the operator's convenience. public string Provider { get; } /// /// Why the application did not apply the upgrade itself: a privilege error from the driver, or /// null when automatic application is disabled by configuration. /// public Exception? Cause { get; } public RedbSchemaOutdatedException( string provider, string? deployedVersion, string requiredVersion, Exception? cause) : base(BuildMessage(provider, deployedVersion, requiredVersion, cause), cause) { Provider = provider; DeployedVersion = deployedVersion; RequiredVersion = requiredVersion; Cause = cause; } /// /// For a caller outside the service start, such as a tool, that reads the version and judges it itself and does /// not upgrade the database. is null. /// /// Provider name as the dialect reports it. /// Module version the database reports (SQLite: file schema version), null when absent. /// Module version (SQLite: file schema version) this build requires. /// Why the caller did not upgrade the database, completing "and ..." in the first sentence. /// What the operator does about it: the closing sentence of the message. public RedbSchemaOutdatedException( string provider, string? deployedVersion, string requiredVersion, string reason, string remedy) : base($"{Outdated(provider, deployedVersion, requiredVersion, reason)} Nothing was changed. {remedy}") { Provider = provider; DeployedVersion = deployedVersion; RequiredVersion = requiredVersion; } private static string BuildMessage(string provider, string? deployed, string required, Exception? cause) { var reason = cause is null ? "automatic upgrades are disabled (AutoApplyDatabaseUpgrades = false)" : $"the connected role is not allowed to apply it ({cause.GetType().Name}: {cause.Message})"; return $"{Outdated(provider, deployed, required, reason)} " + "Nothing was changed. Have the schema owner apply the upgrade script: export it with " + "IRedbService.GetUpgradeScript() or `redb schema --upgrade --provider `, then " + "run it with psql / sqlcmd. The script is idempotent and safe to re-run."; } /// The first sentence of every message: what is deployed, what is required, and why it stays so. private static string Outdated(string provider, string? deployed, string required, string reason) => $"The {provider} database schema is outdated: deployed module version is " + $"'{deployed ?? ""}', this build requires '{required}', and {reason}."; } Path: redb/redb.Core/Exceptions/RedbSchemeMismatchException.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/Exceptions/RedbSchemeMismatchException.cs ---- namespace redb.Core.Exceptions; /// /// Thrown by LoadAsync<TProps> when the loaded object belongs to a different scheme than /// TProps maps to, and RedbServiceConfiguration.ThrowOnSchemeMismatch is set. /// By default the mismatch is not thrown — LoadAsync returns null instead, so a /// soft-deleted object (scheme -10) reads as null. Set the flag to surface a genuine type /// mistake loudly. /// /// The check exists because loading an object under the wrong Props type deserializes garbage into the /// fields and — with EnablePropsCache — caches it under that type, so a following /// GetWithoutHashValidation would keep returning the garbage. Whether it throws or returns null, /// the garbage never reaches the cache. /// /// /// The untyped LoadAsync(objectId) (returning IRedbObject without Props) is never affected. /// /// public class RedbSchemeMismatchException : Exception { /// Id of the object that was loaded. public long ObjectId { get; } /// The Props type the caller asked for. public Type RequestedType { get; } /// Scheme id that maps to. public long ExpectedSchemeId { get; } /// Scheme id the loaded object actually has. public long ActualSchemeId { get; } public RedbSchemeMismatchException(long objectId, Type requestedType, long expectedSchemeId, long actualSchemeId) : base($"Object {objectId} belongs to scheme {actualSchemeId}, but was loaded as " + $"'{requestedType.FullName ?? requestedType.Name}' which maps to scheme {expectedSchemeId}. " + "Loading an object under the wrong Props type yields garbage and poisons the cache. " + "Use the correct TProps, load untyped via LoadAsync(objectId), or unset " + "RedbServiceConfiguration.ThrowOnSchemeMismatch to get null instead of this exception.") { ObjectId = objectId; RequestedType = requestedType; ExpectedSchemeId = expectedSchemeId; ActualSchemeId = actualSchemeId; } /// /// The same mismatch met elsewhere than in a load (a save under the id of an object of another scheme): the caller /// says what happened and what was left untouched. /// public RedbSchemeMismatchException(long objectId, Type requestedType, long expectedSchemeId, long actualSchemeId, string message) : base(message) { ObjectId = objectId; RequestedType = requestedType; ExpectedSchemeId = expectedSchemeId; ActualSchemeId = actualSchemeId; } } Path: redb/redb.Core/Exceptions/RedbSchemeNameConflictException.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/Exceptions/RedbSchemeNameConflictException.cs ---- namespace redb.Core.Exceptions; /// /// Thrown when two CLR types claim the same explicit scheme name. Both types are named in the /// message — the whole point is that neither is more "correct" than the other, and the developer /// has to pick. /// /// Only conflicts involving an explicit Name are fatal. Alias collisions have always been /// resolved last-write-wins and stay that way, so projects that predate explicit names are unaffected. /// /// public class RedbSchemeNameConflictException : Exception { /// The contested scheme name. public string SchemeName { get; } /// The type already registered under this name. public Type ExistingType { get; } /// The type that tried to claim the same name. public Type ConflictingType { get; } public RedbSchemeNameConflictException(string schemeName, Type existingType, Type conflictingType) : base($"Scheme name '{schemeName}' is claimed by two types: " + $"'{existingType.FullName ?? existingType.Name}' and " + $"'{conflictingType.FullName ?? conflictingType.Name}'. " + "A scheme name is unique across the database — rename one of them or drop the explicit Name.") { SchemeName = schemeName; ExistingType = existingType; ConflictingType = conflictingType; } } Path: redb/redb.Core/Exceptions/RedbSchemeNameException.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/Exceptions/RedbSchemeNameException.cs ---- namespace redb.Core.Exceptions; /// /// Thrown when a type declares an explicit scheme name ([RedbScheme(Name = "...")]) that /// breaks the scheme naming rules. Raised before any SQL is issued, so the developer gets the /// offending type and the broken rule instead of a raw constraint violation from the driver. /// public class RedbSchemeNameException : Exception { /// The class that declared the invalid name. public Type DeclaringType { get; } /// The rejected name, as written in the attribute. public string? SchemeName { get; } public RedbSchemeNameException(Type declaringType, string? schemeName, string reason) : base($"Type '{declaringType.FullName ?? declaringType.Name}' declares " + $"[RedbScheme(Name = \"{schemeName}\")], which is not a valid scheme name: {reason}. " + "Scheme names follow C# identifier rules (Latin letters, digits, '_', '.' and '+'); " + "use Alias for human-readable titles.") { DeclaringType = declaringType; SchemeName = schemeName; } } Path: redb/redb.Core/Exceptions/RedbSchemeNameTakenException.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/Exceptions/RedbSchemeNameTakenException.cs ---- namespace redb.Core.Exceptions; /// /// Thrown when a type wants to rename its scheme to an explicit name that another scheme in the /// database already occupies. Raised instead of letting the UNIQUE(_name) violation surface as a /// provider-specific error code (23505 / 2627 / SQLITE_CONSTRAINT_UNIQUE), and the database is left /// untouched. /// public class RedbSchemeNameTakenException : Exception { /// The type that asked for the name. public Type DeclaringType { get; } /// The contested scheme name. public string SchemeName { get; } /// Id of the scheme already holding the name. public long OccupiedBySchemeId { get; } public RedbSchemeNameTakenException(Type declaringType, string schemeName, long occupiedBySchemeId) : base($"Type '{declaringType.FullName ?? declaringType.Name}' declares " + $"[RedbScheme(Name = \"{schemeName}\")], but scheme id={occupiedBySchemeId} already uses that name. " + "Scheme names are unique — pick another name, or remove the stale scheme first.") { DeclaringType = declaringType; SchemeName = schemeName; OccupiedBySchemeId = occupiedBySchemeId; } /// /// The type resolves to two different schemes at once: one already carries the explicit name, and /// another still sits under a previous name. That is the split-brain of a rename - /// typically an older binary re-created the scheme under its old name after a newer one had renamed it, and /// objects are now being written to both. /// public RedbSchemeNameTakenException( Type declaringType, string schemeName, long occupiedBySchemeId, string previousName, long previousSchemeId) : base($"Type '{declaringType.FullName ?? declaringType.Name}' maps to two schemes at once: " + $"id={occupiedBySchemeId} named '{schemeName}' and id={previousSchemeId} named '{previousName}'. " + "The rename to the explicit name has already happened, yet the old scheme was re-created — " + "most likely by an application version that predates the explicit name. Objects may be split " + "across both schemes; merge them and remove the stale one before continuing.") { DeclaringType = declaringType; SchemeName = schemeName; OccupiedBySchemeId = occupiedBySchemeId; } } Path: redb/redb.Core/Exceptions/RedbSchemeNamespaceMismatchException.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/Exceptions/RedbSchemeNamespaceMismatchException.cs ---- namespace redb.Core.Exceptions; /// /// Thrown when a type resolves to a scheme (by explicit name, FullName, short-name fallback or as the /// loser of a creation race) that is owned by a different namespace (_schemes._name_space). Adopting it would silently attach /// one project's type to another project's data — two unrelated Order classes are the textbook /// case. Schemes written before namespaces were recorded carry NULL there and are still adopted, with /// a warning, because a pre-namespace database has no other way in (V4, К7). /// public class RedbSchemeNamespaceMismatchException : Exception { /// The type that asked for the scheme. public Type DeclaringType { get; } /// The scheme name the type resolved to. public string SchemeName { get; } /// Id of the scheme the type resolved to. public long SchemeId { get; } /// The namespace recorded on the scheme — its owner. public string SchemeNameSpace { get; } /// The namespace of the requesting type (null for the global namespace). public string? TypeNameSpace { get; } public RedbSchemeNamespaceMismatchException( Type declaringType, string schemeName, long schemeId, string schemeNameSpace, string? typeNameSpace) : base($"Type '{declaringType.FullName ?? declaringType.Name}' resolves to scheme id={schemeId} " + $"named '{schemeName}', but that scheme belongs to namespace " + $"'{schemeNameSpace}', not '{typeNameSpace ?? ""}'. Adopting it would attach this " + "type to another project's data (a scheme has one owner). If the scheme really is this type's - " + "the type moved - set _schemes._name_space to the new namespace (or NULL to re-adopt); otherwise " + "give one of the two types a different scheme name.") { DeclaringType = declaringType; SchemeName = schemeName; SchemeId = schemeId; SchemeNameSpace = schemeNameSpace; TypeNameSpace = typeNameSpace; } } Path: redb/redb.Core/Exceptions/RedbSynchronousLazyLoadException.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/Exceptions/RedbSynchronousLazyLoadException.cs ---- using System; namespace redb.Core.Exceptions; /// /// Thrown by the Props getter of an unloaded reference when /// RedbServiceConfiguration.LazyReferenceAccess is Throw: the host has said that a /// hidden, blocking database round trip on property access is a defect (Blazor WebAssembly cannot /// block at all; a UI thread should not), so the getter names the explicit way instead of loading. /// public class RedbSynchronousLazyLoadException : InvalidOperationException { /// Id of the object whose Props were asked for. public long ObjectId { get; } /// Scheme of that object. public long SchemeId { get; } public RedbSynchronousLazyLoadException(long objectId, long schemeId) : base($"Object {objectId} (scheme {schemeId}) is an unloaded reference and LazyReferenceAccess is Throw: " + "synchronous loading on Props access is disabled for this host. Load it explicitly - " + "await obj.LoadPropsAsync(), or redb.LoadReferencesAsync(parent, p => p.Reference) for a batch - " + "or load the parent with a larger depth.") { ObjectId = objectId; SchemeId = schemeId; } } Path: redb/redb.Core/Exceptions/RedbTypeMigrationException.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/Exceptions/RedbTypeMigrationException.cs ---- namespace redb.Core.Exceptions; /// /// Thrown by scheme synchronisation when a property's type changed but the stored values could not be /// moved to the column the new type reads from. /// /// /// Why this stops synchronisation instead of warning. The two failure modes are both silent if /// allowed through. Updating _structures._id_type without moving the values leaves every row /// reading as null — and with the default PropsSaveStrategy.DeleteInsert /// the stranded values are physically deleted the next time the object is saved. Leaving the type alone /// instead makes the CLR class and the structure disagree, which surfaces later and further from the /// cause. Failing here is the only outcome that keeps the data intact and the state describable. /// /// /// /// The type is deliberately distinct rather than a plain InvalidOperationException: the caller has /// to be able to tell "values are waiting for a manual migration" from any other start-up failure, and /// tell it from the exception type rather than by matching on message text. /// /// public class RedbTypeMigrationException : Exception { /// Structure whose values could not be migrated. public long StructureId { get; } /// Name of the property backing that structure. public string PropertyName { get; } /// Scheme the structure belongs to. public long SchemeId { get; } /// Scheme name, when it could be resolved; the id is always present. public string? SchemeName { get; } /// REDB type name the structure had. public string OldTypeName { get; } /// REDB type name the property now maps to. public string NewTypeName { get; } /// Rows holding a value under the old type, as reported by the migration. public int AffectedRows { get; } /// Rows the migration did move. Zero when it never ran. public int MigratedRows { get; } /// Rows left behind: they still hold their original value. public int StrandedRows { get; } /// Verbatim diagnostics from the provider's migration, when it produced any. public string? MigrationErrors { get; } public RedbTypeMigrationException( long structureId, string propertyName, long schemeId, string? schemeName, string oldTypeName, string newTypeName, int affectedRows, int migratedRows, int strandedRows, string? migrationErrors) : base(BuildMessage(structureId, propertyName, schemeId, schemeName, oldTypeName, newTypeName, affectedRows, migratedRows, strandedRows, migrationErrors)) { StructureId = structureId; PropertyName = propertyName; SchemeId = schemeId; SchemeName = schemeName; OldTypeName = oldTypeName; NewTypeName = newTypeName; AffectedRows = affectedRows; MigratedRows = migratedRows; StrandedRows = strandedRows; MigrationErrors = migrationErrors; } /// /// A change the synchronisation refuses before any value is touched, because no conversion between the two types /// keeps the meaning of the stored values. says why; it is also . /// public RedbTypeMigrationException( long structureId, string propertyName, long schemeId, string? schemeName, string oldTypeName, string newTypeName, int affectedRows, string reason) : base(BuildRefusalMessage(propertyName, schemeId, schemeName, oldTypeName, newTypeName, affectedRows, reason)) { StructureId = structureId; PropertyName = propertyName; SchemeId = schemeId; SchemeName = schemeName; OldTypeName = oldTypeName; NewTypeName = newTypeName; AffectedRows = affectedRows; MigratedRows = 0; StrandedRows = affectedRows; MigrationErrors = reason; } private static string BuildRefusalMessage( string propertyName, long schemeId, string? schemeName, string oldTypeName, string newTypeName, int affectedRows, string reason) { var scheme = schemeName is null ? $"id={schemeId}" : $"'{schemeName}' (id={schemeId})"; return $"Scheme {scheme}: property '{propertyName}' cannot change from '{oldTypeName}' to '{newTypeName}' " + $"while it holds {affectedRows} stored value(s): {reason} " + $"The structure was left at '{oldTypeName}' and no value was changed. Revert the property to " + $"'{oldTypeName}' in the CLR class, or move the values to a new property yourself."; } private static string BuildMessage( long structureId, string propertyName, long schemeId, string? schemeName, string oldTypeName, string newTypeName, int affectedRows, int migratedRows, int strandedRows, string? migrationErrors) { var scheme = schemeName is null ? $"id={schemeId}" : $"'{schemeName}' (id={schemeId})"; // The two cases differ in what the database now holds, so they must not share a wording. var state = migratedRows == 0 ? $"nothing was moved: all {affectedRows} value(s) still hold their original content" : $"{migratedRows} of {affectedRows} value(s) were moved and {strandedRows} could not be — " + "no value was destroyed, but the two groups now live in different columns"; var detail = string.IsNullOrWhiteSpace(migrationErrors) ? "" : $" Provider says: {migrationErrors}"; return $"Scheme {scheme}: property '{propertyName}' changed type from '{oldTypeName}' to '{newTypeName}', " + $"but the migration did not complete — {state}. " + $"The structure type was left at '{oldTypeName}' on purpose, so this keeps failing until it is " + $"resolved rather than turning into silently missing values.{detail} " + $"Either migrate manually and start again: " + $"SELECT * FROM migrate_structure_type({structureId}, '{oldTypeName}', '{newTypeName}', false); " + $"— or revert the property to '{oldTypeName}' in the CLR class."; } } Path: redb/redb.Core/Exceptions/RedbUniqueKeyDefinitionException.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/Exceptions/RedbUniqueKeyDefinitionException.cs ---- using System; namespace redb.Core.Exceptions; /// /// Thrown by scheme synchronisation when [RedbUnique] sits where it cannot be enforced: on a /// property inside an array, a dictionary or a nested class, on a reference, a list item, an enum, a /// collection, or on a type with no canonical form. Rejected at synchronisation, not at insert — /// otherwise the behaviour would degrade into an index that silently never fires. /// /// /// Also thrown by GetByUniqueAsync when asked for a property that is not a unique key. /// /// public class RedbUniqueKeyDefinitionException : Exception { /// CLR type or scheme the property belongs to. public string SchemeName { get; } /// The offending property. public string PropertyName { get; } /// Why it cannot be a unique key. public string Reason { get; } public RedbUniqueKeyDefinitionException(string schemeName, string propertyName, string reason) : base($"[RedbUnique] on '{schemeName}.{propertyName}' cannot be enforced: {reason}. " + "A unique key must be a scalar property — string, integer, Guid, bool, double, " + "decimal, date/time or byte[] — of the Props class or of a nested class reached " + "without crossing a collection.") { SchemeName = schemeName; PropertyName = propertyName; Reason = reason; } } Path: redb/redb.Core/Exceptions/RedbUniqueKeyValueException.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/Exceptions/RedbUniqueKeyValueException.cs ---- using System; namespace redb.Core.Exceptions; /// /// A value written into a [RedbUnique] field has no canonical form — NaN, an /// infinity — so no key can be computed for it. Raised at save time by UniqueKeyEncoder. /// public class RedbUniqueKeyValueException : Exception { /// Structure (field) the value was meant for. public long StructureId { get; } /// Why the value cannot be a key. public string Reason { get; } public RedbUniqueKeyValueException(long structureId, string reason) : base($"Value for unique key structure id={structureId} cannot be stored: {reason}.") { StructureId = structureId; Reason = reason; } /// An object-level key (Э1, _objects._value_unique) that cannot be stored. public RedbUniqueKeyValueException(string reason) : base($"Object unique key cannot be stored: {reason}.") { Reason = reason; } } Path: redb/redb.Core/Exceptions/RedbUniqueViolationException.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/Exceptions/RedbUniqueViolationException.cs ---- using System; namespace redb.Core.Exceptions; /// /// A save was rejected because a [RedbUnique] key is already taken by another object of the /// scheme. Raised in place of the driver's own unique-violation error (PostgreSQL 23505, SQL Server /// 2601/2627, SQLite 2067) so that callers can catch one type on every provider and read which key /// collided, rather than match on message text. /// /// /// Everything but is best-effort: the driver message names the index and, on /// PostgreSQL and SQL Server, the key tuple — from which the structure and therefore the scheme and /// property are resolved. SQLite names only the columns. When something could not be resolved the /// property is null; the original exception is always attached. /// /// public class RedbUniqueViolationException : Exception { /// Scheme of the object that was being saved, when resolved. public long? SchemeId { get; } /// Scheme name, when resolved. public string? SchemeName { get; } /// Structure (field) whose key collided, when the driver reported the key tuple. public long? StructureId { get; } /// Property backing that structure, when resolved. public string? PropertyName { get; } /// Name of the unique index or constraint the database reported, when it did. public string? ConstraintName { get; } /// The driver's own detail line (PostgreSQL DETAIL, SQL Server message), verbatim. public string? Detail { get; } /// Which unique index rejected the save - the object key (ValueUnique) or a /// [RedbUnique] property (BR-8, 2026-09-02). Classified on every provider: PostgreSQL /// and MSSQL name the index, SQLite names the columns; both spellings resolve. public RedbUniqueViolationKind Kind { get; } /// The driver exception. public Exception Cause { get; } public RedbUniqueViolationException( long? schemeId, string? schemeName, long? structureId, string? propertyName, string? constraintName, string? detail, Exception cause, RedbUniqueViolationKind kind = RedbUniqueViolationKind.Unknown) : base(BuildMessage(schemeId, schemeName, structureId, propertyName, constraintName, detail, kind), cause) { SchemeId = schemeId; SchemeName = schemeName; StructureId = structureId; PropertyName = propertyName; ConstraintName = constraintName; Detail = detail; Cause = cause; Kind = kind; } private static string BuildMessage( long? schemeId, string? schemeName, long? structureId, string? propertyName, string? constraintName, string? detail, RedbUniqueViolationKind kind) { var where = kind == RedbUniqueViolationKind.ObjectKey && propertyName == null ? "the object key (ValueUnique)" + (schemeName != null ? $" of scheme '{schemeName}'" : schemeId.HasValue ? $" of scheme id={schemeId}" : "") : propertyName != null ? $"property '{propertyName}'" + (schemeName != null ? $" of scheme '{schemeName}'" : schemeId.HasValue ? $" of scheme id={schemeId}" : "") : structureId.HasValue ? $"structure id={structureId}" : constraintName != null ? $"index '{constraintName}'" : "a unique key"; var tail = string.IsNullOrWhiteSpace(detail) ? "" : $" Database says: {detail}"; return $"Unique key violated on {where}: another object of the scheme already holds this value. " + $"Keys are compared on their canonical form (see UniqueKeyEncoder); a soft-deleted object " + $"releases its key, a live one does not.{tail}"; } } Path: redb/redb.Core/Exceptions/RedbUniqueViolationKind.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/Exceptions/RedbUniqueViolationKind.cs ---- namespace redb.Core.Exceptions; /// /// Which unique index rejected a save - first-class discrimination for /// (BR-8, Tsak report, 2026-09-02), so callers /// branch on a value instead of matching provider-specific constraint-name strings. /// public enum RedbUniqueViolationKind { /// The driver's report could not be classified; inspect /// / Detail / Cause. Unknown = 0, /// The object key: UIX__objects__scheme_unique over /// (_id_scheme, _value_unique) - another object of the scheme already holds this /// ValueUnique. SaveByUniqueAsync retries exactly this kind once onto the /// current winner's row. ObjectKey = 1, /// A [RedbUnique] property key: UIX__values__structure_unique - another /// object holds this value in the same property. Never retried by the object-key upsert. Property = 2, } Path: redb/redb.Core/Exceptions/RedbUnloadedReferenceException.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/Exceptions/RedbUnloadedReferenceException.cs ---- using System; namespace redb.Core.Exceptions; /// /// Thrown when a reference whose properties were never loaded is saved directly: the object has an id and no loaded /// properties - a hand-written new RedbObject<T> { id = x }, a stub whose lazy load the getter did not /// keep (a shared instance inside a transaction). It names another object; it is not that object. Saving it saved /// whatever a fresh load returned, and the caller's edits were lost silently (review after 4.0.0). Reading the /// Props of such a reference still answers null: plain System.Text.Json serialization of a graph reads the /// getter, and an exception there would fail every API response carrying a hand-made reference. /// public class RedbUnloadedReferenceException : InvalidOperationException { /// Id of the referenced object. public long ObjectId { get; } /// Scheme of that object; 0 when the reference does not carry it. public long SchemeId { get; } public RedbUnloadedReferenceException(long objectId, long schemeId) : base($"Object {objectId} (scheme {schemeId}) is a reference whose properties were never loaded: it names " + "another object, it is not that object, and saving it would save a fresh reload instead of your edits. " + "Load it explicitly - redb.LoadAsync(id), redb.LoadReferencesAsync(parent, p => p.Reference) - edit " + "and save the loaded object; a shared (cached) instance read inside a transaction keeps nothing it loads.") { ObjectId = objectId; SchemeId = schemeId; } } Path: redb/redb.Core/Exceptions/RedbUnsupportedCollectionException.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/Exceptions/RedbUnsupportedCollectionException.cs ---- using System; namespace redb.Core.Exceptions; /// /// A property is declared with a collection type that redb does not store: HashSet<T>, /// ISet<T>, ObservableCollection<T>, Queue<T>, Stack<T>, /// IReadOnlyList<T>, SortedDictionary<K, V>, IReadOnlyDictionary<K, V> or any other /// collection outside . Before, such a property was stored as one text value holding the name /// of its type, and the object could not be loaded afterwards. The scheme sync refuses such a property before it writes /// anything; a save that meets a collection in a single-value property (a scheme synced before the refusal existed) /// refuses before any row is deleted or written. A class of the application that implements IEnumerable is a class and /// is not refused. /// public class RedbUnsupportedCollectionException : Exception { /// The collection types redb stores, as the refusal text lists them. public const string SupportedTypes = "T[], List, IList, ICollection, IEnumerable, Dictionary and IDictionary"; /// The class (or scheme) that declares the property. public string OwnerName { get; } /// The property. public string PropertyName { get; } /// The declared type of the property, or the type the save met in it, in C# notation. public string PropertyTypeName { get; } /// Refusal of a declared property type, at the scheme sync. public RedbUnsupportedCollectionException(Type ownerType, string propertyName, Type propertyType) : this(RedbNestedCollectionException.Display(ownerType), propertyName, RedbNestedCollectionException.Display(propertyType), atSave: false) { } /// Refusal at a save: the single-value property holds a collection of . public RedbUnsupportedCollectionException(string ownerName, string propertyName, Type foundType) : this(ownerName, propertyName, RedbNestedCollectionException.Display(foundType), atSave: true) { } private RedbUnsupportedCollectionException(string ownerName, string propertyName, string typeName, bool atSave) : base((atSave ? $"The save is refused: the property '{ownerName}.{propertyName}' holds a collection of type '{typeName}'. " : $"The property '{ownerName}.{propertyName}' of type '{typeName}' is refused. ") + $"redb stores a collection property declared as {SupportedTypes}; any other collection type would be " + "written as the name of its type and the object could not be loaded. Declare the property as one of " + "these types, for example List for a set, a queue or a stack and Dictionary for a " + "sorted or read-only dictionary.") { OwnerName = ownerName; PropertyName = propertyName; PropertyTypeName = typeName; } } Path: redb/redb.Core/Exceptions/RedbValueStringTooLongException.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/Exceptions/RedbValueStringTooLongException.cs ---- using System; namespace redb.Core.Exceptions; /// /// _objects._value_string is an identifier column (owner decision 2026-09-02): 450 /// characters, the MSSQL index-key width, enforced in C# so the text-typed PostgreSQL and SQLite /// columns hold the same contract. Long text belongs in _note or in a Props field. /// public class RedbValueStringTooLongException : InvalidOperationException { /// Id of the object whose value was rejected (0 for a new object). public long ObjectId { get; } /// The rejected value's length. public int Length { get; } public RedbValueStringTooLongException(long objectId, int length) : base($"object id={objectId}: _value_string is {length} characters, the limit is 450. " + "The column is for identifiers and external keys; long text belongs in _note or in a Props field.") { ObjectId = objectId; Length = length; } } Path: redb/redb.Core/Extensions/PropertyInfoExtensions.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/Extensions/PropertyInfoExtensions.cs ---- using System.Reflection; using System.Text.Json.Serialization; using redb.Core.Attributes; namespace redb.Core.Extensions { /// /// Extensions for working with PropertyInfo /// internal static class PropertyInfoExtensions { /// /// Checks if property should be ignored by REDB /// /// Property to check /// true if property should be ignored public static bool ShouldIgnoreForRedb(this PropertyInfo property) { return //property.GetCustomAttributes(typeof(JsonIgnoreAttribute), false).Length > 0 || property.GetCustomAttributes(typeof(RedbIgnoreAttribute), false).Length > 0; } } } Path: redb/redb.Core/Extensions/RedbObjectExtensions.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/Extensions/RedbObjectExtensions.cs ---- using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using redb.Core.Providers; using redb.Core.Utils; namespace redb.Core.Extensions { /// /// Extension methods for IRedbObject for convenient work with trees and objects /// public static class RedbObjectExtensions { // ===== SOFT DELETE ===== /// /// Checks whether the object has been soft-deleted (scheme changed to @@__deleted). /// public static bool IsSoftDeleted(this IRedbObject obj) => obj.SchemeId == RedbTypeIds.DeletedScheme; // ===== TREE OPERATIONS ===== /// /// OPTIMIZED version: Checks if object is descendant of specified parent /// Uses already loaded hierarchy from GetPathToRootAsync, but adds cycle protection /// /// Object to check /// Potential ancestor /// Provider for tree operations public static async Task IsDescendantOfAsync( this IRedbObject obj, IRedbObject potentialAncestor, ITreeProvider treeProvider) where T : class, new() { if (obj.Id == potentialAncestor.Id) return false; // Object cannot be descendant of itself try { // Use existing method, but with cycle protection var pathToRoot = await treeProvider.GetPathToRootAsync(obj); // OPTIMIZATION: Use HashSet for O(1) search instead of linear scan var ancestorIds = new HashSet(pathToRoot.Select(ancestor => ancestor.Id)); return ancestorIds.Contains(potentialAncestor.Id); } catch { return false; // In case of error return false } } /// /// Checks if object is an ancestor of the specified descendant /// /// Object to check /// Potential descendant /// Provider for tree operations public static async Task IsAncestorOfAsync( this IRedbObject obj, IRedbObject potentialDescendant, ITreeProvider treeProvider) where T : class, new() { return await potentialDescendant.IsDescendantOfAsync(obj, treeProvider); } /// /// OPTIMIZED version: Gets object level in tree (root = 0) /// Uses cycle protection and more efficient approach /// /// Object /// Provider for tree operations public static async Task GetTreeLevelAsync( this IRedbObject obj, ITreeProvider treeProvider) where T : class, new() { try { var pathToRoot = await treeProvider.GetPathToRootAsync(obj); var pathCount = pathToRoot.Count(); // PROTECTION: If path is too long, there may be a cycle if (pathCount > 1000) { return -1; // Suspiciously deep tree - possible cycle } return Math.Max(0, pathCount - 1); // -1 because path includes the object itself } catch { return -1; // Error determining level } } /// /// Checks if object is a tree leaf (without children) /// /// Object /// Provider for tree operations public static async Task IsLeafAsync( this IRedbObject obj, ITreeProvider treeProvider) where T : class, new() { try { var children = await treeProvider.GetChildrenAsync(obj); return !children.Any(); } catch { return true; // In case of error consider as leaf } } /// /// Gets count of object children /// /// Object /// Provider for tree operations public static async Task GetChildrenCountAsync( this IRedbObject obj, ITreeProvider treeProvider) where T : class, new() { try { var children = await treeProvider.GetChildrenAsync(obj); return children.Count(); } catch { return 0; } } /// /// Gets count of all object descendants /// /// Object /// Provider for tree operations /// Maximum search depth public static async Task GetDescendantsCountAsync( this IRedbObject obj, ITreeProvider treeProvider, int? maxDepth = null) where T : class, new() { try { var descendants = await treeProvider.GetDescendantsAsync(obj, maxDepth); return descendants.Count(); } catch { return 0; } } // ===== STATE CHECKS ===== /// /// Checks if object is active by timestamps /// /// Object /// Date to check (default - current) public static bool IsActiveAt(this IRedbObject obj, DateTime? checkDate = null) { var date = checkDate ?? DateTime.Now; // Check begin date if (obj.DateBegin.HasValue && date < obj.DateBegin.Value) return false; // Check end date if (obj.DateComplete.HasValue && date > obj.DateComplete.Value) return false; return true; } /// /// Checks if object validity has expired /// /// Object /// Date to check (default - current) public static bool IsExpired(this IRedbObject obj, DateTime? checkDate = null) { var date = checkDate ?? DateTime.Now; return obj.DateComplete.HasValue && date > obj.DateComplete.Value; } /// /// Checks if object has started its validity /// /// Object /// Date to check (default - current) public static bool HasStarted(this IRedbObject obj, DateTime? checkDate = null) { var date = checkDate ?? DateTime.Now; return !obj.DateBegin.HasValue || date >= obj.DateBegin.Value; } /// /// Gets object age (time since creation) /// /// Object /// Reference date (default - current) public static TimeSpan GetAge(this IRedbObject obj, DateTime? referenceDate = null) { var date = referenceDate ?? DateTime.Now; return date - obj.DateCreate; } /// /// Gets time since last object modification /// /// Object /// Reference date (default - current) public static TimeSpan GetTimeSinceLastModification(this IRedbObject obj, DateTime? referenceDate = null) { var date = referenceDate ?? DateTime.Now; return date - obj.DateModify; } // ===== UTILITIES ===== /// /// Gets object display name with fallback logic /// /// Object /// Whether to include ID in display name public static string GetDisplayName(this IRedbObject obj, bool includeId = true) { var displayName = obj.Name; // Fallback to values if (string.IsNullOrWhiteSpace(displayName)) { if (!string.IsNullOrWhiteSpace(obj.ValueString)) displayName = obj.ValueString; else if (obj.ValueLong.HasValue) displayName = $"Value_{obj.ValueLong.Value}"; else if (obj.ValueGuid.HasValue) displayName = obj.ValueGuid.Value.ToString("D").Substring(0, 8); else if (obj.Key.HasValue) displayName = $"Key_{obj.Key.Value}"; else displayName = $"Object_{obj.Id}"; } return includeId ? $"{displayName} (#{obj.Id})" : displayName; } /// /// Gets brief object information for debugging /// /// Object public static string GetDebugInfo(this IRedbObject obj) { return $"Object[Id={obj.Id}, Scheme={obj.SchemeId}, Name='{obj.Name}', Parent={obj.ParentId}, Owner={obj.OwnerId}]"; } /// /// Creates hierarchical path string for object /// /// Path objects from root to object /// Separator (default "/") public static string CreateHierarchicalPath(this IEnumerable pathObjects, string separator = "/") { return string.Join(separator, pathObjects.Select(obj => obj.Name ?? $"#{obj.Id}")); } } } Path: redb/redb.Core/Extensions/RedbOptionsBuilder.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/Extensions/RedbOptionsBuilder.cs ---- using Microsoft.Extensions.DependencyInjection; using redb.Core.Models.Configuration; using redb.Core.Services; namespace redb.Core.Extensions; /// /// Infrastructure interface for database providers and Pro extensions. /// Similar to EF Core's IDbContextOptionsBuilderInfrastructure. /// Used by UsePostgres(), UseMsSql(), AddRedbPro(), etc. /// public interface IRedbOptionsBuilderInfrastructure { /// /// Service collection for registering services. /// IServiceCollection Services { get; } /// /// Configuration instance to be populated by provider. /// RedbServiceConfiguration Configuration { get; } /// /// Whether Pro version is being configured. /// Used by AddRedbPro() to mark Pro mode. /// bool IsPro { get; set; } /// /// Kept for source compatibility. redb Pro needs no key: every Pro feature is on without one, and a value given here /// unlocks nothing. /// string? LicenseKey { get; set; } /// /// Register provider-specific services. /// Called by UsePostgres(), UseMsSql(), etc. /// /// Action that registers provider services. /// Parameters: services, configuration, isPro void SetProviderRegistration(Action registration); /// /// Finalize configuration and register all services. /// Called after UseXxx() and Configure() methods. /// void Build(); } /// /// Builder for configuring REDB services. /// Database providers (UsePostgres, UseMsSql) register their implementations via IRedbOptionsBuilderInfrastructure. /// public class RedbOptionsBuilder : IRedbOptionsBuilderInfrastructure { private readonly IServiceCollection _services; private readonly RedbServiceConfiguration _configuration = new(); private Action? _providerRegistration; private bool _isPro; private string? _licenseKey; public RedbOptionsBuilder(IServiceCollection services) { _services = services; } /// /// Kept for source compatibility. redb Pro needs no key: every Pro feature is on without one, and a value given here /// unlocks nothing. /// /// Kept for source compatibility; unlocks nothing. /// Builder for chaining public RedbOptionsBuilder WithLicense(string licenseKey) { _licenseKey = licenseKey; return this; } /// /// Configure RedbServiceConfiguration options. /// /// /// builder.Configure(c => { /// c.EnablePropsCache = true; /// c.PropsSaveStrategy = PropsSaveStrategy.ChangeTracking; /// }); /// public RedbOptionsBuilder Configure(Action configure) { configure(_configuration); return this; } // === IRedbOptionsBuilderInfrastructure explicit implementation === // Available to providers/Pro via cast: ((IRedbOptionsBuilderInfrastructure)builder) IServiceCollection IRedbOptionsBuilderInfrastructure.Services => _services; RedbServiceConfiguration IRedbOptionsBuilderInfrastructure.Configuration => _configuration; bool IRedbOptionsBuilderInfrastructure.IsPro { get => _isPro; set => _isPro = value; } string? IRedbOptionsBuilderInfrastructure.LicenseKey { get => _licenseKey; set => _licenseKey = value; } void IRedbOptionsBuilderInfrastructure.SetProviderRegistration( Action registration) { if (_providerRegistration != null) throw new InvalidOperationException( "Database provider already configured. Call UsePostgres/UseMsSql only once."); _providerRegistration = registration; } void IRedbOptionsBuilderInfrastructure.Build() { if (_providerRegistration == null) throw new InvalidOperationException( "No database provider configured. Call UsePostgres() or UseMsSql() in the options builder."); // Register configuration _services.AddSingleton(_configuration); // Default password hasher: bcrypt, DI-overridable. TryAdd so a user registration made // before AddRedb wins. Never SimplePasswordHasher here - a bare deployment must not // fall back to salted SHA256 (external security report, 2026-09-08). Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions .TryAddSingleton(_services); // Save interceptors subscribed at run time. TryAdd: a registry put in before AddRedb is kept, so containers // that receive the same instance (a host and the named instances it builds) share one set of subscriptions. Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions .TryAddSingleton(_services); // Schema init hosted service — must be registered BEFORE provider services // so it runs before BackgroundDeletionService that queries _objects table _services.AddHostedService(); // Register provider-specific services _providerRegistration(_services, _configuration, _isPro); } } Path: redb/redb.Core/Extensions/RedbServiceCollectionExtensions.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/Extensions/RedbServiceCollectionExtensions.cs ---- using Microsoft.Extensions.DependencyInjection; namespace redb.Core.Extensions; /// /// Extension methods for registering REDB services. /// public static class RedbServiceCollectionExtensions { /// /// Registers REDB OpenSource services with the specified database provider. /// /// /// services.AddRedb(options => options /// .UsePostgres(connectionString) /// .Configure(c => c.EnablePropsCache = true)); /// /// The service collection. /// Action to configure REDB options including database provider. /// The service collection for chaining. public static IServiceCollection AddRedb( this IServiceCollection services, Action configure) { var builder = new RedbOptionsBuilder(services); var infrastructure = (IRedbOptionsBuilderInfrastructure)builder; infrastructure.IsPro = false; configure(builder); infrastructure.Build(); return services; } } Path: redb/redb.Core/Extensions/RedbServiceConfigurationExtensions.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/Extensions/RedbServiceConfigurationExtensions.cs ---- #pragma warning disable CS0618 // implements or uses the deprecated object permissions and roles (RedbDeprecation) using System; using redb.Core.Models.Configuration; namespace redb.Core.Extensions { /// /// Extension methods for working with RedbService configuration /// public static class RedbServiceConfigurationExtensions { /// /// Create builder for configuration /// public static RedbServiceConfigurationBuilder CreateBuilder(this RedbServiceConfiguration configuration) { return new RedbServiceConfigurationBuilder(configuration); } /// /// Merge configurations (target is overwritten with source values) /// public static RedbServiceConfiguration MergeWith(this RedbServiceConfiguration target, RedbServiceConfiguration source) { var result = target.Clone(); // Merge only non-default values if (source.IdResetStrategy != ObjectIdResetStrategy.Manual) result.IdResetStrategy = source.IdResetStrategy; if (source.MissingObjectStrategy != MissingObjectStrategy.ThrowException) result.MissingObjectStrategy = source.MissingObjectStrategy; // Security - always merge result.DefaultCheckPermissionsOnLoad = source.DefaultCheckPermissionsOnLoad; result.DefaultCheckPermissionsOnSave = source.DefaultCheckPermissionsOnSave; result.DefaultCheckPermissionsOnDelete = source.DefaultCheckPermissionsOnDelete; // Other settings result.DefaultStrictDeleteExtra = source.DefaultStrictDeleteExtra; result.AutoSyncSchemesOnSave = source.AutoSyncSchemesOnSave; result.DefaultLoadDepth = source.DefaultLoadDepth; result.DefaultMaxTreeDepth = source.DefaultMaxTreeDepth; result.EnableMetadataCache = source.EnableMetadataCache; result.MetadataCacheLifetimeMinutes = source.MetadataCacheLifetimeMinutes; result.EnableSchemaValidation = source.EnableSchemaValidation; result.EnableDataValidation = source.EnableDataValidation; result.AutoSetModifyDate = source.AutoSetModifyDate; result.AutoRecomputeHash = source.AutoRecomputeHash; // result.DefaultSecurityPriority = source.DefaultSecurityPriority; // Removed result.SystemUserId = source.SystemUserId; // JSON settings result.JsonOptions.WriteIndented = source.JsonOptions.WriteIndented; result.JsonOptions.UseUnsafeRelaxedJsonEscaping = source.JsonOptions.UseUnsafeRelaxedJsonEscaping; return result; } /// /// Check if configuration is safe for production /// public static bool IsProductionSafe(this RedbServiceConfiguration configuration) { return configuration.DefaultCheckPermissionsOnLoad && configuration.DefaultCheckPermissionsOnSave && configuration.DefaultCheckPermissionsOnDelete && configuration.EnableSchemaValidation && configuration.EnableDataValidation && configuration.MissingObjectStrategy == MissingObjectStrategy.ThrowException; } /// /// Check if configuration is optimized for performance /// public static bool IsPerformanceOptimized(this RedbServiceConfiguration configuration) { return !configuration.DefaultCheckPermissionsOnLoad && !configuration.DefaultCheckPermissionsOnSave && !configuration.EnableSchemaValidation && !configuration.EnableDataValidation && configuration.DefaultLoadDepth <= 3 && configuration.EnableMetadataCache; } /// /// Get configuration description /// public static string GetDescription(this RedbServiceConfiguration configuration) { var features = new System.Collections.Generic.List(); // Security if (configuration.DefaultCheckPermissionsOnLoad || configuration.DefaultCheckPermissionsOnSave || configuration.DefaultCheckPermissionsOnDelete) { features.Add("Security enabled"); } // Strategies if (configuration.IdResetStrategy != ObjectIdResetStrategy.Manual) features.Add($"ID Reset: {configuration.IdResetStrategy}"); if (configuration.MissingObjectStrategy != MissingObjectStrategy.ThrowException) features.Add($"Missing Objects: {configuration.MissingObjectStrategy}"); // Performance if (configuration.EnableMetadataCache) features.Add($"Cache: {configuration.MetadataCacheLifetimeMinutes}min"); if (configuration.DefaultLoadDepth != 10) features.Add($"Load Depth: {configuration.DefaultLoadDepth}"); // Validation if (!configuration.EnableSchemaValidation || !configuration.EnableDataValidation) features.Add("Validation disabled"); return string.Join(", ", features); } /// /// Apply temporary configuration with automatic restore /// public static IDisposable ApplyTemporary(this IRedbService service, RedbServiceConfiguration temporaryConfig) { // CFG-1: every behaviour setting, in place (providers hold the same configuration instance); the // connection identity stays. It used to be a hand-written list of fourteen settings out of thirty-six. var originalConfig = service.Configuration.Clone(); service.UpdateConfiguration(config => config.CopyBehaviourFrom(temporaryConfig)); return new TemporaryConfigurationScope(service, originalConfig); } /// /// Apply temporary configuration via builder /// public static IDisposable ApplyTemporary(this IRedbService service, Func configure) { // CFG-1: the builder works on a copy. On the live configuration the change was applied before the // snapshot meant to undo it was taken, and the scope "restored" the changed values. var builder = new RedbServiceConfigurationBuilder(service.Configuration.Clone()); var temporaryConfig = configure(builder).Build(); return service.ApplyTemporary(temporaryConfig); } } /// /// Scope for temporary configuration /// internal class TemporaryConfigurationScope : IDisposable { private readonly IRedbService _service; private readonly RedbServiceConfiguration _originalConfiguration; private bool _disposed = false; public TemporaryConfigurationScope(IRedbService service, RedbServiceConfiguration originalConfiguration) { _service = service; _originalConfiguration = originalConfiguration; } public void Dispose() { if (!_disposed) { _service.UpdateConfiguration(config => config.CopyBehaviourFrom(_originalConfiguration)); _disposed = true; } } } } Path: redb/redb.Core/Extensions/RedbServiceInitializationExtensions.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/Extensions/RedbServiceInitializationExtensions.cs ---- using System; using System.Reflection; using System.Threading.Tasks; namespace redb.Core.Extensions { /// /// Obsolete initialization entry points, kept for callers that invoke them explicitly. Both delegate to /// . /// /// /// INIT-1 (review 2026-09-24): these used to carry a copy of the start-up sequence. The copy synchronized the /// schemes in parallel on one service instance (Task.WhenAll) - the one thing a single instance does not /// support - skipped the up-front validation of scheme names, and swallowed every synchronization error in a /// bare catch. The service's own InitializeAsync does all of it sequentially and loudly, and more. /// public static class RedbServiceInitializationExtensions { /// /// Initializes REDB at application start-up. Same as await redb.InitializeAsync(assemblies), /// which C# already picks over this extension when called on an instance. /// /// IRedbService instance /// Assemblies to scan. If not specified - all loaded assemblies are scanned [Obsolete("Use await redb.InitializeAsync() directly - method is integrated into IRedbService")] public static Task InitializeAsync(this IRedbService redb, params Assembly[] assemblies) => redb.InitializeAsync(assemblies); /// /// Synchronizes every scheme with [RedbScheme] - as part of the full initialization, which is the /// only supported way to do it. /// /// IRedbService instance /// Assemblies to scan. If not specified - all loaded are scanned [Obsolete("Use await redb.InitializeAsync() - method includes scheme synchronization")] public static Task AutoSyncSchemesAsync(this IRedbService redb, params Assembly[] assemblies) => redb.InitializeAsync(assemblies); } } Path: redb/redb.Core/IRedbScopeSource.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/IRedbScopeSource.cs ---- using System; namespace redb.Core; /// /// A service that opens scopes of the container it came from: for code that holds one service and needs another of /// the same database per unit of work - a parallel flow, a background job, an audit written outside any request. /// One is one connection, so parallel work needs a service each; a service resolved from /// the root provider lends its lazy loads a scope the same way (review after 4.0.0, finding 4). A service built /// without a container has nothing to open a scope from (). /// public interface IRedbScopeSource { /// Whether can open a scope: the service came from a container with a scope factory. bool CanCreateScope { get; } /// /// Opens a scope of the service's container and returns its service of the same database; the holder owns the /// scope and disposes it when the unit of work ends. Throws when there is /// no container ( is false), or when the scope's service reads another database - a /// container that registers differently per resolution. /// RedbScope CreateScope(); } Path: redb/redb.Core/IRedbService.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/IRedbService.cs ---- using redb.Core.Query; using redb.Core.Providers; using redb.Core.Data; using System; using System.Collections.Generic; using System.Reflection; using System.Threading; using System.Threading.Tasks; using redb.Core.Models.Contracts; using redb.Core.Models.Configuration; namespace redb.Core { /// /// Main REDB service interface - composition of all providers. /// public interface IRedbService : ISchemeSyncProvider, IObjectStorageProvider, ITreeProvider, IPermissionProvider, IQueryableProvider, IValidationProvider, IRedbScopeSource { // === DATABASE CONTEXT === /// /// Database context for direct SQL queries. /// Replaces EF Core RedbContext. /// IRedbContext Context { get; } // === PROVIDERS === /// /// Provider for user management. /// IUserProvider UserProvider { get; } /// /// Provider for role management. /// [Obsolete(RedbDeprecation.PermissionsAndRoles)] IRoleProvider RoleProvider { get; } /// /// Provider for list management. /// IListProvider ListProvider { get; } /// /// Makes this service the scope lazy loads run on, for the returned block (owner decision 2026-09-15): a data /// object owns no connection, and RedbListItem.Object or the Props of a reference stub load on the live redb /// scope of whoever reads them. A service is current by itself in the flow that resolved it; UI event handlers /// (Blazor Server, WebAssembly, MAUI) and callbacks that run in another execution context wrap their reads in /// using (redb.BeginAccess()) { ... }. /// IDisposable BeginAccess(); /// /// The block form of the query planner option /// (): the option turns the query /// planner on or off for the whole service, this method for the returned block only. /// using (redb.WithQueryPlanner(false)) { ... } reads the queries inside it with the query planner off, in /// the aggregate pivot form; true turns the query planner on, and it chooses the streams form where it can. /// Pro only; on Free, which has no /// planner, the block changes nothing. /// /// Scope rules (an , as ): /// the block holds for the flow that opened it, the awaits inside it included, and for every task started inside /// it (parallel queries of one block all see it); concurrent requests keep the configuration. What counts is /// where a query runs, not where it was built: an IRedbQueryable composed inside a block and enumerated /// after it runs with the value in effect at the enumeration, while a call such as ToListAsync() made inside /// the block keeps the block's value even if it is awaited after it. Blocks nest; disposing one restores the value /// before it. Open the block in the method that runs the queries: a value set inside an async method does not flow /// back to its caller. /// /// IDisposable WithQueryPlanner(bool enabled) => redb.Core.Query.QueryPlannerScope.Unchanged; /// /// Loads the linked objects of in one query on this service's connection, publishes them /// on the items and returns them by id. Items already carrying their object and items without a link are skipped; /// an object that does not exist is absent from the result and its item stays lazy. /// Task> LoadLinkedObjectsAsync( System.Collections.Generic.IEnumerable items, CancellationToken cancellationToken = default); /// /// Storage maintenance: planner statistics (AnalyzeAsync after bulk writes) and /// index health (GetIndexStatsAsync). Explicit calls only - never a side effect. /// IMaintenanceProvider Maintenance { get; } // === CONFIGURATION === /// /// Current service configuration. /// RedbServiceConfiguration Configuration { get; } /// /// Cache domain identifier for this service instance. /// Used to isolate caches between different database connections. /// string CacheDomain { get; } /// /// Update configuration. /// void UpdateConfiguration(Action configure); /// /// Update configuration via builder. /// void UpdateConfiguration(Action configureBuilder); // === SECURITY CONTEXT === /// /// Security context for user and permission management. /// IRedbSecurityContext SecurityContext { get; } /// /// Set current user. /// void SetCurrentUser(IRedbUser user); /// /// Create temporary system context. /// IDisposable CreateSystemContext(); /// /// Get effective user ID with fallback logic. /// long GetEffectiveUserId(); // === INITIALIZATION === /// /// Initialize REDB system at application startup. /// Automatically performs: /// 1. Synchronization of all schemes with RedbSchemeAttribute /// 2. RedbObjectFactory initialization /// 3. AutomaticTypeRegistry initialization /// 4. GlobalPropsCache initialization (if enabled in configuration) /// 5. Setting global scheme provider for RedbObject /// /// Assemblies to scan. If not specified - all loaded assemblies are scanned Task InitializeAsync(params Assembly[] assemblies); // === DATABASE SCHEMA MANAGEMENT === /// /// Ensures the REDB database schema exists. /// If the core tables are not found, executes the full initialization script. /// Safe to call on every startup — idempotent. /// Task EnsureDatabaseAsync(); /// /// Returns the full SQL script that creates the REDB schema. /// Useful for manual database setup or CI/CD pipelines. /// string GetSchemaScript(); /// /// Returns the SQL script that brings an existing database up to the module version this /// build requires — the same text start-up applies automatically when the connected role is /// allowed to. Hand it to the schema owner when it is not (see /// ). Idempotent: safe to re-run. /// Returns null for providers that have no versioned module (SQLite upgrades itself, /// the database file belongs to the process). /// string? GetUpgradeScript(); /// /// Problems of the database schema that do not stop the service but need a person, as found by the last /// , or scheme synchronization: each is logged as /// an error when found, at every start until resolved. Empty when the schema is sound. Shared by every instance /// of the service on one database (cache domain): a scoped instance of a health check sees what the start found /// in its own scope. Meant for a health check (Degraded while not empty); cheap, reads no database. /// IReadOnlyList SchemaProblems => Array.Empty(); /// /// Looks for schema problems in the database again (read only, no schema lock) and returns the current list, /// the one holds from then on. /// Task> CheckSchemaAsync(CancellationToken cancellationToken = default) => Task.FromResult(SchemaProblems); /// /// Compares the indexes of the database with those a fresh database of this build has: the base schema, and with /// Pro the indexes of the modules in use. Reports every expected index that is missing, INVALID (PostgreSQL, an /// interrupted concurrent build) or defined otherwise, with what it serves. Read only; indexes the database has /// beyond these are not reported. Also run at start-up (CheckBaseIndexesOnStart), which logs one Warning. /// Task CheckBaseIndexesAsync(CancellationToken cancellationToken = default) => throw new NotSupportedException("This service does not check its indexes."); /// /// Builds the expected indexes the check finds missing or INVALID (an INVALID one is dropped first); an index /// defined otherwise is reported and never touched. limits it to those indexes. /// PostgreSQL builds with CREATE INDEX CONCURRENTLY, so reads and writes go on; SQL Server with ONLINE = ON on /// the editions that have it, and on the others builds nothing unless is set, /// returning the statements instead (an offline build blocks writes to the table while it runs); SQLite builds /// plainly. Runs under the schema lock. An explicit act: start-up never builds a missing base index. On SQLite, /// before it builds a unique index on the place of a value it looks for places that hold more than one row; such an /// index is not built, the places are listed in , nothing is /// deleted. /// Task RepairBaseIndexesAsync(IReadOnlyCollection? names = null, bool allowOffline = false, CancellationToken cancellationToken = default) => throw new NotSupportedException("This service does not repair its indexes."); /// /// Initialize REDB system at application startup, optionally creating the database schema first. /// /// If true, calls before initialization. /// If false and the database has no redb schema yet, initialization stops with /// - creation is opt-in, never a side effect. /// Assemblies to scan. If not specified — all loaded assemblies are scanned. Task InitializeAsync(bool ensureCreated, params Assembly[] assemblies); string dbVersion { get; } /// /// Database type (e.g., "PostgreSQL"). /// string dbType { get; } /// /// Database migration version. /// string dbMigration { get; } /// /// Database size in bytes, as the server reports it (optional). /// long? dbSize { get; } /// /// Asynchronously retrieves the database version using the provider-specific version SQL. /// Intended for health probes and other non-blocking callers (the synchronous /// blocks the calling thread and must not be used from request-pipeline code). /// /// Cancellation token propagated to the underlying ADO.NET call. /// Version string returned by the database, or null when the query yields no row. Task GetDbVersionAsync(CancellationToken cancellationToken = default); } } Path: redb/redb.Core/Interception/IRedbSaveInterceptor.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/Interception/IRedbSaveInterceptor.cs ---- using redb.Core.Models.Configuration; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using redb.Core.Models.Security; namespace redb.Core.Interception; /// /// Save-pipeline interceptor (discussion #12, items 3-4), deliberately shaped after EF Core's /// ISaveChangesInterceptor so the behaviour is familiar: /// /// runs after the object graph is collected and BEFORE the /// transaction opens; an exception thrown here CANCELS the save and propagates to the caller — /// nothing has touched the database yet. /// runs after the transaction has committed; an exception /// propagates to the caller (exactly like EF), but the data IS saved — the save cannot be /// un-committed from here. /// /// Register any number via DI (services.AddSingleton<IRedbSaveInterceptor, ...>()); /// they run in registration order. Code that cannot reach that container (a module in its own /// AssemblyLoadContext) subscribes at run time through ; /// those run after the DI ones. With none registered and none subscribed the pipeline pays nothing — /// the change feed below is not even collected. /// /// Both hooks run INSIDE the SaveAsync call, and one scope is one save (the CT-4 guard): an /// interceptor that writes its journal as redb objects through the SAME service scope will trip /// that guard deterministically. Write through a separate scope (scoped IRedbService from a /// scope factory), or buffer and flush outside the save. /// /// /// Audit and impersonation live here by design: the application sees every object (and under /// ChangeTracking every value-level change) next to whatever pair of real/effective users it /// tracks, and writes its own journal - the framework does not prescribe one. /// /// /// Atomic audit (discussion #12 follow-up): by default the hooks do not share the save's /// transaction (Saving runs before BEGIN so a veto needs no rollback; Saved runs after COMMIT /// so a hook can never unwind it). When the audit row must be atomic with the write, wrap the /// call in your own transaction: /// /// await redb.Context.ExecuteAtomicAsync(async () => /// { /// await redb.SaveAsync(obj); // the whole pipeline, SavedAsync included, runs inside /// }); /// /// Inside that scope an insert from SavedAsync via redb.Context.ExecuteAsync(...) (a /// plain flat audit table is the recommended shape) joins the same transaction and commits or /// rolls back together with the save. The same works for DeleteAsync and DeletedAsync. /// /// public interface IRedbSaveInterceptor { Task SavingAsync(RedbSavingContext context, CancellationToken cancellationToken = default) => Task.CompletedTask; Task SavedAsync(RedbSavedContext context, CancellationToken cancellationToken = default) => Task.CompletedTask; /// /// Before a hard delete executes (owner decision: deletes are intercepted too). An exception /// cancels the delete - nothing has been removed yet. Fires for the intent: some of the ids /// may turn out not to exist. /// Task DeletingAsync(RedbDeletingContext context, CancellationToken cancellationToken = default) => Task.CompletedTask; /// /// After a hard delete committed. An exception propagates, but the rows are gone. /// Task DeletedAsync(RedbDeletedContext context, CancellationToken cancellationToken = default) => Task.CompletedTask; } /// What a hard delete is about to remove. public sealed class RedbDeletingContext { /// /// Ids the caller asked to delete (the intent). For DeleteSubtreeAsync: the start object and every descendant it /// collected. /// public required IReadOnlyList ObjectIds { get; init; } /// /// The object instances, when the caller had them (delete-by-object overloads); empty for /// delete-by-id. Database-side cascades (children) are not enumerated here. /// public required IReadOnlyList KnownObjects { get; init; } public required IRedbUser EffectiveUser { get; init; } } /// What a hard delete has removed. public sealed class RedbDeletedContext { public required IReadOnlyList ObjectIds { get; init; } public required IReadOnlyList KnownObjects { get; init; } public required IRedbUser EffectiveUser { get; init; } /// /// The objects of this call deleted (cascades not included); for DeleteSubtreeAsync, the /// objects of the subtree it deleted. /// public required int DeletedCount { get; init; } } /// What a save is about to do. Handed to . public sealed class RedbSavingContext { /// The objects the caller passed to SaveAsync. public required IReadOnlyList RootObjects { get; init; } /// The full collected graph: roots plus nested objects reached through Props. public required IReadOnlyList AllObjects { get; init; } /// The user the save is executed as (the effective user). public required IRedbUser EffectiveUser { get; init; } public required PropsSaveStrategy Strategy { get; init; } /// /// The objects this save CREATES - the ones that arrived without an id. At this point their /// Id is still 0 (EF temporary-key semantics: Saving runs before ids, hashes and the /// unchanged-set are computed, precisely so the interceptor MAY mutate Props and every /// derived artefact reflects the edit); the final ids arrive in /// . The exotic case of a hand-assigned id that /// does not exist in the database is inserted by the strategy but not listed here. /// public required IReadOnlyList NewObjects { get; init; } } /// What a save has done. Handed to . public sealed class RedbSavedContext { public required IReadOnlyList RootObjects { get; init; } public required IReadOnlyList AllObjects { get; init; } public required IRedbUser EffectiveUser { get; init; } public required PropsSaveStrategy Strategy { get; init; } /// Ids of the root objects, in the order the caller passed them. public required IReadOnlyList SavedIds { get; init; } /// Final ids of the objects this save created (). public required IReadOnlySet NewObjectIds { get; init; } /// /// Ids of existing objects the hash shortcut (F1) excluded from the value pipeline - their /// content was unchanged and no value-level work happened. Null when the shortcut found /// nothing or is inactive. Computed after Saving (so it reflects Saving-time edits), hence /// it lives here and not in the Saving context. /// public IReadOnlySet? UnchangedByHash { get; init; } /// /// Value-level changes the diff actually applied — ChangeTracking only (null under /// DeleteInsert, which rewrites everything and diffs nothing). The diff covers EXISTING /// objects: values of objects this save created go straight to insert and are not listed - /// read creations from and the objects themselves. The list holds /// the diff's own working rows: treat it as a read-only snapshot. /// public IReadOnlyList? Changes { get; init; } } public enum RedbValueChangeType { Insert, Update, Delete, } /// /// One value-level change from the ChangeTracking diff, flattened onto Core types (the tree /// machinery itself is a Pro internal). Old is null for an insert, New for a delete. /// public sealed class RedbValueChange { public required RedbValueChangeType Type { get; init; } /// /// The change in the model's terms: the property path as declared on Props — /// "Title", "Items[1].Price", "Meta[m0]". What an audit journal prints; /// the raw rows below are for consumers that need the storage-level detail. /// public required string PropertyPath { get; init; } public RedbValue? OldValue { get; init; } public RedbValue? NewValue { get; init; } public long ObjectId => (NewValue ?? OldValue)?.IdObject ?? 0; } Path: redb/redb.Core/Interception/IRedbSaveInterceptorRegistry.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/Interception/IRedbSaveInterceptorRegistry.cs ---- namespace redb.Core.Interception; /// /// Save interceptors added and removed while the process runs: code that cannot reach the DI container the redb /// service was built from (a module loaded into its own AssemblyLoadContext, for instance) subscribes here for as /// long as it lives. Registered as a singleton by AddRedb and AddRedbPro (TryAdd: an instance put into /// the container before is kept, so several containers may share one registry); resolve it as /// IRedbSaveInterceptorRegistry. /// /// An interceptor from the registry runs after the ones registered in DI, in the order of /// , with exactly the semantics of (Saving and Deleting before /// the transaction, Saved and Deleted after the commit, everything inside an ExecuteAtomicAsync scope). /// /// /// Scope of a subscription: it sees EVERY save and delete of the process made through a redb service whose container /// holds this registry, scopes already open included, other modules' saves included, and the named instances of /// RedbInstanceFactory built over the same registry. An exception thrown from SavingAsync or /// DeletingAsync therefore cancels any save or delete of the process, not only the subscriber's own. /// /// /// A subscription is picked up by the next save or delete; an operation already running keeps the set it started /// with, so its Saving and Saved (Deleting and Deleted) always reach the same interceptors. Disposing the returned /// handle removes the interceptor for every operation that starts afterwards, and the registry keeps no reference /// to it: an AssemblyLoadContext that held the interceptor's type can unload once its running operations end. /// /// public interface IRedbSaveInterceptorRegistry { /// /// Subscribes . Dispose the result to remove it; disposing twice, or from another /// thread, is safe. The same instance added twice runs twice, and each handle removes one of the two. /// IDisposable Add(IRedbSaveInterceptor interceptor); /// The interceptors subscribed right now, in the order they were added. An immutable snapshot. IReadOnlyList Current { get; } } /// /// The default : an immutable array replaced atomically on every change, /// so a reader takes a snapshot with one read and never locks. /// public sealed class RedbSaveInterceptorRegistry : IRedbSaveInterceptorRegistry { private IRedbSaveInterceptor[] _interceptors = []; /// public IReadOnlyList Current => Volatile.Read(ref _interceptors); /// public IDisposable Add(IRedbSaveInterceptor interceptor) { ArgumentNullException.ThrowIfNull(interceptor); while (true) { var current = Volatile.Read(ref _interceptors); var next = new IRedbSaveInterceptor[current.Length + 1]; current.CopyTo(next, 0); next[^1] = interceptor; if (Interlocked.CompareExchange(ref _interceptors, next, current) == current) return new Subscription(this, interceptor); } } private void Remove(IRedbSaveInterceptor interceptor) { while (true) { var current = Volatile.Read(ref _interceptors); var index = Array.IndexOf(current, interceptor); if (index < 0) return; IRedbSaveInterceptor[] next; if (current.Length == 1) { next = []; } else { next = new IRedbSaveInterceptor[current.Length - 1]; Array.Copy(current, 0, next, 0, index); Array.Copy(current, index + 1, next, index, current.Length - index - 1); } if (Interlocked.CompareExchange(ref _interceptors, next, current) == current) return; } } /// /// The handle of one subscription. Drops its own references on Dispose: a handle the subscriber forgets to /// release does not pin the interceptor either. /// private sealed class Subscription(RedbSaveInterceptorRegistry registry, IRedbSaveInterceptor interceptor) : IDisposable { private RedbSaveInterceptorRegistry? _registry = registry; private IRedbSaveInterceptor? _interceptor = interceptor; public void Dispose() { var interceptor = Interlocked.Exchange(ref _interceptor, null); if (interceptor is null) return; var registry = _registry!; _registry = null; registry.Remove(interceptor); } } } /// /// The interceptors a storage provider runs: the ones registered in DI, fixed when the service is built, followed by /// the current subscriptions of the . The provider takes one /// per save or delete. /// public sealed class RedbSaveInterceptorPipeline { /// No interceptors at all: nothing in DI, no registry. public static RedbSaveInterceptorPipeline Empty { get; } = new(null, null); private readonly IRedbSaveInterceptor[] _fromDi; private readonly IRedbSaveInterceptorRegistry? _registry; public RedbSaveInterceptorPipeline(IEnumerable? fromDi, IRedbSaveInterceptorRegistry? registry) { _fromDi = fromDi?.ToArray() ?? []; _registry = registry; } /// /// The interceptors for one operation, DI first, then the registry in subscription order. Allocates only when /// both sources are non-empty; with neither it returns an empty list, and the operation collects nothing for them. /// public IReadOnlyList Snapshot() { var subscribed = _registry?.Current; if (subscribed is null || subscribed.Count == 0) return _fromDi; if (_fromDi.Length == 0) return subscribed; var all = new IRedbSaveInterceptor[_fromDi.Length + subscribed.Count]; _fromDi.CopyTo(all, 0); for (var i = 0; i < subscribed.Count; i++) all[_fromDi.Length + i] = subscribed[i]; return all; } } Path: redb/redb.Core/Materialization/IPropsMaterializer.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/Materialization/IPropsMaterializer.cs ---- using redb.Core.Models.Contracts; namespace redb.Core.Materialization; /// /// Materializes Props objects from database values. /// Implementation-specific: Pro uses PVT values, Open-Source uses JSON from SQL functions. /// public interface IPropsMaterializer { /// /// Batch materialize Props for multiple objects. /// Loads values from database and populates Props property on each object. /// /// Props class type /// Objects to materialize Props for /// /// Optional: structure IDs to include in projection. /// If null, all fields are loaded. /// Task MaterializeManyAsync( IReadOnlyList objects, IEnumerable? projectedStructureIds = null) where TProps : class, new(); } Path: redb/redb.Core/Models/Collections/TreeCollection.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Core/Models/Collections/TreeCollection.cs ---- using System; using System.Collections.Generic; using System.Collections; using System.Linq; using redb.Core.Utils; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; namespace redb.Core.Models.Collections { /// /// Specialized collection for working with tree-structured objects /// Automatically builds hierarchy when adding nodes /// Supports polymorphic trees (objects of different schemes in one tree) /// public class TreeCollection : IEnumerable { private readonly Dictionary _nodesById = new(); private readonly List _roots = new(); private readonly List _orphans = new(); // Nodes whose parents haven't been added yet /// /// Gets count of nodes in collection /// public int Count => _nodesById.Count; /// /// Gets all root nodes (without parents) /// public IEnumerable Roots => _roots.AsReadOnly(); /// /// Gets all leaf nodes (without children) /// public IEnumerable Leaves => _nodesById.Values.Where(n => n.IsLeaf); /// /// Gets orphan nodes (whose parents haven't been added to collection) /// public IEnumerable Orphans => _orphans.AsReadOnly(); /// /// Adds node to collection and automatically builds hierarchy /// /// Node to add public void Add(ITreeRedbObject node) { if (node == null) throw new ArgumentNullException(nameof(node)); // Check if this node hasn't been added already if (_nodesById.ContainsKey(node.Id)) { throw new InvalidOperationException($"Node with ID {node.Id} already added to collection"); } _nodesById[node.Id] = node; // If this is a root node if (node.IsRoot) { _roots.Add(node); } else { // Look for parent if (_nodesById.TryGetValue(node.ParentId!.Value, out var parent)) { // Parent found - establish connections ConnectChild(parent, node); // Remove from orphans list if it was there _orphans.Remove(node); } else { // Parent not found - add to orphans list _orphans.Add(node); } } // Check if this node became parent for any orphans CheckForOrphansToAdopt(node); } /// /// Adds range of nodes /// /// Nodes to add public void AddRange(IEnumerable nodes) { foreach (var node in nodes) { Add(node); } } /// /// Finds node by ID /// /// Node ID /// Found node or null public ITreeRedbObject? FindById(long id) { return _nodesById.GetValueOrDefault(id); } /// /// Finds nodes by predicate /// /// Search condition /// Collection of found nodes public IEnumerable FindNodes(Func predicate) { return _nodesById.Values.Where(predicate); } /// /// Removes node from collection /// /// ID of node to remove /// true if node was removed public bool Remove(long id) { if (!_nodesById.TryGetValue(id, out var node)) return false; // Remove node from structure if (node.IsRoot) { _roots.Remove(node); } else if (node.Parent != null) { node.Parent.Children.Remove(node); } // Make children orphans foreach (var child in node.Children.ToList()) { child.Parent = null; _orphans.Add(child); } // Remove from all collections _nodesById.Remove(id); _orphans.Remove(node); return true; } /// /// Clears collection /// public void Clear() { _nodesById.Clear(); _roots.Clear(); _orphans.Clear(); } /// /// Checks if node with specified ID is contained /// /// Node ID /// true if node is contained in collection public bool Contains(long id) { return _nodesById.ContainsKey(id); } /// /// Gets collection statistics /// /// Statistics object public TreeCollectionStats GetStats() { var allNodes = _nodesById.Values; var maxDepth = _roots.Any() ? _roots.Max(root => root.MaxDepth) : 0; var totalNodes = allNodes.Count(); return new TreeCollectionStats { TotalNodes = totalNodes, RootNodes = _roots.Count, LeafNodes = Leaves.Count(), OrphanNodes = _orphans.Count, MaxDepth = maxDepth, AverageChildrenPerNode = totalNodes > 0 ? allNodes.Average(n => n.Children.Count) : 0 }; } /// /// Gets flattened list of all nodes with level indication /// /// List of (node, level) pairs public IEnumerable<(ITreeRedbObject Node, int Level)> GetFlattenedWithLevels() { var result = new List<(ITreeRedbObject, int)>(); foreach (var root in _roots) { foreach (var node in root.GetSubtree()) { var level = node.Level; result.Add((node, level)); } } // Add orphans with level -1 (undefined) foreach (var orphan in _orphans) { result.Add((orphan, -1)); } return result; } /// /// Validates tree integrity /// /// List of found issues public IEnumerable ValidateIntegrity() { var issues = new List(); foreach (var node in _nodesById.Values) { // Check that ParentId matches Parent if (node.ParentId.HasValue) { if (node.Parent == null) { issues.Add($"Node {node.Id} has ParentId={node.ParentId}, but Parent=null"); } else if (node.Parent.Id != node.ParentId.Value) { issues.Add($"Node {node.Id}: ParentId={node.ParentId} doesn't match Parent.Id={node.Parent.Id}"); } } // Check that all children have correct back reference foreach (var child in node.Children) { if (child.Parent != node) { issues.Add($"Child node {child.Id} doesn't reference parent {node.Id}"); } if (child.ParentId != node.Id) { issues.Add($"Child node {child.Id}: ParentId={child.ParentId} doesn't match parent {node.Id}"); } } } return issues; } #region Private Methods /// /// Establishes parent-child relationship /// private void ConnectChild(ITreeRedbObject parent, ITreeRedbObject child) { child.Parent = parent; if (!parent.Children.Contains(child)) { parent.Children.Add(child); } } /// /// Checks if node became parent for any orphans /// private void CheckForOrphansToAdopt(ITreeRedbObject potentialParent) { var childrenToAdopt = _orphans.Where(orphan => orphan.ParentId == potentialParent.Id).ToList(); foreach (var child in childrenToAdopt) { ConnectChild(potentialParent, child); _orphans.Remove(child); } } #endregion #region IEnumerable Implementation public IEnumerator GetEnumerator() { return _nodesById.Values.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } #endregion } /// /// Typed version of collection for backward compatibility /// Wrapper over polymorphic TreeCollection with type safety /// /// Type of object properties public class TreeCollection : IEnumerable> where TProps : class, new() { private readonly TreeCollection _baseCollection = new(); /// /// Gets count of nodes in collection /// public int Count => _baseCollection.Count; /// /// Gets all root nodes (without parents) /// public IEnumerable> Roots => _baseCollection.Roots.Cast>(); /// /// Gets all leaf nodes (without children) /// public IEnumerable> Leaves => _baseCollection.Leaves.Cast>(); /// /// Gets orphan nodes (whose parents haven't been added to collection) /// public IEnumerable> Orphans => _baseCollection.Orphans.Cast>(); /// /// Adds typed node to collection /// public void Add(ITreeRedbObject node) { _baseCollection.Add(node); } /// /// Adds range of typed nodes /// public void AddRange(IEnumerable> nodes) { _baseCollection.AddRange(nodes.Cast()); } /// /// Finds typed node by ID /// public ITreeRedbObject? FindById(long id) { return _baseCollection.FindById(id) as ITreeRedbObject; } /// /// Finds typed nodes by predicate /// public IEnumerable> FindNodes(Func, bool> predicate) { return _baseCollection.FindNodes(node => node is ITreeRedbObject typed && predicate(typed)) .Cast>(); } /// /// Removes node from collection /// public bool Remove(long id) => _baseCollection.Remove(id); /// /// Clears collection /// public void Clear() => _baseCollection.Clear(); /// /// Checks if node with specified ID is contained /// public bool Contains(long id) => _baseCollection.Contains(id); /// /// Gets collection statistics /// public TreeCollectionStats GetStats() => _baseCollection.GetStats(); /// /// Gets flattened list of all typed nodes with level indication /// public IEnumerable<(ITreeRedbObject Node, int Level)> GetFlattenedWithLevels() { return _baseCollection.GetFlattenedWithLevels() .Where(item => item.Node is ITreeRedbObject) .Select(item => ((ITreeRedbObject)item.Node, item.Level)); } /// /// Validates tree integrity /// public IEnumerable ValidateIntegrity() => _baseCollection.ValidateIntegrity(); public IEnumerator> GetEnumerator() { return _baseCollection.Cast>().GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } /// /// Tree collection statistics /// public class TreeCollectionStats { public int TotalNodes { get; set; } public int RootNodes { get; set; } public int LeafNodes { get; set; } public int OrphanNodes { get; set; } public int MaxDepth { get; set; } public double AverageChildrenPerNode { get; set; } public override string ToString() { return $"Nodes: {TotalNodes}, Roots: {RootNodes}, Leaves: {LeafNodes}, Orphans: {OrphanNodes}, MaxDepth: {MaxDepth}, AvgChildren: {AverageChildrenPerNode:F1}"; } } } Path: redb/redb.Core/Models/Configuration/ConfigurationValidation.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Core/Models/Configuration/ConfigurationValidation.cs ---- #pragma warning disable CS0618 // implements or uses the deprecated object permissions and roles (RedbDeprecation) using System; using System.Collections.Generic; using System.Linq; namespace redb.Core.Models.Configuration { /// /// Configuration validation result /// public class ConfigurationValidationResult { public bool IsValid { get; set; } public List Errors { get; set; } = new(); public List Warnings { get; set; } = new(); /// /// Are there critical errors /// public bool HasCriticalErrors => Errors.Any(e => e.Severity == ConfigurationValidationSeverity.Critical); /// /// Are there warnings /// public bool HasWarnings => Warnings.Any(); /// /// Get all messages /// public IEnumerable GetAllMessages() { foreach (var error in Errors) yield return $"ERROR: {error.Message}"; foreach (var warning in Warnings) yield return $"WARNING: {warning.Message}"; } } /// /// Configuration validation error /// public class ConfigurationValidationError { public string PropertyName { get; set; } = string.Empty; public string Message { get; set; } = string.Empty; public ConfigurationValidationSeverity Severity { get; set; } = ConfigurationValidationSeverity.Error; public object? CurrentValue { get; set; } public string? SuggestedFix { get; set; } } /// /// Configuration validation warning /// public class ConfigurationValidationWarning { public string PropertyName { get; set; } = string.Empty; public string Message { get; set; } = string.Empty; public string? Recommendation { get; set; } } /// /// Configuration validation error severity level /// public enum ConfigurationValidationSeverity { Warning, Error, Critical } /// /// RedbService configuration validator /// public static class ConfigurationValidator { /// /// Validate configuration /// public static ConfigurationValidationResult Validate(RedbServiceConfiguration configuration) { var result = new ConfigurationValidationResult { IsValid = true }; // Load depth validation ValidateLoadDepth(configuration, result); // Caching validation ValidateCaching(configuration, result); // Security validation ValidateSecurity(configuration, result); // Strategies validation ValidateStrategies(configuration, result); // JSON options validation ValidateJsonOptions(configuration, result); // Settings compatibility check ValidateCompatibility(configuration, result); result.IsValid = !result.HasCriticalErrors; return result; } private static void ValidateLoadDepth(RedbServiceConfiguration config, ConfigurationValidationResult result) { if (config.DefaultLoadDepth < 1) { result.Errors.Add(new ConfigurationValidationError { PropertyName = nameof(config.DefaultLoadDepth), Message = "DefaultLoadDepth must be greater than 0", Severity = ConfigurationValidationSeverity.Critical, CurrentValue = config.DefaultLoadDepth, SuggestedFix = "Set value >= 1" }); } if (config.DefaultLoadDepth > 50) { result.Warnings.Add(new ConfigurationValidationWarning { PropertyName = nameof(config.DefaultLoadDepth), Message = "Large load depth can reduce performance", Recommendation = "Consider using value <= 10 for better performance" }); } if (config.DefaultMaxTreeDepth < 1) { result.Errors.Add(new ConfigurationValidationError { PropertyName = nameof(config.DefaultMaxTreeDepth), Message = "DefaultMaxTreeDepth must be greater than 0", Severity = ConfigurationValidationSeverity.Critical, CurrentValue = config.DefaultMaxTreeDepth, SuggestedFix = "Set value >= 1" }); } if (config.DefaultMaxTreeDepth > 100) { result.Warnings.Add(new ConfigurationValidationWarning { PropertyName = nameof(config.DefaultMaxTreeDepth), Message = "Very large tree depth can cause performance issues", Recommendation = "Consider using value <= 50" }); } } private static void ValidateCaching(RedbServiceConfiguration config, ConfigurationValidationResult result) { if (config.EnableMetadataCache && config.MetadataCacheLifetimeMinutes < 1) { result.Errors.Add(new ConfigurationValidationError { PropertyName = nameof(config.MetadataCacheLifetimeMinutes), Message = "Cache lifetime must be greater than 0 minutes when caching is enabled", Severity = ConfigurationValidationSeverity.Error, CurrentValue = config.MetadataCacheLifetimeMinutes, SuggestedFix = "Set value >= 1 or disable caching" }); } if (config.MetadataCacheLifetimeMinutes > 1440) // 24 hours { result.Warnings.Add(new ConfigurationValidationWarning { PropertyName = nameof(config.MetadataCacheLifetimeMinutes), Message = "Very long cache lifetime can lead to stale data", Recommendation = "Consider using value <= 120 minutes" }); } } private static void ValidateSecurity(RedbServiceConfiguration config, ConfigurationValidationResult result) { if (config.SystemUserId < 0) { result.Errors.Add(new ConfigurationValidationError { PropertyName = nameof(config.SystemUserId), Message = "SystemUserId cannot be negative", Severity = ConfigurationValidationSeverity.Error, CurrentValue = config.SystemUserId, SuggestedFix = "Set value >= 0" }); } // Warning about unsafe configuration if (!config.DefaultCheckPermissionsOnLoad && !config.DefaultCheckPermissionsOnSave && !config.DefaultCheckPermissionsOnDelete) { result.Warnings.Add(new ConfigurationValidationWarning { PropertyName = "Security", Message = "All permission checks are disabled - this may be unsafe", Recommendation = "Enable permission checks for production" }); } } private static void ValidateStrategies(RedbServiceConfiguration config, ConfigurationValidationResult result) { // Strategy compatibility check if (config.IdResetStrategy == ObjectIdResetStrategy.AutoCreateNewOnSave && config.MissingObjectStrategy == MissingObjectStrategy.ThrowException) { result.Warnings.Add(new ConfigurationValidationWarning { PropertyName = "Strategies", Message = "Strategy conflict: AutoCreateNewOnSave + ThrowException may lead to unexpected behavior", Recommendation = "Use MissingObjectStrategy.AutoSwitchToInsert with AutoCreateNewOnSave" }); } } private static void ValidateJsonOptions(RedbServiceConfiguration config, ConfigurationValidationResult result) { if (config.JsonOptions.WriteIndented) { result.Warnings.Add(new ConfigurationValidationWarning { PropertyName = nameof(config.JsonOptions.WriteIndented), Message = "Formatted JSON increases data size", Recommendation = "Disable WriteIndented for production" }); } } private static void ValidateCompatibility(RedbServiceConfiguration config, ConfigurationValidationResult result) { // High performance configuration check if (!config.EnableSchemaValidation && !config.EnableDataValidation && config.EnableMetadataCache) { // This is normal for high-performance scenarios result.Warnings.Add(new ConfigurationValidationWarning { PropertyName = "Performance", Message = "Configuration is optimized for performance (validation disabled)", Recommendation = "Ensure data is valid at application level" }); } // Development configuration check if (config.IdResetStrategy == ObjectIdResetStrategy.AutoCreateNewOnSave && config.MissingObjectStrategy == MissingObjectStrategy.AutoSwitchToInsert && !config.DefaultCheckPermissionsOnLoad) { result.Warnings.Add(new ConfigurationValidationWarning { PropertyName = "Development", Message = "Configuration looks like development settings", Recommendation = "Do not use this configuration in production" }); } } /// /// Quick check for critical errors /// public static bool HasCriticalErrors(RedbServiceConfiguration configuration) { return configuration.DefaultLoadDepth < 1 || configuration.DefaultMaxTreeDepth < 1 || configuration.SystemUserId < 0 || configuration.EnableMetadataCache && configuration.MetadataCacheLifetimeMinutes < 1; } /// /// Fix critical errors automatically /// public static RedbServiceConfiguration FixCriticalErrors(RedbServiceConfiguration configuration) { var fixedConfig = configuration.Clone(); if (fixedConfig.DefaultLoadDepth < 1) fixedConfig.DefaultLoadDepth = 10; if (fixedConfig.DefaultMaxTreeDepth < 1) fixedConfig.DefaultMaxTreeDepth = 50; if (fixedConfig.SystemUserId < 0) fixedConfig.SystemUserId = 0; if (fixedConfig.EnableMetadataCache && fixedConfig.MetadataCacheLifetimeMinutes < 1) fixedConfig.MetadataCacheLifetimeMinutes = 30; return fixedConfig; } } } Path: redb/redb.Core/Models/Configuration/EffectiveUserConfiguration.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Core/Models/Configuration/EffectiveUserConfiguration.cs ---- using System; using System.Collections.Generic; namespace redb.Core.Models.Configuration { /// /// Effective user configuration (result of merging all configurations) /// All values are resolved (no null), obtained from chain: /// RedbServiceConfiguration -> Default User Config -> Role Config -> User Config /// public class EffectiveUserConfiguration { // === CACHE QUOTAS === /// /// The props cache limit of the process (): the /// cache has one limit, not a quota per user, so no user configuration changes this value. /// public int? PropsCacheSize { get; set; } /// /// User list cache quota /// null = no limits (for sys user) /// public int? ListCacheSize { get; set; } /// /// Object cache TTL /// public TimeSpan PropsCacheTtl { get; set; } /// /// List cache TTL /// public TimeSpan ListCacheTtl { get; set; } // === LOADING LIMITS === /// /// Maximum object loading depth /// public int MaxLoadDepth { get; set; } /// /// Maximum tree depth /// public int MaxTreeDepth { get; set; } // === PERFORMANCE === // === SECURITY === /// /// Always check permissions on load /// public bool AlwaysCheckPermissionsOnLoad { get; set; } /// /// Always check permissions on save /// public bool AlwaysCheckPermissionsOnSave { get; set; } // === API QUOTAS === /// /// Maximum number of requests per minute /// null = no limits /// public int? MaxRequestsPerMinute { get; set; } /// /// Maximum batch operation size /// public int MaxBatchSize { get; set; } // === STRATEGIES === /// /// How a save writes the Props of an object (DeleteInsert or ChangeTracking) /// public PropsSaveStrategy PropsSaveStrategy { get; set; } // === METADATA === /// /// List of configuration parameter sources /// Shows where each value was taken from /// public List Sources { get; set; } = new(); /// /// User ID for which the configuration was built /// public long UserId { get; set; } /// /// Effective configuration creation time (for caching) /// public DateTime CreatedAt { get; set; } = DateTime.UtcNow; } /// /// Configuration parameter source /// Used for debugging and understanding where value was taken from /// public class ConfigurationSource { /// /// Parameter name /// public string ParameterName { get; set; } = string.Empty; /// /// Value source /// Examples: "RedbServiceConfiguration", "Default User Config", "Role:Admin", "User" /// public string Source { get; set; } = string.Empty; /// /// Source priority (higher means more important) /// public int Priority { get; set; } /// /// Parameter value (as string for debugging) /// public string? Value { get; set; } } } Path: redb/redb.Core/Models/Configuration/LazyLoadWithoutScopeMode.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Core/Models/Configuration/LazyLoadWithoutScopeMode.cs ---- namespace redb.Core.Models.Configuration; /// /// What a lazy load does when no live redb scope reads it (owner decision 2026-09-15). See /// . /// public enum LazyLoadWithoutScopeMode { /// /// Refuse with , naming the explicit ways (the default): a data /// object owns no connection, and a hidden scope per read is how connection pools run dry. /// Refuse = 0, /// /// Open a fresh scope - and a pooled connection - for each such load, outside any ambient transaction, and warn once /// the rate gets high. An explicit opt-in for hosts that accept the cost. /// FreshScope = 1, } Path: redb/redb.Core/Models/Configuration/LazyReferenceAccessMode.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Core/Models/Configuration/LazyReferenceAccessMode.cs ---- namespace redb.Core.Models.Configuration; /// /// How the Props getter of an unloaded reference behaves (V4, review). See /// . /// public enum LazyReferenceAccessMode { /// Load synchronously on first access (the default, the transparent form). Blocking = 0, /// /// Refuse with ; only the explicit async /// APIs load a reference. For hosts where a blocking query on property access is a defect. /// Throw = 1, } Path: redb/redb.Core/Models/Configuration/PredefinedConfigurations.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Core/Models/Configuration/PredefinedConfigurations.cs ---- #pragma warning disable CS0618 // implements or uses the deprecated object permissions and roles (RedbDeprecation) using System; namespace redb.Core.Models.Configuration { /// /// Predefined configurations for various usage scenarios /// public static class PredefinedConfigurations { /// /// Default configuration (balanced) /// public static RedbServiceConfiguration Default => new RedbServiceConfiguration(); /// /// Configuration for development and testing /// Priority: development convenience, detailed diagnostics /// public static RedbServiceConfiguration Development => new RedbServiceConfiguration { // A type changed on a local database without raising the scheme version is still migrated DefaultDestructiveSyncAtEqualVersion = true, // Disable permission checks for convenience DefaultCheckPermissionsOnLoad = false, DefaultCheckPermissionsOnSave = false, DefaultCheckPermissionsOnDelete = false, // Automatic recovery after errors IdResetStrategy = ObjectIdResetStrategy.AutoCreateNewOnSave, MissingObjectStrategy = MissingObjectStrategy.AutoSwitchToInsert, // Enable all validations for early problem detection EnableSchemaValidation = true, EnableDataValidation = true, // Disable cache for data freshness during development EnableMetadataCache = false, // Detailed JSON logging JsonOptions = new JsonSerializationOptions { WriteIndented = true, UseUnsafeRelaxedJsonEscaping = true }, // Standard depths DefaultLoadDepth = 10, DefaultMaxTreeDepth = 50, // Automatic audit AutoSetModifyDate = true, AutoRecomputeHash = true, // System user for tests SystemUserId = 0, // DefaultSecurityPriority removed }; /// /// Configuration for production (high security) /// Priority: security, stability, control /// public static RedbServiceConfiguration Production => new RedbServiceConfiguration { // Strict permission checks everywhere DefaultCheckPermissionsOnLoad = true, DefaultCheckPermissionsOnSave = true, DefaultCheckPermissionsOnDelete = true, // Conservative error handling IdResetStrategy = ObjectIdResetStrategy.Manual, MissingObjectStrategy = MissingObjectStrategy.ThrowException, // Full validation EnableSchemaValidation = true, EnableDataValidation = true, // Aggressive caching for performance EnableMetadataCache = true, MetadataCacheLifetimeMinutes = 60, // Compact JSON JsonOptions = new JsonSerializationOptions { WriteIndented = false, UseUnsafeRelaxedJsonEscaping = true }, // Limited depths for performance DefaultLoadDepth = 5, DefaultMaxTreeDepth = 30, // Full audit AutoSetModifyDate = true, AutoRecomputeHash = true, // Strict schema settings DefaultStrictDeleteExtra = true, AutoSyncSchemesOnSave = true, SystemUserId = 0, // DefaultSecurityPriority removed }; /// /// Configuration for bulk operations /// Priority: maximum speed, minimum checks /// public static RedbServiceConfiguration BulkOperations => new RedbServiceConfiguration { // Disable all permission checks DefaultCheckPermissionsOnLoad = false, DefaultCheckPermissionsOnSave = false, DefaultCheckPermissionsOnDelete = false, // Automatic recovery to continue operations IdResetStrategy = ObjectIdResetStrategy.AutoCreateNewOnSave, MissingObjectStrategy = MissingObjectStrategy.AutoSwitchToInsert, // Disable validation for speed EnableSchemaValidation = false, EnableDataValidation = false, // Disable cache (may be stale during bulk changes) EnableMetadataCache = false, // Minimal JSON JsonOptions = new JsonSerializationOptions { WriteIndented = false, UseUnsafeRelaxedJsonEscaping = true }, // Minimum depths DefaultLoadDepth = 1, DefaultMaxTreeDepth = 1, // Disable automatic audit for speed AutoSetModifyDate = false, AutoRecomputeHash = false, // Auto-syncing schemas can slow down bulk operations AutoSyncSchemesOnSave = false, DefaultStrictDeleteExtra = false, SystemUserId = 0, // DefaultSecurityPriority removed }; /// /// Configuration for high performance /// Priority: speed, caching, optimization /// public static RedbServiceConfiguration HighPerformance => new RedbServiceConfiguration { // Minimum permission checks DefaultCheckPermissionsOnLoad = false, DefaultCheckPermissionsOnSave = false, DefaultCheckPermissionsOnDelete = true, // Keep for security // Moderate recovery IdResetStrategy = ObjectIdResetStrategy.AutoResetOnDelete, MissingObjectStrategy = MissingObjectStrategy.AutoSwitchToInsert, // Disable data validation, keep schemas EnableSchemaValidation = true, EnableDataValidation = false, // Aggressive caching EnableMetadataCache = true, MetadataCacheLifetimeMinutes = 120, // Compact JSON JsonOptions = new JsonSerializationOptions { WriteIndented = false, UseUnsafeRelaxedJsonEscaping = true }, // Optimal depths DefaultLoadDepth = 3, DefaultMaxTreeDepth = 10, // Minimal audit AutoSetModifyDate = true, AutoRecomputeHash = false, // Disable for speed // Optimized synchronization AutoSyncSchemesOnSave = true, DefaultStrictDeleteExtra = false, // Don't delete extra fields for speed SystemUserId = 0, // DefaultSecurityPriority removed }; /// /// Configuration for debugging /// Priority: maximum information, detailed diagnostics /// public static RedbServiceConfiguration Debug => new RedbServiceConfiguration { // Disable checks for debugging convenience DefaultCheckPermissionsOnLoad = false, DefaultCheckPermissionsOnSave = false, DefaultCheckPermissionsOnDelete = false, // Auto-recovery to continue debugging IdResetStrategy = ObjectIdResetStrategy.AutoCreateNewOnSave, MissingObjectStrategy = MissingObjectStrategy.AutoSwitchToInsert, // Maximum validation EnableSchemaValidation = true, EnableDataValidation = true, // Disable cache for freshness EnableMetadataCache = false, // Detailed JSON for analysis JsonOptions = new JsonSerializationOptions { WriteIndented = true, UseUnsafeRelaxedJsonEscaping = true }, // Large depths for complete picture DefaultLoadDepth = 20, DefaultMaxTreeDepth = 100, // Full audit AutoSetModifyDate = true, AutoRecomputeHash = true, // Detailed synchronization AutoSyncSchemesOnSave = true, DefaultStrictDeleteExtra = true, SystemUserId = 0, // DefaultSecurityPriority removed }; /// /// Configuration for integration tests /// Priority: predictability, isolation, reproducibility /// public static RedbServiceConfiguration IntegrationTesting => new RedbServiceConfiguration { // Enable permission checks for security testing DefaultCheckPermissionsOnLoad = true, DefaultCheckPermissionsOnSave = true, DefaultCheckPermissionsOnDelete = true, // Strict error handling to identify issues IdResetStrategy = ObjectIdResetStrategy.Manual, MissingObjectStrategy = MissingObjectStrategy.ThrowException, // Full validation EnableSchemaValidation = true, EnableDataValidation = true, // Disable cache for test isolation EnableMetadataCache = false, // Readable JSON for result analysis JsonOptions = new JsonSerializationOptions { WriteIndented = true, UseUnsafeRelaxedJsonEscaping = true }, // Standard depths DefaultLoadDepth = 10, DefaultMaxTreeDepth = 50, // Full audit for verification AutoSetModifyDate = true, AutoRecomputeHash = true, // Strict synchronization AutoSyncSchemesOnSave = true, DefaultStrictDeleteExtra = true, SystemUserId = 0, // DefaultSecurityPriority removed }; /// /// Configuration for data migration /// Priority: reliability, recovery, schema flexibility /// public static RedbServiceConfiguration DataMigration => new RedbServiceConfiguration { // Disable permission checks for system operations DefaultCheckPermissionsOnLoad = false, DefaultCheckPermissionsOnSave = false, DefaultCheckPermissionsOnDelete = false, // Maximum error tolerance IdResetStrategy = ObjectIdResetStrategy.AutoCreateNewOnSave, MissingObjectStrategy = MissingObjectStrategy.AutoSwitchToInsert, // Schema validation is important, data validation is not (may have incorrect data) EnableSchemaValidation = true, EnableDataValidation = false, // Disable cache (schemas may change frequently) EnableMetadataCache = false, // Compact JSON to save space JsonOptions = new JsonSerializationOptions { WriteIndented = false, UseUnsafeRelaxedJsonEscaping = true }, // Medium depths DefaultLoadDepth = 5, DefaultMaxTreeDepth = 25, // Full audit for migration tracking AutoSetModifyDate = true, AutoRecomputeHash = true, // Flexible schema synchronization AutoSyncSchemesOnSave = true, DefaultStrictDeleteExtra = false, // Don't delete fields during migration SystemUserId = 0, // DefaultSecurityPriority removed }; /// /// Get configuration by name /// public static RedbServiceConfiguration GetByName(string name) { return name.ToLowerInvariant() switch { "default" => Default, "development" => Development, "production" => Production, "bulk" or "bulkoperations" => BulkOperations, "performance" or "highperformance" => HighPerformance, "debug" => Debug, "test" or "integrationtesting" => IntegrationTesting, "migration" or "datamigration" => DataMigration, _ => throw new ArgumentException($"Unknown configuration name: {name}") }; } /// /// Get all available configuration names /// public static string[] GetAvailableNames() { return new[] { "Default", "Development", "Production", "BulkOperations", "HighPerformance", "Debug", "IntegrationTesting", "DataMigration" }; } } } Path: redb/redb.Core/Models/Configuration/RedbServiceConfiguration.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Core/Models/Configuration/RedbServiceConfiguration.cs ---- #pragma warning disable CS0618 // implements or uses the deprecated object permissions and roles (RedbDeprecation) using System; using System.Security.Cryptography; using System.Text; using System.Text.Json.Serialization; using redb.Core.Configuration; using redb.Core.Caching; namespace redb.Core.Models.Configuration { /// /// RedbService behavior configuration. /// public class RedbServiceConfiguration { // === CONNECTION SETTINGS === /// /// PostgreSQL connection string. Required for automatic IRedbContext registration. /// If not set, user must register IRedbContext manually. /// public string? ConnectionString { get; set; } /// /// Cache domain name for isolating scheme caches between different databases. /// If not set, computed from connection string hash. /// Use explicit name when connecting to same DB from multiple services. /// public string? CacheDomain { get; set; } // === OBJECT DELETION SETTINGS === /// /// Strategy for handling ID after object deletion. /// [JsonConverter(typeof(ObjectIdResetStrategyJsonConverter))] public ObjectIdResetStrategy IdResetStrategy { get; set; } = ObjectIdResetStrategy.Manual; /// /// Strategy for handling non-existent objects on UPDATE. /// [JsonConverter(typeof(MissingObjectStrategyJsonConverter))] public MissingObjectStrategy MissingObjectStrategy { get; set; } = MissingObjectStrategy.AutoSwitchToInsert; // === DEFAULT SECURITY SETTINGS === /// /// Check permissions by default when loading objects. /// [Obsolete(RedbDeprecation.PermissionsAndRoles)] public bool DefaultCheckPermissionsOnLoad { get; set; } = false; /// /// Check permissions by default when saving objects. /// [Obsolete(RedbDeprecation.PermissionsAndRoles)] public bool DefaultCheckPermissionsOnSave { get; set; } = false; /// /// Check permissions by default when deleting objects. /// [Obsolete(RedbDeprecation.PermissionsAndRoles)] public bool DefaultCheckPermissionsOnDelete { get; set; } = true; /// /// Check permissions by default when executing queries. Read by the free providers only, which filter the loaded /// page row by row; the queries of redb Pro are not filtered by permissions. /// [Obsolete(RedbDeprecation.PermissionsAndRoles)] public bool DefaultCheckPermissionsOnQuery { get; set; } = false; // === SCHEME SETTINGS === /// /// Strictly delete extra fields when synchronizing schemes by default. /// public bool DefaultStrictDeleteExtra { get; set; } = true; /// /// Lets the sync delete a structure or change its type for a Props class of the same version as the one the /// database recorded (). Off by default: such a class adds /// what it lacks, leaves the rest and warns, so only a class of a higher version takes data away. On in the /// Development profile, where a programmer changes a type on a local database without raising the version; /// without it the type would not be migrated and the property would read and write the wrong column. /// public bool DefaultDestructiveSyncAtEqualVersion { get; set; } /// /// Automatically synchronize schemes when saving objects. /// public bool AutoSyncSchemesOnSave { get; set; } = true; // === OBJECT LOADING SETTINGS === /// /// Default depth for loading nested objects. /// private int _defaultLoadDepth = 10; public int DefaultLoadDepth { get => _defaultLoadDepth; set { if (value < 1) throw new ArgumentOutOfRangeException(nameof(DefaultLoadDepth), "Minimum 1"); if (value > 100) throw new ArgumentOutOfRangeException(nameof(DefaultLoadDepth), "Maximum 100"); _defaultLoadDepth = value; } } /// /// Maximum depth for tree structures. /// private int _defaultMaxTreeDepth = 50; public int DefaultMaxTreeDepth { get => _defaultMaxTreeDepth; set { if (value < 1) throw new ArgumentOutOfRangeException(nameof(DefaultMaxTreeDepth), "Minimum 1"); if (value > 1000) throw new ArgumentOutOfRangeException(nameof(DefaultMaxTreeDepth), "Maximum 1000"); _defaultMaxTreeDepth = value; } } /// /// Throw exception if object not found in LoadAsync. /// false (default) - returns null for a single object and skips it in a batch load /// true - throws InvalidOperationException /// public bool ThrowOnObjectNotFound { get; set; } = false; // === PERFORMANCE SETTINGS === /// /// The query planner (Pro, all three providers: PostgreSQL, SQL Server, SQLite). On by default. /// /// Where it applies, a query is read in the streams form: the objects of the scheme drive the /// statement and every Props field is a join of its own to its rows of _values, with no /// GROUP BY. The filter, the ordering and the page, a count, an existence check, aggregates, /// GroupBy and windows run in that one statement, so a page or a count does not pivot every /// object of the scheme first. /// /// /// A field of a nested class is one value row per object and reads through the streams form. /// The aggregate pivot remains for array element forms (field[], field[0], /// aggregates over elements), classes inside arrays, the first step of WhereHasAncestor and /// WhereHasDescendant, and tree-window fields that are arrays. There the planner may narrow /// the object set before the aggregate. It only ever narrows to a superset: results never /// change, and a filter it cannot analyse runs as without it. /// /// Set it to false to read every query in the aggregate pivot form. For one block of code, without touching /// concurrent requests: using (redb.WithQueryPlanner(false)) { ... } (). /// public bool EnablePvtPrefilter { get; set; } = true; private string? _stringCollation; /// /// Unicode-aware case folding for case-insensitive text operations /// (ContainsIgnoreCase, StartsWithIgnoreCase, EndsWithIgnoreCase, /// ToLower, ToUpper). /// /// /// Why it exists. Case folding is driven by the database's own rules, and those cover /// only ASCII in two of the three providers. On PostgreSQL created with LC_CTYPE=C, /// 'Привет' ILIKE '%привет%' is false and lower('Привет') returns the string /// unchanged. On SQLite this is unconditional: LIKE, lower(), upper() and /// COLLATE NOCASE are ASCII-only in every database. MSSQL is unaffected because its /// default collation is case-insensitive for all scripts. /// /// /// /// What it fixes. Every script whose case mapping is one character to one character: /// Cyrillic, Greek, Hungarian, Polish, Czech, French, most of German. There is no per-language /// work; one setting covers all of them. /// /// /// /// What it does NOT fix, and cannot, because no collation can: /// foldings that change length (German ß against SS: upper() expands it, /// pattern matching does not, so the two disagree); language-dependent foldings (Turkish /// İ does not fold to i, and Turkish wants I→ı where every other /// locale wants I→i); and insensitivity to diacritics (Müller against /// muller), which is a different feature and is rejected outright by PostgreSQL for /// pattern matching. See COLLATION.md. /// /// /// /// Cost on PostgreSQL. Pro with on pushes an ignore-case /// search onto _values as (_String COLLATE "und-x-icu") ILIKE, which the stock trigram /// index over bare _String cannot serve: the search reads every row, silently. It needs an /// index over the same collation, /// CREATE INDEX ... USING gin ((_String COLLATE "und-x-icu") gin_trgm_ops); start-up logs a /// Warning while it is missing. The free forms read no trigram index in either case. On a database /// with a UTF-8 ctype plain ILIKE already folds every script and the setting is not needed; under /// ctype C pg_trgm builds no trigram from non-ASCII text, so no index serves a non-ASCII pattern. /// /// /// Default is null: behaviour is exactly what it was, on every provider. /// public string? StringCollation { get => _stringCollation; set { var normalised = string.IsNullOrWhiteSpace(value) ? null : value.Trim(); if (normalised != null) Core.Query.CollationNameValidator.Validate(normalised); _stringCollation = normalised; } } /// /// PostgreSQL Pro with on: build at start-up the trigram index that serves an /// ignore-case search under , /// IX__values__String_pattern_<collation> ON _values USING gin ((_String COLLATE "<collation>") gin_trgm_ops), /// when the database has none. On a database with ctype C it serves patterns with ASCII letters only: pg_trgm /// builds no trigram from other text there. /// /// /// The build is CREATE INDEX CONCURRENTLY on a connection of its own under the schema lock: reads and /// writes go on, start-up waits for it (minutes on a large _values). An index left INVALID by an /// interrupted build is dropped and built again. Nothing is built with /// off or without the right to create an index: start-up logs a Warning and goes on. The free provider and Pro /// with the planner off read no trigram index; there the option logs one Warning and builds nothing. /// /// /// Default is false: start-up only checks for the index and warns while it is missing. /// public bool CreateStringCollationIndex { get; set; } = false; /// /// V4 (LAZY Л2): lazy references. With the option on, the JSON builders emit a STUB for /// every reference whose structure carries the `virtual` marker (`_structures._lazy`), /// regardless of depth; first access to the stub's Props loads exactly that object. /// The option travels to the builders as a session flag of the context's connection /// (PostgreSQL GUC `redb.lazy_refs`, MSSQL SESSION_CONTEXT, a connection flag of the /// SQLite native extension) - no builder signature changes (plan decision 5). /// Per-query override: `WithLazyReferences(bool)`; with the Pro packages the override has no /// effect and this global option applies. Default is false: behaviour is exactly what it was. /// public bool EnableLazyReferences { get; set; } = false; /// /// V4 (review): what the Props getter of an UNLOADED reference does. Blocking /// (default) loads the object synchronously - a hidden database round trip that waits for /// the query on the calling thread (the load itself runs on the thread pool, so a host with a /// SynchronizationContext does not deadlock). Throw refuses with /// and names the explicit way /// (LoadPropsAsync, LoadReferencesAsync, a larger depth): for Blazor WebAssembly, /// which cannot block at all, and for UI hosts where a synchronous query on property access /// is a defect. The async APIs work in both modes. /// public LazyReferenceAccessMode LazyReferenceAccess { get; set; } = LazyReferenceAccessMode.Blocking; /// /// What a lazy load - the Props of a reference stub, RedbListItem.Object - does when no live redb scope reads /// it. A data object owns no connection: the load runs on the scope of whoever reads it (owner decision 2026-09-15). /// Refuse (default) throws ; FreshScope opens a /// scope and a pooled connection per such load. /// public LazyLoadWithoutScopeMode LazyLoadWithoutScope { get; set; } = LazyLoadWithoutScopeMode.Refuse; /// /// Apply the versioned SQL module (functions and, from V4, schema upgrades) automatically at /// start-up when the database reports a different module version than this build requires. /// /// /// true (default) keeps the long-standing behaviour: pull, restart, the database /// follows. When the connected role is not allowed to — the DBA revoked owner rights after the /// initial installation — start-up stops with /// naming the script for the DBA, rather than a raw driver error. /// /// /// /// false is for installations where the policy is "only the DBA changes the schema": /// start-up then checks the version and stops with the same exception without trying. /// SQLite ignores this setting — the database file belongs to the process and there is no /// DBA to defer to. /// /// public bool AutoApplyDatabaseUpgrades { get; set; } = true; /// /// How long start-up waits for the schema lock that another process holds. Processes starting against one /// database (the nodes of a cluster, the replicas of a service) take it in turn to create or upgrade the schema /// and to synchronize the schemes; the one that waits finds the work done when it gets the lock. The default /// covers building the indexes of a large table. Past it start-up stops with /// . /// public TimeSpan SchemaLockTimeout { get; set; } = TimeSpan.FromMinutes(15); private TimeSpan? _bulkInsertTimeout; /// /// How long one bulk load of a save may run: the SqlBulkCopy of SQL Server and the binary COPY of /// PostgreSQL that AddNewObjectsAsync and the batch save use for large sets. null (the default) /// keeps the driver's value: 30 seconds on SQL Server, which the connection string's Command Timeout /// does not reach. means no limit. Small sets that go as INSERT statements, and /// every statement on SQLite, keep the timeout of the connection string. /// public TimeSpan? BulkInsertTimeout { get => _bulkInsertTimeout; set { if (value < TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(BulkInsertTimeout), value, "BulkInsertTimeout cannot be negative: TimeSpan.Zero means no limit, null keeps the driver's value."); _bulkInsertTimeout = value; } } /// /// Enable transparent whole-object (Props) caching, validated by object hash. /// Default is false. /// public bool EnablePropsCache { get; set; } = false; /// /// When list items are handed out (list reads, item lookups), load their linked objects /// () in ONE batch up front, so touching /// the property later is a field read: no database call, no blocked thread. Lists are /// dictionaries by design (dozens of rows), so the batch is one cheap SELECT; disable only /// when a list is unusually large AND its objects are rarely needed. Default: enabled - /// the lazy sync getter blocks a thread per touch, and a hot loop over fresh items froze /// a production process (2026-09-09). /// public bool PreloadListItemLinkedObjects { get; set; } = true; /// /// Sample bound for SQLite's ANALYZE in IMaintenanceProvider.AnalyzeAsync /// (PRAGMA analysis_limit; 0 = unbounded full scan). PostgreSQL and MSSQL ignore it. /// The bounded form turns a minutes-long full-file ANALYZE into seconds while producing /// estimates just as good for redb's query shapes. Default: 1000 (SQLite's own /// recommended ballpark). /// public int MaintenanceAnalysisLimit { get; set; } = 1000; /// /// SQLite: keep the planner statistics of the file at start-up. A file with no statistics for _objects /// and _values and at least 10 000 value rows is analyzed once, bounded by /// ; a file that has statistics gets PRAGMA optimize, which analyzes /// again only the tables whose row count changed a lot since. Without statistics SQLite costs every index lookup /// at a few rows and may drive a large table where a small set should drive it. /// A file that cannot be written (read-only, or locked by another process) is left as it is with a Warning. /// PostgreSQL and SQL Server ignore it. Default: true. /// public bool KeepSqlitePlannerStatistics { get; set; } = true; /// /// At start-up, compare the indexes of the database with those of the base schema and of the Pro modules in use, /// and log one Warning naming every index that is missing, INVALID or defined otherwise /// ( gives the full report). Nothing is created at start-up: an /// operator may have dropped an index on purpose; or /// redb indexes repair builds the missing ones. One catalog read. Turn it off where indexes were dropped /// on purpose and the line is noise. Default: true. /// public bool CheckBaseIndexesOnStart { get; set; } = true; /// /// Maximum number of objects in Props cache. /// On overflow the least recently used tenth is evicted at once; a working set above the limit /// is logged as a warning /// private int _propsCacheMaxSize = 10000; public int PropsCacheMaxSize { get => _propsCacheMaxSize; set { if (value <= 0) throw new ArgumentOutOfRangeException(nameof(PropsCacheMaxSize), "Must be greater than 0"); if (value > 10_000_000) throw new ArgumentOutOfRangeException(nameof(PropsCacheMaxSize), "Maximum 10,000,000"); _propsCacheMaxSize = value; } } /// /// Lifetime of Props cache entry. /// After expiration - entry considered stale /// private TimeSpan _propsCacheTtl = TimeSpan.FromMinutes(60); public TimeSpan PropsCacheTtl { get => _propsCacheTtl; set { if (value <= TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(PropsCacheTtl), "TTL must be greater than 0"); if (value > TimeSpan.FromDays(7)) throw new ArgumentOutOfRangeException(nameof(PropsCacheTtl), "Maximum 7 days"); _propsCacheTtl = value; } } /// /// Skip hash validation in DB before cache access. /// true - for monolithic apps (faster, trust cache) /// false - for distributed systems (safer, check freshness) /// Default false (safe) /// /// /// The zero-DB shortcut applies OUTSIDE transactions only: inside an active transaction /// (explicit or ambient) a load always consults the database hash, so the canonical /// ExecuteAtomicAsync + LockForUpdateAsync + re-read pattern stays correct even with this /// flag on (bug report п.1, 2026-09-02). The flag remains a single-writer trade-off: outside /// transactions, changes committed by ANOTHER process stay invisible until the TTL expires. /// public bool SkipHashValidationOnCacheCheck { get; set; } = false; /// /// Controls what LoadAsync<TProps> does when the loaded object belongs to a different /// scheme than TProps maps to. The check itself always runs (garbage never reaches the /// cache); this flag only chooses the reaction: /// /// false (default) — return null. A soft-deleted object (scheme -10) /// therefore reads as null, which is what callers that soft-delete expect. /// true — throw RedbSchemeMismatchException, to surface a genuine type mistake /// loudly. /// /// The untyped LoadAsync(objectId) is never affected. /// public bool ThrowOnSchemeMismatch { get; set; } = false; // === LIST CACHE SETTINGS === /// /// Enable caching of lists and their items. /// public bool EnableListCache { get; set; } = true; /// /// Lifetime of list cache entry (TTL). /// Eventual consistency: other clients see changes after TTL /// private TimeSpan _listCacheTtl = TimeSpan.FromMinutes(5); public TimeSpan ListCacheTtl { get => _listCacheTtl; set { if (value <= TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(ListCacheTtl), "TTL must be greater than 0"); if (value > TimeSpan.FromDays(7)) throw new ArgumentOutOfRangeException(nameof(ListCacheTtl), "Maximum 7 days"); _listCacheTtl = value; } } /// /// Enable scheme metadata caching (OBSOLETE - use MetadataCache). /// //[Obsolete("Use MetadataCache.EnableMetadataCache instead")] public bool EnableMetadataCache { get; set; } = true; /// /// Metadata cache lifetime in minutes (OBSOLETE - use MetadataCache). /// //[Obsolete("Use MetadataCache.Schemes.LifetimeMinutes instead")] private int _metadataCacheLifetimeMinutes = 30; public int MetadataCacheLifetimeMinutes { get => _metadataCacheLifetimeMinutes; set { if (value < 1) throw new ArgumentOutOfRangeException(nameof(MetadataCacheLifetimeMinutes), "Minimum 1 minute"); if (value > 10080) throw new ArgumentOutOfRangeException(nameof(MetadataCacheLifetimeMinutes), "Maximum 10080 minutes (7 days)"); _metadataCacheLifetimeMinutes = value; } } /// /// Warm up scheme metadata cache during RedbService initialization. /// Calls warmup_all_metadata_caches() in InitializeAsync() /// Recommended for production (predictable performance) /// Default: true /// public bool WarmupMetadataCacheOnInit { get; set; } = true; // === STARTUP SETTINGS === /// /// Automatically create database schema on startup via IHostedService. /// When true, RedbInitHostedService calls InitializeAsync(ensureCreated: true) /// before other hosted services that depend on the schema. /// Default: false (explicit opt-in). /// public bool EnsureCreated { get; set; } = false; // === METADATA CACHING SETTINGS (NEW) === //public MetadataCacheConfiguration MetadataCache { get; set; } = new(); // === VALIDATION SETTINGS === /// /// Enable scheme validation before synchronization. /// public bool EnableSchemaValidation { get; set; } = true; /// /// Enable data validation when saving. /// public bool EnableDataValidation { get; set; } = true; // === AUDIT SETTINGS === /// /// Automatically set modification date when saving. /// public bool AutoSetModifyDate { get; set; } = true; /// /// Automatically recompute hash when saving. /// public bool AutoRecomputeHash { get; set; } = true; // === SECURITY CONTEXT SETTINGS === // Security context priority removed - simple GetEffectiveUser() logic used /// /// System user ID for operations without permission checks. /// public long SystemUserId { get; set; } = 0; // === PROPS SAVE SETTINGS === /// /// How a save writes the Props of an object: DeleteInsert (default) or ChangeTracking (redb Pro). /// [JsonConverter(typeof(PropsSaveStrategyJsonConverter))] public PropsSaveStrategy PropsSaveStrategy { get; set; } = PropsSaveStrategy.DeleteInsert; // === SERIALIZATION SETTINGS === /// /// JSON serialization settings for arrays. /// public JsonSerializationOptions JsonOptions { get; set; } = new JsonSerializationOptions(); // === METHODS === /// /// Copy every setting of into this instance, the connection identity /// (, ) included. /// public void CopyFrom(RedbServiceConfiguration source) { ArgumentNullException.ThrowIfNull(source); ConnectionString = source.ConnectionString; CacheDomain = source.CacheDomain; CopyBehaviourFrom(source); } /// /// Copy every setting of into this instance except the connection identity /// (, ): what a temporary scope may change on a /// running service. This is the one list of the behaviour settings - Clone, CopyFrom and ApplyTemporary /// all go through it; a new setting is added here (RedbServiceConfigurationCopyTests fails otherwise). /// public void CopyBehaviourFrom(RedbServiceConfiguration source) { ArgumentNullException.ThrowIfNull(source); IdResetStrategy = source.IdResetStrategy; MissingObjectStrategy = source.MissingObjectStrategy; DefaultCheckPermissionsOnLoad = source.DefaultCheckPermissionsOnLoad; DefaultCheckPermissionsOnSave = source.DefaultCheckPermissionsOnSave; DefaultCheckPermissionsOnDelete = source.DefaultCheckPermissionsOnDelete; DefaultCheckPermissionsOnQuery = source.DefaultCheckPermissionsOnQuery; DefaultStrictDeleteExtra = source.DefaultStrictDeleteExtra; DefaultDestructiveSyncAtEqualVersion = source.DefaultDestructiveSyncAtEqualVersion; AutoSyncSchemesOnSave = source.AutoSyncSchemesOnSave; DefaultLoadDepth = source.DefaultLoadDepth; DefaultMaxTreeDepth = source.DefaultMaxTreeDepth; ThrowOnObjectNotFound = source.ThrowOnObjectNotFound; EnablePvtPrefilter = source.EnablePvtPrefilter; StringCollation = source.StringCollation; CreateStringCollationIndex = source.CreateStringCollationIndex; EnableLazyReferences = source.EnableLazyReferences; LazyReferenceAccess = source.LazyReferenceAccess; LazyLoadWithoutScope = source.LazyLoadWithoutScope; AutoApplyDatabaseUpgrades = source.AutoApplyDatabaseUpgrades; SchemaLockTimeout = source.SchemaLockTimeout; BulkInsertTimeout = source.BulkInsertTimeout; EnablePropsCache = source.EnablePropsCache; PreloadListItemLinkedObjects = source.PreloadListItemLinkedObjects; MaintenanceAnalysisLimit = source.MaintenanceAnalysisLimit; KeepSqlitePlannerStatistics = source.KeepSqlitePlannerStatistics; CheckBaseIndexesOnStart = source.CheckBaseIndexesOnStart; PropsCacheMaxSize = source.PropsCacheMaxSize; PropsCacheTtl = source.PropsCacheTtl; SkipHashValidationOnCacheCheck = source.SkipHashValidationOnCacheCheck; ThrowOnSchemeMismatch = source.ThrowOnSchemeMismatch; EnableListCache = source.EnableListCache; ListCacheTtl = source.ListCacheTtl; EnableMetadataCache = source.EnableMetadataCache; MetadataCacheLifetimeMinutes = source.MetadataCacheLifetimeMinutes; WarmupMetadataCacheOnInit = source.WarmupMetadataCacheOnInit; EnsureCreated = source.EnsureCreated; EnableSchemaValidation = source.EnableSchemaValidation; EnableDataValidation = source.EnableDataValidation; AutoSetModifyDate = source.AutoSetModifyDate; AutoRecomputeHash = source.AutoRecomputeHash; SystemUserId = source.SystemUserId; PropsSaveStrategy = source.PropsSaveStrategy; JsonOptions = new JsonSerializationOptions { WriteIndented = source.JsonOptions.WriteIndented, UseUnsafeRelaxedJsonEscaping = source.JsonOptions.UseUnsafeRelaxedJsonEscaping }; } /// /// Create configuration copy. /// public RedbServiceConfiguration Clone() { // CFG-1: one list of settings (CopyFrom); a hand-written copy here had fallen five settings behind. var copy = new RedbServiceConfiguration(); copy.CopyFrom(this); return copy; } /// /// Get configuration description. /// public string GetDescription() { return $"RedbService Configuration: " + $"LoadDepth={DefaultLoadDepth}, " + $"TreeDepth={DefaultMaxTreeDepth}, " + $"Cache={EnableMetadataCache}, " + // $"Security={DefaultSecurityPriority}, " + $"IdReset={IdResetStrategy}, " + $"MissingObj={MissingObjectStrategy}"; } /// /// Check if configuration is safe for production /// public bool IsProductionSafe() { return DefaultCheckPermissionsOnLoad && DefaultCheckPermissionsOnSave && DefaultCheckPermissionsOnDelete && EnableSchemaValidation && EnableDataValidation && DefaultLoadDepth <= 10 && !JsonOptions.WriteIndented; } /// /// Check if configuration is optimized for performance /// public bool IsPerformanceOptimized() { return !DefaultCheckPermissionsOnLoad && !DefaultCheckPermissionsOnSave && !DefaultCheckPermissionsOnDelete && (EnableMetadataCache/* || MetadataCache.EnableMetadataCache*/) && // Support for new and old settings DefaultLoadDepth <= 5 && DefaultMaxTreeDepth <= 10 && !JsonOptions.WriteIndented; //&& MetadataCache.Warmup.EnableWarmup; // Additional performance check } /// /// Gets effective cache domain name. /// Returns explicit CacheDomain if set, otherwise computes from connection string. /// public string GetEffectiveCacheDomain() { if (!string.IsNullOrEmpty(CacheDomain)) return CacheDomain; if (string.IsNullOrEmpty(ConnectionString)) return "default"; // Compute short hash from connection string (sanitized - without password) var sanitized = SanitizeConnectionString(ConnectionString); var hash = SHA256.HashData(Encoding.UTF8.GetBytes(sanitized)); return Convert.ToHexString(hash)[..16].ToLowerInvariant(); } /// /// Computes cache domain from a connection string (SHA256 hash, password-stripped). /// Used by contexts and key generators that don't have access to full configuration. /// public static string ComputeCacheDomain(string connectionString) { if (string.IsNullOrEmpty(connectionString)) return "default"; var sanitized = SanitizeConnectionString(connectionString); var hash = SHA256.HashData(Encoding.UTF8.GetBytes(sanitized)); return Convert.ToHexString(hash)[..16].ToLowerInvariant(); } /// /// Removes sensitive info (password) from connection string for hashing. /// private static string SanitizeConnectionString(string connectionString) { // Remove password= or pwd= from connection string var result = System.Text.RegularExpressions.Regex.Replace( connectionString, @"(password|pwd)\s*=\s*[^;]*;?", "", System.Text.RegularExpressions.RegexOptions.IgnoreCase); return result.ToLowerInvariant().Trim(); } } /// /// Object ID handling strategy after deletion /// public enum ObjectIdResetStrategy { /// /// Manual ID reset (current behavior) /// Manual, /// /// Automatic ID reset when deleting via DeleteAsync(RedbObject) /// AutoResetOnDelete, /// /// Automatic creation of new object when trying to save deleted object /// AutoCreateNewOnSave } /// /// Strategy for handling non-existent objects on UPDATE /// public enum MissingObjectStrategy { /// /// Throw exception (current behavior) /// ThrowException, /// /// Automatically switch to INSERT /// AutoSwitchToInsert, /// /// Return null/false without error /// ReturnNull } /// /// How a save writes the Props of an object (DeleteInsert or ChangeTracking) /// public enum PropsSaveStrategy { /// /// Simple strategy - always DELETE + INSERT all properties /// Reliable, but inefficient for large objects /// DeleteInsert, /// /// Efficient strategy - compare with DB and update only changed properties /// Recommended by default /// ChangeTracking } /// /// JSON serialization settings /// public class JsonSerializationOptions { /// /// Format JSON with indentation /// public bool WriteIndented { get; set; } = false; /// /// Use unsafe relaxed JavaScript encoding /// public bool UseUnsafeRelaxedJsonEscaping { get; set; } = true; } } Path: redb/redb.Core/Models/Configuration/RedbServiceConfigurationBuilder.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Core/Models/Configuration/RedbServiceConfigurationBuilder.cs ---- #pragma warning disable CS0618 // implements or uses the deprecated object permissions and roles (RedbDeprecation) using System; namespace redb.Core.Models.Configuration { /// /// Builder for convenient RedbService configuration setup /// public class RedbServiceConfigurationBuilder { private RedbServiceConfiguration _configuration; public RedbServiceConfigurationBuilder() { _configuration = new RedbServiceConfiguration(); } public RedbServiceConfigurationBuilder(RedbServiceConfiguration baseConfiguration) { _configuration = baseConfiguration ?? new RedbServiceConfiguration(); } // === OBJECT DELETION SETTINGS === /// /// Configure ID handling strategy after object deletion /// public RedbServiceConfigurationBuilder WithIdResetStrategy(ObjectIdResetStrategy strategy) { _configuration.IdResetStrategy = strategy; return this; } /// /// Configure strategy for handling non-existent objects on UPDATE /// public RedbServiceConfigurationBuilder WithMissingObjectStrategy(MissingObjectStrategy strategy) { _configuration.MissingObjectStrategy = strategy; return this; } // === SECURITY SETTINGS === /// /// Configure default permission checks /// [Obsolete(RedbDeprecation.PermissionsAndRoles)] public RedbServiceConfigurationBuilder WithDefaultPermissions( bool checkOnLoad = false, bool checkOnSave = false, bool checkOnDelete = true) { _configuration.DefaultCheckPermissionsOnLoad = checkOnLoad; _configuration.DefaultCheckPermissionsOnSave = checkOnSave; _configuration.DefaultCheckPermissionsOnDelete = checkOnDelete; return this; } /// /// Enable strict security (permission checks everywhere) /// public RedbServiceConfigurationBuilder WithStrictSecurity() { return WithDefaultPermissions(checkOnLoad: true, checkOnSave: true, checkOnDelete: true); } /// /// Disable permission checks (for development/testing) /// public RedbServiceConfigurationBuilder WithoutPermissionChecks() { return WithDefaultPermissions(checkOnLoad: false, checkOnSave: false, checkOnDelete: false); } /// /// Configure system user ID /// public RedbServiceConfigurationBuilder WithSystemUser(long systemUserId) { _configuration.SystemUserId = systemUserId; return this; } // public RedbServiceConfigurationBuilder WithSecurityPriority(SecurityContextPriority priority) // { // _configuration.DefaultSecurityPriority = priority; // return this; // } // === SCHEMA SETTINGS === /// /// Configure schema synchronization behavior /// public RedbServiceConfigurationBuilder WithSchemaSync( bool strictDeleteExtra = true, bool autoSyncOnSave = true) { _configuration.DefaultStrictDeleteExtra = strictDeleteExtra; _configuration.AutoSyncSchemesOnSave = autoSyncOnSave; return this; } // === LOADING SETTINGS === /// /// Configure object loading depth /// public RedbServiceConfigurationBuilder WithLoadDepth(int defaultDepth = 10, int maxTreeDepth = 50) { _configuration.DefaultLoadDepth = defaultDepth; _configuration.DefaultMaxTreeDepth = maxTreeDepth; return this; } // === PERFORMANCE SETTINGS === /// /// Configure metadata caching /// public RedbServiceConfigurationBuilder WithMetadataCache( bool enabled = true, int lifetimeMinutes = 30) { _configuration.EnableMetadataCache = enabled; _configuration.MetadataCacheLifetimeMinutes = lifetimeMinutes; return this; } /// /// Disable caching (for debugging) /// public RedbServiceConfigurationBuilder WithoutCache() { return WithMetadataCache(enabled: false); } // === VALIDATION SETTINGS === /// /// Configure validation /// public RedbServiceConfigurationBuilder WithValidation( bool schemaValidation = true, bool dataValidation = true) { _configuration.EnableSchemaValidation = schemaValidation; _configuration.EnableDataValidation = dataValidation; return this; } /// /// Disable validation (for performance) /// public RedbServiceConfigurationBuilder WithoutValidation() { return WithValidation(schemaValidation: false, dataValidation: false); } // === AUDIT SETTINGS === /// /// Configure automatic audit /// public RedbServiceConfigurationBuilder WithAudit( bool autoSetModifyDate = true, bool autoRecomputeHash = true) { _configuration.AutoSetModifyDate = autoSetModifyDate; _configuration.AutoRecomputeHash = autoRecomputeHash; return this; } // === JSON SETTINGS === /// /// Configure JSON serialization /// public RedbServiceConfigurationBuilder WithJsonOptions(Action configure) { configure(_configuration.JsonOptions); return this; } /// /// Enable pretty JSON formatting /// public RedbServiceConfigurationBuilder WithPrettyJson() { _configuration.JsonOptions.WriteIndented = true; return this; } /// /// Configure list cache /// public RedbServiceConfigurationBuilder WithListCache(bool enabled = true, int ttlMinutes = 5) { _configuration.EnableListCache = enabled; _configuration.ListCacheTtl = TimeSpan.FromMinutes(ttlMinutes); return this; } // === PREDEFINED CONFIGURATIONS === /// /// Configuration for development/testing /// public RedbServiceConfigurationBuilder ForDevelopment() { return WithoutPermissionChecks() .WithIdResetStrategy(ObjectIdResetStrategy.AutoCreateNewOnSave) .WithMissingObjectStrategy(MissingObjectStrategy.AutoSwitchToInsert) .WithValidation(schemaValidation: true, dataValidation: true) .WithPrettyJson() .WithMetadataCache(enabled: false); // Disable cache for debugging } /// /// Configuration for production (high security) /// public RedbServiceConfigurationBuilder ForProduction() { return WithStrictSecurity() .WithIdResetStrategy(ObjectIdResetStrategy.Manual) .WithMissingObjectStrategy(MissingObjectStrategy.ThrowException) .WithValidation(schemaValidation: true, dataValidation: true) .WithLoadDepth(defaultDepth: 5, maxTreeDepth: 30) // Less for performance .WithMetadataCache(enabled: true, lifetimeMinutes: 60); } /// /// Configuration for bulk operations /// public RedbServiceConfigurationBuilder ForBulkOperations() { return WithoutPermissionChecks() .WithIdResetStrategy(ObjectIdResetStrategy.AutoCreateNewOnSave) .WithMissingObjectStrategy(MissingObjectStrategy.AutoSwitchToInsert) .WithoutValidation() .WithLoadDepth(defaultDepth: 1, maxTreeDepth: 1) .WithoutCache(); } /// /// Configuration for high performance /// public RedbServiceConfigurationBuilder ForHighPerformance() { return WithoutPermissionChecks() .WithoutValidation() .WithLoadDepth(defaultDepth: 3, maxTreeDepth: 10) .WithMetadataCache(enabled: true, lifetimeMinutes: 120) .WithAudit(autoSetModifyDate: false, autoRecomputeHash: false); } /// /// Build configuration /// public RedbServiceConfiguration Build() { return _configuration; } /// /// Apply additional configuration /// public RedbServiceConfigurationBuilder Configure(Action configure) { configure(_configuration); return this; } /// /// Configuration for integration testing /// public RedbServiceConfigurationBuilder ForIntegrationTesting() { _configuration = PredefinedConfigurations.IntegrationTesting.Clone(); return this; } } } Path: redb/redb.Core/Models/Configuration/UserConfigurationProps.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Core/Models/Configuration/UserConfigurationProps.cs ---- using System; using redb.Core.Attributes; using redb.Core.Models.Entities; namespace redb.Core.Models.Configuration { /// /// User configuration - personal settings and quotas /// All fields are nullable - null means "not overridden, take from higher configuration" /// Priority chain: RedbServiceConfiguration (sys) -> Default User Config -> Role Config -> User Config /// [RedbScheme("User configuration")] public class UserConfigurationProps { // === CACHE QUOTAS === /// /// Not applied: the props cache has one process-wide limit, /// , and no quota per user. The value is /// still stored with the configuration object, and no longer merged into /// . /// [Obsolete("Not applied: the props cache has one process-wide limit, RedbServiceConfiguration.PropsCacheMaxSize. " + "The value is stored but no longer merged into the effective configuration.")] public int? PropsCacheSize { get; set; } /// /// User list cache quota /// null = use value from higher configuration /// public int? ListCacheSize { get; set; } /// /// Object cache TTL (in minutes) /// null = use value from higher configuration /// public int? PropsCacheTtlMinutes { get; set; } /// /// List cache TTL (in minutes) /// null = use value from higher configuration /// public int? ListCacheTtlMinutes { get; set; } // === LOADING LIMITS === /// /// Maximum object loading depth /// null = use value from higher configuration /// public int? MaxLoadDepth { get; set; } /// /// Maximum tree depth /// null = use value from higher configuration /// public int? MaxTreeDepth { get; set; } // === PERFORMANCE === // === SECURITY === /// /// Always check permissions on load /// null = use value from higher configuration /// public bool? AlwaysCheckPermissionsOnLoad { get; set; } /// /// Always check permissions on save /// null = use value from higher configuration /// public bool? AlwaysCheckPermissionsOnSave { get; set; } // === API QUOTAS === /// /// Maximum number of requests per minute /// null = no limits or use value from higher configuration /// public int? MaxRequestsPerMinute { get; set; } /// /// Maximum batch operation size /// null = use value from higher configuration /// public int? MaxBatchSize { get; set; } // === STRATEGIES === /// /// How a save writes the Props of an object (DeleteInsert or ChangeTracking) /// null = use value from higher configuration /// public PropsSaveStrategy? PropsSaveStrategy { get; set; } // === METADATA === /// /// Configuration description /// public string? Description { get; set; } /// /// Configuration priority (for roles) /// Higher priority means more important configuration during merging /// User configurations are always applied last /// public int Priority { get; set; } = 0; } } Path: redb/redb.Core/Models/Contracts/IRedbList.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Core/Models/Contracts/IRedbList.cs ---- using System; using System.Collections.Generic; namespace redb.Core.Models.Contracts { /// /// REDB list interface /// Represents a reference list for list-type fields /// public interface IRedbList { /// /// Unique list identifier /// long Id { get; } /// /// List name /// string Name { get; } /// /// List alias (short name) /// string? Alias { get; } // === DDD methods === /// /// List items collection (read-only) /// IReadOnlyCollection Items { get; } /// /// Add item to list (Aggregate Root pattern) /// Automatically sets IdList /// IRedbListItem AddItem(string value, long? idObject = null, string? alias = null); /// /// Add item to list with linked object (Aggregate Root pattern) /// Automatically extracts Id from object /// IRedbListItem AddItem(string value, IRedbObject linkedObject, string? alias = null); /// /// Create item for list without adding to collection /// Useful when you need to save item separately /// IRedbListItem CreateItem(string value, long? idObject = null, string? alias = null); /// /// Create item for list with linked object /// Automatically extracts Id from object /// IRedbListItem CreateItem(string value, IRedbObject linkedObject, string? alias = null); /// /// Remove item from list /// bool RemoveItem(IRedbListItem item); /// /// Find item by value /// IRedbListItem? FindItemByValue(string value); } } Path: redb/redb.Core/Models/Contracts/IRedbListItem.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Core/Models/Contracts/IRedbListItem.cs ---- using System; namespace redb.Core.Models.Contracts { /// /// REDB list item interface /// Represents a reference list element /// public interface IRedbListItem { /// /// Unique list item identifier /// long Id { get; } /// /// Identifier of the list to which the item belongs /// long IdList { get; } /// /// List item text value /// string Value { get; } /// /// Object identifier (if list item references an object) /// long? IdObject { get; } /// /// List item alias (short description) /// string? Alias { get; } /// /// Fully lazy loading of linked object /// Automatically loaded on first access through global loader /// Returns null if IdObject is null or loader is not configured /// IRedbObject? Object { get; } } } Path: redb/redb.Core/Models/Contracts/IRedbObject.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Core/Models/Contracts/IRedbObject.cs ---- using System; namespace redb.Core.Models.Contracts { /// /// Base interface for all REDB objects /// Allows working with objects as classes rather than IDs /// Enriched with full functionality for working with trees, timestamps and auditing /// public interface IRedbObject { // ===== BASIC IDENTIFIERS ===== /// /// Unique object identifier /// Used for extracting ID from object in new methods /// long Id { get; set; } /// /// Object scheme identifier /// Used for schema permissions checking and validation /// long SchemeId { get; set; } /// /// Object name /// Used for logging, debugging and user interface /// string Name { get; set; } // ===== TREE STRUCTURE ===== /// /// Parent object identifier /// null - if object is root /// long? ParentId { get; set; } /// /// Checks if object has a parent /// bool HasParent { get; } /// /// Checks if object is root (has no parent) /// bool IsRoot { get; } // ===== TIMESTAMPS ===== /// /// Object creation date and time /// DateTimeOffset DateCreate { get; set; } /// /// Object last modification date and time /// DateTimeOffset DateModify { get; set; } /// /// Object validity start date (optional) /// DateTimeOffset? DateBegin { get; set; } /// /// Object validity end date (optional) /// DateTimeOffset? DateComplete { get; set; } // ===== OWNERSHIP AND AUDIT ===== /// /// Object owner identifier /// long OwnerId { get; set; } /// /// Identifier of user who last modified the object /// long WhoChangeId { get; set; } // ===== ADDITIONAL IDENTIFIERS ===== /// /// Object key field /// long? Key { get; set; } // ===== PRIMITIVE VALUES (stored directly in _objects table) ===== /// /// Primitive long value (for primitive schemas) /// long? ValueLong { get; set; } /// /// Primitive string value (for primitive schemas) /// /// Identifier / external-key value; contract limit 450 (C#-enforced), long text belongs in Note. string? ValueString { get; set; } /// /// Primitive GUID value (for primitive schemas) /// Guid? ValueGuid { get; set; } /// /// Primitive boolean value (for primitive schemas) /// bool? ValueBool { get; set; } /// /// Primitive double value (for primitive schemas) /// double? ValueDouble { get; set; } /// /// Primitive decimal value (for primitive schemas) /// decimal? ValueNumeric { get; set; } /// /// Primitive datetime value (for primitive schemas) /// DateTimeOffset? ValueDatetime { get; set; } /// /// Primitive byte array value (for primitive schemas) /// byte[]? ValueBytes { get; set; } /// /// Application-defined unique key of the object within its scheme (V4, UNIQUE stage 1). /// A plain readable string up to 440 characters; the database enforces uniqueness over /// (_id_scheme, _value_unique). NULL never participates; a soft-deleted object releases its /// key. Composite keys are the application's concatenation with a separator impossible /// inside a component. Compared exactly as the database compares strings - redb neither /// trims nor folds case. /// string? ValueUnique { get; set; } // ===== OBJECT STATE ===== /// /// Object notes /// string? Note { get; set; } /// /// MD5 hash of object for integrity control /// Guid? Hash { get; set; } /// /// Reset object ID to 0 and optionally ParentId to null /// /// If true, also resets ParentId to null (default true) void ResetId(bool withParent = true); /// /// Reset object ID and ParentId (recursively processes nested objects) /// /// If true, recursively resets ID in all nested IRedbObject in Props void ResetIds(bool recursive = false); } } Path: redb/redb.Core/Models/Contracts/IRedbObjectGeneric.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Core/Models/Contracts/IRedbObjectGeneric.cs ---- using System; using System.Threading.Tasks; namespace redb.Core.Models.Contracts { /// /// Typed interface for REDB objects with specific properties type /// Extends base IRedbObject adding type-safe access to properties /// Provides IntelliSense and compile-time type checking /// /// Type of object properties class public interface IRedbObject : IRedbObject where TProps : class { /// /// Typed access to object properties /// Replaces the need to work with raw JSON or type casting /// TProps Props { get; set; } /// /// Get scheme for TProps type (with cache usage) /// Convenient method for getting metadata of specific type /// Task GetSchemeForTypeAsync(); /// /// Get scheme structures for TProps type (with cache usage) /// Returns encapsulated structures from scheme /// Task> GetStructuresForTypeAsync(); /// /// Get structure by field name for TProps type /// Uses fast name lookup in encapsulated scheme /// Task GetStructureByNameAsync(string fieldName); /// /// Recompute hash based on current TProps type properties /// Typed version of RecomputeHash() considering specific type /// void RecomputeHashForType(); /// /// Get new hash based on current properties without changing object /// Typed version of GetComputedHash() /// Guid ComputeHashForType(); /// /// Check if current hash matches TProps type properties /// Typed data integrity check /// bool IsHashValidForType(); /// /// Create object copy with same metadata but new properties /// Useful for creating similar objects /// IRedbObject CloneWithProperties(TProps newProperties); /// /// Clear metadata cache for TProps type /// Convenient method for cache invalidation at object level /// void InvalidateCacheForType(); /// /// Preload metadata cache for TProps type /// Useful for performance optimization /// Task WarmupCacheForTypeAsync(); } } Path: redb/redb.Core/Models/Contracts/IRedbPermission.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Core/Models/Contracts/IRedbPermission.cs ---- using System; namespace redb.Core.Models.Contracts { /// /// REDB permission interface /// Represents user or role access rights to object/schema /// public interface IRedbPermission { /// /// Unique permission identifier /// long Id { get; } /// /// Role identifier (if permission is assigned to role) /// long? IdRole { get; } /// /// User identifier (if permission is assigned to user) /// long? IdUser { get; } /// /// Identifier of object/schema to which permission applies /// long IdRef { get; } /// /// Read permission (SELECT) /// bool? Select { get; } /// /// Create permission (INSERT) /// bool? Insert { get; } /// /// Update permission (UPDATE) /// bool? Update { get; } /// /// Delete permission (DELETE) /// bool? Delete { get; } } } Path: redb/redb.Core/Models/Contracts/IRedbRole.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Core/Models/Contracts/IRedbRole.cs ---- using System; namespace redb.Core.Models.Contracts { /// /// REDB role interface /// Represents user role in security system /// public interface IRedbRole { /// /// Unique role identifier /// long Id { get; } /// /// Role name /// string Name { get; } } } Path: redb/redb.Core/Models/Contracts/IRedbScheme.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Core/Models/Contracts/IRedbScheme.cs ---- using System; using System.Collections.Generic; namespace redb.Core.Models.Contracts { /// /// REDB scheme interface /// Represents scheme (type) of objects in system with structure encapsulation /// public interface IRedbScheme { /// /// Unique scheme identifier /// long Id { get; } /// /// Parent scheme identifier (for scheme hierarchy) /// long? IdParent { get; } /// /// Scheme name /// string Name { get; } /// /// Scheme alias (short name) /// string? Alias { get; } /// /// Scheme namespace (for C# classes) /// string? NameSpace { get; } /// /// MD5 hash of all scheme structures (aggregated) /// Used for automatic change detection and cache invalidation /// Guid? StructureHash { get; } /// /// Free-form marker for future / custom extensions (450 chars), written by [RedbTags] /// at synchronisation. Default implementation returns null so third-party /// implementations keep compiling - the same contract as . /// string? Tags => null; /// /// Collection of structures (fields) of this scheme /// Scheme encapsulates its structures for data integrity /// IReadOnlyCollection Structures { get; } /// /// Fast access to structure by name /// Avoids the need to search in collection /// IRedbStructure? GetStructureByName(string name); } } Path: redb/redb.Core/Models/Contracts/IRedbSecurityContext.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Core/Models/Contracts/IRedbSecurityContext.cs ---- using System; namespace redb.Core.Models.Contracts { /// /// REDB security context /// Manages current user and operation mode /// public interface IRedbSecurityContext { /// /// Current user (can be null for system context) /// IRedbUser? CurrentUser { get; } /// /// System context (no permission checking) /// bool IsSystemContext { get; } /// /// User is authenticated (not system context and user is set) /// bool IsAuthenticated { get; } /// /// Get effective user ID with fallback logic /// Returns current user ID or sys ID (0) /// long GetEffectiveUserId(); /// /// Get effective user /// Returns current user or system user /// IRedbUser GetEffectiveUser(); /// /// Set current user /// void SetCurrentUser(IRedbUser? user); /// /// Create temporary system context /// IDisposable CreateSystemContext(); } } Path: redb/redb.Core/Models/Contracts/IRedbStructure.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Core/Models/Contracts/IRedbStructure.cs ---- using System; namespace redb.Core.Models.Contracts { /// /// REDB scheme field structure interface /// Represents field metadata in object scheme /// public interface IRedbStructure { /// /// Unique structure identifier /// long Id { get; } /// /// Parent structure identifier (for nested fields) /// long? IdParent { get; } /// /// Identifier of scheme to which structure belongs /// long IdScheme { get; } /// /// Identifier of overridden structure (for inheritance) /// long? IdOverride { get; } /// /// Data type identifier /// long IdType { get; } /// /// List identifier (for list-type fields) /// long? IdList { get; } /// /// Field name /// string Name { get; } /// /// Field alias (short name) /// string? Alias { get; } /// /// Field order in scheme /// long? Order { get; } /// /// Read-only field /// bool? Readonly { get; } /// /// Field is required for filling /// bool? AllowNotNull { get; } /// /// Collection type ID: Array (-9223372036854775668) or Dictionary (-9223372036854775667) /// NULL for non-collection fields /// long? CollectionType { get; } /// /// Key type ID for Dictionary fields. NULL for non-dictionary fields /// long? KeyType { get; } /// /// Compress field values /// bool? IsCompress { get; } /// /// Store null values /// bool? StoreNull { get; } /// /// V4 (LAZY Л2): the reference is lazy (`virtual` on the property). With the option on, /// the JSON builders emit a stub for it regardless of depth. /// bool? Lazy { get; } /// /// The field is a unique key within its scheme ([RedbUnique]); its values carry a hash in /// _values._unique and the database enforces uniqueness over it. /// bool? Unique { get; } /// /// UniqueKeyEncoder.Version the stored keys were computed with; a structure whose stamp is /// behind the current encoder is recomputed at synchronisation. /// long? UniqueVersion { get; } /// /// S3: element-key scope of a collection key (NULL = default reading; 1 = element values /// unique per scheme; 2 = no duplicate elements per collection). Default implementation /// returns null so third-party implementations keep compiling. /// long? UniqueScope => null; /// /// Free-form marker for future / custom extensions. Default implementation returns null. /// string? Tags => null; /// /// Default value (in binary form) /// byte[]? DefaultValue { get; } /// /// Default editor for field /// string? DefaultEditor { get; } } } Path: redb/redb.Core/Models/Contracts/IRedbType.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Core/Models/Contracts/IRedbType.cs ---- using System; namespace redb.Core.Models.Contracts { /// /// REDB data type interface /// Represents data type for fields in schemes /// public interface IRedbType { /// /// Unique type identifier /// long Id { get; } /// /// Type name (String, Long, DateTimeOffset, Boolean, etc.) /// string Name { get; } /// /// Type in database (varchar, bigint, timestamp, boolean, etc.) /// string? DbType { get; } /// /// Type in .NET (System.String, System.Int64, System.DateTimeOffset, etc.) /// string? Type1 { get; } } } Path: redb/redb.Core/Models/Contracts/IRedbUser.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Core/Models/Contracts/IRedbUser.cs ---- using System; namespace redb.Core.Models.Contracts { /// /// REDB user interface /// Represents system user with his basic properties /// public interface IRedbUser { /// /// Unique user identifier /// long Id { get; } /// /// User login (unique) /// string Login { get; } /// /// User name /// string Name { get; } /// /// User password (hashed) /// string Password { get; } /// /// Is user active /// bool Enabled { get; } /// /// User registration date /// DateTimeOffset DateRegister { get; } /// /// Dismissal date (if null - user is active) /// DateTimeOffset? DateDismiss { get; } /// /// User phone (optional) /// string? Phone { get; } /// /// User email (optional) /// string? Email { get; } /// /// Additional user key (optional) /// Can be used for external integrations or additional identification /// long? Key { get; } /// /// User integer code (optional) /// Can be used for categorization, access groups or external systems /// long? CodeInt { get; } /// /// User string code (optional) /// Can be used for department codes, branches or special labels /// string? CodeString { get; } /// /// User GUID code (optional) /// Can be used for unique identification in distributed systems /// Guid? CodeGuid { get; } /// /// User note or comment (optional) /// May contain additional information, instructions or notes /// string? Note { get; } /// /// User hash for data integrity check (optional) /// Generated automatically based on user basic properties /// Guid? Hash { get; } } } Path: redb/redb.Core/Models/Contracts/IRedbUserRole.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Core/Models/Contracts/IRedbUserRole.cs ---- using System; namespace redb.Core.Models.Contracts { /// /// REDB user-role relationship interface /// Represents role assignment to a user /// public interface IRedbUserRole { /// /// Unique identifier of the relationship /// long Id { get; } /// /// Role identifier /// long IdRole { get; } /// /// User identifier /// long IdUser { get; } } } Path: redb/redb.Core/Models/Contracts/ISchemeCacheProvider.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Core/Models/Contracts/ISchemeCacheProvider.cs ---- using System; using System.Threading; using System.Threading.Tasks; using redb.Core.Caching; namespace redb.Core.Models.Contracts { /// /// Extension of ISchemeSyncProvider with metadata cache management methods /// Adds capabilities for hot switching, invalidation and cache warmup /// public interface ISchemeCacheProvider { // ===== CACHE STATE MANAGEMENT ===== /// /// Enable/disable metadata caching on the fly (hot toggle) /// When disabled, automatically clears all cache /// /// true - enable cache, false - disable void SetCacheEnabled(bool enabled); /// /// Check if caching is enabled /// bool IsCacheEnabled { get; } // ===== CACHE INVALIDATION ===== /// /// Complete clearing of all metadata caches /// Resets statistics to zero /// void InvalidateCache(); /// /// Clear metadata cache for specific C# type /// /// Object properties type void InvalidateSchemeCache() where TProps : class; /// /// Clear metadata cache for scheme by ID /// /// Scheme ID in database void InvalidateSchemeCache(long schemeId); /// /// Clear metadata cache for scheme by name /// /// Scheme name void InvalidateSchemeCache(string schemeName); // ===== STATISTICS AND MONITORING ===== /// /// Get detailed cache performance statistics /// CacheStatistics GetCacheStatistics(); /// /// Reset cache statistics (zero out counters) /// The cache itself remains untouched /// void ResetCacheStatistics(); // ===== CACHE PRELOADING (WARMUP) ===== /// /// Preload metadata for C# type /// Useful for performance optimization during application startup /// /// Object properties type Task WarmupCacheAsync(CancellationToken cancellationToken = default) where TProps : class; /// /// Preload metadata for array of C# types /// /// Array of types to preload /// Cancels the operation (OCE only; a rollback in flight always completes). Task WarmupCacheAsync(Type[] types, CancellationToken cancellationToken = default); /// /// Preload metadata for all known schemes /// Use carefully - can be resource-intensive /// Task WarmupAllSchemesAsync(CancellationToken cancellationToken = default); // ===== DIAGNOSTICS ===== /// /// Get diagnostic information about cache state /// Includes optimization recommendations /// CacheDiagnosticInfo GetCacheDiagnosticInfo(); /// /// Estimate current memory consumption by cache in bytes /// Approximate value for monitoring /// long EstimateMemoryUsage(); } } Path: redb/redb.Core/Models/Contracts/ITreeNode.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Core/Models/Contracts/ITreeNode.cs ---- using System; using System.Collections.Generic; using System.Linq; namespace redb.Core.Models.Contracts { /// /// Interface for tree nodes with navigational properties and traversal operations /// /// Tree node type public interface ITreeNode where T : class, ITreeNode { /// /// Unique node identifier /// long Id { get; set; } /// /// Parent node identifier (null for root nodes) /// long? ParentId { get; set; } /// /// Reference to parent node (filled when loading tree) /// T? Parent { get; set; } /// /// Collection of child nodes (filled when loading tree) /// ICollection Children { get; set; } /// /// Checks if node is root (has no parent) /// bool IsRoot => ParentId == null; /// /// Checks if node is leaf (has no children) /// bool IsLeaf => !Children.Any(); /// /// Gets node level in tree (0 for root) /// Requires loaded hierarchy up to root /// int Level { get { int level = 0; var current = Parent; while (current != null) { level++; current = current.Parent; } return level; } } /// /// Gets all node ancestors (from parent to root) /// Requires loaded hierarchy up to root /// IEnumerable Ancestors { get { var current = Parent; while (current != null) { yield return current; current = current.Parent; } } } /// /// Gets all node descendants recursively /// Requires loaded hierarchy downwards /// IEnumerable Descendants { get { foreach (var child in Children) { yield return child; foreach (var descendant in child.Descendants) yield return descendant; } } } } } Path: redb/redb.Core/Models/Contracts/ITreeRedbObject.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Core/Models/Contracts/ITreeRedbObject.cs ---- using System; using System.Collections.Generic; namespace redb.Core.Models.Contracts { /// /// Interface for REDB tree objects with navigational properties /// Extends IRedbObject adding tree navigation capabilities in memory /// Supports polymorphic trees (objects of different schemes in one tree) /// public interface ITreeRedbObject : IRedbObject { /// /// Reference to parent object (filled when loading tree) /// null for root nodes /// ITreeRedbObject? Parent { get; set; } /// /// Collection of child objects (filled when loading tree) /// Empty collection for leaf nodes /// ICollection Children { get; set; } /// /// Checks if node is leaf (has no children) /// bool IsLeaf { get; } /// /// Gets node level in tree (0 for root) /// Requires loaded hierarchy up to root through Parent references /// int Level { get; } /// /// Gets path from root to current node as sequence of IDs /// /// Sequence of IDs from root to current node IEnumerable GetPathIds(); /// /// Gets breadcrumbs for navigation /// /// Separator between elements (default " > ") /// Whether to include IDs in parentheses (default false) /// String like "Root > Category > Subcategory" or "Root (1) > Category (5) > Subcategory (23)" string GetBreadcrumbs(string separator = " > ", bool includeIds = false); /// /// Checks if current node is descendant of specified node /// /// Alleged ancestor /// true if current node is descendant of ancestor bool IsDescendantOf(ITreeRedbObject ancestor); /// /// Checks if current node is ancestor of specified node /// /// Alleged descendant /// true if current node is ancestor of descendant bool IsAncestorOf(ITreeRedbObject descendant); /// /// Gets all subtree nodes (including current) in depth-first order /// /// Sequence of subtree nodes IEnumerable GetSubtree(); /// /// Gets number of nodes in subtree (including current) /// int SubtreeSize { get; } /// /// Gets maximum depth of subtree from current node /// int MaxDepth { get; } /// /// Gets all node ancestors (from parent to root) /// Requires loaded hierarchy up to root through Parent references /// IEnumerable Ancestors { get; } /// /// Gets all node descendants recursively /// Requires loaded hierarchy downwards through Children collections /// IEnumerable Descendants { get; } } /// /// Typed interface for tree objects with specific property type. /// Combines ITreeRedbObject (untyped navigation) and IRedbObject<TProps> (typed data). /// Supports polymorphic trees - parents and children can be different types. /// /// Object properties type. public interface ITreeRedbObject : ITreeRedbObject, IRedbObject where TProps : class, new() { // Empty interface - combines ITreeRedbObject + IRedbObject // Parent and Children inherited from ITreeRedbObject (untyped) // Props inherited from IRedbObject (typed) } } Path: redb/redb.Core/Models/Entities/RedbList.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Core/Models/Entities/RedbList.cs ---- using redb.Core.Models.Contracts; using System; using System.Collections.Generic; using System.Linq; using System.Text.Json.Serialization; namespace redb.Core.Models.Entities { /// /// REDB list entity with direct data storage (Aggregate Root). /// Maps to _lists table in PostgreSQL. /// public class RedbList : IRedbList { /// /// Unique list identifier. /// [JsonPropertyName("id")] public long Id { get; set; } /// /// List name. /// [JsonPropertyName("name")] public string Name { get; set; } = string.Empty; /// /// List alias (short name). /// [JsonPropertyName("alias")] public string? Alias { get; set; } // === Items collection (Aggregate Root) === private List _items = new(); /// /// Collection of list items (read-only). /// [JsonIgnore] public IReadOnlyCollection Items => _items.AsReadOnly(); /// /// Internal items list (for provider). /// internal List ItemsInternal => _items; /// /// Set items collection (for mapping). /// public void SetItems(IEnumerable items) { _items = items?.ToList() ?? new List(); } // === Constructors === /// /// Default constructor for deserialization and mapping. /// public RedbList() { } /// /// Constructor with name. /// public RedbList(string name, string? alias = null) { Name = name ?? throw new ArgumentNullException(nameof(name)); Alias = alias; } // === Static factory methods === /// /// Create new list. /// public static RedbList Create(string name, string? alias = null) { return new RedbList(name, alias); } // === DDD methods for Items === /// /// Add item to list (Aggregate Root pattern). /// Automatically sets IdList. /// public IRedbListItem AddItem(string value, long? idObject = null, string? alias = null) { var item = new RedbListItem { IdList = this.Id, Value = value, Alias = alias, IdObject = idObject }; _items.Add(item); return item; } /// /// Add item with linked object (Aggregate Root pattern). /// Automatically extracts Id from object. /// public IRedbListItem AddItem(string value, IRedbObject linkedObject, string? alias = null) { var item = new RedbListItem(this, value, alias, linkedObject); _items.Add(item); return item; } /// /// Create item without adding to collection. /// Useful for separate save. /// public IRedbListItem CreateItem(string value, long? idObject = null, string? alias = null) { return new RedbListItem { IdList = this.Id, Value = value, Alias = alias, IdObject = idObject }; } /// /// Create item with linked object. /// public IRedbListItem CreateItem(string value, IRedbObject linkedObject, string? alias = null) { return new RedbListItem(this, value, alias, linkedObject); } /// /// Remove item from list. /// public bool RemoveItem(IRedbListItem item) { if (item is RedbListItem redbItem) { return _items.Remove(redbItem); } var toRemove = _items.FirstOrDefault(i => i.Id == item.Id); if (toRemove != null) { return _items.Remove(toRemove); } return false; } /// /// Find item by value. /// public IRedbListItem? FindItemByValue(string value) { return _items.FirstOrDefault(i => i.Value == value); } /// /// Indexer to access list items by value. /// public IRedbListItem? this[string value] => FindItemByValue(value); /// /// Clear items collection. /// public void ClearItems() { _items.Clear(); } public override string ToString() { var aliasStr = !string.IsNullOrEmpty(Alias) ? $" ({Alias})" : ""; return $"List {Id}: {Name}{aliasStr}"; } } } Path: redb/redb.Core/Models/Entities/RedbListItem.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Core/Models/Entities/RedbListItem.cs ---- using redb.Core.Attributes; using redb.Core.Exceptions; using redb.Core.Models.Contracts; using System; using System.Text.Json.Serialization; using System.Threading; using System.Threading.Tasks; namespace redb.Core.Models.Entities { /// /// REDB list item entity with direct data storage. /// Maps to _list_items table in PostgreSQL. /// public class RedbListItem : IRedbListItem { /// /// Unique item identifier. /// [JsonPropertyName("id")] public long Id { get; set; } /// /// List identifier this item belongs to. /// [JsonPropertyName("id_list")] public long IdList { get; set; } /// /// Item value. /// [JsonPropertyName("value")] public string Value { get; set; } = string.Empty; /// /// Linked object identifier (optional). /// [JsonPropertyName("id_object")] public long? IdObject { get; set; } /// /// Item alias (display name). /// [JsonPropertyName("alias")] public string? Alias { get; set; } // === Linked object: loaded on the reader's scope === // A data object owns no connection. // The item carries no loader delegate - it remembers only the database it came from - and Object loads on the live // redb scope of whoever reads it. The delegates it carried before (a per-item loader over the handing-out scope, a // process-wide fallback) opened a fresh scope and pooled connection per read wherever the right one was missing. // The database (cache domain) the item was materialized from; null for an item built in user code. internal string? _cacheDomain; // Set by the list cache and the props cache: the instance is shared by every scope. internal bool _isShared; // The service that materialized the item, held weakly; asked when no scope is current for the reader, while it // lives. A shared item has none. internal WeakReference? _origin; // The scope current for the reader, else the materializing scope while it lives (owner decision 2026-09-15). private RedbServiceBase? Reader() => RedbAmbientScope.Resolve(_cacheDomain) ?? RedbAmbientScope.LiveOrigin(_origin); private IRedbObject? _object = null; private bool _objectLoaded = false; private readonly object _lazyLoadLock = new(); /// Whether the linked object has been resolved (set, preloaded or lazily loaded). [JsonIgnore] public bool IsObjectLoaded => _objectLoaded; /// The object this item already carries, without loading; null when none is loaded. internal IRedbObject? LoadedObject => _objectLoaded ? _object : null; /// /// Makes this item, a key of a grouping that carried only the id, the item is: its /// fields, the database it came from and its linked object when loaded. See ListItemGroupKeys. /// internal void TakeFrom(RedbListItem source) { Id = source.Id; IdList = source.IdList; Value = source.Value; IdObject = source.IdObject; Alias = source.Alias; _cacheDomain = source._cacheDomain; _origin = source._origin; if (source._objectLoaded) { _object = source._object; _objectLoaded = true; } } /// /// Asynchronous form of : resolves the linked object on the reader's scope without blocking a /// thread. Prefer this - or redb.LoadLinkedObjectsAsync(items) for many items, one query - on hot paths. /// public async Task GetObjectAsync(CancellationToken cancellationToken = default) { if (_objectLoaded) return _object; if (!IdObject.HasValue) return _object; var objectId = IdObject.Value; var reader = Reader(); // A captive reader (a service of the root provider, outside a transaction) lends its scope factory, never its one connection. if (reader is { LendsScope: true } captive) return Publish(await RedbDomainRegistry.InScopeOfAsync(captive, service => service.LoadLinkedObjectAsync(objectId, cancellationToken)).ConfigureAwait(false), readerContext: null); if (reader == null) return Publish(await RedbDomainRegistry.InFreshScopeAsync(_cacheDomain, service => service.LoadLinkedObjectAsync(objectId, cancellationToken), Refusal).ConfigureAwait(false), readerContext: null); var loaded = await reader.LoadLinkedObjectAsync(objectId, cancellationToken).ConfigureAwait(false); return Publish(loaded, reader.Context); } /// /// Linked object, loaded lazily on the live redb scope of whoever reads it. Reading it may hit the database; it is /// deliberately invisible to System.Text.Json so that serializing an item (an HTTP response, an audit record) never /// turns into a load. With no live scope reading here the getter refuses with /// (see RedbServiceConfiguration.LazyLoadWithoutScope). /// [JsonIgnore] [RedbIgnore] public IRedbObject? Object { get { if (_objectLoaded) return _object; if (!IdObject.HasValue) return _object; // The freeze anatomy this shape avoids (a production report, 2026-09-09, reproduced locally): items are shared // through the static list cache, so a lock held ACROSS the load parked every toucher of the item // process-wide behind the first one; and Task.Run needed a second pool thread per touch. So: load OUTSIDE // any lock and on the calling thread, down to ADO.NET; concurrent touchers proceed independently (a racing // duplicate load is harmless: the first published result wins). var objectId = IdObject.Value; var reader = Reader(); if (reader is { LendsScope: true } captive) return Publish(RedbDomainRegistry.InScopeOf(captive, service => service.LoadLinkedObjectSync(objectId)), readerContext: null); if (reader == null) return Publish(RedbDomainRegistry.InFreshScope(_cacheDomain, service => service.LoadLinkedObjectSync(objectId), Refusal), readerContext: null); var loaded = reader.LoadLinkedObjectSync(objectId); return Publish(loaded, reader.Context); } set { _object = value; _objectLoaded = true; IdObject = value?.Id > 0 ? value.Id : null; } } private Exception Refusal() => RedbLazyLoadScopeEndedException.ForListItem(Id, IdObject ?? 0); /// /// Publishes a loaded object on the item and returns what readers get. A shared instance does not keep what one /// transaction saw - the write behind it may roll back (owner decision 2026-09-15); the reader still gets it. /// internal IRedbObject? Publish(IRedbObject? loaded, Data.IRedbContext? readerContext) { // A shared item keeps what a transaction loads while that transaction has written nothing - committed state - // and forgets it if the transaction rolls back; once the transaction has written, it keeps nothing (owner // decisions 2026-09-15, 2026-09-17). The reader still gets it. if (_isShared && readerContext != null && !Data.TransactionWrites.ReadsCommitted(readerContext)) return loaded; // What a shared item keeps is shared too: its references and items load on the reader's scope only, never on // the scope that happened to load it. Marked before publishing, outside the lock; a racing duplicate that // loses is marked for nothing. if (_isShared && loaded != null) global::redb.Core.Utils.LazyReferenceInstaller.MarkShared(loaded); var kept = false; lock (_lazyLoadLock) { if (!_objectLoaded) { _object = loaded; _objectLoaded = true; kept = true; } } if (kept && _isShared && readerContext != null) Data.TransactionHooks.OnCompleted(readerContext, committed => { if (!committed) Forget(loaded); }); return _object; } // What a rolled-back transaction loaded into a shared item is dropped: the next read loads again. private void Forget(IRedbObject? loaded) { lock (_lazyLoadLock) { if (!_objectLoaded || !ReferenceEquals(_object, loaded)) return; _object = null; _objectLoaded = false; } } /// /// Check if item is object reference. /// [JsonIgnore] public bool IsObjectReference => IdObject.HasValue; // === Constructors === /// /// Default constructor for deserialization and mapping. /// public RedbListItem() { } /// /// Constructor for creating item linked to list. /// public RedbListItem(IRedbList list, string? value, string? alias = null, long? idObject = null) { if (list == null) throw new ArgumentNullException(nameof(list)); IdList = list.Id; Value = value; Alias = alias; IdObject = idObject; } /// /// Constructor for creating item with linked object. /// public RedbListItem(IRedbList list, string? value, string? alias, IRedbObject linkedObject) { if (list == null) throw new ArgumentNullException(nameof(list)); if (linkedObject == null) throw new ArgumentNullException(nameof(linkedObject)); IdList = list.Id; Value = value; Alias = alias; IdObject = linkedObject.Id > 0 ? linkedObject.Id : null; _object = linkedObject; _objectLoaded = true; } // === Static factory methods === /// /// Create ListItem for specific list. /// public static RedbListItem ForList(IRedbList list, string? value, string? alias = null, long? idObject = null) { return new RedbListItem(list, value, alias, idObject); } /// /// Create ListItem with linked object. /// public static RedbListItem ForList(IRedbList list, string? value, string? alias, IRedbObject linkedObject) { return new RedbListItem(list, value, alias, linkedObject); } /// /// Get display value. /// public string GetDisplayValue() { if (!string.IsNullOrEmpty(Alias)) return Alias; if (!string.IsNullOrEmpty(Value)) return Value; if (IdObject.HasValue) return $"Object #{IdObject}"; return $"Item #{Id}"; } public override string ToString() { var displayValue = GetDisplayValue(); var aliasStr = !string.IsNullOrEmpty(Alias) && Alias != displayValue ? $" ({Alias})" : ""; return $"ListItem {Id}: {displayValue}{aliasStr} [List: {IdList}]"; } } } Path: redb/redb.Core/Models/Entities/RedbObject.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Core/Models/Entities/RedbObject.cs ---- using redb.Core.Models.Contracts; using redb.Core.Models.Configuration; using redb.Core.Utils; using redb.Core.Caching; using redb.Core.Providers; using System; using System.Reflection; using System.Threading.Tasks; using System.Text.Json.Serialization; namespace redb.Core.Models.Entities { /// /// Generic wrapper for JSON from get_object_json with typed interface. /// Field names match JSON/DB (snake_case) to work without attributes and settings. /// Inherits from base RedbObject for API unification. /// Implements typed interface IRedbObject<TProps> for type safety. /// /// A save writes the Props by : /// DeleteInsert by default; ChangeTracking (redb Pro) writes only the values that changed. /// /// Type of object properties. public class RedbObject : RedbObject, IRedbObject where TProps : class, new() { /// /// Default constructor for deserialization. /// public RedbObject() { } /// /// Constructor with properties. /// /// Initial properties object. public RedbObject(TProps props) { _properties = props; _propsLoaded = true; } /// /// Explicit cast to TProps. /// public static explicit operator TProps(RedbObject obj) => obj.Props; /// /// Implicit cast to TProps. /// // public static implicit operator TProps(RedbObject obj) => obj.Props; // SINGLE SOURCE OF DATA - always current (serialized to JSON) private TProps? _properties = null; // === LAZY LOADING FIELDS === /// /// Props loader (set during lazy loading) - public for Provider access. /// [JsonIgnore] public ILazyPropsLoader? _lazyLoader = null; /// /// Props loaded flag (public for Provider access). /// public bool _propsLoaded = false; /// /// Synchronization object for lazy loading. /// private readonly object _lazyLoadLock = new object(); /// /// Object properties with lazy loading support. /// [JsonPropertyName("properties")] public TProps Props { get { // Lazy loading on first access lock (_lazyLoadLock) { if (!_propsLoaded && _lazyLoader != null && id > 0) { var loader = _lazyLoader; try { // Synchronous loading from DB, on the reader's scope var loaded = loader.LoadProps(id, scheme_id); // A shared instance (props cache) keeps what a transaction reads while that transaction has // written nothing - committed state - and forgets it if the transaction rolls back; once the // transaction has written, it keeps nothing (owner decisions 2026-09-15, 2026-09-17). The // reader still gets it. var ambient = loader as AmbientLazyPropsLoader; if (_isShared && ambient != null && !ambient.ReaderKeepsLoads) return loaded!; _properties = loaded; _propsLoaded = true; _lazyLoader = null; if (_isShared) { LazyReferenceInstaller.MarkShared(loaded); ambient?.OnReaderTransactionCompleted(committed => { if (!committed) Forget(loaded, loader); }); } } catch (Exception ex) when (ex is not Exceptions.RedbSynchronousLazyLoadException and not Exceptions.RedbLazyLoadScopeEndedException) { throw new InvalidOperationException( $"Error during lazy loading Props for object {id}: {ex.Message}", ex); } } // A reference nothing can load - an id, no properties, no loader - answers null: plain // System.Text.Json serialization of a graph with hand-made references reads this getter, and an // exception here would fail every such API response (review after 4.0.0, LazyStubSerializationRepro). // Saving such a reference is refused instead (RedbUnloadedReferenceException). } return _properties!; } set { _properties = value; _propsLoaded = true; _lazyLoader = null; } } /// [JsonIgnore] public override bool IsPropsLoaded => _propsLoaded; /// /// Get Props without triggering lazy loading (for internal use in cache). /// public TProps? GetPropsDirectly() { return _properties; } // What a rolled-back transaction loaded into a shared instance is dropped: the next read loads again. private void Forget(TProps? loaded, ILazyPropsLoader loader) { lock (_lazyLoadLock) { if (!_propsLoaded || !ReferenceEquals(_properties, loaded)) return; _properties = null; _propsLoaded = false; _lazyLoader = loader; } } /// /// Explicit async Props preloading (for eager loading scenarios). /// public async Task LoadPropsAsync() { if (!_propsLoaded && _lazyLoader != null && id > 0) { var loader = _lazyLoader; var loaded = await loader.LoadPropsAsync(id, scheme_id); // The rule of the Props getter: kept while the reader's transaction has written nothing, forgotten on its // rollback; what a shared instance keeps is shared too (owner decisions 2026-09-15, 2026-09-17). var ambient = loader as AmbientLazyPropsLoader; if (_isShared && ambient != null && !ambient.ReaderKeepsLoads) return; _properties = loaded; _propsLoaded = true; _lazyLoader = null; if (_isShared) { LazyReferenceInstaller.MarkShared(loaded); ambient?.OnReaderTransactionCompleted(committed => { if (!committed) Forget(loaded, loader); }); } } } /// /// Recompute MD5 hash from Props values and write to hash field. /// public override void RecomputeHash() { hash = RedbHash.ComputeFor(this); } /// /// Get MD5 hash from Props values without changing hash field. /// public override Guid ComputeHash() => RedbHash.ComputeFor(this) ?? Guid.Empty; // ===== TYPED CACHE AND METADATA METHODS ===== /// /// Get scheme for type TProps (using cache and provider). /// Tries cache first, then provider, and only then throws exception. /// public async Task GetSchemeForTypeAsync() { var typeName = typeof(TProps).Name; // 1. Check cache via provider var provider = GetSchemeSyncProvider(); if (provider != null) { var cachedScheme = provider.Cache.GetScheme(typeName); if (cachedScheme != null) return cachedScheme; } // 2. If not in cache and provider exists - try to load if (provider != null) { var scheme = await provider.GetSchemeByTypeAsync(); if (scheme != null) return scheme; // Try to create scheme automatically try { var newScheme = await provider.EnsureSchemeFromTypeAsync(); return newScheme; } catch { // If failed to create - proceed to exceptions } } // 3. If nothing worked - exceptions with hints if (provider == null) { throw new InvalidOperationException( "Scheme provider not initialized. Call RedbObjectFactory.Initialize() or " + "RedbObject.SetSchemeSyncProvider() to set provider."); } throw new InvalidOperationException( $"Scheme for type '{typeName}' not found and cannot be created automatically. " + $"Use provider.EnsureSchemeFromTypeAsync<{typeName}>() to create scheme manually."); } /// /// Get scheme structures for type TProps. /// public async Task> GetStructuresForTypeAsync() { var scheme = await GetSchemeForTypeAsync(); return scheme.Structures; } /// /// Get structure by field name for type TProps. /// public new async Task GetStructureByNameAsync(string fieldName) { var scheme = await GetSchemeForTypeAsync(); return scheme.GetStructureByName(fieldName); } /// /// Recompute hash based on current TProps properties. /// public void RecomputeHashForType() { RecomputeHash(); } /// /// Get new hash based on current properties without changing object. /// public Guid ComputeHashForType() { return ComputeHash(); } /// /// Check if current hash matches TProps properties. /// public bool IsHashValidForType() { if (!hash.HasValue) return false; var computedHash = ComputeHashForType(); return hash.Value == computedHash; } /// /// Create object copy with same metadata but new properties. The copy is a NEW object: /// it takes no id, no hash (recomputed from the new properties on save) and /// no value_unique - the object key is identity, not content, and a copy must /// claim its own or none (copying it would trip UIX__objects__scheme_unique on the /// first save). /// public IRedbObject CloneWithProperties(TProps newProperties) { return new RedbObject(newProperties) { // Copy all metadata except ID (to create new object). Deliberately NOT copied: // value_unique (the key is identity - one object per key per scheme) and hash // (the new Props get their own on save). parent_id = this.parent_id, scheme_id = this.scheme_id, owner_id = this.owner_id, who_change_id = this.who_change_id, date_create = DateTimeOffset.UtcNow, date_modify = DateTimeOffset.UtcNow, date_begin = this.date_begin, date_complete = this.date_complete, key = this.key, value_long = this.value_long, value_string = this.value_string, value_guid = this.value_guid, value_bool = this.value_bool, value_double = this.value_double, value_numeric = this.value_numeric, value_datetime = this.value_datetime, value_bytes = this.value_bytes, name = this.name, note = this.note }; } /// /// Clear metadata cache for type TProps. /// public void InvalidateCacheForType() { var provider = GetSchemeSyncProvider(); if (provider is ISchemeCacheProvider cacheProvider) { cacheProvider.InvalidateSchemeCache(); } } /// /// Preload metadata cache for type TProps. /// public async Task WarmupCacheForTypeAsync() { var provider = GetSchemeSyncProvider(); if (provider is ISchemeCacheProvider cacheProvider) { await cacheProvider.WarmupCacheAsync(); } } /// /// Override with recursive Props processing. /// Resets ID and ParentId for current object and all nested IRedbObject. /// /// If true, recursively processes all nested IRedbObject in Props. public override void ResetIds(bool recursive = false) { // Reset base fields id = 0; parent_id = null; // Recursive Props processing if (recursive && Props != null) { ProcessNestedObjectsForReset(Props); } } /// /// Recursively processes Props to reset nested object IDs. /// private void ProcessNestedObjectsForReset(object obj) { if (obj == null) return; var objType = obj.GetType(); var objProperties = objType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (var property in objProperties) { try { var value = property.GetValue(obj); if (value == null) continue; // Process single IRedbObject if (value is IRedbObject redbObj) { redbObj.ResetIds(true); continue; } // Process IRedbObject collections if (value is System.Collections.IEnumerable enumerable && value is not string) { foreach (var item in enumerable) { if (item is IRedbObject redbItem) { redbItem.ResetIds(true); } } } } catch { // Ignore property access errors continue; } } } } } Path: redb/redb.Core/Models/Entities/RedbObjectBase.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Core/Models/Entities/RedbObjectBase.cs ---- using System; using System.Text.Json.Serialization; using System.Threading.Tasks; using redb.Core.Models.Contracts; using redb.Core.Providers; using redb.Core.Caching; using redb.Core.Utils; namespace redb.Core.Models.Entities { /// /// Base class for all Redb objects with access to metadata. /// Contains all fields from _objects table and methods for working with cached metadata. /// Can be used directly for Object schemes (without Props) or as base for RedbObject{TProps}. /// /// /// The debugger shows the short display string below (the debugger prefers it over /// and walks up the hierarchy, so every derived object gets it); /// returns the object's canonical JSON (discussion #12, item 2). /// [System.Diagnostics.DebuggerDisplay("{name,nq} (id={id}, scheme={scheme_id})")] public class RedbObject : IRedbObject { // ===== GLOBAL PROVIDER FOR METADATA ACCESS ===== private static ISchemeSyncProvider? _globalProvider; /// /// Set global scheme provider for all objects /// Allows objects to access their metadata /// public static void SetSchemeSyncProvider(ISchemeSyncProvider provider) { _globalProvider = provider ?? throw new ArgumentNullException(nameof(provider)); } /// /// Get global scheme provider /// protected static ISchemeSyncProvider? GetSchemeSyncProvider() => _globalProvider; /// /// Check if scheme provider is available /// public static bool IsProviderAvailable => _globalProvider != null; // ===== ROOT FIELDS (_objects) ===== public long id { get; set; } public long? parent_id { get; set; } public long scheme_id { get; set; } public long owner_id { get; set; } public long who_change_id { get; set; } public DateTimeOffset date_create { get; set; } public DateTimeOffset date_modify { get; set; } public DateTimeOffset? date_begin { get; set; } public DateTimeOffset? date_complete { get; set; } public long? key { get; set; } public long? value_long { get; set; } /// /// Identifier / external-key value (RedbPrimitive<string>). Contract limit 450 characters /// (the MSSQL index-key width, enforced in C# on every provider; owner decision 2026-09-02) - /// long text belongs in or in a Props field. /// public string? value_string { get; set; } public Guid? value_guid { get; set; } public bool? value_bool { get; set; } public double? value_double { get; set; } public decimal? value_numeric { get; set; } public DateTimeOffset? value_datetime { get; set; } public byte[]? value_bytes { get; set; } public string? value_unique { get; set; } // V4: unique key within the scheme (UNIQUE stage 1) public string? name { get; set; } public string? note { get; set; } public Guid? hash { get; set; } /// /// Whether the object's properties are present in memory. A non-generic object has none, /// so it is always "loaded"; RedbObject<TProps> overrides this with its lazy-loading /// state. The save path uses it to tell a reference (an object with an id whose /// properties were never loaded: a stub from the depth boundary of a load, or /// new RedbObject<T> { id = x } written by hand) from a nested object to persist. /// A reference is written as its id only and is never re-saved by a parent. /// [JsonIgnore] public virtual bool IsPropsLoaded => true; /// /// Set by the props cache: this instance is shared by every scope. A lazy load under it runs on the reader's scope /// and, inside the reader's transaction, keeps nothing (owner decision 2026-09-15). /// internal bool _isShared; /// /// Recompute MD5 hash and store in hash field. /// For non-generic RedbObject: hash from base value_* fields. /// For RedbObject{TProps}: overridden to hash from Props. /// public virtual void RecomputeHash() { hash = ComputeHash(); } /// /// Compute MD5 hash without modifying the hash field. /// For non-generic RedbObject: hash from base value_* fields. /// For RedbObject{TProps}: overridden to hash from Props. /// public virtual Guid ComputeHash() { return RedbHash.ComputeForBaseFields(this); } // ===== ENRICHED IRedbObject IMPLEMENTATION ===== // (excluded from JSON serialization) public void ResetId(long id) { this.id = id; } // Main identifiers [JsonIgnore] public long Id { get => id; set => id = value; } [JsonIgnore] public long SchemeId { get => scheme_id; set => scheme_id = value; } [JsonIgnore] public string Name { get => name ?? $"Object_{id}"; set => name = value; } // Tree structure [JsonIgnore] public long? ParentId { get => parent_id; set => parent_id = value; } [JsonIgnore] public bool HasParent => parent_id.HasValue; [JsonIgnore] public bool IsRoot => !parent_id.HasValue; // Timestamps [JsonIgnore] public DateTimeOffset DateCreate { get => date_create; set => date_create = value; } [JsonIgnore] public DateTimeOffset DateModify { get => date_modify; set => date_modify = value; } [JsonIgnore] public DateTimeOffset? DateBegin { get => date_begin; set => date_begin = value; } [JsonIgnore] public DateTimeOffset? DateComplete { get => date_complete; set => date_complete = value; } // Ownership and audit [JsonIgnore] public long OwnerId { get => owner_id; set => owner_id = value; } [JsonIgnore] public long WhoChangeId { get => who_change_id; set => who_change_id = value; } // Additional identifiers [JsonIgnore] public long? Key { get => key; set => key = value; } // Primitive values stored directly in _objects table (for primitive schemas) [JsonIgnore] public long? ValueLong { get => value_long; set => value_long = value; } [JsonIgnore] public string? ValueString { get => value_string; set => value_string = value; } [JsonIgnore] public Guid? ValueGuid { get => value_guid; set => value_guid = value; } [JsonIgnore] public bool? ValueBool { get => value_bool; set => value_bool = value; } [JsonIgnore] public double? ValueDouble { get => value_double; set => value_double = value; } [JsonIgnore] public decimal? ValueNumeric { get => value_numeric; set => value_numeric = value; } [JsonIgnore] public DateTimeOffset? ValueDatetime { get => value_datetime; set => value_datetime = value; } [JsonIgnore] public byte[]? ValueBytes { get => value_bytes; set => value_bytes = value; } [JsonIgnore] public string? ValueUnique { get => value_unique; set => value_unique = value; } // Object state [JsonIgnore] public string? Note { get => note; set => note = value; } [JsonIgnore] public Guid? Hash { get => hash; set => hash = value; } // ===== METADATA ACCESS METHODS ===== /// /// Get object scheme by scheme_id (using cache) /// public async Task GetSchemeAsync() { if (_globalProvider == null) return null; return await _globalProvider.GetSchemeByIdAsync(scheme_id); } /// /// Get object scheme structures (using cache) /// public async Task?> GetStructuresAsync() { var scheme = await GetSchemeAsync(); return scheme?.Structures; } /// /// Get structure by field name (using cache) /// public async Task GetStructureByNameAsync(string fieldName) { var scheme = await GetSchemeAsync(); return scheme?.GetStructureByName(fieldName); } /// /// Invalidate cache of this object's scheme /// public void InvalidateSchemeCache() { if (_globalProvider is ISchemeCacheProvider cacheProvider) { cacheProvider.InvalidateSchemeCache(scheme_id); } } /// /// Reset object ID and optionally ParentId (IRedbObject.ResetId implementation) /// /// If true, also resets ParentId to null (default true) public void ResetId(bool withParent = true) { id = 0; if (withParent) { parent_id = null; } } /// /// Reset object ID and ParentId (base implementation of IRedbObject.ResetIds) /// Recursive processing is overridden in RedbObject<TProps> /// /// If true, should recursively reset IDs in all nested IRedbObject public virtual void ResetIds(bool recursive = false) { id = 0; parent_id = null; // Recursive logic is overridden in descendants with access to Props } /// /// The object's canonical JSON - the same contract get_object_json(id) returns and /// the same serializer that parses it, so a loaded object stringifies to exactly what the /// database holds. A lazy stub never triggers loading: the stub write converter emits base /// fields only ("properties": null). Mind the price in logs - a large Props graph /// (a blob above all) serializes whole; the debugger is unaffected, it shows the short /// DebuggerDisplay line instead. /// public override string ToString() { try { // Serialize AS the canonical RedbObject view, whatever the runtime type: the // stub write converter matches exactly RedbObject<> (review find) - serializing a // TreeRedbObject by its own type would bypass it into reflection, which walks // Parent/Children (a cycle) and the Props GETTER (a lazy load). The canonical view // is also what get_object_json returns - tree navigation is not part of it. for (var t = GetType(); t != null; t = t.BaseType) { if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(RedbObject<>)) return System.Text.Json.JsonSerializer.Serialize( this, t, Serialization.SystemTextJsonRedbSerializer.Options); } // No RedbObject shape in the hierarchy (the non-generic RedbObject of an Object // scheme): reflection would hit surprise getters, so write the short form by hand. return $"{{\"id\":{id},\"scheme_id\":{scheme_id},\"name\":{System.Text.Json.JsonSerializer.Serialize(name)},\"hash\":{System.Text.Json.JsonSerializer.Serialize(hash)}}}"; } catch (Exception ex) { // ToString must not throw (debuggers and log formatters call it blindly), and the // failure must not vanish either - it rides inside the fallback JSON. return $"{{\"id\":{id},\"scheme_id\":{scheme_id},\"toStringError\":\"{ex.GetType().Name}: {System.Text.Json.JsonEncodedText.Encode(ex.Message)}\"}}"; } } } } Path: redb/redb.Core/Models/Entities/RedbObjectRow.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Core/Models/Entities/RedbObjectRow.cs ---- using System; using System.Text.Json.Serialization; namespace redb.Core.Models.Entities { /// /// POCO for _objects table. /// Used for direct SQL queries to objects table. /// Not to be confused with RedbObject<TProps> which is a domain wrapper. /// public class RedbObjectRow { /// /// Object ID. /// [JsonPropertyName("id")] public long Id { get; set; } /// /// Parent object ID. /// [JsonPropertyName("id_parent")] public long? IdParent { get; set; } /// /// Scheme ID. /// [JsonPropertyName("id_scheme")] public long IdScheme { get; set; } /// /// Owner user ID. /// [JsonPropertyName("id_owner")] public long IdOwner { get; set; } /// /// Last modifier user ID. /// [JsonPropertyName("id_who_change")] public long IdWhoChange { get; set; } /// /// Creation date. /// [JsonPropertyName("date_create")] public DateTimeOffset DateCreate { get; set; } /// /// Last modification date. /// [JsonPropertyName("date_modify")] public DateTimeOffset DateModify { get; set; } /// /// Begin date (for temporal objects). /// [JsonPropertyName("date_begin")] public DateTimeOffset? DateBegin { get; set; } /// /// Complete date (for temporal objects). /// [JsonPropertyName("date_complete")] public DateTimeOffset? DateComplete { get; set; } /// /// External key for integration. /// [JsonPropertyName("key")] public long? Key { get; set; } /// /// Object name. /// [JsonPropertyName("name")] public string? Name { get; set; } /// /// Object note. /// [JsonPropertyName("note")] public string? Note { get; set; } /// /// Hash for change tracking. /// [JsonPropertyName("hash")] public Guid? Hash { get; set; } // Value columns for primitive storage in object itself /// /// Long value stored directly in object row. /// [JsonPropertyName("_value_long")] public long? ValueLong { get; set; } /// /// String value stored directly in object row. /// [JsonPropertyName("_value_string")] public string? ValueString { get; set; } /// /// Guid value stored directly in object row. /// [JsonPropertyName("_value_guid")] public Guid? ValueGuid { get; set; } /// /// Boolean value stored directly in object row. /// [JsonPropertyName("_value_bool")] public bool? ValueBool { get; set; } /// /// Double value stored directly in object row. /// [JsonPropertyName("_value_double")] public double? ValueDouble { get; set; } /// /// Numeric/decimal value stored directly in object row. /// [JsonPropertyName("_value_numeric")] public decimal? ValueNumeric { get; set; } /// /// DateTime value stored directly in object row. /// [JsonPropertyName("_value_datetime")] public DateTimeOffset? ValueDatetime { get; set; } /// /// Binary data stored directly in object row. /// [JsonPropertyName("_value_bytes")] public byte[]? ValueBytes { get; set; } /// Unique key within the scheme (V4, UNIQUE stage 1). [JsonPropertyName("_value_unique")] public string? ValueUnique { get; set; } public override string ToString() { return $"ObjectRow {Id} (Scheme:{IdScheme}, Name:{Name ?? "null"})"; } } } Path: redb/redb.Core/Models/Entities/RedbObjectRowExtensions.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Core/Models/Entities/RedbObjectRowExtensions.cs ---- namespace redb.Core.Models.Entities { /// /// The one place that turns a raw _objects row into an object header. Every provider /// used to carry its own copy of this column list, and a column added to the row /// (value_unique) reached some copies and not others. /// public static class RedbObjectRowExtensions { /// A typed object carrying the row's header; Props stay unloaded. public static RedbObject ToRedbObject(this RedbObjectRow row) where TProps : class, new() { var obj = new RedbObject(); row.ApplyHeaderTo(obj); return obj; } /// /// Copies the row's header columns onto an existing object of any RedbObject shape - the /// non-generic one, a typed one, or one created by reflection for a scheme's CLR type. /// Props are not touched. /// public static void ApplyHeaderTo(this RedbObjectRow row, RedbObject target) { target.id = row.Id; target.name = row.Name; target.scheme_id = row.IdScheme; target.parent_id = row.IdParent; target.owner_id = row.IdOwner; target.who_change_id = row.IdWhoChange; target.date_create = row.DateCreate; target.date_modify = row.DateModify; target.date_begin = row.DateBegin; target.date_complete = row.DateComplete; target.key = row.Key; target.value_long = row.ValueLong; target.value_string = row.ValueString; target.value_guid = row.ValueGuid; target.value_bool = row.ValueBool; target.value_double = row.ValueDouble; target.value_numeric = row.ValueNumeric; target.value_datetime = row.ValueDatetime; target.value_bytes = row.ValueBytes; target.value_unique = row.ValueUnique; target.note = row.Note; target.hash = row.Hash; } } } Path: redb/redb.Core/Models/Entities/RedbPermission.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Core/Models/Entities/RedbPermission.cs ---- using redb.Core.Models.Contracts; using System.Collections.Generic; using System.Text.Json.Serialization; namespace redb.Core.Models.Entities { /// /// REDB permission entity with direct data storage. /// Maps to _permissions table in PostgreSQL. /// public class RedbPermission : IRedbPermission { /// /// Unique permission identifier. /// [JsonPropertyName("id")] public long Id { get; set; } /// /// Role identifier (null if user-specific permission). /// [JsonPropertyName("id_role")] public long? IdRole { get; set; } /// /// User identifier (null if role-based permission). /// [JsonPropertyName("id_user")] public long? IdUser { get; set; } /// /// Reference object identifier (scheme, object, etc.). /// [JsonPropertyName("id_ref")] public long IdRef { get; set; } /// /// SELECT (read) permission. /// [JsonPropertyName("select")] public bool? Select { get; set; } /// /// INSERT (create) permission. /// [JsonPropertyName("insert")] public bool? Insert { get; set; } /// /// UPDATE (edit) permission. /// [JsonPropertyName("update")] public bool? Update { get; set; } /// /// DELETE (remove) permission. /// [JsonPropertyName("delete")] public bool? Delete { get; set; } /// /// Default constructor for deserialization and mapping. /// public RedbPermission() { } /// /// Check if specific permission is granted. /// public bool HasPermission(string action) { return action.ToLower() switch { "select" or "read" => Select == true, "insert" or "create" => Insert == true, "update" or "edit" => Update == true, "delete" or "remove" => Delete == true, _ => false }; } /// /// Get list of active permissions. /// public IEnumerable GetActivePermissions() { var permissions = new List(); if (Select == true) permissions.Add("Select"); if (Insert == true) permissions.Add("Insert"); if (Update == true) permissions.Add("Update"); if (Delete == true) permissions.Add("Delete"); return permissions; } public override string ToString() { var target = IdRole.HasValue ? $"Role {IdRole}" : $"User {IdUser}"; var permissions = string.Join(", ", GetActivePermissions()); return $"Permission {Id}: {target} -> Ref {IdRef} [{permissions}]"; } } } Path: redb/redb.Core/Models/Entities/RedbPrimitive.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Core/Models/Entities/RedbPrimitive.cs ---- //using redb.Core.Utils; //using System; //using System.Text.Json.Serialization; //namespace redb.Core.Models.Entities; ///// ///// RedbObject with primitive value stored directly in _objects._value_* columns ///// No _values records created. For simple scalar schemas like RedbPrimitive, RedbPrimitive ///// Value is stored in appropriate _value_* column based on type ///// ///// Primitive type (long, string, Guid, bool, double, decimal, DateTimeOffset, byte[]) //public class RedbPrimitive : RedbObject //{ // /// // /// Primitive value stored in _objects._value_* column (which column depends on type T) // /// // [JsonPropertyName("value")] // public T? Value // { // get => GetPrimitiveValue(); // set => SetPrimitiveValue(value); // } // private T? GetPrimitiveValue() // { // var type = typeof(T); // if (type == typeof(long) || type == typeof(int) || type == typeof(short) || type == typeof(byte)) // return ValueLong.HasValue ? (T)(object)ValueLong.Value : default; // if (type == typeof(string)) // return (T)(object?)ValueString; // if (type == typeof(Guid)) // return ValueGuid.HasValue ? (T)(object)ValueGuid.Value : default; // if (type == typeof(bool)) // return ValueBool.HasValue ? (T)(object)ValueBool.Value : default; // if (type == typeof(double) || type == typeof(float)) // return ValueDouble.HasValue ? (T)(object)ValueDouble.Value : default; // if (type == typeof(decimal)) // return ValueNumeric.HasValue ? (T)(object)ValueNumeric.Value : default; // if (type == typeof(DateTimeOffset) || type == typeof(DateTime)) // return ValueDatetime.HasValue ? (T)(object)ValueDatetime.Value : default; // if (type == typeof(byte[])) // return (T)(object?)ValueBytes; // throw new NotSupportedException($"Type {typeof(T).Name} is not supported for RedbPrimitive"); // } // private void SetPrimitiveValue(T? value) // { // if (value == null) // { // // Clear all value columns // ValueLong = null; // ValueString = null; // ValueGuid = null; // ValueBool = null; // ValueDouble = null; // ValueNumeric = null; // ValueDatetime = null; // ValueBytes = null; // return; // } // switch (value) // { // case long v: // ValueLong = v; // break; // case int v: // ValueLong = v; // break; // case short v: // ValueLong = v; // break; // case byte v: // ValueLong = v; // break; // case string v: // ValueString = v; // break; // case Guid v: // ValueGuid = v; // break; // case bool v: // ValueBool = v; // break; // case double v: // ValueDouble = v; // break; // case float v: // ValueDouble = v; // break; // case decimal v: // ValueNumeric = v; // break; // case DateTimeOffset v: // ValueDatetime = v; // break; // case DateTime v: // ValueDatetime = v; // break; // case byte[] v: // ValueBytes = v; // break; // default: // throw new NotSupportedException($"Type {typeof(T).Name} is not supported for RedbPrimitive"); // } // } // /// // /// Recompute hash based on primitive value and store in hash field // /// // public override void RecomputeHash() // { // hash = ComputeHash(); // } // /// // /// Compute MD5 hash based on primitive value without changing hash field // /// // public override Guid ComputeHash() // { // var value = Value; // if (value == null) // return Guid.Empty; // var bytes = System.Text.Encoding.UTF8.GetBytes(value.ToString() ?? string.Empty); // using var md5 = System.Security.Cryptography.MD5.Create(); // var hashBytes = md5.ComputeHash(bytes); // return new Guid(hashBytes); // } //} Path: redb/redb.Core/Models/Entities/RedbRole.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Core/Models/Entities/RedbRole.cs ---- using redb.Core.Models.Contracts; using System; using System.Text.Json.Serialization; namespace redb.Core.Models.Entities { /// /// REDB role entity with direct data storage. /// Maps to _roles table in PostgreSQL. /// public class RedbRole : IRedbRole { /// /// Unique role identifier. /// [JsonPropertyName("id")] public long Id { get; set; } /// /// Role name. /// [JsonPropertyName("name")] public string Name { get; set; } = string.Empty; /// /// Configuration object ID (optional). /// [JsonPropertyName("id_configuration")] public long? IdConfiguration { get; set; } /// /// Default constructor for deserialization and mapping. /// public RedbRole() { } /// /// Constructor with name. /// public RedbRole(string name) { Name = name ?? throw new ArgumentNullException(nameof(name)); } public override string ToString() { return $"Role {Id}: {Name}"; } } } Path: redb/redb.Core/Models/Entities/RedbScheme.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Core/Models/Entities/RedbScheme.cs ---- using redb.Core.Models.Contracts; using System; using System.Collections.Generic; using System.Linq; using System.Text.Json.Serialization; namespace redb.Core.Models.Entities { /// /// REDB scheme entity with direct data storage. /// Maps to _schemes table in PostgreSQL. /// Contains collection of structures (fields). /// public class RedbScheme : IRedbScheme { /// /// Unique scheme identifier. /// [JsonPropertyName("id")] public long Id { get; set; } /// /// Parent scheme identifier (for scheme hierarchy). /// [JsonPropertyName("id_parent")] public long? IdParent { get; set; } /// /// Scheme name. /// [JsonPropertyName("name")] public string Name { get; set; } = string.Empty; /// /// Scheme alias (short name). /// [JsonPropertyName("alias")] public string? Alias { get; set; } /// /// Namespace for C# class generation. /// [JsonPropertyName("name_space")] public string? NameSpace { get; set; } /// /// MD5 hash of all structures (aggregated). /// Used for change detection and cache invalidation. /// [JsonPropertyName("structure_hash")] public Guid? StructureHash { get; set; } /// /// Free-form marker for future / custom extensions (450 chars). Written by /// [RedbTags] at synchronisation when present; direct writes survive sync. /// public string? Tags { get; set; } /// /// The previous names of the scheme, oldest first, as a JSON array of strings; NULL when it was never renamed. /// Written by the sync when it applies 's previous names; read by /// the sync to stop a class that predates the rename. /// public string? RenamedFrom { get; set; } /// /// The version of the Props class the scheme was last synchronised with (_schemes._version, /// ); NULL or 0 for a class without one. Written by the sync /// when a class of a higher version synchronises; never lowered. /// public int? Version { get; set; } /// /// Scheme type ID (Class, Array, Dictionary, JsonDocument, XDocument). /// [JsonPropertyName("type")] public long Type { get; set; } = -9223372036854775675; // Default: Class // === Structures collection === private List _structures = new(); private Dictionary? _structuresByName; /// /// Collection of structures (fields) for this scheme. /// [JsonPropertyName("structures")] public IReadOnlyCollection Structures => _structures.AsReadOnly(); /// /// Internal structures list (for provider). /// internal List StructuresInternal => _structures; /// /// Set structures collection (for mapping). /// public void SetStructures(IEnumerable structures) { _structures = structures?.ToList() ?? new List(); _structuresByName = null; // Invalidate cache } /// /// Fast lookup of structure by name. /// public IRedbStructure? GetStructureByName(string name) { if (_structuresByName == null) { _structuresByName = _structures.ToDictionary(s => s.Name, s => (IRedbStructure)s); } return _structuresByName.TryGetValue(name, out var structure) ? structure : null; } /// /// Default constructor for deserialization and mapping. /// public RedbScheme() { } /// /// Constructor with name. /// public RedbScheme(string name) { Name = name ?? throw new ArgumentNullException(nameof(name)); } public override string ToString() { var nameSpace = !string.IsNullOrEmpty(NameSpace) ? $"{NameSpace}." : ""; var alias = !string.IsNullOrEmpty(Alias) ? $" ({Alias})" : ""; return $"Scheme {Id}: {nameSpace}{Name}{alias}"; } } } Path: redb/redb.Core/Models/Entities/RedbStructure.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Core/Models/Entities/RedbStructure.cs ---- using redb.Core.Models.Contracts; using System.Text.Json.Serialization; namespace redb.Core.Models.Entities { /// /// REDB structure (field definition) entity with direct data storage. /// Maps to _structures table in PostgreSQL. /// public class RedbStructure : IRedbStructure { /// /// Unique structure identifier. /// [JsonPropertyName("id")] public long Id { get; set; } /// /// Parent structure identifier (for nested fields). /// [JsonPropertyName("id_parent")] public long? IdParent { get; set; } /// /// Scheme identifier this structure belongs to. /// [JsonPropertyName("id_scheme")] public long IdScheme { get; set; } /// /// Override structure identifier (for inheritance). /// [JsonPropertyName("id_override")] public long? IdOverride { get; set; } /// /// Type identifier for this field. /// [JsonPropertyName("id_type")] public long IdType { get; set; } /// /// List identifier (for list-type fields). /// [JsonPropertyName("id_list")] public long? IdList { get; set; } /// /// Field name. /// [JsonPropertyName("name")] public string Name { get; set; } = string.Empty; /// /// Field alias (short name). /// [JsonPropertyName("alias")] public string? Alias { get; set; } /// /// Field order in scheme. /// [JsonPropertyName("order")] public long? Order { get; set; } /// /// Is field read-only. /// [JsonPropertyName("readonly")] public bool? Readonly { get; set; } /// /// Is field required (not null). /// [JsonPropertyName("allow_not_null")] public bool? AllowNotNull { get; set; } /// /// Collection type ID: Array (-9223372036854775668) or Dictionary (-9223372036854775667). /// NULL for non-collection fields. /// [JsonPropertyName("collection_type")] public long? CollectionType { get; set; } /// /// Key type ID for Dictionary fields. NULL for non-dictionary fields. /// [JsonPropertyName("key_type")] public long? KeyType { get; set; } /// /// Compress field values. /// [JsonPropertyName("is_compress")] public bool? IsCompress { get; set; } /// /// Store null values. /// [JsonPropertyName("store_null")] public bool? StoreNull { get; set; } /// /// V4 (LAZY Л2): the reference is lazy - read from the `virtual` marker on the property at /// synchronisation. Builders emit a stub for such a reference when the option is on. /// [JsonPropertyName("lazy")] public bool? Lazy { get; set; } /// /// Unique key within the scheme ([RedbUnique]). /// [JsonPropertyName("unique")] public bool? Unique { get; set; } /// /// Encoder version the stored keys were computed with. /// [JsonPropertyName("unique_version")] public long? UniqueVersion { get; set; } /// /// S3: element-key scope of a collection key (NULL = default reading; 1 = element values /// unique per scheme; 2 = no duplicate elements per collection). Values mirror /// . /// [JsonPropertyName("unique_scope")] public long? UniqueScope { get; set; } /// /// Free-form marker for future / custom extensions (450 chars). Written by /// [RedbTags] at synchronisation when present; direct writes survive sync. /// [JsonPropertyName("tags")] public string? Tags { get; set; } /// /// The previous names of the structure, oldest first, as a JSON array of strings; NULL when it was never /// renamed. Written by the sync when it applies [RedbRename]; read by the sync to stop a class that predates /// the rename. /// [JsonPropertyName("renamed_from")] public string? RenamedFrom { get; set; } /// /// Default value (binary). /// [JsonPropertyName("default_value")] public byte[]? DefaultValue { get; set; } /// /// Default editor for field. /// [JsonPropertyName("default_editor")] public string? DefaultEditor { get; set; } /// /// Computed property: is this an array field. /// [JsonIgnore] public bool? IsArray => CollectionType != null; /// /// Default constructor for deserialization and mapping. /// public RedbStructure() { } public override string ToString() { var alias = !string.IsNullOrEmpty(Alias) ? $" ({Alias})" : ""; var arrayIndicator = IsArray == true ? "[]" : ""; var requiredIndicator = AllowNotNull == true ? "*" : ""; return $"Structure {Id}: {Name}{alias}{arrayIndicator}{requiredIndicator} [Type: {IdType}]"; } } } Path: redb/redb.Core/Models/Entities/RedbType.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Core/Models/Entities/RedbType.cs ---- using redb.Core.Models.Contracts; using System; using System.Text.Json.Serialization; namespace redb.Core.Models.Entities { /// /// REDB type entity with direct data storage. /// Maps to _types table in PostgreSQL. /// public class RedbType : IRedbType { /// /// Unique type identifier. /// [JsonPropertyName("id")] public long Id { get; set; } /// /// Type name. /// [JsonPropertyName("name")] public string Name { get; set; } = string.Empty; /// /// Database type name (e.g., "String", "Long", "Boolean"). /// [JsonPropertyName("db_type")] public string? DbType { get; set; } /// /// .NET type full name (e.g., "System.String", "System.Int64"). /// [JsonPropertyName("type")] public string? Type1 { get; set; } /// /// Default constructor for deserialization and mapping. /// public RedbType() { } /// /// Constructor with name. /// public RedbType(string name) { Name = name ?? throw new ArgumentNullException(nameof(name)); } /// /// Get .NET Type from string representation. /// public Type? GetDotNetType() { if (string.IsNullOrEmpty(Type1)) return null; return Type1 switch { "System.String" => typeof(string), "System.Int64" => typeof(long), "System.Int32" => typeof(int), "System.Double" => typeof(double), "System.DateTimeOffset" => typeof(DateTimeOffset), "System.Boolean" => typeof(bool), "System.Guid" => typeof(Guid), _ => Type.GetType(Type1) }; } /// /// Check if type supports arrays. /// public bool SupportsArrays() { return !string.IsNullOrEmpty(Name); } public override string ToString() { var dotNetType = !string.IsNullOrEmpty(Type1) ? $" (.NET: {Type1})" : ""; var dbType = !string.IsNullOrEmpty(DbType) ? $" (DB: {DbType})" : ""; return $"Type {Id}: {Name}{dotNetType}{dbType}"; } } } Path: redb/redb.Core/Models/Entities/RedbUser.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Core/Models/Entities/RedbUser.cs ---- using redb.Core.Models.Contracts; using System; using System.Collections.Generic; using System.Text.Json.Serialization; namespace redb.Core.Models.Entities { /// /// REDB user entity with direct data storage. /// Maps to _users table in PostgreSQL. /// public class RedbUser : IRedbUser { /// /// Unique user identifier. /// [JsonPropertyName("id")] public long Id { get; set; } /// /// User login (unique). /// [JsonPropertyName("login")] public string Login { get; set; } = string.Empty; /// /// User display name. /// [JsonPropertyName("name")] public string Name { get; set; } = string.Empty; /// /// User password (hashed). /// [JsonPropertyName("password")] public string Password { get; set; } = string.Empty; /// /// Whether user is active. /// [JsonPropertyName("enabled")] public bool Enabled { get; set; } = true; /// /// User registration date. /// [JsonPropertyName("date_register")] public DateTimeOffset DateRegister { get; set; } = DateTimeOffset.UtcNow; /// /// User dismissal date (null if active). /// [JsonPropertyName("date_dismiss")] public DateTimeOffset? DateDismiss { get; set; } /// /// User phone (optional). /// [JsonPropertyName("phone")] public string? Phone { get; set; } /// /// User email (optional). /// [JsonPropertyName("email")] public string? Email { get; set; } /// /// Additional user key (optional). /// [JsonPropertyName("key")] public long? Key { get; set; } /// /// Integer code for categorization (optional). /// [JsonPropertyName("code_int")] public long? CodeInt { get; set; } /// /// String code for departments/branches (optional). /// [JsonPropertyName("code_string")] public string? CodeString { get; set; } /// /// GUID code for distributed systems (optional). /// [JsonPropertyName("code_guid")] public Guid? CodeGuid { get; set; } /// /// User notes or comments (optional). /// [JsonPropertyName("note")] public string? Note { get; set; } /// /// Hash for data integrity verification (optional). /// [JsonPropertyName("hash")] public Guid? Hash { get; set; } /// /// Configuration object ID (optional). /// [JsonPropertyName("id_configuration")] public long? IdConfiguration { get; set; } /// /// Default constructor for deserialization and mapping. /// public RedbUser() { } /// /// Constructor with required fields. /// public RedbUser(string login, string name, string password) { Login = login ?? throw new ArgumentNullException(nameof(login)); Name = name ?? throw new ArgumentNullException(nameof(name)); Password = password ?? throw new ArgumentNullException(nameof(password)); } /// /// System user (SYS_USER_ID = 0). /// public static RedbUser SystemUser => new RedbUser { Id = 0, Login = "sys", Name = "System User", Password = "", Enabled = true, DateRegister = DateTimeOffset.MinValue, DateDismiss = null, Phone = null, Email = null, Key = null, CodeInt = 0, CodeString = "SYS", CodeGuid = new Guid("00000000-0000-0000-0000-000000000001"), Note = "System user REDB", Hash = null }; public override string ToString() { var status = Enabled ? "Active" : "Disabled"; var codes = new List(); if (CodeInt.HasValue) codes.Add($"Int={CodeInt}"); if (!string.IsNullOrEmpty(CodeString)) codes.Add($"Str={CodeString}"); if (Key.HasValue) codes.Add($"Key={Key}"); var codesStr = codes.Count > 0 ? $" [{string.Join(", ", codes)}]" : ""; return $"User {Id}: {Login} ({Name}) - {status}{codesStr}"; } } } Path: redb/redb.Core/Models/Entities/RedbUserRole.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Core/Models/Entities/RedbUserRole.cs ---- using redb.Core.Models.Contracts; using System.Text.Json.Serialization; namespace redb.Core.Models.Entities { /// /// REDB user-role association entity with direct data storage. /// Maps to _users_roles table in PostgreSQL. /// public class RedbUserRole : IRedbUserRole { /// /// Unique association identifier. /// [JsonPropertyName("id")] public long Id { get; set; } /// /// Role identifier. /// [JsonPropertyName("id_role")] public long IdRole { get; set; } /// /// User identifier. /// [JsonPropertyName("id_user")] public long IdUser { get; set; } /// /// Default constructor for deserialization and mapping. /// public RedbUserRole() { } /// /// Constructor with user and role IDs. /// public RedbUserRole(long idUser, long idRole) { IdUser = idUser; IdRole = idRole; } public override string ToString() { return $"UserRole {Id}: User {IdUser} -> Role {IdRole}"; } } } Path: redb/redb.Core/Models/Entities/RedbValue.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Core/Models/Entities/RedbValue.cs ---- using System; using System.Text.Json.Serialization; namespace redb.Core.Models.Entities { /// /// REDB value entity with direct data storage. /// Maps to _values table in PostgreSQL. /// Stores field values for objects (EAV pattern). /// public class RedbValue { /// /// Unique value identifier. /// [JsonPropertyName("id")] public long Id { get; set; } /// /// Structure (field definition) identifier. /// [JsonPropertyName("id_structure")] public long IdStructure { get; set; } /// /// Object identifier this value belongs to. /// [JsonPropertyName("id_object")] public long IdObject { get; set; } /// /// String value. /// [JsonPropertyName("string")] public string? String { get; set; } /// /// Long integer value. /// [JsonPropertyName("long")] public long? Long { get; set; } /// /// GUID value. /// [JsonPropertyName("guid")] public Guid? Guid { get; set; } /// /// Double value. /// [JsonPropertyName("double")] public double? Double { get; set; } /// /// DateTime with timezone value. /// [JsonPropertyName("date_time_offset")] public DateTimeOffset? DateTimeOffset { get; set; } /// /// Boolean value. /// [JsonPropertyName("boolean")] public bool? Boolean { get; set; } /// /// Binary data value. /// [JsonPropertyName("byte_array")] public byte[]? ByteArray { get; set; } /// /// Decimal value (high precision). /// [JsonPropertyName("numeric")] public decimal? Numeric { get; set; } /// /// List item reference ID. /// [JsonPropertyName("list_item")] public long? ListItem { get; set; } /// /// Object reference ID. /// [JsonPropertyName("object")] public long? Object { get; set; } /// /// Parent value ID for nested structures (arrays, dictionaries). /// [JsonPropertyName("array_parent_id")] public long? ArrayParentId { get; set; } /// /// Array index or dictionary key. /// For arrays: "0", "1", "2", etc. /// For dictionaries: string key. /// NULL for non-collection fields. /// [JsonPropertyName("array_index")] public string? ArrayIndex { get; set; } /// /// Unique-key hash of the typed value (UniqueKeyEncoder) for a [RedbUnique] root scalar; NULL /// for every other row. Backs the unique index over (_id_structure, _unique). /// [JsonPropertyName("unique")] public Guid? Unique { get; set; } /// /// Default constructor for deserialization and mapping. /// public RedbValue() { } /// /// Check if this is an array/collection element. /// [JsonIgnore] public bool IsArrayElement => !string.IsNullOrEmpty(ArrayIndex); public override string ToString() { var valueStr = String ?? Long?.ToString() ?? Guid?.ToString() ?? Double?.ToString() ?? Boolean?.ToString() ?? "[binary]"; var indexStr = IsArrayElement ? $"[{ArrayIndex}]" : ""; return $"Value {Id}: Struct={IdStructure}, Obj={IdObject}{indexStr} = {valueStr}"; } } } Path: redb/redb.Core/Models/Entities/StructureTreeNode.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Core/Models/Entities/StructureTreeNode.cs ---- using redb.Core.Models.Contracts; using System; using System.Collections.Generic; using System.Linq; namespace redb.Core.Models.Entities { /// /// Structure tree node for hierarchical navigation /// Solves the problem of flat structure search in SaveAsync /// public class StructureTreeNode { public IRedbStructure Structure { get; set; } = null!; public List Children { get; set; } = new(); public StructureTreeNode? Parent { get; set; } /// /// TREE NAVIGATION /// public bool IsRoot => Parent == null; public bool IsLeaf => Children.Count == 0; public int Depth => Parent?.Depth + 1 ?? 0; public string Path => Parent != null ? $"{Parent.Path}.{Structure.Name}" : Structure.Name; /// /// TREE SEARCH /// public StructureTreeNode? FindChild(string name) { return Children.FirstOrDefault(c => c.Structure.Name.Equals(name, StringComparison.OrdinalIgnoreCase)); } public StructureTreeNode? FindDescendant(long structureId) { if (Structure.Id == structureId) return this; foreach (var child in Children) { var found = child.FindDescendant(structureId); if (found != null) return found; } return null; } public StructureTreeNode? FindDescendantByName(string name) { if (Structure.Name.Equals(name, StringComparison.OrdinalIgnoreCase)) return this; foreach (var child in Children) { var found = child.FindDescendantByName(name); if (found != null) return found; } return null; } public List GetAllDescendants() { var result = new List(); foreach (var child in Children) { result.Add(child); result.AddRange(child.GetAllDescendants()); } return result; } public List GetChildrenStructures() { return Children.Select(c => c.Structure).ToList(); } public List GetLeafNodes() { var result = new List(); if (IsLeaf) { result.Add(this); } else { foreach (var child in Children) { result.AddRange(child.GetLeafNodes()); } } return result; } /// /// TREE TRAVERSAL /// public void WalkTree(Action visitor) { visitor(this); foreach (var child in Children) { child.WalkTree(visitor); } } public void WalkTreeWithDepth(Action visitor, int currentDepth = 0) { visitor(this, currentDepth); foreach (var child in Children) { child.WalkTreeWithDepth(visitor, currentDepth + 1); } } /// /// HIERARCHY CHECKS /// public bool HasChild(string name) { return Children.Any(c => c.Structure.Name.Equals(name, StringComparison.OrdinalIgnoreCase)); } public bool HasDescendant(long structureId) { return FindDescendant(structureId) != null; } public bool IsDescendantOf(StructureTreeNode ancestor) { var current = Parent; while (current != null) { if (current.Structure.Id == ancestor.Structure.Id) return true; current = current.Parent; } return false; } /// /// DIAGNOSTICS /// public override string ToString() { var indent = new string(' ', Depth * 2); var arrayIndicator = Structure.CollectionType != null ? "[]" : ""; var childrenCount = Children.Count > 0 ? $" ({Children.Count} children)" : ""; return $"{indent}{Structure.Name}{arrayIndicator}{childrenCount}"; } public string ToDetailedString() { return $"Structure {Structure.Id}: {Path} [Type: {Structure.IdType}, CollectionType: {Structure.CollectionType}, Depth: {Depth}]"; } /// /// Print entire tree for diagnostics /// public string PrintTree() { var result = new List(); WalkTreeWithDepth((node, depth) => { var indent = new string(' ', depth * 2); var arrayIndicator = node.Structure.CollectionType != null ? "[]" : ""; result.Add($"{indent}└─ {node.Structure.Name}{arrayIndicator} (ID: {node.Structure.Id})"); }); return string.Join("\n", result); } } /// /// Structure tree builder from flat lists /// public static class StructureTreeBuilder { /// /// Build tree from flat structure list /// public static List BuildFromFlat(List flatStructures) { var allNodes = new Dictionary(); var rootNodes = new List(); // Create all nodes foreach (var structure in flatStructures) { var node = new StructureTreeNode { Structure = structure }; allNodes[structure.Id] = node; } // Set parent-child relationships foreach (var node in allNodes.Values) { if (node.Structure.IdParent.HasValue) { if (allNodes.TryGetValue(node.Structure.IdParent.Value, out var parentNode)) { node.Parent = parentNode; parentNode.Children.Add(node); } } else { rootNodes.Add(node); } } // Sort children by Order foreach (var node in allNodes.Values) { node.Children = node.Children .OrderBy(c => c.Structure.Order ?? 0) .ThenBy(c => c.Structure.Id) .ToList(); } // Sort root nodes return rootNodes .OrderBy(n => n.Structure.Order ?? 0) .ThenBy(n => n.Structure.Id) .ToList(); } /// /// Find node by path (e.g. "Address1.Details.Floor") /// public static StructureTreeNode? FindNodeByPath(List tree, string path) { var parts = path.Split('.'); StructureTreeNode? current = null; // Find root node current = tree.FirstOrDefault(n => n.Structure.Name.Equals(parts[0], StringComparison.OrdinalIgnoreCase)); if (current == null) return null; // Follow the path for (int i = 1; i < parts.Length; i++) { current = current.FindChild(parts[i]); if (current == null) return null; } return current; } /// /// Get all tree nodes in flat list /// public static List FlattenTree(List tree) { var result = new List(); foreach (var root in tree) { result.Add(root); result.AddRange(root.GetAllDescendants()); } return result; } /// /// Tree diagnostics - find issues /// public static TreeDiagnosticReport DiagnoseTree(List tree, Type? csharpType = null) { var report = new TreeDiagnosticReport(); // Find orphaned nodes var allNodes = FlattenTree(tree); foreach (var node in allNodes) { if (node.Structure.IdParent.HasValue && node.Parent == null) { report.OrphanedNodes.Add($"Structure {node.Structure.Id} ({node.Structure.Name}) has parent ID but no parent node"); } } // Check C# type correspondence if (csharpType != null) { var csharpProperties = csharpType.GetProperties().Select(p => p.Name).ToHashSet(); foreach (var root in tree) { if (!csharpProperties.Contains(root.Structure.Name)) { report.ExcessiveStructures.Add($"Structure '{root.Structure.Name}' not found in C# type {csharpType.Name}"); } } foreach (var propertyName in csharpProperties) { if (!tree.Any(n => n.Structure.Name == propertyName)) { report.MissingStructures.Add($"C# property '{propertyName}' has no corresponding structure"); } } } return report; } } /// /// Structure tree diagnostic report /// public class TreeDiagnosticReport { public List ExcessiveStructures { get; set; } = new(); public List MissingStructures { get; set; } = new(); public List OrphanedNodes { get; set; } = new(); public List TypeMismatches { get; set; } = new(); public List Recommendations { get; set; } = new(); public bool IsValid => !ExcessiveStructures.Any() && !MissingStructures.Any() && !OrphanedNodes.Any() && !TypeMismatches.Any(); public string Summary => $"Valid: {IsValid}, Issues: {ExcessiveStructures.Count + MissingStructures.Count + OrphanedNodes.Count + TypeMismatches.Count}"; } } Path: redb/redb.Core/Models/Entities/TreeRedbObject.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Core/Models/Entities/TreeRedbObject.cs ---- using redb.Core.Models.Contracts; using redb.Core.Utils; using System; using System.Collections.Generic; using System.Linq; namespace redb.Core.Models.Entities { /// /// Base class for REDB tree objects with hierarchy navigation /// Supports polymorphic trees - objects of different schemes in one tree /// Extends RedbObject by adding navigational properties and traversal methods /// public class TreeRedbObject : RedbObject, ITreeRedbObject { /// /// Reference to parent object (filled when loading tree) /// public ITreeRedbObject? Parent { get; set; } /// /// Collection of child objects (filled when loading tree) /// public ICollection Children { get; set; } = new List(); /// /// Checks if node is leaf (has no children) /// public bool IsLeaf => !Children.Any(); /// /// Gets node level in tree (0 for root) /// public int Level { get { int level = 0; var current = Parent; while (current != null) { level++; current = current.Parent; } return level; } } /// /// Gets all node ancestors (from parent to root) /// public IEnumerable Ancestors { get { var current = Parent; while (current != null) { yield return current; current = current.Parent; } } } /// /// Gets all node descendants recursively /// public IEnumerable Descendants { get { foreach (var child in Children) { yield return child; foreach (var descendant in child.Descendants) yield return descendant; } } } /// /// Gets path from root to current node as IDs /// public IEnumerable GetPathIds() { var path = new List(); var current = this; while (current != null) { path.Insert(0, current.Id); current = current.Parent as TreeRedbObject; } return path; } /// /// Gets breadcrumbs for navigation /// /// Separator between elements /// Whether to include IDs in parentheses /// String like "Root > Category > Subcategory" public string GetBreadcrumbs(string separator = " > ", bool includeIds = false) { var ancestors = Ancestors.Reverse().ToList(); var path = ancestors.Append(this); var names = path.Select(node => { var displayName = node.Name ?? $"Object {node.Id}"; return includeIds ? $"{displayName} ({node.Id})" : displayName; }); return string.Join(separator, names); } /// /// Checks if current node is descendant of specified node /// /// Alleged ancestor /// true if current is descendant of ancestor public bool IsDescendantOf(ITreeRedbObject ancestor) { var current = Parent; while (current != null) { if (current.Id == ancestor.Id) return true; current = current.Parent; } return false; } /// /// Checks if current node is ancestor of specified node /// /// Alleged descendant /// true if current is ancestor of descendant public bool IsAncestorOf(ITreeRedbObject descendant) { return descendant.IsDescendantOf(this); } /// /// Gets all subtree nodes (including current) in depth-first order /// /// Sequence of subtree nodes public IEnumerable GetSubtree() { yield return this; foreach (var child in Children) { foreach (var node in child.GetSubtree()) yield return node; } } /// /// Gets number of nodes in subtree (including current) /// public int SubtreeSize => GetSubtree().Count(); /// /// Gets maximum depth of subtree from current node /// public int MaxDepth { get { if (!Children.Any()) return 0; return 1 + Children.Max(child => child.MaxDepth); } } /// /// Recompute MD5 hash from object values and store in hash field /// public override void RecomputeHash() { hash = RedbHash.ComputeFor((IRedbObject)this); } /// /// Get MD5 hash from object values without modifying hash field /// public override Guid ComputeHash() => RedbHash.ComputeFor((IRedbObject)this) ?? Guid.Empty; } /// /// ARCHITECTURAL FIX: Typed version of REDB tree object /// NEW INHERITANCE: RedbObject<TProps> instead of TreeRedbObject /// ADVANTAGES: Direct type casting, Props duplication elimination, no conversion /// POLYMORPHISM: Implements ITreeRedbObject for untyped operations support /// /// Object properties type public class TreeRedbObject : RedbObject, ITreeRedbObject, ITreeRedbObject where TProps : class, new() { // FIX: Props inherited from RedbObject - duplication eliminated! // === TREE-SPECIFIC PROPERTIES - untyped navigation === // Supports polymorphic trees - parents and children can be different types /// /// Reference to parent object (untyped to support polymorphic trees) /// public ITreeRedbObject? Parent { get; set; } /// /// Collection of child objects (untyped to support polymorphic trees) /// public ICollection Children { get; set; } = new List(); // === TREE NAVIGATION PROPERTIES (moved from base TreeRedbObject) === /// /// Checks if node is leaf (has no children) /// public bool IsLeaf => !Children.Any(); /// /// Gets node level in tree (0 for root) /// public int Level { get { int level = 0; var current = Parent; while (current != null) { level++; current = current.Parent; } return level; } } /// /// Gets all subtree nodes (including current) in depth-first order /// public IEnumerable GetSubtree() { yield return this; foreach (var child in Children) { foreach (var node in child.GetSubtree()) yield return node; } } /// /// Gets all node ancestors (from parent to root) /// public IEnumerable Ancestors { get { var current = Parent; while (current != null) { yield return current; current = current.Parent; } } } /// /// Gets all node descendants recursively /// public IEnumerable Descendants { get { foreach (var child in Children) { yield return child; foreach (var descendant in child.Descendants) yield return descendant; } } } // === NAVIGATION METHODS (moved from base TreeRedbObject) === /// /// Gets path from root to current node as IDs /// public IEnumerable GetPathIds() { var path = new List(); var current = (ITreeRedbObject?)this; while (current != null) { path.Insert(0, current.Id); current = current.Parent; } return path; } /// /// Gets breadcrumbs for navigation /// public string GetBreadcrumbs(string separator = " > ", bool includeIds = false) { var ancestors = Ancestors.Reverse().ToList(); var path = ancestors.Append(this); var names = path.Select(node => { var displayName = node.Name ?? $"Object {node.Id}"; return includeIds ? $"{displayName} ({node.Id})" : displayName; }); return string.Join(separator, names); } /// /// Checks if current node is descendant of specified node /// public bool IsDescendantOf(ITreeRedbObject ancestor) { var current = Parent; while (current != null) { if (current.Id == ancestor.Id) return true; current = current.Parent; } return false; } /// /// Checks if current node is ancestor of specified node /// public bool IsAncestorOf(ITreeRedbObject descendant) { return descendant.IsDescendantOf(this); } /// /// Gets number of nodes in subtree (including current) /// public int SubtreeSize => GetSubtree().Count(); /// /// Gets maximum depth of subtree from current node /// public int MaxDepth { get { if (!Children.Any()) return 0; return 1 + Children.Max(child => child.MaxDepth); } } // Cache and metadata methods inherited from RedbObject // Navigation methods now directly implement ITreeRedbObject (untyped) // Explicit interface implementations no longer needed! } } Path: redb/redb.Core/Models/Enums/PermissionAction.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Core/Models/Enums/PermissionAction.cs ---- using System; namespace redb.Core.Models.Enums { /// /// Permission actions (flags for combining) /// [Flags] public enum PermissionAction { /// /// No permissions /// None = 0, /// /// Read permission /// Select = 1, /// /// Permission to create child objects /// Insert = 2, /// /// Edit permission /// Update = 4, /// /// Delete permission /// Delete = 8, /// /// All permissions /// All = Select | Insert | Update | Delete, /// /// Read and edit permissions /// ReadWrite = Select | Update, /// /// Read and create permissions /// ReadCreate = Select | Insert } } Path: redb/redb.Core/Models/Enums/UserStatus.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Core/Models/Enums/UserStatus.cs ---- namespace redb.Core.Models.Enums { /// /// User status /// public enum UserStatus { /// /// Active user /// Active, /// /// Disabled user /// Disabled, /// /// Dismissed user /// Dismissed, /// /// Blocked user /// Blocked, /// /// System user /// System } } Path: redb/redb.Core/Models/Permissions/EffectivePermissionResult.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Core/Models/Permissions/EffectivePermissionResult.cs ---- namespace redb.Core.Models.Permissions { /// /// Result of getting user's effective permissions on object /// public class EffectivePermissionResult { /// /// Object ID /// public long ObjectId { get; set; } /// /// User ID /// public long UserId { get; set; } /// /// Permission source ID (object from which permission is inherited) /// public long PermissionSourceId { get; set; } /// /// Permission type (user or role-based) /// public string PermissionType { get; set; } = ""; /// /// Role ID (if permission is role-based) /// public long? RoleId { get; set; } /// /// User ID in permission (if permission is user-based) /// public long? PermissionUserId { get; set; } /// /// Read permission /// public bool CanSelect { get; set; } /// /// Permission to create child objects /// public bool CanInsert { get; set; } /// /// Edit permission /// public bool CanUpdate { get; set; } /// /// Delete permission /// public bool CanDelete { get; set; } /// /// Permission is inherited from parent object /// public bool IsInherited => PermissionSourceId != ObjectId; /// /// Has any permissions /// public bool HasAnyPermission => CanSelect || CanInsert || CanUpdate || CanDelete; /// /// Has full permissions (all actions allowed) /// public bool HasFullPermission => CanSelect && CanInsert && CanUpdate && CanDelete; } } Path: redb/redb.Core/Models/Permissions/PermissionFlags.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Core/Models/Permissions/PermissionFlags.cs ---- using System; namespace redb.Core.Models.Permissions { /// /// Permission flags for REDB objects /// Correspond to _select, _insert, _update, _delete fields in _permissions table /// [Flags] public enum PermissionFlags { /// /// No permissions /// None = 0, /// /// Read permission (SELECT) /// Select = 1, /// /// Create permission (INSERT) /// Insert = 2, /// /// Update permission (UPDATE) /// Update = 4, /// /// Delete permission (DELETE) /// Delete = 8, /// /// All permissions (RIUD) /// All = Select | Insert | Update | Delete, /// /// Read and write (RI_U) /// ReadWrite = Select | Insert | Update, /// /// Read only (R) /// ReadOnly = Select } /// /// Extensions for working with PermissionFlags /// public static class PermissionFlagsExtensions { /// /// Check if has read permission /// public static bool CanSelect(this PermissionFlags flags) => flags.HasFlag(PermissionFlags.Select); /// /// Check if has create permission /// public static bool CanInsert(this PermissionFlags flags) => flags.HasFlag(PermissionFlags.Insert); /// /// Check if has update permission /// public static bool CanUpdate(this PermissionFlags flags) => flags.HasFlag(PermissionFlags.Update); /// /// Check if has delete permission /// public static bool CanDelete(this PermissionFlags flags) => flags.HasFlag(PermissionFlags.Delete); /// /// Convert to display string (e.g. "RIUD") /// public static string ToDisplayString(this PermissionFlags flags) { var result = ""; if (flags.CanSelect()) result += "R"; if (flags.CanInsert()) result += "I"; if (flags.CanUpdate()) result += "U"; if (flags.CanDelete()) result += "D"; return string.IsNullOrEmpty(result) ? "----" : result; } /// /// Create PermissionFlags from boolean values (as in DB) /// public static PermissionFlags FromBooleans(bool select, bool insert, bool update, bool delete) { var flags = PermissionFlags.None; if (select) flags |= PermissionFlags.Select; if (insert) flags |= PermissionFlags.Insert; if (update) flags |= PermissionFlags.Update; if (delete) flags |= PermissionFlags.Delete; return flags; } } } Path: redb/redb.Core/Models/Permissions/PermissionRequest.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Core/Models/Permissions/PermissionRequest.cs ---- namespace redb.Core.Models.Permissions { /// /// Request for creating or updating permission /// public class PermissionRequest { /// /// User ID (null if permission is for role) /// public long? UserId { get; set; } /// /// Role ID (null if permission is for user) /// public long? RoleId { get; set; } /// /// Object ID (0 for global permissions) /// public long ObjectId { get; set; } /// /// Read permission /// public bool? CanSelect { get; set; } /// /// Permission to create child objects /// public bool? CanInsert { get; set; } /// /// Edit permission /// public bool? CanUpdate { get; set; } /// /// Delete permission /// public bool? CanDelete { get; set; } /// /// Validate request /// public bool IsValid() { // Either user or role must be specified, but not both if (UserId.HasValue && RoleId.HasValue) return false; if (!UserId.HasValue && !RoleId.HasValue) return false; // At least one permission must be specified if (!CanSelect.HasValue && !CanInsert.HasValue && !CanUpdate.HasValue && !CanDelete.HasValue) return false; return true; } } } Path: redb/redb.Core/Models/Permissions/UserPermissionResult.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Core/Models/Permissions/UserPermissionResult.cs ---- using System; using System.ComponentModel.DataAnnotations.Schema; namespace redb.Core.Models.Permissions { // Result of get_user_permissions_for_object(object_id, user_id) function public class UserPermissionResult { [Column("object_id")] public long ObjectId { get; set; } [Column("user_id")] public long? UserId { get; set; } // Can be NULL when called with user_id = NULL [Column("permission_source_id")] public long PermissionSourceId { get; set; } [Column("permission_type")] public string PermissionType { get; set; } = string.Empty; // 'user' | 'role' [Column("_id_role")] public long? IdRole { get; set; } [Column("_id_user")] public long? IdUser { get; set; } [Column("can_select")] public bool CanSelect { get; set; } [Column("can_insert")] public bool CanInsert { get; set; } [Column("can_update")] public bool CanUpdate { get; set; } [Column("can_delete")] public bool CanDelete { get; set; } } } Path: redb/redb.Core/Models/Permissions/UserPermissionSet.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Core/Models/Permissions/UserPermissionSet.cs ---- using System; using System.Collections.Generic; namespace redb.Core.Models.Permissions { /// /// User permissions set for caching /// Contains all user permissions for quick access /// public class UserPermissionSet { /// /// User ID /// public long UserId { get; set; } /// /// Permission set creation time /// public DateTimeOffset CreatedAt { get; set; } = DateTimeOffset.UtcNow; /// /// Cache expiration time /// public DateTimeOffset ExpiresAt { get; set; } = DateTimeOffset.UtcNow.AddMinutes(30); /// /// Permissions on specific objects /// Key: ObjectId, Value: PermissionFlags /// public Dictionary ObjectPermissions { get; set; } = new(); /// /// Global permissions (for all objects) /// public PermissionFlags GlobalPermissions { get; set; } = PermissionFlags.None; /// /// Permissions on schemes /// Key: SchemeId, Value: PermissionFlags /// public Dictionary SchemePermissions { get; set; } = new(); /// /// Cache version (for invalidation) /// public long Version { get; set; } = 1; /// /// Check if cache is expired /// public bool IsExpired => DateTimeOffset.UtcNow > ExpiresAt; /// /// Get permissions for object considering hierarchy /// public PermissionFlags GetPermissionsForObject(long objectId, long schemeId) { // 1. Check specific permissions on object if (ObjectPermissions.TryGetValue(objectId, out var objectPerms) && objectPerms != PermissionFlags.None) { return objectPerms; } // 2. Check permissions on scheme if (SchemePermissions.TryGetValue(schemeId, out var schemePerms) && schemePerms != PermissionFlags.None) { return schemePerms; } // 3. Return global permissions return GlobalPermissions; } /// /// Add permission on object /// public void AddObjectPermission(long objectId, PermissionFlags permissions) { ObjectPermissions[objectId] = permissions; } /// /// Add permission on scheme /// public void AddSchemePermission(long schemeId, PermissionFlags permissions) { SchemePermissions[schemeId] = permissions; } /// /// Set global permissions /// public void SetGlobalPermissions(PermissionFlags permissions) { GlobalPermissions = permissions; } /// /// Check if user can perform operation on object /// public bool CanPerformOperation(long objectId, long schemeId, PermissionFlags requiredPermission) { var userPermissions = GetPermissionsForObject(objectId, schemeId); return userPermissions.HasFlag(requiredPermission); } /// /// Invalidate cache (set as expired) /// public void Invalidate() { ExpiresAt = DateTimeOffset.UtcNow.AddSeconds(-1); } /// /// Extend cache lifetime /// public void ExtendExpiration(TimeSpan extension) { ExpiresAt = DateTimeOffset.UtcNow.Add(extension); } /// /// Get cache statistics /// public CacheStatistics GetStatistics() { return new CacheStatistics { UserId = UserId, ObjectPermissionsCount = ObjectPermissions.Count, SchemePermissionsCount = SchemePermissions.Count, HasGlobalPermissions = GlobalPermissions != PermissionFlags.None, CreatedAt = CreatedAt, ExpiresAt = ExpiresAt, IsExpired = IsExpired, Version = Version }; } } /// /// Permissions cache statistics /// public class CacheStatistics { public long UserId { get; set; } public int ObjectPermissionsCount { get; set; } public int SchemePermissionsCount { get; set; } public bool HasGlobalPermissions { get; set; } public DateTimeOffset CreatedAt { get; set; } public DateTimeOffset ExpiresAt { get; set; } public bool IsExpired { get; set; } public long Version { get; set; } public override string ToString() { return $"User {UserId}: {ObjectPermissionsCount} objects, {SchemePermissionsCount} schemes, " + $"Global: {HasGlobalPermissions}, Expired: {IsExpired}, Version: {Version}"; } } } Path: redb/redb.Core/Models/Permissions/VUserPermission.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Core/Models/Permissions/VUserPermission.cs ---- using System; namespace redb.Core.Models.Permissions { // Model for VIEW v_user_permissions (keyless) public class VUserPermission { public long ObjectId { get; set; } public long UserId { get; set; } public long PermissionId { get; set; } public string PermissionType { get; set; } = string.Empty; // 'user' | 'role' public long? IdRole { get; set; } public bool CanSelect { get; set; } public bool CanInsert { get; set; } public bool CanUpdate { get; set; } public bool CanDelete { get; set; } } } Path: redb/redb.Core/Models/RedbDropReport.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Core/Models/RedbDropReport.cs ---- using System.Collections.Generic; namespace redb.Core.Models; /// /// What found and did: the structures of /// the scheme its Props class does not declare, with the number of stored values of each. /// public sealed record RedbDropReport( string SchemeName, long SchemeId, int ClassVersion, int StoredVersion, bool DryRun, IReadOnlyList Items) { /// One line for a log: the scheme, both versions and what was (or would be) deleted. public override string ToString() => $"Scheme '{SchemeName}' (id {SchemeId}), class version {ClassVersion}, database version {StoredVersion}: " + (Items.Count == 0 ? "no structure the class does not declare." : (DryRun ? "would delete " : "deleted ") + string.Join(", ", Items.Select(i => $"{i.Path} ({i.Values} values)")) + "."); } /// A structure the class does not declare: its path in the scheme, its id and its stored values. public sealed record RedbDropReportItem(string Path, long StructureId, long Values, bool Deleted); Path: redb/redb.Core/Models/RedbIndexCheck.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Core/Models/RedbIndexCheck.cs ---- using System; using System.Collections.Generic; using System.Linq; namespace redb.Core.Models { /// Where an expected index comes from. public enum RedbIndexOrigin { /// The base schema every redb database has. Base = 1, /// A Pro module (the indexes of the streams query form), built once at the module step that brings it. ProModule = 2, } /// What the check found about one expected index. public enum RedbIndexState { /// No index of that name. Missing = 1, /// PostgreSQL: the index exists but is INVALID, left by an interrupted CREATE INDEX CONCURRENTLY. Invalid = 2, /// An index of that name exists with other key columns, included columns or uniqueness. Never changed by the repair. Differs = 3, } /// One index the database is expected to have, as a fresh database of this build has it. public sealed class RedbExpectedIndex { public RedbExpectedIndex(string name, string table, bool isUnique, IReadOnlyList keyColumns, IReadOnlyList includedColumns, string createSql, RedbIndexOrigin origin = RedbIndexOrigin.Base) { Name = name; Table = table; IsUnique = isUnique; KeyColumns = keyColumns; IncludedColumns = includedColumns; CreateSql = createSql; Origin = origin; } /// Index name. public string Name { get; } /// Table of the index. public string Table { get; } /// Whether it is unique. public bool IsUnique { get; } /// Key columns in index order, lower case. public IReadOnlyList KeyColumns { get; } /// Included (covered, not keyed) columns, lower case, in no particular order. public IReadOnlyList IncludedColumns { get; } /// The statement that creates it on this provider, as a fresh database of this build has it. public string CreateSql { get; } /// Base schema or a Pro module. public RedbIndexOrigin Origin { get; } /// The same index with another origin. public RedbExpectedIndex WithOrigin(RedbIndexOrigin origin) => new(Name, Table, IsUnique, KeyColumns, IncludedColumns, CreateSql, origin); /// /// A statement on one line: every run of whitespace outside quoted text ('...', "...", [...]) becomes one space. /// The tables keep their statements this way, so line endings of a checkout cannot change them. /// public static string OneLine(string sql) { var sb = new System.Text.StringBuilder(sql.Length); char quote = '\0'; var space = false; foreach (var ch in sql.Trim()) { if (quote != '\0') { sb.Append(ch); if (ch == quote) quote = '\0'; continue; } if (char.IsWhiteSpace(ch)) { space = true; continue; } if (space) { sb.Append(' '); space = false; } sb.Append(ch); if (ch == '\'' || ch == '"') quote = ch; else if (ch == '[') quote = ']'; } return sb.ToString(); } } /// One index as the database has it, read from its catalog for the check. public sealed class RedbIndexShape { /// Index name. public string Name { get; set; } = string.Empty; /// Table of the index. public string Table { get; set; } = string.Empty; /// Whether it is unique. public bool IsUnique { get; set; } /// Key columns in index order. public IReadOnlyList KeyColumns { get; set; } = Array.Empty(); /// Included columns. public IReadOnlyList IncludedColumns { get; set; } = Array.Empty(); /// False only for a PostgreSQL index left INVALID by an interrupted concurrent build. public bool IsValid { get; set; } = true; } /// An expected index that is missing, INVALID, or defined otherwise. public sealed class RedbIndexFinding { public RedbIndexFinding(RedbExpectedIndex expected, RedbIndexState state, RedbIndexShape? actual, string serves) { Expected = expected; State = state; Actual = actual; Serves = serves; } /// The index as this build expects it. public RedbExpectedIndex Expected { get; } /// Missing, Invalid or Differs. public RedbIndexState State { get; } /// The index of that name the database has; null when it is missing. public RedbIndexShape? Actual { get; } /// What the index serves, in a few words: an operator who dropped it on purpose can judge from this. public string Serves { get; } /// Index name. public string Name => Expected.Name; /// One line for a log or a console. public override string ToString() { var origin = Expected.Origin == RedbIndexOrigin.Base ? "base" : "Pro module"; var text = $"{Name} on {Expected.Table} ({origin}): {State}"; if (State == RedbIndexState.Differs && Actual != null) text += $" - expected ({string.Join(", ", Expected.KeyColumns)})" + (Expected.IncludedColumns.Count > 0 ? $" INCLUDE ({string.Join(", ", Expected.IncludedColumns)})" : "") + (Expected.IsUnique ? " UNIQUE" : "") + $", found ({string.Join(", ", Actual.KeyColumns)})" + (Actual.IncludedColumns.Count > 0 ? $" INCLUDE ({string.Join(", ", Actual.IncludedColumns)})" : "") + (Actual.IsUnique ? " UNIQUE" : ""); if (Serves.Length > 0) text += $"; serves {Serves}"; return text; } } /// /// What found: the expected indexes of the base schema and of the Pro /// modules in use that are missing, INVALID or defined otherwise. Indexes the database has beyond these are not /// reported: an operator may add his own. /// public sealed class RedbIndexReport { public RedbIndexReport(IReadOnlyList findings, int expectedCount) { Findings = findings; ExpectedCount = expectedCount; } /// The findings, base indexes first. public IReadOnlyList Findings { get; } /// How many indexes were expected. public int ExpectedCount { get; } /// True when every expected index is there as expected. public bool IsClean => Findings.Count == 0; /// The findings the repair acts on: Missing and Invalid. public IEnumerable Repairable => Findings.Where(f => f.State != RedbIndexState.Differs); } /// /// A place in _values that holds more than one row where a unique index allows one: the index, the object, the /// structure and how many rows. Found by before it builds. /// public sealed record RedbIndexDuplicate(string Index, long ObjectId, long StructureId, long Rows) { public override string ToString() => $"{Index}: object {ObjectId}, structure {StructureId}, {Rows} rows"; } /// What did. public sealed class RedbIndexRepairResult { /// A result with no duplicate rows found (the constructor of 4.8.0). public RedbIndexRepairResult(IReadOnlyList built, IReadOnlyList notBuilt, IReadOnlyList statements, string? reason) : this(built, notBuilt, statements, reason, null) { } public RedbIndexRepairResult(IReadOnlyList built, IReadOnlyList notBuilt, IReadOnlyList statements, string? reason, IReadOnlyList? duplicates) { Built = built; NotBuilt = notBuilt; Statements = statements; Reason = reason; Duplicates = duplicates ?? Array.Empty(); } /// /// The rows that kept a unique index from being built: for each such index, the places that hold more than one /// row (at most 100 per index). The repair deletes nothing; those indexes are in . /// public IReadOnlyList Duplicates { get; } /// Names of the indexes built (an INVALID one dropped and built again). public IReadOnlyList Built { get; } /// Repairable findings left as they are (see ), and every Differs finding. public IReadOnlyList NotBuilt { get; } /// /// The statements for the indexes not built when the engine cannot build them online (SQL Server editions without /// ONLINE index operations): to run in a maintenance window, or again with offline building allowed. /// public IReadOnlyList Statements { get; } /// Why repairable findings were not built; null when all were. public string? Reason { get; } } /// The comparison of expected indexes with the catalog, shared by every provider. public static class RedbIndexComparer { /// /// Findings for against : by name, case-insensitive; column /// lists compared case-insensitively, key columns in order, included columns as a set. /// public static RedbIndexReport Compare(IReadOnlyList expected, IReadOnlyList actual) { var byName = new Dictionary(StringComparer.OrdinalIgnoreCase); foreach (var index in actual) byName.TryAdd(index.Name, index); var findings = new List(); foreach (var index in expected.OrderBy(e => e.Origin).ThenBy(e => e.Table, StringComparer.Ordinal) .ThenBy(e => e.Name, StringComparer.Ordinal)) { var serves = RedbIndexPurpose.Of(index.Name); if (!byName.TryGetValue(index.Name, out var found)) findings.Add(new RedbIndexFinding(index, RedbIndexState.Missing, null, serves)); else if (!found.IsValid) findings.Add(new RedbIndexFinding(index, RedbIndexState.Invalid, found, serves)); else if (!SameShape(index, found)) findings.Add(new RedbIndexFinding(index, RedbIndexState.Differs, found, serves)); } return new RedbIndexReport(findings, expected.Count); } private static bool SameShape(RedbExpectedIndex expected, RedbIndexShape actual) => expected.IsUnique == actual.IsUnique && string.Equals(expected.Table, actual.Table, StringComparison.OrdinalIgnoreCase) && expected.KeyColumns.Select(Norm).SequenceEqual(actual.KeyColumns.Select(Norm)) && expected.IncludedColumns.Select(Norm).OrderBy(c => c, StringComparer.Ordinal) .SequenceEqual(actual.IncludedColumns.Select(Norm).OrderBy(c => c, StringComparer.Ordinal)); private static string Norm(string column) => column.Trim().Trim('"', '[', ']').ToLowerInvariant(); } } Path: redb/redb.Core/Models/RedbIndexPurpose.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Core/Models/RedbIndexPurpose.cs ---- using System; using System.Collections.Generic; namespace redb.Core.Models { /// /// What an index of the redb schema serves, in a few words, for the index check: an operator who dropped an index on /// purpose judges from this whether his workload needs it. Named entries first, then the families of the typed value /// indexes; an index this list does not know gets an empty text. /// public static class RedbIndexPurpose { private static readonly Dictionary Named = new(StringComparer.OrdinalIgnoreCase) { // _values ["IX__values__objects"] = "loading the values of an object, deleting an object", ["IX__values__structures"] = "reading or removing every value of one field (scheme changes, migrations)", ["IX__values__array_key"] = "dictionary key filters (Dict[key] == x)", ["IX__values__array_parent_index"] = "collection elements under their parent row, and the cascade when a parent row is deleted", ["IX__values__array_parent_id"] = "collection elements under their parent row, and the cascade when a parent row is deleted", ["IX__values__parent_structure"] = "fields of a class stored in a collection or dictionary (Dict[key].Field)", ["IX__values__structure_parent_batch"] = "batch loading of nested fields by parent row", ["IX__values__object_structure_lookup"] = "conditions on nested and collection fields (EXISTS by object and field)", ["IX__values__object_array_null"] = "reading the scalar fields of a page of objects (covering)", ["IX__values__structure_object_scalar"] = "the streams query form of Pro: a field read for many objects (covering)", ["IX__values__structure_object_lookup"] = "a field read for one object", ["IX__values__structure_object_string"] = "Field == null on a text field", ["IX__values__element_string_object"] = "Contains over an array of strings", ["IX__values__ListItem_not_null"] = "references to list items (deleting a list item)", ["IX__values__Object_not_null"] = "references to objects (deleting a referenced object)", ["UIX__values__structure_object"] = "one value per field and object (integrity)", ["UIX__values__structure_object_parent"] = "one value per field, object and parent row (integrity)", ["UIX__values__structure_object_array_index"] = "one element per position or key (integrity)", ["UIX__values__structure_unique"] = "[RedbUnique] fields (integrity and lookup)", // _objects ["IX__objects__objects"] = "tree walks: children of an object (parent id)", ["IX__objects__id_parent"] = "tree walks: children of an object (parent id)", ["IX__objects__parent_scheme_id"] = "tree walks restricted to one scheme", ["IX__objects__schemes"] = "queries of one scheme, counting a scheme", ["IX__objects__scheme_id"] = "the streams query form of Pro: the objects of a scheme by id", ["IX__objects__users1"] = "objects by owner", ["IX__objects__users2"] = "objects by last editor", ["IX__objects__date_create"] = "filters and sorts on the creation date", ["IX__objects__date_modify"] = "filters and sorts on the modification date", ["IX__objects__hash"] = "change detection by hash", ["IX__objects__name"] = "filters and sorts on the object name", ["IX__objects__value_datetime"] = "filters on the object's own date value", ["IX__objects__value_guid"] = "filters on the object's own Guid value", ["IX__objects__value_long"] = "filters on the object's own number value", ["IX__objects__value_numeric"] = "filters on the object's own decimal value", ["IX__objects__value_string"] = "filters on the object's own text value", // metadata and security ["IX__structures__schemes"] = "loading the fields of a scheme", ["IX__structures__structures"] = "nested fields of a field", ["UX__structures__root"] = "one root field per name and scheme (integrity)", ["IX__list_items__id_list"] = "the items of a list", ["IX__list_items__objects"] = "list items that point at an object", ["IX__permissions__ref"] = "permission checks by object", ["IX__permissions__users"] = "permission checks by user", ["IX__users_roles__users"] = "the roles of a user", }; /// What serves; empty when it is not known here. public static string Of(string indexName) { if (Named.TryGetValue(indexName, out var text)) return text; // IX__values__structure__object: the value index of one type. const string prefix = "IX__values__structure_"; const string suffix = "_object"; if (indexName.StartsWith(prefix, StringComparison.OrdinalIgnoreCase) && indexName.EndsWith(suffix, StringComparison.OrdinalIgnoreCase) && indexName.Length > prefix.Length + suffix.Length) { var type = indexName.Substring(prefix.Length, indexName.Length - prefix.Length - suffix.Length); return $"filters, ranges and sorts on {type} fields (value lookups)"; } return string.Empty; } } } Path: redb/redb.Core/Models/RedbObjectFactory.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Core/Models/RedbObjectFactory.cs ---- using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using redb.Core.Models.Contracts; using redb.Core.Models.Security; using redb.Core.Providers; using redb.Core.Caching; using redb.Core.Models.Entities; namespace redb.Core.Models { /// /// Factory for creating typed RedbObject<TProps> objects /// Ensures proper metadata initialization and caching integration /// /// Usage example: /// /// 1. Factory initialization (once at startup) /// RedbObjectFactory.Initialize(schemeSyncProvider, ownerId: 1, whoChangeId: 1); /// /// 2. Fast creation without provider /// var employee = RedbObjectFactory.CreateFast(new Employee { Name = "Ivan" }); /// /// 3. Creation with automatic scheme determination /// var employee = await RedbObjectFactory.CreateAsync(new Employee { Name = "Ivan" }); /// /// 4. Child object creation /// var child = await RedbObjectFactory.CreateChildAsync(parent, new Employee { Name = "Subordinate" }); /// /// 5. Batch creation with cache optimization /// var employees = await RedbObjectFactory.CreateBatchAsync( /// new Employee { Name = "Ivan" }, /// new Employee { Name = "Peter" }, /// new Employee { Name = "Sidor" } /// ); /// /// public static class RedbObjectFactory { private static ISchemeSyncProvider? _provider; // Remove static IDs - we'll use user context /// /// Initialize the factory with a scheme provider /// Required for automatic scheme determination /// Also sets the provider in RedbObjectBase for global access /// public static void Initialize(ISchemeSyncProvider provider) { _provider = provider ?? throw new ArgumentNullException(nameof(provider)); // Set provider in base class for global access RedbObject.SetSchemeSyncProvider(provider); } /// /// Check if the factory is initialized /// public static bool IsInitialized => _provider != null; /// /// Set the scheme provider /// public static void SetProvider(ISchemeSyncProvider provider) { _provider = provider ?? throw new ArgumentNullException(nameof(provider)); RedbObject.SetSchemeSyncProvider(provider); } // ===== OBJECT CREATION METHODS ===== /// /// Create a new object without property initialization /// Automatically determines scheme by TProps type /// public static async Task> CreateAsync() where TProps : class, new() { return await CreateAsync(new TProps()); } /// /// Create a new object with initialized properties /// Automatically determines scheme by TProps type /// public static async Task> CreateAsync(TProps properties) where TProps : class, new() { return await CreateAsync(properties, initializeMetadata: true); } /// /// Create a new object with initialized properties /// /// Properties of the object being created /// Automatically initialize metadata (scheme, owner, dates). Set to false for batch insertion via AddNewObjectsAsync public static async Task> CreateAsync(TProps properties, bool initializeMetadata) where TProps : class, new() { if (properties == null) throw new ArgumentNullException(nameof(properties)); var obj = new RedbObject(properties); if (initializeMetadata) { // Automatic metadata initialization await InitializeMetadataAsync(obj); } return obj; } /// /// Create a new object as a child of an existing parent /// public static async Task> CreateChildAsync( IRedbObject parent, TProps properties) where TProps : class, new() { return await CreateChildAsync(parent, properties, initializeMetadata: true); } /// /// Create a new object as a child of an existing parent /// /// Parent object /// Properties of the object being created /// Automatically initialize metadata (scheme, owner, dates). Set to false for batch insertion via AddNewObjectsAsync public static async Task> CreateChildAsync( IRedbObject parent, TProps properties, bool initializeMetadata) where TProps : class, new() { if (parent == null) throw new ArgumentNullException(nameof(parent)); if (properties == null) throw new ArgumentNullException(nameof(properties)); var obj = new RedbObject(properties) { parent_id = parent.Id }; if (initializeMetadata) { await InitializeMetadataAsync(obj); } return obj; } /// /// Create copy of existing object with new properties /// Preserves all metadata except ID (for creating new object) /// public static async Task> CreateCopyAsync( IRedbObject source, TProps newProperties) where TProps : class, new() { if (source == null) throw new ArgumentNullException(nameof(source)); if (newProperties == null) throw new ArgumentNullException(nameof(newProperties)); var obj = source.CloneWithProperties(newProperties); // ID will be set on save // Update only timestamps var redbObj = (RedbObject)obj; redbObj.date_create = DateTimeOffset.UtcNow; redbObj.date_modify = DateTimeOffset.UtcNow; return redbObj; } // ===== FAST METHODS WITHOUT PROVIDER ===== /// /// Create object without automatic scheme initialization (fast) /// Scheme will need to be set manually or through provider /// public static RedbObject CreateFast() where TProps : class, new() { return CreateFast(new TProps()); } /// /// Create object with properties without automatic scheme initialization (fast) /// public static RedbObject CreateFast(TProps properties) where TProps : class, new() { var obj = new RedbObject(properties); // Basic initialization without accessing provider var now = DateTimeOffset.UtcNow; var securityContext = AmbientSecurityContext.GetOrCreateDefault(); var effectiveUser = securityContext.GetEffectiveUser(); obj.date_create = now; obj.date_modify = now; obj.owner_id = effectiveUser.Id; obj.who_change_id = effectiveUser.Id; return obj; } /// /// Create object with full manual initialization of all fields /// public static RedbObject CreateWithMetadata( TProps properties, long schemeId, string? name = null, long? parentId = null, long? ownerId = null, long? whoChangeId = null) where TProps : class, new() { var obj = new RedbObject(properties); var now = DateTimeOffset.UtcNow; var securityContext = AmbientSecurityContext.GetOrCreateDefault(); var effectiveUser = securityContext.GetEffectiveUser(); obj.scheme_id = schemeId; obj.name = name ?? $"Object_{typeof(TProps).Name}"; obj.parent_id = parentId; obj.owner_id = ownerId ?? effectiveUser.Id; obj.who_change_id = whoChangeId ?? effectiveUser.Id; obj.date_create = now; obj.date_modify = now; return obj; } // ===== PRIVATE METHODS ===== /// /// Initialize object metadata automatically /// private static async Task InitializeMetadataAsync(RedbObject obj) where TProps : class, new() { var now = DateTimeOffset.UtcNow; var securityContext = AmbientSecurityContext.GetOrCreateDefault(); var effectiveUser = securityContext.GetEffectiveUser(); // Timestamps obj.date_create = now; obj.date_modify = now; // Use current user from security context obj.owner_id = effectiveUser.Id; obj.who_change_id = effectiveUser.Id; // Default object name if (string.IsNullOrEmpty(obj.name)) { obj.name = $"New{typeof(TProps).Name}"; } // Automatic scheme determination (if provider is available) if (_provider != null) { try { var scheme = await _provider.GetSchemeByTypeAsync(); if (scheme != null) { obj.scheme_id = scheme.Id; } else { // Try to create scheme automatically var newScheme = await _provider.EnsureSchemeFromTypeAsync(); obj.scheme_id = newScheme.Id; } } catch { // If scheme determination failed, leave as 0 // Scheme will be determined on save obj.scheme_id = 0; } } else { // Without provider, scheme will be determined later obj.scheme_id = 0; } } // ===== INFORMATION METHODS ===== /// /// Get current factory settings /// public static (bool IsInitialized, long CurrentUserId, string CurrentUserName) GetSettings() { var securityContext = AmbientSecurityContext.GetOrCreateDefault(); var effectiveUser = securityContext.GetEffectiveUser(); return (IsInitialized, effectiveUser.Id, effectiveUser.Name ?? "Unknown user"); } // ===== CACHING INTEGRATION ===== /// /// Create object with metadata preload to cache /// Useful for batch creation of objects of the same type /// public static async Task> CreateWithWarmupAsync(TProps properties) where TProps : class, new() { // Preload metadata to cache if (_provider is ISchemeCacheProvider cacheProvider) { await cacheProvider.WarmupCacheAsync(); } return await CreateAsync(properties); } /// /// Batch creation of objects with cache preloading /// Optimized for creating multiple objects of the same type /// public static async Task>> CreateBatchAsync(IEnumerable properties) where TProps : class, new() { return await CreateBatchAsync(properties, initializeMetadata: true); } /// /// Batch creation of objects with cache preloading /// Optimized for creating multiple objects of the same type /// /// Collection of properties for objects being created /// Automatically initialize metadata (scheme, owner, dates). Set to false for batch insertion via AddNewObjectsAsync public static async Task>> CreateBatchAsync(IEnumerable properties, bool initializeMetadata) where TProps : class, new() { var propsList = properties?.ToList() ?? new List(); if (propsList.Count == 0) return new List>(); // Preload cache once for all objects if (initializeMetadata && _provider is ISchemeCacheProvider cacheProvider) { await cacheProvider.WarmupCacheAsync(); } var results = new List>(propsList.Count); foreach (var prop in propsList) { results.Add(await CreateAsync(prop, initializeMetadata)); } return results; } /// /// Batch creation of child objects with cache preloading /// All created objects will be children of the specified parent /// Optimized for creating multiple child objects of the same type /// public static async Task>> CreateBatchChildAsync( IRedbObject parent, IEnumerable properties) where TProps : class, new() { return await CreateBatchChildAsync(parent, properties, initializeMetadata: true); } /// /// Batch creation of child objects with cache preloading /// All created objects will be children of the specified parent /// Optimized for creating multiple child objects of the same type /// /// Parent object /// Collection of properties for objects being created /// Automatically initialize metadata (scheme, owner, dates). Set to false for batch insertion via AddNewObjectsAsync public static async Task>> CreateBatchChildAsync( IRedbObject parent, IEnumerable properties, bool initializeMetadata) where TProps : class, new() { if (parent == null) throw new ArgumentNullException(nameof(parent)); var propsList = properties?.ToList() ?? new List(); if (propsList.Count == 0) return new List>(); // Preload cache once for all objects if (initializeMetadata && _provider is ISchemeCacheProvider cacheProvider) { await cacheProvider.WarmupCacheAsync(); } var results = new List>(propsList.Count); foreach (var prop in propsList) { results.Add(await CreateChildAsync(parent, prop, initializeMetadata)); } return results; } // ===== NON-GENERIC OBJECT CREATION ===== /// /// Create non-generic RedbObject with basic metadata. /// Scheme will be auto-determined on save (Object scheme). /// public static RedbObject CreateObject(string? name = null) { var obj = new RedbObject(); var now = DateTimeOffset.UtcNow; var securityContext = AmbientSecurityContext.GetOrCreateDefault(); var effectiveUser = securityContext.GetEffectiveUser(); obj.name = name ?? "NewObject"; obj.date_create = now; obj.date_modify = now; obj.owner_id = effectiveUser.Id; obj.who_change_id = effectiveUser.Id; return obj; } } } Path: redb/redb.Core/Models/RedbSchemaProblem.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Core/Models/RedbSchemaProblem.cs ---- using System.Collections.Generic; namespace redb.Core.Models { /// Kinds of . public enum RedbSchemaProblemKind { /// /// A root field of a scheme exists more than once in _structures, and the copies could not be merged /// automatically because more than one holds values. Left by nodes that synchronized one scheme at the same /// moment before the schema lock (PostgreSQL, SQLite). Resolved by hand: UPGRADING.md, "Duplicate root /// structures". /// DuplicateRootStructure = 1, } /// /// A problem of the database schema that does not stop the service but needs a person: it is logged as an error at /// every start until it is resolved, and listed by for health checks. /// public sealed class RedbSchemaProblem { /// Creates a problem. public RedbSchemaProblem(RedbSchemaProblemKind kind, long schemeId, string schemeName, string field, IReadOnlyList structureIds, string message) { Kind = kind; SchemeId = schemeId; SchemeName = schemeName; Field = field; StructureIds = structureIds; Message = message; } /// What is wrong. public RedbSchemaProblemKind Kind { get; } /// Id of the scheme in _schemes. public long SchemeId { get; } /// Name of the scheme. public string SchemeName { get; } /// Name of the field concerned. public string Field { get; } /// Ids of the structures concerned, every copy of the field. public IReadOnlyList StructureIds { get; } /// The text that is logged: what is wrong and where the fix is described. public string Message { get; } /// public override string ToString() => Message; } } Path: redb/redb.Core/Models/Roles/CreateRoleRequest.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Core/Models/Roles/CreateRoleRequest.cs ---- using redb.Core.Models.Contracts; namespace redb.Core.Models.Roles { /// /// Request for creating new role /// public class CreateRoleRequest { /// /// Role name (unique) /// public string Name { get; set; } = ""; /// /// Role description (optional) /// public string? Description { get; set; } /// /// Users to assign to role upon creation (objects) /// For backward compatibility and programmatic usage /// public IRedbUser[]? Users { get; set; } /// /// User logins to assign to role upon creation /// Example: ["admin", "manager", "user123"] /// If both Users and UserLogins are specified - UserLogins are used (priority) /// public string[]? UserLogins { get; set; } } } Path: redb/redb.Core/Models/SchemeWithJson.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Core/Models/SchemeWithJson.cs ---- using System; namespace redb.Core.Models { /// /// Model for optimized SQL query result /// Contains scheme_id and object JSON data in one query /// public class SchemeWithJson { /// /// Object scheme ID /// public long SchemeId { get; set; } /// /// Object JSON data (result of get_object_json) /// public string JsonData { get; set; } = string.Empty; } /// /// Model for SQL query result when loading object children /// Contains object_id, scheme_id and JSON data in one query /// public class ChildObjectInfo { /// /// Object ID /// public long ObjectId { get; set; } /// /// Object scheme ID /// public long SchemeId { get; set; } /// /// Object JSON data (result of get_object_json) /// public string JsonData { get; set; } = string.Empty; } } Path: redb/redb.Core/Models/Security/AmbientSecurityContext.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Core/Models/Security/AmbientSecurityContext.cs ---- using redb.Core.Models.Contracts; using System; using System.Threading; namespace redb.Core.Models.Security { /// /// Ambient security context (Thread-Local) /// Allows automatic access to current security context anywhere in code /// public static class AmbientSecurityContext { private static readonly AsyncLocal _current = new(); /// /// Current security context for this thread /// public static IRedbSecurityContext? Current { get => _current.Value; set => _current.Value = value; } /// /// Get current context or create default system context /// public static IRedbSecurityContext GetOrCreateDefault() { return Current ?? RedbSecurityContext.WithAdmin(); } /// /// Set context for the duration of an action /// public static IDisposable SetContext(IRedbSecurityContext context) { return new AmbientContextScope(context); } /// /// Create temporary system context /// public static IDisposable CreateSystemContext() { return SetContext(RedbSecurityContext.System()); } /// /// Create temporary context with user /// public static IDisposable CreateUserContext(IRedbUser user) { return SetContext(RedbSecurityContext.WithUser(user)); } /// /// Create temporary admin context /// public static IDisposable CreateAdminContext() { return SetContext(RedbSecurityContext.WithAdmin()); } } /// /// Scope for temporary ambient context change /// internal class AmbientContextScope : IDisposable { private readonly IRedbSecurityContext? _previousContext; public AmbientContextScope(IRedbSecurityContext newContext) { _previousContext = AmbientSecurityContext.Current; AmbientSecurityContext.Current = newContext; } public void Dispose() { AmbientSecurityContext.Current = _previousContext; } } } Path: redb/redb.Core/Models/Security/RedbSecurityContext.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Core/Models/Security/RedbSecurityContext.cs ---- using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using System; namespace redb.Core.Models.Security { /// /// REDB security context implementation /// Manages current user and system context /// public class RedbSecurityContext : IRedbSecurityContext { internal IRedbUser? _currentUser; internal bool _isSystemContext; public IRedbUser? CurrentUser => _currentUser; public bool IsSystemContext => _isSystemContext; public bool IsAuthenticated => _currentUser != null && !_isSystemContext; public long GetEffectiveUserId() { var user = GetEffectiveUser(); return user.Id; } /// /// Get effective user /// public IRedbUser GetEffectiveUser() { // If there is current user and not system context if (_currentUser != null && !_isSystemContext) { return _currentUser; } // Otherwise return system user return RedbUser.SystemUser; } public void SetCurrentUser(IRedbUser? user) { _currentUser = user; _isSystemContext = false; // Reset system mode when setting user } public IDisposable CreateSystemContext() { return new SystemContextScope(this); } /// /// Create context with specified user /// public static RedbSecurityContext WithUser(IRedbUser user) { var context = new RedbSecurityContext(); context.SetCurrentUser(user); return context; } /// /// Create system context /// public static RedbSecurityContext System() { return new RedbSecurityContext { _isSystemContext = true }; } /// /// Create context with admin user /// public static RedbSecurityContext WithAdmin() { var context = new RedbSecurityContext(); context.SetCurrentUser(RedbUser.SystemUser); return context; } } /// /// Temporary system context (IDisposable) /// internal class SystemContextScope : IDisposable { private readonly RedbSecurityContext _context; private readonly IRedbUser? _previousUser; private readonly bool _previousSystemMode; public SystemContextScope(RedbSecurityContext context) { _context = context; _previousUser = context.CurrentUser; _previousSystemMode = context.IsSystemContext; // Set system mode _context._isSystemContext = true; } public void Dispose() { // Restore previous state _context._currentUser = _previousUser; _context._isSystemContext = _previousSystemMode; } } } Path: redb/redb.Core/Models/UniqueRecomputeReport.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Core/Models/UniqueRecomputeReport.cs ---- using System.Collections.Generic; using System.Linq; namespace redb.Core.Models { /// /// What a recomputation of _values._unique for one key structure found. Produced when a /// [RedbUnique] attribute appears on a populated structure, when the structure's encoder /// version is behind UniqueKeyEncoder.Version, when rows are found with a value but no key /// (a SQL-side writer touched them), and on an explicit RecomputeUniqueAsync. /// /// /// Duplicates are reported, not thrown: the first row of each duplicate group (lowest value id) /// keeps the key, the others stay with _unique IS NULL — outside the index, visible here, /// and to a query WHERE _id_structure = … AND _unique IS NULL AND <column> IS NOT NULL. /// Uniqueness is enforced for every row that has a key from this point on; the losers are the /// application's to resolve. /// /// public sealed class UniqueRecomputeReport { public long SchemeId { get; init; } public string SchemeName { get; init; } = string.Empty; public long StructureId { get; init; } public string PropertyName { get; init; } = string.Empty; /// Root scalar rows of the structure that were examined. public int TotalRows { get; init; } /// Rows that received a key (rows with a NULL value get none and are not counted). public int HashedRows { get; init; } /// Groups of rows sharing one key; each group's first id kept the key. public IReadOnlyList Duplicates { get; init; } = []; public bool HasDuplicates => Duplicates.Count > 0; /// Rows left without a key because another row already holds it. public int LosingRows => Duplicates.Sum(g => g.ValueIds.Count - 1); } /// One set of rows whose values canonicalise to the same key. public sealed class UniqueDuplicateGroup { /// The colliding key. public System.Guid Key { get; init; } /// _values._id of every row in the group, lowest first; the first kept the key. public IReadOnlyList ValueIds { get; init; } = []; /// _objects._id for the same rows, in the same order. public IReadOnlyList ObjectIds { get; init; } = []; } } Path: redb/redb.Core/Models/Users/CreateUserRequest.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Core/Models/Users/CreateUserRequest.cs ---- using System; using redb.Core.Models.Contracts; namespace redb.Core.Models.Users { /// /// Request for creating new user /// public class CreateUserRequest { /// /// User login (unique) /// public string Login { get; set; } = ""; /// /// User password (in plain text, will be hashed) /// public string Password { get; set; } = ""; /// /// User name /// public string Name { get; set; } = ""; /// /// User phone (optional) /// public string? Phone { get; set; } /// /// User email (optional) /// public string? Email { get; set; } /// /// Is user active upon creation /// public bool Enabled { get; set; } = true; /// /// Roles to assign to user upon creation (objects) /// For backward compatibility and programmatic usage /// public IRedbRole[]? Roles { get; set; } /// /// Role names to assign to user upon creation /// Example: ["Admin", "Manager", "User"] /// If both Roles and RoleNames are specified - RoleNames are used (priority) /// public string[]? RoleNames { get; set; } /// /// Registration date (if not specified, current date is used) /// public DateTimeOffset? DateRegister { get; set; } // === NEW EXTENDED FIELDS === /// /// Additional user key (optional) /// Can be used for external integrations or additional identification /// public long? Key { get; set; } /// /// Integer user code (optional) /// Can be used for categorization, access groups or external systems /// public long? CodeInt { get; set; } /// /// String user code (optional) /// Can be used for department codes, branches or special labels /// public string? CodeString { get; set; } /// /// GUID user code (optional) /// Can be used for unique identification in distributed systems /// public Guid? CodeGuid { get; set; } /// /// Note or comment for user (optional) /// Can contain additional information, instructions or notes /// public string? Note { get; set; } // Hash is NOT added to CreateUserRequest - it is generated automatically! } } Path: redb/redb.Core/Models/Users/UpdateUserRequest.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Core/Models/Users/UpdateUserRequest.cs ---- using System; using redb.Core.Models.Contracts; namespace redb.Core.Models.Users { /// /// Request for updating user data /// public class UpdateUserRequest { /// /// New user login (if null - not changed) /// System users (ID 0, 1) cannot change login /// public string? Login { get; set; } /// /// New user name (if null - not changed) /// System users (ID 0, 1) cannot change name /// public string? Name { get; set; } /// /// New user phone (if null - not changed) /// public string? Phone { get; set; } /// /// New user email (if null - not changed) /// public string? Email { get; set; } /// /// New activity status (if null - not changed) /// public bool? Enabled { get; set; } /// /// Dismissal date (if null - not changed) /// public DateTimeOffset? DateDismiss { get; set; } /// /// New user roles as objects (if null - not changed) /// For backward compatibility and programmatic usage /// If empty array is specified - all roles are removed /// public IRedbRole[]? Roles { get; set; } /// /// Names of new user roles (if null - not changed) /// Example: ["Admin", "Manager"] /// If both Roles and RoleNames are specified - RoleNames are used (priority) /// If empty array is specified - all roles are removed /// public string[]? RoleNames { get; set; } // === NEW EXTENDED FIELDS === /// /// New additional key (if null - not changed) /// public long? Key { get; set; } /// /// New integer code (if null - not changed) /// public long? CodeInt { get; set; } /// /// New string code (if null - not changed) /// If empty string - code is cleared /// public string? CodeString { get; set; } /// /// New GUID code (if null - not changed) /// public Guid? CodeGuid { get; set; } /// /// New note (if null - not changed) /// If empty string - note is cleared /// public string? Note { get; set; } // Hash is NOT added to UpdateUserRequest - it is recalculated automatically! } } Path: redb/redb.Core/Models/Users/UserSearchCriteria.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Core/Models/Users/UserSearchCriteria.cs ---- using System; namespace redb.Core.Models.Users { /// /// User search criteria /// public class UserSearchCriteria { /// /// Search by login (partial match) /// public string? LoginPattern { get; set; } /// /// Search by name (partial match) /// public string? NamePattern { get; set; } /// /// Search by email (partial match) /// public string? EmailPattern { get; set; } /// /// Exact match by login (case-insensitive) /// public string? LoginExact { get; set; } /// /// Exact match by name (case-insensitive) /// public string? NameExact { get; set; } /// /// Exact match by email (case-insensitive) /// public string? EmailExact { get; set; } /// /// Login starts with (case-insensitive) /// public string? LoginStartsWith { get; set; } /// /// Name starts with (case-insensitive) /// public string? NameStartsWith { get; set; } /// /// Email starts with (case-insensitive) /// public string? EmailStartsWith { get; set; } /// /// Not equal by login (case-insensitive) /// public string? LoginNotEqual { get; set; } /// /// Not equal by name (case-insensitive) /// public string? NameNotEqual { get; set; } /// /// Not equal by email (case-insensitive) /// public string? EmailNotEqual { get; set; } /// /// Filter by activity status /// null - all users, true - only active, false - only inactive /// public bool? Enabled { get; set; } /// /// Filter by role (role ID) /// public long? RoleId { get; set; } /// /// Filter by registration date (from) /// public DateTimeOffset? RegisteredFrom { get; set; } /// /// Filter by registration date (to) /// public DateTimeOffset? RegisteredTo { get; set; } /// /// Exclude system users (ID 0, 1) /// public bool ExcludeSystemUsers { get; set; } = true; // === NEW FIELDS FOR FILTERING === /// /// Filter by user key (exact match) /// public long? KeyValue { get; set; } /// /// Filter by integer code (exact match) /// public long? CodeIntValue { get; set; } /// /// Search by string code (partial match) /// public string? CodeStringPattern { get; set; } /// /// Search by note (partial match) /// public string? NotePattern { get; set; } /// /// Filter by GUID code (exact match, rarely used) /// public Guid? CodeGuidValue { get; set; } /// /// Maximum number of results (0 = no limit) /// public int Limit { get; set; } = 100; /// /// Offset for pagination /// public int Offset { get; set; } = 0; /// /// Field for sorting /// public UserSortField SortBy { get; set; } = UserSortField.Name; /// /// Sort direction /// public UserSortDirection SortDirection { get; set; } = UserSortDirection.Ascending; } /// /// Fields for sorting users /// public enum UserSortField { Id, Login, Name, Email, DateRegister, DateDismiss, Enabled, // === NEW FIELDS FOR SORTING === Key, CodeInt, CodeString, Note // Hash not added - technical field // CodeGuid rarely used for sorting } /// /// User sort direction /// public enum UserSortDirection { Ascending, Descending } } Path: redb/redb.Core/Models/Users/UserValidationResult.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Core/Models/Users/UserValidationResult.cs ---- using System.Collections.Generic; namespace redb.Core.Models.Users { /// /// User data validation result /// public class UserValidationResult { /// /// Validation passed successfully /// public bool IsValid { get; set; } /// /// List of validation errors /// public List Errors { get; set; } = new(); /// /// Add validation error /// public void AddError(string field, string message) { Errors.Add(new ValidationError { Field = field, Message = message }); IsValid = false; } /// /// Add validation error /// public void AddError(ValidationError error) { Errors.Add(error); IsValid = false; } /// /// Create successful validation result /// public static UserValidationResult Success() { return new UserValidationResult { IsValid = true }; } /// /// Create validation result with error /// public static UserValidationResult WithError(string field, string message) { var result = new UserValidationResult(); result.AddError(field, message); return result; } } /// /// Validation error /// public class ValidationError { /// /// Field with error /// public string Field { get; set; } = ""; /// /// Error message /// public string Message { get; set; } = ""; /// /// Error code (optional) /// public string? ErrorCode { get; set; } } } Path: redb/redb.Core/Providers/AmbientLazyPropsLoader.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/AmbientLazyPropsLoader.cs ---- using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using redb.Core.Exceptions; using redb.Core.Models.Entities; namespace redb.Core.Providers; /// /// The loader every reference stub carries. It owns no scope and no connection. A load runs on, in this order: /// /// the live redb scope current for the reader (the flow that resolved it, or BeginAccess); /// the scope that materialized the stub (its origin, held weakly), while that scope lives - never for a shared /// instance of a cache, whose stubs carry the origin-less loader of their database; /// otherwise it refuses with , or opens a fresh scope when the /// configuration asks for it. /// /// It replaces the scope-bound loaders on stubs, the detached loader of the props cache and its dead-scope fallback: those /// rode the connection of the materializing scope whoever read, or rented a fresh scope per load. /// internal sealed class AmbientLazyPropsLoader : ILazyPropsLoader { private static readonly ConcurrentDictionary ByDomain = new(); private static readonly ConditionalWeakTable ByOrigin = new(); private readonly string _domain; private AmbientLazyPropsLoader(string domain, RedbServiceBase? origin) { _domain = domain; Origin = origin?.SelfReference; } /// The loader of for a shared instance: the reader's scope only. public static AmbientLazyPropsLoader For(string domain) => ByDomain.GetOrAdd(domain, d => new AmbientLazyPropsLoader(d, null)); /// /// The loader of an instance materialized by : the reader's scope, else the origin while it /// lives. Without an origin, the shared loader of the database. /// public static AmbientLazyPropsLoader For(string domain, RedbServiceBase? origin) => origin == null ? For(domain) : ByOrigin.GetValue(origin, o => new AmbientLazyPropsLoader(domain, o)); /// The origin-less loader of the same database, for an instance that became shared. public AmbientLazyPropsLoader Shared => Origin == null ? this : For(_domain); /// The service that materialized the instances carrying this loader; null for a shared loader. public WeakReference? Origin { get; } /// public string? CacheDomain => _domain; private RedbServiceBase? Reader() => RedbAmbientScope.Resolve(_domain) ?? RedbAmbientScope.LiveOrigin(Origin); /// /// Whether a shared instance keeps what a load on the reader makes now: outside a transaction, or inside one that has /// written nothing yet - what it reads is committed state. Once the reader's transaction has written, what it reads /// may be its own uncommitted work, and a shared instance keeps nothing of it (owner decisions 2026-09-15, 2026-09-17). /// public bool ReaderKeepsLoads => Reader() is not { } reader || reader.LendsScope || Data.TransactionWrites.ReadsCommitted(reader.Context); /// Runs when the reader's transaction ends; false when the reader is in none. public bool OnReaderTransactionCompleted(Action onCompleted) => Reader() is { LendsScope: false } reader && Data.TransactionHooks.OnCompleted(reader.Context, onCompleted); public TProps? LoadProps(long objectId, long schemeId) where TProps : class, new() { var reader = Reader(); // A captive reader (a service of the root provider, outside a transaction) lends its scope factory, never its one connection. if (reader is { LendsScope: true } captive) return RedbDomainRegistry.InScopeOf(captive, service => service.LazyPropsLoader.LoadProps(objectId, schemeId)); return reader != null ? reader.LazyPropsLoader.LoadProps(objectId, schemeId) : RedbDomainRegistry.InFreshScope(_domain, service => service.LazyPropsLoader.LoadProps(objectId, schemeId), () => new RedbLazyLoadScopeEndedException(objectId, schemeId)); } public async Task LoadPropsAsync(long objectId, long schemeId, CancellationToken cancellationToken = default) where TProps : class, new() { var reader = Reader(); if (reader is { LendsScope: true } captive) return await RedbDomainRegistry.InScopeOfAsync(captive, service => service.LazyPropsLoader.LoadPropsAsync(objectId, schemeId, cancellationToken)).ConfigureAwait(false); return reader != null ? await reader.LazyPropsLoader.LoadPropsAsync(objectId, schemeId, cancellationToken).ConfigureAwait(false) : await RedbDomainRegistry.InFreshScopeAsync(_domain, service => service.LazyPropsLoader.LoadPropsAsync(objectId, schemeId, cancellationToken), () => new RedbLazyLoadScopeEndedException(objectId, schemeId)).ConfigureAwait(false); } public Task LoadPropsForManyAsync(List> objects, CancellationToken cancellationToken = default) where TProps : class, new() => ForManyAsync(objects, (loader, list) => loader.LoadPropsForManyAsync(list, cancellationToken)); public Task LoadPropsForManyAsync(List> objects, HashSet? projectedStructureIds, CancellationToken cancellationToken = default) where TProps : class, new() => ForManyAsync(objects, (loader, list) => loader.LoadPropsForManyAsync(list, projectedStructureIds, cancellationToken)); public Task LoadPropsForManyAsync(List> objects, int? propsDepth, CancellationToken cancellationToken = default) where TProps : class, new() => ForManyAsync(objects, (loader, list) => loader.LoadPropsForManyAsync(list, propsDepth, cancellationToken)); public Task LoadPropsForManyAsync(List> objects, HashSet? projectedStructureIds, int? propsDepth, CancellationToken cancellationToken = default) where TProps : class, new() => ForManyAsync(objects, (loader, list) => loader.LoadPropsForManyAsync(list, projectedStructureIds, propsDepth, cancellationToken)); private async Task ForManyAsync(List> objects, Func>, Task> load) where TProps : class, new() { if (objects.Count == 0) return; var reader = Reader(); if (reader is { LendsScope: true } captive) { await RedbDomainRegistry.InScopeOfAsync(captive, async service => { await load(service.LazyPropsLoader, objects).ConfigureAwait(false); return true; }).ConfigureAwait(false); return; } if (reader != null) { await load(reader.LazyPropsLoader, objects).ConfigureAwait(false); return; } await RedbDomainRegistry.InFreshScopeAsync(_domain, async service => { await load(service.LazyPropsLoader, objects).ConfigureAwait(false); return true; }, () => new RedbLazyLoadScopeEndedException(objects[0].id, objects[0].scheme_id)).ConfigureAwait(false); } } Path: redb/redb.Core/Providers/Base/ListProviderBase.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/ListProviderBase.cs ---- using redb.Core.Attributes; using redb.Core.Caching; using redb.Core.Data; using redb.Core.Models.Configuration; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using redb.Core.Query; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; namespace redb.Core.Providers.Base { /// /// Base class for IListProvider implementations. /// Contains all business logic for list and list item operations with caching. /// SQL queries are abstracted via ISqlDialect. /// public abstract class ListProviderBase : IListProvider { protected readonly IRedbContext Context; protected readonly RedbServiceConfiguration Configuration; protected readonly ISqlDialect Sql; protected readonly ILogger? Logger; protected readonly GlobalListCache ListCache; /// public Func, CancellationToken, Task>>? LinkedObjectsBatchLoader { get; set; } /// /// Hand-out preload (PreloadListItemLinkedObjects, default on): resolve the linked /// objects of the items in ONE batch and publish them, so a later touch of /// is a field read - no database call, no blocked /// thread (a hot loop over fresh lazy items froze a production process, 2026-09-09). /// Items already carrying their object are skipped; a missing id stays lazy. /// private async Task PreloadLinkedObjectsAsync(IReadOnlyList items, CancellationToken cancellationToken) { var batchLoader = LinkedObjectsBatchLoader; if (batchLoader == null || !Configuration.PreloadListItemLinkedObjects) return; var ids = new List(); foreach (var item in items) if (item is { IsObjectLoaded: false, IdObject: long id }) ids.Add(id); if (ids.Count == 0) return; var byId = await batchLoader(ids, cancellationToken); foreach (var item in items) if (!item.IsObjectLoaded && item.IdObject is long id && byId.TryGetValue(id, out var obj)) item.Publish(obj, Context); } /// /// Binds the items to this provider's database, and a not-shared item to this scope as its origin, before they leave /// it. The item keeps no loader: loads on the scope current for the reader, else on /// the origin while it lives (owner decision 2026-09-15). An item of the list cache is shared and has no origin. /// protected List Attach(List items) { foreach (var item in items) Bind(item); return items; } /// protected RedbListItem? Attach(RedbListItem? item) { if (item != null) Bind(item); return item; } private void Bind(RedbListItem item) { item._cacheDomain ??= ListCache.Domain; if (!item._isShared) item._origin ??= RedbServiceBase.ServiceOf(Context)?.AsOrigin.SelfReference; } protected ListProviderBase( IRedbContext context, RedbServiceConfiguration configuration, ISqlDialect sql, ISchemeSyncProvider schemeSync, ILogger? logger = null) { Context = context ?? throw new ArgumentNullException(nameof(context)); Configuration = configuration ?? throw new ArgumentNullException(nameof(configuration)); Sql = sql ?? throw new ArgumentNullException(nameof(sql)); ListCache = schemeSync?.ListCache ?? throw new ArgumentNullException(nameof(schemeSync)); Logger = logger; } // === CRUD for lists === public async Task GetListAsync(long listId, CancellationToken cancellationToken = default) { var cached = ListCache.GetList(listId); if (cached != null) return cached; var list = await Context.QueryFirstOrDefaultAsync(Sql.Lists_SelectById(), new object[] { listId }, cancellationToken); if (list == null) return null; ListCache.CacheList(list); return list; } public async Task GetListByNameAsync(string name, CancellationToken cancellationToken = default) { var cached = ListCache.GetListByName(name); if (cached != null) return cached; var list = await Context.QueryFirstOrDefaultAsync(Sql.Lists_SelectByName(), new object[] { name }, cancellationToken); if (list == null) return null; ListCache.CacheList(list); return list; } public async Task> GetAllListsAsync(CancellationToken cancellationToken = default) { var lists = await Context.QueryAsync(Sql.Lists_SelectAll(), System.Array.Empty(), cancellationToken); foreach (var list in lists) { ListCache.CacheList(list); } return lists; } /// /// Get list with all its items loaded. /// public async Task GetListWithItemsAsync(long listId, CancellationToken cancellationToken = default) { var list = await GetListAsync(listId); if (list == null) return null; var items = await GetListItemsAsync(listId); list.SetItems(items); return list; } /// /// Get list by name with all its items loaded. /// public async Task GetListByNameWithItemsAsync(string name, CancellationToken cancellationToken = default) { var list = await GetListByNameAsync(name); if (list == null) return null; var items = await GetListItemsAsync(list.Id); list.SetItems(items); return list; } public async Task SaveListAsync(IRedbList list, CancellationToken cancellationToken = default) { RedbList entity; if (list.Id == 0) { var newId = await Context.NextObjectIdAsync(); entity = new RedbList { Id = newId, Name = list.Name, Alias = list.Alias }; await Context.ExecuteAsync(Sql.Lists_Insert(), new object[] { entity.Id, entity.Name, entity.Alias }, cancellationToken); } else { var existing = await Context.QueryFirstOrDefaultAsync(Sql.Lists_SelectById(), new object[] { list.Id }, cancellationToken); if (existing == null) throw new InvalidOperationException($"List with ID {list.Id} not found"); entity = new RedbList { Id = list.Id, Name = list.Name, Alias = list.Alias }; await Context.ExecuteAsync(Sql.Lists_Update(), new object[] { entity.Name, entity.Alias, entity.Id }, cancellationToken); } ListCache.InvalidateList(entity.Id); return entity; } public async Task DeleteListAsync(long listId, CancellationToken cancellationToken = default) { if (await IsListUsedInStructuresAsync(listId)) { return false; } var result = await Context.ExecuteAsync(Sql.Lists_Delete(), new object[] { listId }, cancellationToken); if (result == 0) return false; ListCache.InvalidateList(listId); return true; } // === CRUD for list items === public async Task GetListItemAsync(long itemId, CancellationToken cancellationToken = default) { var item = ListCache.GetListItem(itemId) ?? await Context.QueryFirstOrDefaultAsync(Sql.ListItems_SelectById(), new object[] { itemId }, cancellationToken); if (item == null) return null; Attach(item); await PreloadLinkedObjectsAsync(new[] { item }, cancellationToken); return item; } public async Task> GetListItemsByIdsAsync(IEnumerable itemIds, CancellationToken cancellationToken = default) { var items = new List(); var missing = new List(); foreach (var id in itemIds.Distinct()) { var cached = ListCache.GetListItem(id); if (cached != null) items.Add(cached); else missing.Add(id); } if (missing.Count > 0) items.AddRange(await Context.QueryAsync(Sql.ListItems_SelectByIds(), new object[] { missing.ToArray() }, cancellationToken)); Attach(items); await PreloadLinkedObjectsAsync(items, cancellationToken); return items; } public async Task> GetListItemsAsync(long listId, CancellationToken cancellationToken = default) { var items = ListCache.GetListItems(listId); if (items == null) { items = await Context.QueryAsync(Sql.ListItems_SelectByListId(), new object[] { listId }, cancellationToken); // Cached - and so shared - once the transaction commits: until then the items are the reader's own. Caching.CachePublication.AfterCommit(Context, () => ListCache.CacheListItems(listId, items)); } Attach(items); await PreloadLinkedObjectsAsync(items, cancellationToken); return items; } public async Task GetListItemByValueAsync(long listId, string value, CancellationToken cancellationToken = default) { var items = await GetListItemsAsync(listId); return items.FirstOrDefault(i => i.Value == value); } public async Task SaveListItemAsync(IRedbListItem item, CancellationToken cancellationToken = default) { RedbListItem entity; if (item.Id == 0) { var existing = await Context.QueryFirstOrDefaultAsync( Sql.ListItems_SelectByListIdAndValue(), new object[] { item.IdList, item.Value }, cancellationToken); if (existing != null) { entity = existing; entity.Alias = item.Alias; entity.IdObject = item.IdObject; await Context.ExecuteAsync(Sql.ListItems_UpdateAliasAndObject(), new object[] { entity.Alias, entity.IdObject, entity.Id }, cancellationToken); } else { entity = new RedbListItem { Id = await Context.NextObjectIdAsync(), IdList = item.IdList, Value = item.Value, Alias = item.Alias, IdObject = item.IdObject }; await Context.ExecuteAsync(Sql.ListItems_Insert(), new object[] { entity.Id, entity.IdList, entity.Value, entity.Alias, entity.IdObject }, cancellationToken); } } else { var existing = await Context.QueryFirstOrDefaultAsync( Sql.ListItems_SelectById(), new object[] { item.Id }, cancellationToken); if (existing == null) throw new InvalidOperationException($"ListItem with ID {item.Id} not found"); entity = existing; entity.Value = item.Value; entity.Alias = item.Alias; entity.IdObject = item.IdObject; await Context.ExecuteAsync(Sql.ListItems_Update(), new object[] { entity.Value, entity.Alias, entity.IdObject, entity.Id }, cancellationToken); } ListCache.InvalidateListItems(entity.IdList); return Attach(entity)!; } public async Task DeleteListItemAsync(long itemId, CancellationToken cancellationToken = default) { var entity = await Context.QueryFirstOrDefaultAsync( Sql.ListItems_SelectById(), new object[] { itemId }, cancellationToken); if (entity == null) return false; var listId = entity.IdList; await Context.ExecuteAsync(Sql.ListItems_Delete(), new object[] { itemId }, cancellationToken); ListCache.InvalidateListItems(listId); return true; } public async Task> AddItemsAsync(IRedbList list, IEnumerable items, CancellationToken cancellationToken = default) { var entities = new List(); foreach (var item in items) { var entity = new RedbListItem { Id = item.Id == 0 ? await Context.NextObjectIdAsync() : item.Id, IdList = list.Id, Value = item.Value, Alias = item.Alias, IdObject = item.IdObject }; entities.Add(entity); await Context.ExecuteAsync(Sql.ListItems_Insert(), new object[] { entity.Id, entity.IdList, entity.Value, entity.Alias, entity.IdObject }, cancellationToken); } ListCache.InvalidateListItems(list.Id); return Attach(entities); } public async Task> AddItemsAsync(IRedbList list, IEnumerable values, IEnumerable? aliases = null, CancellationToken cancellationToken = default) { var valuesList = values.ToList(); var aliasesList = aliases?.ToList(); var itemsToAdd = valuesList.Select((value, i) => (IRedbListItem)new RedbListItem { IdList = list.Id, Value = value, Alias = aliasesList != null && i < aliasesList.Count ? aliasesList[i] : null }); return await AddItemsAsync(list, itemsToAdd); } public async Task SaveListWithItemsAsync(IRedbList list, CancellationToken cancellationToken = default) { var savedList = await SaveListAsync(list); // 1. Get current items from DB var dbItems = await Context.QueryAsync(Sql.ListItems_SelectByListId(), new object[] { savedList.Id }, cancellationToken); var dbItemIds = dbItems.Select(i => i.Id).ToHashSet(); // 2. Get IDs from memory (existing items only, Id > 0) var memoryItemIds = list.Items .Where(i => i.Id > 0) .Select(i => i.Id) .ToHashSet(); // 3. Find deleted items: exist in DB but not in memory var toDeleteIds = dbItemIds.Except(memoryItemIds).ToList(); // 4. Delete removed items from DB foreach (var itemId in toDeleteIds) { await Context.ExecuteAsync(Sql.ListItems_Delete(), new object[] { itemId }, cancellationToken); } // 5. Add new items (Id == 0) var newItems = list.Items .Where(item => item.Id == 0) .Select(item => new RedbListItem { IdList = savedList.Id, Value = item.Value, Alias = item.Alias, IdObject = item.IdObject }) .Cast() .ToList(); if (newItems.Any()) { await AddItemsAsync(savedList, newItems); } // 6. Invalidate cache if items were deleted if (toDeleteIds.Any()) { ListCache.InvalidateListItems(savedList.Id); } // 7. Load fresh items from DB and attach to result var items = await GetListItemsAsync(savedList.Id); savedList.SetItems(items); return savedList; } // === Specific methods === public async Task> GetItemsByObjectReferenceAsync(long objectId, CancellationToken cancellationToken = default) { return Attach(await Context.QueryAsync(Sql.ListItems_SelectByObjectId(), new object[] { objectId }, cancellationToken)); } public async Task IsListUsedInStructuresAsync(long listId, CancellationToken cancellationToken = default) { var result = await Context.ExecuteScalarAsync(Sql.Lists_IsUsedInStructures(), new object[] { listId }, cancellationToken); return result.HasValue; } public async Task SyncListFromEnumAsync(string? listName = null, CancellationToken cancellationToken = default) where TEnum : struct, Enum { var enumType = typeof(TEnum); var name = listName ?? enumType.Name; var list = await GetListByNameAsync(name); if (list == null) { list = RedbList.Create(name, $"Enum: {name}"); list = await SaveListAsync(list); } var existingItems = await GetListItemsAsync(list.Id); var existingValues = existingItems.Select(i => i.Value).ToHashSet(); var enumValues = Enum.GetValues(); var newItems = new List(); foreach (var enumValue in enumValues) { var valueName = enumValue.ToString(); if (!existingValues.Contains(valueName)) { var field = enumType.GetField(valueName); var aliasAttr = field?.GetCustomAttribute(); var alias = aliasAttr?.Alias; var item = (RedbListItem)list.CreateItem(valueName, alias: alias); newItems.Add(item); } } if (newItems.Any()) { await AddItemsAsync(list, newItems); } return list; } } } Path: redb/redb.Core/Providers/Base/MaintenanceProviderBase.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/MaintenanceProviderBase.cs ---- using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using redb.Core.Data; using redb.Core.Query; namespace redb.Core.Providers.Base; /// /// The single implementation of : every provider-specific /// difference lives in the SQL the dialect returns, normalized to ONE column-alias contract, /// so the subclasses degenerate to wiring their dialect in (same shape as ValidationProvider). /// public abstract class MaintenanceProviderBase : IMaintenanceProvider { protected IRedbContext Context { get; } protected ISqlDialect Sql { get; } protected ILogger? Logger { get; } /// SQLite's bounded-ANALYZE limit; other engines ignore it. See configuration. private readonly int _analysisLimit; protected MaintenanceProviderBase( IRedbContext context, ISqlDialect sql, int analysisLimit, ILogger? logger = null) { Context = context ?? throw new System.ArgumentNullException(nameof(context)); Sql = sql ?? throw new System.ArgumentNullException(nameof(sql)); _analysisLimit = analysisLimit; Logger = logger; } /// public virtual async Task AnalyzeAsync(CancellationToken cancellationToken = default) { var sql = Sql.Maintenance_Analyze(_analysisLimit); Logger?.LogInformation("REDB maintenance: refreshing planner statistics ({Sql})", sql); await Context.ExecuteAsync(sql, System.Array.Empty(), cancellationToken); } /// public virtual async Task AnalyzeTableAsync(string table, string? schema = null, CancellationToken cancellationToken = default) { if (string.IsNullOrWhiteSpace(table)) throw new ArgumentException("Table name is required.", nameof(table)); // An identifier cannot travel as a parameter, and this one comes from an operator's // screen: it is checked against the catalogs first, and the dialect quotes what survives. var exists = await Context.ExecuteScalarAsync( Sql.Maintenance_SelectTableExists(), new object[] { table, (object?)schema ?? DBNull.Value }, cancellationToken); if (exists <= 0) throw new InvalidOperationException( $"Table '{(schema == null ? table : schema + "." + table)}' was not found in this database, " + "so its planner statistics were not refreshed. Names come from GetTableStatsAsync()."); var sql = Sql.Maintenance_AnalyzeTable(schema, table, _analysisLimit); Logger?.LogInformation("REDB maintenance: refreshing planner statistics of one table ({Sql})", sql); await Context.ExecuteAsync(sql, System.Array.Empty(), cancellationToken); } /// public virtual async Task> GetIndexStatsAsync(CancellationToken cancellationToken = default) { // The dialect SQL normalizes each engine's catalogs to one alias contract, so this is // the only mapping in existence. The single allowed branch: the dialect's fallback form, // for SQLite without dbstat (no sizes) and SQL Server without VIEW SERVER STATE (no counters). List rows; try { rows = await Context.QueryAsync( Sql.Maintenance_SelectIndexStats(), System.Array.Empty(), cancellationToken); } catch (System.Exception ex) when (Sql.Maintenance_SelectIndexStatsNoSize() is { } fallback && fallback != Sql.Maintenance_SelectIndexStats()) { Logger?.LogDebug(ex, "REDB maintenance: index-stats query failed (dbstat not compiled in, or no " + "VIEW SERVER STATE right); falling back to the dialect's reduced form."); rows = await Context.QueryAsync( fallback, System.Array.Empty(), cancellationToken); } return rows.Select(ToStatistics).ToList(); } /// public virtual async Task> GetTableStatsAsync(CancellationToken cancellationToken = default) { // The optional parts of a SQLite database decide how much of this question can be answered: // dbstat may not be compiled in, and sqlite_stat1 does not exist until the first ANALYZE - // a statement naming a missing table does not even prepare. The dialect lists the forms in // decreasing capability, and the first one that runs wins; the last failure is rethrown. var forms = Sql.Maintenance_SelectTableStatsForms(); List? rows = null; for (var i = 0; i < forms.Count; i++) { try { rows = await Context.QueryAsync( forms[i], System.Array.Empty(), cancellationToken); break; } catch (System.Exception ex) when (i < forms.Count - 1) { Logger?.LogDebug(ex, "REDB maintenance: table-stats form {Form} of {Count} did not run on this database " + "(an optional catalog is missing); trying the next, less detailed one.", i + 1, forms.Count); } } foreach (var row in rows!) row.IsRedbOwned = IsRedbTable(row.Table); return rows; } /// public virtual async Task GetStatisticsWindowAsync(CancellationToken cancellationToken = default) { var rows = await Context.QueryAsync( Sql.Maintenance_SelectStatisticsWindow(), System.Array.Empty(), cancellationToken); return rows.FirstOrDefault() ?? new StatisticsWindow(); } // === WHAT MUST SURVIVE === /// /// Tables of the redb type system. Their indexes are read on every scheme sync, every query /// compilation and every materialization, and some of them are read so rarely that a usage /// counter shows zero - which is exactly how a well-meant cleanup removes them. /// private static readonly HashSet MetadataTables = new(StringComparer.OrdinalIgnoreCase) { "_types", "_schemes", "_structures", "_scheme_metadata_cache", "_dependencies", "_functions", "_lists", "_links", "_migrations" }; /// Tables redb checks permissions against. private static readonly HashSet SecurityTables = new(StringComparer.OrdinalIgnoreCase) { "_users", "_roles", "_users_roles", "_permissions" }; /// Tables holding redb data. private static readonly HashSet DataTables = new(StringComparer.OrdinalIgnoreCase) { "_objects", "_values", "_list_items" }; /// /// A table of the redb schema. By table name, never by index name: the schema carries both /// hand-named indexes (IX__values__Object_not_null) and constraint-born ones the engine names /// itself, and only the table is a reliable marker. /// private static bool IsRedbTable(string table) => table.StartsWith("_", StringComparison.Ordinal); private static IndexCriticality ReasonFor(IndexStatsRow row) { if (MetadataTables.Contains(row.Table)) return IndexCriticality.RedbMetadata; if (SecurityTables.Contains(row.Table)) return IndexCriticality.RedbSecurity; if (DataTables.Contains(row.Table)) return IndexCriticality.RedbData; if (IsRedbTable(row.Table)) return IndexCriticality.RedbData; if (row.IsPrimaryKey == true) return IndexCriticality.PrimaryKey; if (row.IsUniqueConstraint == true || row.IsUnique == true) return IndexCriticality.Unique; if (row.BacksForeignKey == true) return IndexCriticality.ForeignKey; return IndexCriticality.None; } private static IndexStatistics ToStatistics(IndexStatsRow row) { var reason = ReasonFor(row); return new IndexStatistics { Schema = row.Schema, Table = row.Table, Name = row.Name, IsUnique = row.IsUnique, Columns = Split(row.ColumnsCsv), IncludedColumns = Split(row.IncludedColumnsCsv), IsPrimaryKey = row.IsPrimaryKey == true, IsUniqueConstraint = row.IsUniqueConstraint == true, IsClustered = row.IsClustered, BacksForeignKey = row.BacksForeignKey == true, IsRedbOwned = IsRedbTable(row.Table), IsSystemCritical = reason != IndexCriticality.None, CriticalReason = reason, SizeBytes = row.SizeBytes, EstimatedRows = row.EstimatedRows, Seeks = row.Seeks, Scans = row.Scans, Updates = row.Updates, LastUsed = row.LastUsed }; } /// /// Column lists travel as one comma-separated value so the catalogs of three engines keep /// fitting one row per index; the list the caller reads is built here, once. /// private static IReadOnlyList Split(string? csv) => string.IsNullOrEmpty(csv) ? Array.Empty() : csv.Split(',').Select(p => p.Trim()).Where(p => p.Length > 0).ToArray(); /// The row shape the dialect SQL produces; the public model is built from it. private sealed class IndexStatsRow { public string? Schema { get; set; } public string Table { get; set; } = string.Empty; public string Name { get; set; } = string.Empty; public bool? IsUnique { get; set; } public string? ColumnsCsv { get; set; } public string? IncludedColumnsCsv { get; set; } public bool? IsPrimaryKey { get; set; } public bool? IsUniqueConstraint { get; set; } public bool? IsClustered { get; set; } public bool? BacksForeignKey { get; set; } public long? SizeBytes { get; set; } public long? EstimatedRows { get; set; } public long? Seeks { get; set; } public long? Scans { get; set; } public long? Updates { get; set; } public DateTimeOffset? LastUsed { get; set; } } } Path: redb/redb.Core/Providers/Base/ObjectDeleteByIds.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/ObjectDeleteByIds.cs ---- using System.Threading; using System.Threading.Tasks; using redb.Core.Data; using redb.Core.Query; namespace redb.Core.Providers.Base; /// /// The delete of objects by ids () and the number of the given objects /// it deleted. Where the delete's rows-affected misses some (SQLite: a child the _id_parent cascade removed with /// its parent before the statement reached it), the dialect's /// counts them in the same transaction, before the delete. /// internal static class ObjectDeleteByIds { /// /// Run again on a deadlock when the delete is the caller's whole unit (no transaction on the context); inside the /// caller's transaction the deadlock leaves to the caller (). /// public static Task RunAsync(IRedbContext context, ISqlDialect sql, long[] ids, CancellationToken cancellationToken) => DeadlockRetryHelper.ExecuteWithRetryAsync(context, () => RunOnceAsync(context, sql, ids, cancellationToken), cancellationToken: cancellationToken); private static async Task RunOnceAsync(IRedbContext context, ISqlDialect sql, long[] ids, CancellationToken cancellationToken) { var countSql = sql.ObjectStorage_CountObjectsByIds(); if (countSql == null) return await context.ExecuteAsync(sql.ObjectStorage_DeleteByIds(), new object[] { ids }, cancellationToken); var counted = 0; await context.ExecuteAtomicAsync(async () => { counted = checked((int)await context.ExecuteScalarAsync(countSql, new object[] { ids }, cancellationToken)); await context.ExecuteAsync(sql.ObjectStorage_DeleteByIds(), new object[] { ids }, cancellationToken); }, cancellationToken); return counted; } } Path: redb/redb.Core/Providers/Base/ObjectStorageProviderBase.AddNewObjects.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/ObjectStorageProviderBase.AddNewObjects.cs ---- using redb.Core.Providers; using redb.Core.Data; using redb.Core.Utils; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using redb.Core.Models.Configuration; using redb.Core.Models.Security; using redb.Core.Query; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System; namespace redb.Core.Providers.Base { /// /// BULK INSERT - high-performance creation of multiple objects /// public abstract partial class ObjectStorageProviderBase { /// /// BULK INSERT: Create multiple new objects in one operation (WITHOUT permission checks) /// The batch save's preparation steps + BulkInsert for maximum performance /// public async Task> AddNewObjectsAsync(IEnumerable> objects, CancellationToken cancellationToken = default) where TProps : class, new() { return await AddNewObjectsAsync(objects, _securityContext.CurrentUser, cancellationToken); } /// /// BULK INSERT with explicit user: Create multiple new objects (WITHOUT permission checks) /// public async Task> AddNewObjectsAsync(IEnumerable> objects, IRedbUser user, CancellationToken cancellationToken = default) where TProps : class, new() { // Materialize IEnumerable to list for multiple iterations var objectsList = objects?.ToList() ?? new List>(); if (objectsList.Count == 0) { return new List(); } // Validation foreach (var obj in objectsList) { if (obj.Props == null) { throw new ArgumentException($"Object properties '{obj.Name}' cannot be null", nameof(objects)); } } // Initial processing of hashes and schemes for main objects foreach (var obj in objectsList) { // Recalculate hash var currentHash = RedbHash.ComputeFor(obj); if (currentHash.HasValue) { obj.Hash = currentHash.Value; } // Auto-determination of scheme (WITHOUT checks for existing objects) if (obj.SchemeId == 0 && _configuration.AutoSyncSchemesOnSave) { var existingScheme = await _schemeSync.GetSchemeByTypeAsync(); if (existingScheme != null) { obj.SchemeId = existingScheme.Id; } else if (_configuration.AutoSyncSchemesOnSave) { try { var scheme = await _schemeSync.SyncSchemeAsync(); obj.SchemeId = scheme.Id; } catch (Exception ex) { throw; } } } } // === THE BATCH SAVE'S PREPARATION STEPS === var objectsToSave = new List(); var valuesToSave = new List(); var processedObjectIds = new HashSet(); var seenInstances = new HashSet(ReferenceEqualityComparer.Instance); // STEP 2: Recursive collection of all objects (main + nested IRedbObject) // References by id carry no hash yet: resolve them in one query, as the batch save does. Hashing before // that wrote "id:" for every reference, and the stored hash never matched the loaded one. var referenceStubs = new List(); foreach (var obj in objectsList) { await CollectAllObjectsRecursively(obj, objectsToSave, processedObjectIds, seenInstances, referenceStubs); } await ResolveReferenceHashesAsync(referenceStubs, cancellationToken); await EnsureNoHeldShapesAsync(objectsToSave, cancellationToken); // A referenced object that already carries an id may be one saved before, by the very instance that was // saved (its props loaded, so the collector takes it). The batch save tells such objects from new ones by // asking the database; the bulk insert inserted them again and failed on the primary key of _objects. A // saved one is a reference here: its referrer writes its id, its own row and values stay as they are. // The same statement reads the stored structure hash of every scheme the bulk insert writes (the save reads it // with its existing objects): a scheme another process changed since this one cached it is read again before // any value row is built, and a class older than the scheme's version is refused. One statement per call, // before anything is written. await EnsureSchemesForAllTypes(objectsToSave, cancellationToken); var passedIn = new HashSet(objectsList, ReferenceEqualityComparer.Instance); var referencedIds = objectsToSave.Where(o => o.Id != 0 && !passedIn.Contains(o)).Select(o => o.Id).Distinct().ToArray(); var (savedRows, hashByScheme) = await SelectExistingAndSchemeHashesAsync(referencedIds, objectsToSave, cancellationToken); if (savedRows.Count > 0) { var saved = savedRows.Select(r => r.Id).ToHashSet(); objectsToSave.RemoveAll(o => !passedIn.Contains(o) && saved.Contains(o.Id)); } await RefreshStaleSchemesAsync(objectsToSave, hashByScheme, cancellationToken); // STEP 3: Assign IDs to all objects without ID (via GetNextKey) var created = objectsToSave.Where(o => o.Id == 0).ToList(); await AssignMissingIds(objectsToSave, user, cancellationToken); // A nested object keeps the ParentId it carries, as in SaveAsync: a reference is not a place in the tree. // The bulk insert used to put every nested new object under the first object it was given. // Hashes are final only once ids and parents are set: a parent hashes "id:hash" of every reference, and // an object created here was still id 0 above. Children before parents across the graph, as the batch // save does. RecomputeHashesPostOrder(objectsToSave); // STEP 5: Recursive processing of Props of all objects into values lists await ProcessAllObjectsPropertiesRecursively(objectsToSave, valuesToSave, cancellationToken: cancellationToken); // STEP 6: WITHOUT Delete strategy - these are NEW objects // STEP 7: BULK INSERT instead of regular saving // The object rows and the value rows go in as one unit: a failed value insert leaves no object behind. In a // caller transaction ExecuteAtomicAsync joins it, and the caller owns the rollback. try { await _context.ExecuteAtomicAsync(() => CommitAllChangesBulk(objectsToSave, valuesToSave, cancellationToken), cancellationToken); } catch (Exception ex) when (Data.DbErrorClassifier.IsUniqueViolation(ex)) { throw await TranslateUniqueViolationAsync(ex, objectsList.FirstOrDefault()?.SchemeId); } catch (Exception ex) when (IsStaleKeyCache(ex, created.Count > 0)) { throw StaleKeyCacheFailure(ex, created); } // Return IDs of all created main objects var resultIds = objectsList.Select(o => o.Id).ToList(); return resultIds; } /// /// Step 7 (BULK): Bulk save with BulkInsert instead of Add(). /// private async Task CommitAllChangesBulk(List objects, List valuesList, CancellationToken cancellationToken) { // 1. BULK INSERT objects if (objects.Count > 0) { var objectRecords = objects.Select(obj => { var record = new RedbObjectRow { Id = obj.Id, IdScheme = obj.SchemeId, IdParent = obj.ParentId, IdOwner = obj.OwnerId, IdWhoChange = obj.WhoChangeId, Name = obj.Name, Hash = obj.Hash, DateBegin = obj.DateBegin, DateComplete = obj.DateComplete, Key = obj.Key, ValueLong = obj.ValueLong, ValueString = obj.ValueString, ValueGuid = obj.ValueGuid, ValueBool = obj.ValueBool, ValueDouble = obj.ValueDouble, ValueNumeric = obj.ValueNumeric, ValueDatetime = obj.ValueDatetime, ValueBytes = obj.ValueBytes, Note = obj.Note }; if (_configuration.AutoSetModifyDate) { record.DateCreate = DateTimeOffset.UtcNow; record.DateModify = DateTimeOffset.UtcNow; } else { var dateCreate = obj.DateCreate; record.DateCreate = dateCreate == DateTimeOffset.MinValue ? DateTimeOffset.UtcNow : dateCreate; var dateModify = obj.DateModify; record.DateModify = dateModify == DateTimeOffset.MinValue ? DateTimeOffset.UtcNow : dateModify; } return record; }).ToList(); await _context.Bulk.BulkInsertObjectsAsync(objectRecords, cancellationToken); } // 2. BULK INSERT values (with topological sort for FK constraint) if (valuesList.Count > 0) { await AssignValueIdsAsync(valuesList, [], cancellationToken); var sortedValues = ValuesTopologicalSort.SortByFkDependency(valuesList); await _context.Bulk.BulkInsertValuesAsync(sortedValues, cancellationToken); } } } } Path: redb/redb.Core/Providers/Base/ObjectStorageProviderBase.ChangeTracking.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/ObjectStorageProviderBase.ChangeTracking.cs ---- using redb.Core.Models.Entities; using System.Collections.Generic; namespace redb.Core.Providers.Base { /// /// Pending-каналы ChangeTracking: дифф (Pro) складывает сюда DELETE/INSERT/UPDATE, а /// SaveBatchWithChangeTrackingStrategy исполняет их одной точкой flush в живом порядке /// DELETE -> UPDATE -> INSERT. В OpenSource остаются пустыми (CT - Pro-фича). /// public abstract partial class ObjectStorageProviderBase { /// /// Values to update (from ChangeTracking diff). Pro only. /// protected List _pendingValuesToUpdate = []; /// /// Values to insert (from ChangeTracking diff). Pro only. /// protected List _pendingValuesToInsert = []; /// /// Value IDs to delete (from ChangeTracking diff). Pro only. /// protected List _pendingValuesToDelete = []; } } Path: redb/redb.Core/Providers/Base/ObjectStorageProviderBase.SaveAsync.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/ObjectStorageProviderBase.SaveAsync.cs ---- using redb.Core.Providers; using redb.Core.Data; using redb.Core.Utils; using redb.Core.Extensions; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using redb.Core.Models.Configuration; using redb.Core.Models.Security; using redb.Core.Caching; using redb.Core.Query; using Microsoft.Extensions.Logging; using System.Text.Json.Serialization; using System.Reflection; using System.Collections.Concurrent; using System.Runtime.CompilerServices; using System.Collections.Generic; using System.Collections; using System.Linq; using System.Threading.Tasks; using System; namespace redb.Core.Providers.Base { /// /// NEW SaveAsync - correct architecture with recursive processing /// public abstract partial class ObjectStorageProviderBase { /// /// STEP 2: Recursive collection of all IRedbObject (main + nested). /// Uses to deduplicate objects that are referenced /// multiple times in the object tree (e.g. two licenses referencing the same Plan). /// protected async Task CollectAllObjectsRecursively(IRedbObject rootObject, List collector, HashSet processed, HashSet seen, List? referenceStubs = null) { // One instance is one object: a new object (id 0, nothing to dedup by) referenced from two places was // collected twice, given an id twice and inserted twice (review after 4.0.0). if (!seen.Add(rootObject)) return; collector.Add(rootObject); ValidateValueUnique(rootObject); // Track root object ID to prevent re-adding if referenced elsewhere in the tree. // New objects (Id == 0) get IDs assigned later and are deduplicated by instance only. if (rootObject.Id != 0) processed.Add(rootObject.Id); var rootProperties = GetPropertiesFromRedbObject(rootObject); await CollectNestedRedbObjectsFromProperties(rootProperties, collector, processed, seen, rootObject.Id, referenceStubs); } /// /// Recursive search for IRedbObject in object Props /// private async Task CollectNestedRedbObjectsFromProperties(object? properties, List collector, HashSet processed, HashSet seen, long parentId, List? referenceStubs) { if (properties == null) return; var propsType = properties.GetType(); var propsProperties = propsType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (var property in propsProperties) { // Skip technical properties with [JsonIgnore] or [RedbIgnore] if (property.ShouldIgnoreForRedb()) continue; // Skip indexers (e.g. Dictionary.Item[key]) - they require index parameters if (property.GetIndexParameters().Length > 0) continue; var value = property.GetValue(properties); if (value == null) continue; // Single IRedbObject (reference or nested child) if (IsRedbObjectType(value.GetType())) { var redbObj = (IRedbObject)value; // A reference (id, no properties) is written by the parent as its id and is not // an object to save. Before the check the stub went into the collector and the // parent's save rewrote the referenced object as an empty one: values deleted, // name reset, hash cleared. Checked before the dedup so that a loaded copy of the // same object elsewhere in the graph is still collected. if (IsUnloadedReference(redbObj)) { // V4 (L.2): a hand-made reference by id has no hash yet; the caller resolves it in one // query so the parent hashes "id:hash" exactly as a loaded stub carries it. if (referenceStubs != null && redbObj.Hash == null && redbObj.Id > 0) referenceStubs.Add(redbObj); continue; } // Dedup: skip objects already collected (same RedbObject referenced // from multiple properties, e.g. two LicenseInfo entries pointing // to the same Plan). New objects (Id == 0) always collected. if (!seen.Add(redbObj) || (redbObj.Id != 0 && !processed.Add(redbObj.Id))) continue; collector.Add(redbObj); ValidateValueUnique(redbObj); var nestedProperties = GetPropertiesFromRedbObject(redbObj); await CollectNestedRedbObjectsFromProperties(nestedProperties, collector, processed, seen, redbObj.Id, referenceStubs); } // IRedbObject array else if (value is IEnumerable enumerable && IsRedbObjectArrayType(value.GetType())) { foreach (var item in enumerable) { if (item != null && IsRedbObjectType(item.GetType())) { var redbObj = (IRedbObject)item; if (IsUnloadedReference(redbObj)) { // V4 (L.2): a hand-made reference by id has no hash yet; the caller resolves it in one // query so the parent hashes "id:hash" exactly as a loaded stub carries it. if (referenceStubs != null && redbObj.Hash == null && redbObj.Id > 0) referenceStubs.Add(redbObj); continue; } // Dedup: same object referenced from multiple array elements if (!seen.Add(redbObj) || (redbObj.Id != 0 && !processed.Add(redbObj.Id))) continue; collector.Add(redbObj); ValidateValueUnique(redbObj); var arrayElementProperties = GetPropertiesFromRedbObject(redbObj); await CollectNestedRedbObjectsFromProperties(arrayElementProperties, collector, processed, seen, redbObj.Id, referenceStubs); } } } // Dictionary with IRedbObject values else if (IsDictionaryWithRedbObjectValue(value.GetType())) { var valuesProperty = value.GetType().GetProperty("Values"); if (valuesProperty != null) { var dictValues = (System.Collections.IEnumerable)valuesProperty.GetValue(value)!; foreach (var item in dictValues) { if (item != null && IsRedbObjectType(item.GetType())) { var redbObj = (IRedbObject)item; if (IsUnloadedReference(redbObj)) { // V4 (L.2): a hand-made reference by id has no hash yet; the caller resolves it in one // query so the parent hashes "id:hash" exactly as a loaded stub carries it. if (referenceStubs != null && redbObj.Hash == null && redbObj.Id > 0) referenceStubs.Add(redbObj); continue; } // Dedup: same object referenced from multiple dict entries if (!seen.Add(redbObj) || (redbObj.Id != 0 && !processed.Add(redbObj.Id))) continue; collector.Add(redbObj); ValidateValueUnique(redbObj); var nestedProperties = GetPropertiesFromRedbObject(redbObj); await CollectNestedRedbObjectsFromProperties(nestedProperties, collector, processed, seen, redbObj.Id, referenceStubs); } } } } // Recursion into business classes else if (IsBusinessClassType(value.GetType())) { await CollectNestedRedbObjectsFromProperties(value, collector, processed, seen, parentId, referenceStubs); } // Recursion into the business classes of a dictionary: enumerated whole it yields key-value pairs, // which are no business class, so a reference inside a class value was never collected - a new // object there got no id and its referrer's row failed on the foreign key. else if (value is IDictionary classDictionary) { foreach (var item in classDictionary.Values) { if (item != null && IsBusinessClassType(item.GetType())) { await CollectNestedRedbObjectsFromProperties(item, collector, processed, seen, parentId, referenceStubs); } } } // Recursion into business class arrays else if (value is IEnumerable businessEnumerable && !IsStringType(value.GetType())) { foreach (var item in businessEnumerable) { if (item != null && IsBusinessClassType(item.GetType())) { await CollectNestedRedbObjectsFromProperties(item, collector, processed, seen, parentId, referenceStubs); } } } } } /// /// Hashes every collected object after the objects it references. A parent hashes "id:hash" of every /// reference, so a reference hashed after its parent leaves the parent with the reference's stale or empty /// hash - stored for ever, a props-cache miss on every load. The collector is pre-order and collects a /// target shared by two parents once, under the first: reversing its order put the second parent before /// the target (review after 4.0.0). Post-order over the graph, each instance once. /// private static void RecomputeHashesPostOrder(IEnumerable objects) { var done = new HashSet(ReferenceEqualityComparer.Instance); foreach (var obj in objects) RecomputeHashDeep(obj, done); } private static void RecomputeHashDeep(IRedbObject obj, HashSet done) { if (!done.Add(obj)) return; ForEachDirectReference(GetPropertiesFromRedbObject(obj), child => { // A stub carries the hash the parent needs; there is nothing loaded to hash. if (!IsUnloadedReference(child)) RecomputeHashDeep(child, done); }); RecomputeHash(obj); } /// /// The objects a Props instance references directly - single, in a collection, as dictionary values, and /// through nested business classes - the walk of . /// private static void ForEachDirectReference(object? properties, Action visit) { if (properties == null) return; foreach (var property in properties.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance)) { if (property.ShouldIgnoreForRedb() || property.GetIndexParameters().Length > 0) continue; var value = property.GetValue(properties); if (value == null) continue; if (IsRedbObjectType(value.GetType())) visit((IRedbObject)value); else if (value is IEnumerable enumerable && IsRedbObjectArrayType(value.GetType())) { foreach (var item in enumerable) if (item != null && IsRedbObjectType(item.GetType())) visit((IRedbObject)item); } else if (IsDictionaryWithRedbObjectValue(value.GetType())) { if (value.GetType().GetProperty("Values")?.GetValue(value) is IEnumerable values) foreach (var item in values) if (item != null && IsRedbObjectType(item.GetType())) visit((IRedbObject)item); } else if (IsBusinessClassType(value.GetType())) ForEachDirectReference(value, visit); else if (value is IEnumerable businessEnumerable && !IsStringType(value.GetType())) { foreach (var item in businessEnumerable) if (item != null && IsBusinessClassType(item.GetType())) ForEachDirectReference(item, visit); } } } /// /// An object with an id whose properties were never loaded: a stub from the depth boundary /// of a load or a hand-written new RedbObject<T> { id = x }. It names another /// object; it is not that object. Reads the flag, never Props — the getter would /// trigger lazy loading. /// private static bool IsUnloadedReference(IRedbObject obj) => obj.Id != 0 && obj is RedbObject typed && !typed.IsPropsLoaded; /// /// A reference whose properties were never loaded names another object; saving it would save whatever a fresh /// load returns, and the caller's edits - made on an instance the getter did not keep (a shared instance inside a /// transaction) - would be lost silently (review after 4.0.0). The collector skips such references inside a /// graph; saved directly, they are refused. /// private static void RefuseUnloadedReference(IRedbObject obj) { // A stub redb attached a lazy loader to (a depth boundary, a cache), still unloaded. An object without a // loader and without loaded Props is the caller's own - a scheme without properties, Props set to null - and // is saved as it is. if (IsUnloadedReference(obj) && obj.GetType().GetField("_lazyLoader")?.GetValue(obj) != null) throw new Exceptions.RedbUnloadedReferenceException(obj.Id, obj.SchemeId); } /// /// The 440-character limit of _objects._value_unique, enforced in C# so every provider /// behaves identically: SQLite does not check VARCHAR lengths at all, and a key accepted /// there would be rejected by PostgreSQL and MSSQL (UNIQUE plan §4.5). /// private static void ValidateValueUnique(IRedbObject obj) { if (obj.ValueUnique is { Length: > 440 }) throw new Exceptions.RedbUniqueKeyValueException( $"object id={obj.Id}: _value_unique is {obj.ValueUnique.Length} characters, the limit is 440"); // Owner decision 2026-09-02: _value_string is an identifier column - 450 is the MSSQL // index-key width, enforced here so the text-typed PostgreSQL and SQLite columns hold // the same contract. Long text belongs in _note or in a Props field. if (obj.ValueString is { Length: > 450 }) throw new Exceptions.RedbValueStringTooLongException(obj.Id, obj.ValueString.Length); } // Answered once per type: every predicate below reflects over the interfaces of the type, and the save asked // them for every property of every object (review after 4.0.0). Keyed weakly: a Props type of a module in a // collectible AssemblyLoadContext must not keep that context alive once the module unloads. private static readonly ConditionalWeakTable RedbObjectTypeByType = new(); private static readonly ConditionalWeakTable RedbObjectArrayTypeByType = new(); private static readonly ConditionalWeakTable DictionaryWithRedbObjectValueByType = new(); private static readonly ConditionalWeakTable BusinessClassTypeByType = new(); private static readonly object CachedTrue = true; private static readonly object CachedFalse = false; private static bool CachedPredicate(ConditionalWeakTable table, Type type, Func compute) { if (table.TryGetValue(type, out var answer)) return (bool)answer; answer = compute(type) ? CachedTrue : CachedFalse; table.AddOrUpdate(type, answer); return (bool)answer; } /// /// IRedbObject type check /// private static bool IsRedbObjectType(Type type) => CachedPredicate(RedbObjectTypeByType, type, static t => IsRedbObjectTypeCore(t)); private static bool IsRedbObjectTypeCore(Type type) { // RedbObject itself or anything derived from it (TreeRedbObject) if (Utils.RedbObjectTypes.GenericOf(type) != null) return true; // Check interfaces for IRedbObject return type.GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition().Name.Contains("IRedbObject")); } /// /// A collection of IRedbObject: an array, or any generic IEnumerable<T> (List, IList, ...) whose element /// is one. Only arrays used to count (props cache review, 2026-09-15): the collector skipped the elements of a /// List - references by id got no hash, so the parent never matched its loaded hash; a new object was never /// saved (foreign key failure); an edit to a loaded one was lost. /// private static bool IsRedbObjectArrayType(Type type) => CachedPredicate(RedbObjectArrayTypeByType, type, static t => IsRedbObjectArrayTypeCore(t)); private static bool IsRedbObjectArrayTypeCore(Type type) { if (type.IsArray) return IsRedbObjectType(type.GetElementType()!); if (type == typeof(string)) return false; var sequence = type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IEnumerable<>) ? type : type.GetInterfaces().FirstOrDefault(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IEnumerable<>)); return sequence != null && IsRedbObjectType(sequence.GetGenericArguments()[0]); } /// /// Checking Dictionary with IRedbObject values /// private static bool IsDictionaryWithRedbObjectValue(Type type) => CachedPredicate(DictionaryWithRedbObjectValueByType, type, static t => IsDictionaryWithRedbObjectValueCore(t)); private static bool IsDictionaryWithRedbObjectValueCore(Type type) { if (!type.IsGenericType) return false; var genericDef = type.GetGenericTypeDefinition(); if (genericDef != typeof(Dictionary<,>) && genericDef != typeof(IDictionary<,>)) return false; var valueType = type.GetGenericArguments()[1]; return IsRedbObjectType(valueType); } /// /// Checking string type /// private static bool IsStringType(Type type) { return type == typeof(string); } /// /// Getting Props from IRedbObject via reflection /// private static object? GetPropertiesFromRedbObject(IRedbObject redbObj) { // Use reflection to get the Props property var propertiesProperty = redbObj.GetType().GetProperty("Props"); return propertiesProperty?.GetValue(redbObj); } /// /// Getting Props type from IRedbObject /// private static Type? GetPropertiesTypeFromRedbObject(IRedbObject redbObj) { // Get TProps from IRedbObject var objType = redbObj.GetType(); if (objType.IsGenericType) { return objType.GetGenericArguments()[0]; // TProps } return null; } /// /// Load all types into GlobalMetadataCache (1 query instead of N!). /// private async Task EnsureTypesCacheLoaded() { if (Cache.HasTypesByIdCache) return; var allTypes = await _context.QueryAsync( Sql.ObjectStorage_SelectAllTypes()); Cache.CacheTypesById(allTypes); } /// /// Checking if structure is Class type (business class) /// private async Task IsClassTypeStructure(IRedbStructure structure) { await EnsureTypesCacheLoaded(); var type = Cache.GetTypeById(structure.IdType); return type?.Type1 == "Object" || type?.Name == "Class"; } /// /// Checking if structure is IRedbObject reference /// private async Task IsRedbObjectStructure(IRedbStructure structure) { await EnsureTypesCacheLoaded(); var type = Cache.GetTypeById(structure.IdType); return type?.Type1 == "RedbObjectRow" || type?.Name == "Object"; } /// /// Checking if structure is ListItem reference /// private async Task IsListItemStructure(IRedbStructure structure) { await EnsureTypesCacheLoaded(); var type = Cache.GetTypeById(structure.IdType); return type?.Type1 == "RedbListItem" || type?.Name == "ListItem"; } /// /// Gets DbType for structure from cache. /// protected async Task GetStructureDbType(IRedbStructure structure) { await EnsureTypesCacheLoaded(); var type = Cache.GetTypeById(structure.IdType); return type?.DbType ?? "String"; } /// /// STEP 3: Assigning ID via GetNextKey() to all objects without ID /// protected async Task AssignMissingIds(List objects, IRedbUser user, CancellationToken cancellationToken = default) { // BATCH: Get all needed IDs in one DB call instead of N calls var objectsNeedingIds = objects.Where(o => o.Id == 0).ToList(); if (objectsNeedingIds.Count > 0) { var newIds = await _context.Keys.NextObjectIdBatchAsync(objectsNeedingIds.Count, cancellationToken); for (int i = 0; i < objectsNeedingIds.Count; i++) { var obj = objectsNeedingIds[i]; obj.Id = newIds[i]; // Apply audit settings obj.OwnerId = user.Id; obj.WhoChangeId = user.Id; if (_configuration.AutoSetModifyDate) { obj.DateCreate = DateTimeOffset.UtcNow; obj.DateModify = DateTimeOffset.UtcNow; } if (_configuration.AutoRecomputeHash) { obj.Hash = RedbHash.ComputeFor(obj); } } Data.AssignedIdRollback.ResetOnRollback(_context, objectsNeedingIds); } // Objects with existing IDs - no changes needed } /// /// STEP 4: Creating/verifying schemas for all object types (using PostgresSchemeSyncProvider) /// protected async Task EnsureSchemesForAllTypes(List objects, CancellationToken cancellationToken = default) { foreach (var obj in objects) { if (obj.SchemeId == 0 && _configuration.AutoSyncSchemesOnSave) { // Get object Props type via reflection var objType = obj.GetType(); if (objType.IsGenericType) { var propsType = objType.GetGenericArguments()[0]; // TProps from IRedbObject // Looking for existing schema var existingScheme = await _schemeSync.GetSchemeByTypeAsync(propsType); if (existingScheme != null) { obj.SchemeId = existingScheme.Id; } else { throw new InvalidOperationException( $"Scheme not found for type '{propsType.FullName}'. Register scheme first or enable AutoCreateSchemes."); } } } } } /// /// STEP 5: Recursive processing of Props of all objects → RedbValue lists /// NEW ARCHITECTURE: Uses a structure tree instead of a flat list! /// Skips non-generic RedbObject and RedbObject{TProps} with Props=null (0 records in _values) /// protected async Task ProcessAllObjectsPropertiesRecursively(List objects, List valuesList, ISet? skipUnchangedIds = null, CancellationToken cancellationToken = default) { foreach (var obj in objects) { // F1 (CT hash shortcut): an existing object whose recomputed content hash equals // the persisted one produces no value records at all - the CT diff never sees it, // so its rows stay untouched. The set is only supplied under ChangeTracking with // AutoRecomputeHash on (hash = content is the props-cache invariant). if (skipUnchangedIds != null && obj.Id > 0 && skipUnchangedIds.Contains(obj.Id)) continue; // Skip non-generic RedbObject (Object scheme) - no _values records var objType = obj.GetType(); if (objType == typeof(RedbObject)) { continue; } // Skip RedbObject (or a TreeRedbObject) with Props=null - no _values records if (Utils.RedbObjectTypes.GenericOf(objType) != null) { var propsProperty = objType.GetProperty("Props"); var propsValue = propsProperty?.GetValue(obj); if (propsValue == null) { continue; } } // Check that the schema exists (from cache without hash validation) var scheme = await GetSchemeFromCacheOrDbAsync(obj.SchemeId); if (scheme == null) { throw new InvalidOperationException( $"Scheme with Id={obj.SchemeId} not found for object Id={obj.Id}."); } // NEW LOGIC: Get the structure tree instead of a flat list var schemeProvider = (SchemeSyncProviderBase)_schemeSync; var rootStructureTree = await schemeProvider.GetSubtreeAsync(obj.SchemeId, null); // root nodes if (rootStructureTree.Count == 0) { try { // Create structures via a universal method var propsType = obj.GetType().GetGenericArguments()[0]; await SyncStructuresForType(scheme, propsType, cancellationToken); // Get the structure tree again schemeProvider.InvalidateStructureTreeCache(obj.SchemeId); // clear cache rootStructureTree = await schemeProvider.GetSubtreeAsync(obj.SchemeId, null); } catch { throw; } } // NEW TRAVERSAL: Via structure tree with subtrees! var valuesCountBefore = valuesList.Count; await ProcessPropertiesWithTreeStructures(obj, rootStructureTree, valuesList, objects); var valuesGenerated = valuesList.Count - valuesCountBefore; } } /// /// NEW METHOD: Props processing via structure tree /// Solves redundant structures issues and correct subtree passing /// internal async Task ProcessPropertiesWithTreeStructures(IRedbObject obj, List structureNodes, List valuesList, List objectsToSave) { var objPropertiesType = GetPropertiesTypeFromRedbObject(obj); foreach (var structureNode in structureNodes) { var dbTypeForLog = await GetStructureDbType(structureNode.Structure); var property = objPropertiesType?.GetProperty(structureNode.Structure.Name); if (property == null || property.GetIndexParameters().Length > 0) { continue; // SOLVES THE REDUNDANT STRUCTURES PROBLEM! } // Get the property value var objProperties = GetPropertiesFromRedbObject(obj); var rawValue = property.GetValue(objProperties); // NULL SEMANTICS if (!ObjectStorageProviderExtensions.ShouldCreateValueRecord(rawValue, structureNode.Structure.StoreNull ?? false)) { continue; } // CRITICAL DISPATCH BY TYPES if (structureNode.Structure.CollectionType == Core.Utils.RedbTypeIds.Dictionary) { await ProcessDictionaryWithSubtree(obj, structureNode, rawValue, valuesList, objectsToSave); } else if (structureNode.Structure.CollectionType == Core.Utils.RedbTypeIds.Array) { var arrayDbType = await GetStructureDbType(structureNode.Structure); await ProcessArrayWithSubtree(obj, structureNode, rawValue, valuesList, objectsToSave, null); } else if (await IsClassTypeStructure(structureNode.Structure)) { await ProcessBusinessClassWithSubtree(obj, structureNode, rawValue, valuesList, objectsToSave, null); // root class - no parent } else if (await IsRedbObjectStructure(structureNode.Structure)) { await ProcessIRedbObjectField(obj, structureNode.Structure, rawValue, objectsToSave, valuesList); } else { var dbTypeForLog2 = await GetStructureDbType(structureNode.Structure); await ProcessSimpleFieldWithTree(obj, structureNode, rawValue, valuesList); } } } /// /// Check if the type is a business class (not a primitive or an array) /// private static bool IsBusinessClassType(Type type) => CachedPredicate(BusinessClassTypeByType, type, static t => IsBusinessClassTypeCore(t)); private static bool IsBusinessClassTypeCore(Type type) { // Primitives and strings are not business classes if (type.IsPrimitive || type == typeof(string) || type == typeof(decimal) || type == typeof(DateTime) || type == typeof(DateTimeOffset) || type == typeof(TimeOnly) || type == typeof(DateOnly) || type == typeof(TimeSpan) || type == typeof(Guid)) return false; // Arrays are not business classes (processed separately) if (type.IsArray || (typeof(IEnumerable).IsAssignableFrom(type) && type != typeof(string))) return false; // IRedbObject is not a business class (processed separately) if (type.GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition().Name.Contains("IRedbObject"))) return false; // Task and Task<> are not business classes (technical types for async/await) if (type == typeof(Task) || (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Task<>))) return false; // IRedbListItem and RedbListItem are not business classes (dictionary elements, processed separately) if (type == typeof(IRedbListItem) || type == typeof(RedbListItem) || type.GetInterfaces().Contains(typeof(IRedbListItem))) return false; // Other classes are business classes return type.IsClass; } /// /// Universal method for creating structures for any type via reflection /// private async Task SyncStructuresForType(IRedbScheme scheme, Type propsType, CancellationToken cancellationToken = default) { // Use reflection to call the generic method SyncStructuresFromTypeAsync var method = typeof(SchemeSyncProviderBase) .GetMethod("SyncStructuresFromTypeAsync", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance); if (method != null) { var genericMethod = method.MakeGenericMethod(propsType); var result = await (Task>)genericMethod.Invoke(_schemeSync, new object[] { scheme, true , cancellationToken })!; } else { // Search for all methods for diagnostics var allMethods = typeof(SchemeSyncProviderBase).GetMethods(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance); var syncMethods = allMethods.Where(m => m.Name.Contains("Sync")).ToList(); foreach (var m in syncMethods) { } throw new InvalidOperationException($"Method SyncStructuresFromTypeAsync not found in SchemeSyncProviderBase"); } } // ===== NEW METHODS FOR WORKING WITH THE STRUCTURE TREE ===== /// /// Simple field with structure tree support /// private async Task ProcessSimpleFieldWithTree(IRedbObject obj, StructureTreeNode structureNode, object? rawValue, List valuesList) { var dbTypeForLog = await GetStructureDbType(structureNode.Structure); RefuseCollectionInSingleValue(obj, structureNode.Structure.Name, rawValue); // Process nested objects (IRedbObject, IRedbListItem) before saving var dbType = await GetStructureDbType(structureNode.Structure); if (rawValue is IRedbListItem && dbType == "Long") { throw new InvalidOperationException( $"Schema mismatch: field '{structureNode.Structure.Name}' has DbType='Long' but value is IRedbListItem. Update schema to use DbType='ListItem'."); } var processedValue = await ProcessNestedObjectsAsync(rawValue, dbType, false); var valueRecord = new RedbValue { Id = NextTemporaryValueId(), IdObject = obj.Id, IdStructure = structureNode.Structure.Id }; SetSimpleValueByType(valueRecord, dbType, processedValue); // A [RedbUnique] field carries the hash of its canonical value; the database enforces // uniqueness over it. NULL values get no key (never take part in uniqueness). if (structureNode.Structure.Unique == true) valueRecord.Unique = Utils.UniqueKeyEncoder.Compute(valueRecord); valuesList.Add(valueRecord); } /// /// Array with structure subtree /// private async Task ProcessArrayWithSubtree(IRedbObject obj, StructureTreeNode arrayStructureNode, object? rawValue, List valuesList, List objectsToSave, long? parentValueId = null) { var arraySubtreeDbType = await GetStructureDbType(arrayStructureNode.Structure); // Check schema mismatch for ListItem arrays if (arraySubtreeDbType == "Long" && rawValue is System.Collections.IEnumerable enumForCheck && rawValue is not string) { var firstItem = enumForCheck.Cast().FirstOrDefault(); if (firstItem is IRedbListItem) { throw new InvalidOperationException( $"Schema mismatch: array '{arrayStructureNode.Structure.Name}' has DbType='Long' but contains IRedbListItem. Update schema to use DbType='ListItem'."); } } if (rawValue == null) return; if (rawValue is not IEnumerable enumerable || rawValue is string) { throw new InvalidOperationException( $"Array field '{arrayStructureNode.Structure.Name}' expected IEnumerable but got '{rawValue.GetType().FullName}'."); } // A multi-dimensional array would be enumerated cell by cell and stored flat; refused before any row is // deleted or written (a scheme synced before the sync refused it). if (rawValue is Array { Rank: > 1 } grid) throw new Exceptions.RedbNestedCollectionException( OwnerNameForRefusal(obj), arrayStructureNode.Structure.Name, "a multi-dimensional array " + Exceptions.RedbNestedCollectionException.Display(grid.GetType())); // Create a base array record for both strategies var baseArrayRecord = new RedbValue { Id = NextTemporaryValueId(), IdObject = obj.Id, IdStructure = arrayStructureNode.Structure.Id, ArrayParentId = parentValueId // Guid will be set AFTER processing elements! }; valuesList.Add(baseArrayRecord); // Processing of array elements with correct subtree await ProcessArrayElementsWithSubtree(obj, arrayStructureNode, baseArrayRecord.Id, enumerable, valuesList, objectsToSave); // FINAL HASH: compute base array record hash from element hashes await ComputeArrayHashFromElements(baseArrayRecord, arrayStructureNode, valuesList, rawValue); } /// /// Save Dictionary field with base record + elements via _array_parent_id + _array_index (serialized key) /// private async Task ProcessDictionaryWithSubtree(IRedbObject obj, StructureTreeNode dictStructureNode, object? rawValue, List valuesList, List objectsToSave, long? parentValueId = null) { if (rawValue == null) return; // Dictionary implements IDictionary, but we need to get key-value pairs via reflection var dictType = rawValue.GetType(); // Fail closed (DataLoss p.3). A dictionary field whose runtime value is not a plain // Dictionary used to be skipped in silence, and under DeleteInsert the stored // values had already been deleted, so the field disappeared. This runs while the value // records are built, i.e. before the delete, so a refusal loses nothing. if (!dictType.IsGenericType || (dictType.GetGenericTypeDefinition() != typeof(Dictionary<,>) && dictType.GetGenericTypeDefinition() != typeof(IDictionary<,>))) { throw new InvalidOperationException( $"Dictionary field '{dictStructureNode.Structure.Name}' holds '{dictType.FullName}', " + "which cannot be stored as rows. Declare the field as Dictionary (or " + "IDictionary) and put a Dictionary instance in it."); } var keyType = dictType.GetGenericArguments()[0]; // Create BASE record for Dictionary with hash var dictHash = RedbHash.ComputeForProps(rawValue); var baseDictRecord = new RedbValue { Id = NextTemporaryValueId(), IdObject = obj.Id, IdStructure = dictStructureNode.Structure.Id, ArrayParentId = parentValueId, // FIX: For nested Dictionary, link to parent Class record Guid = dictHash // Hash of entire Dictionary }; valuesList.Add(baseDictRecord); // Get DbType for value type - check if it's a class type var isClassValue = await IsClassTypeStructure(dictStructureNode.Structure); var dbType = await GetStructureDbType(dictStructureNode.Structure); // Iterate dictionary entries var storedEntries = 0; var enumerator = ((System.Collections.IEnumerable)rawValue).GetEnumerator(); while (enumerator.MoveNext()) { var kvp = enumerator.Current; if (kvp == null) continue; // Get Key and Value via reflection var kvpType = kvp.GetType(); var key = kvpType.GetProperty("Key")!.GetValue(kvp); var value = kvpType.GetProperty("Value")!.GetValue(kvp); if (key == null) continue; // Skip null keys // Serialize key using RedbKeySerializer var serializedKey = RedbKeySerializer.SerializeObject(key, keyType); // SQL Server: _array_index is NVARCHAR(430). Refuse here, while the value records are built and before // any delete or insert, instead of a truncation error from the database in the middle of the save. if (_sql.DictionaryKeyMaxLength is { } keyLimit && serializedKey.Length > keyLimit) throw new Exceptions.RedbDictionaryKeyTooLongException( obj.Id, dictStructureNode.Structure.Name, serializedKey.Length, keyLimit); storedEntries++; // Create element record var elementRecord = new RedbValue { Id = NextTemporaryValueId(), IdObject = obj.Id, IdStructure = dictStructureNode.Structure.Id, ArrayParentId = baseDictRecord.Id, // Link to base Dictionary record ArrayIndex = serializedKey // Serialized key as string }; // If value is null, just add the record with null values if (value == null) { valuesList.Add(elementRecord); continue; } // Check if value is IRedbObject reference - by schema OR by C# type var isRedbObjectValue = await IsRedbObjectStructure(dictStructureNode.Structure) || IsRedbObjectType(value.GetType()); if (isRedbObjectValue) { // RedbObject value in Dictionary - save as reference with _Object field var redbObj = (IRedbObject)value; elementRecord.Object = redbObj.Id; elementRecord.Guid = redbObj.Hash; // V4 (L.2): the reference rides its own persisted hash valuesList.Add(elementRecord); } else if (isClassValue || dictStructureNode.Children.Count > 0) { // If value is Class type, create hash and save children recursively elementRecord.Guid = RedbHash.ComputeForProps(value); valuesList.Add(elementRecord); // Recursively process child fields using subtree await ProcessBusinessClassChildrenWithSubtree(obj, elementRecord.Id, value, dictStructureNode.Children, valuesList, objectsToSave); } else { RefuseNestedCollectionValue(obj, dictStructureNode.Structure.Name, value); // For simple types var processedValue = await ProcessNestedObjectsAsync(value, dbType, false); SetSimpleValueByType(elementRecord, dbType, processedValue); valuesList.Add(elementRecord); } ApplyElementKey(dictStructureNode.Structure, elementRecord, baseDictRecord.Id); } // S1: a subtree key - mirror the canonical content hash into the key. An EMPTY // dictionary claims no key, like an absent one. Element-scoped collections (S3) key // their ELEMENTS instead - the base row stays out of the index. if (dictStructureNode.Structure.Unique == true && dictStructureNode.Structure.UniqueScope is null && storedEntries > 0) baseDictRecord.Unique = Utils.UniqueKeyEncoder.Compute(baseDictRecord); } /// /// Array elements with structure subtree /// /// /// A simple element or dictionary value that is itself a collection (other than a string or byte[]) would /// be stored as the name of its type. The scheme sync refuses such a property; this catches a scheme synced /// before that, while the value rows are built, before any row is deleted or written. /// private static void RefuseNestedCollectionValue(IRedbObject obj, string propertyName, object value) { if (value is IEnumerable and not string and not byte[]) throw new Exceptions.RedbNestedCollectionException( OwnerNameForRefusal(obj), propertyName, "a collection element of type " + Exceptions.RedbNestedCollectionException.Display(value.GetType())); } /// /// A single-value property (one structure, not an array or a dictionary) that holds a collection would be stored /// as the name of its type. The scheme sync refuses such a declared type; this catches a scheme synced before /// that, while the value rows are built, before any row is deleted or written. /// private static void RefuseCollectionInSingleValue(IRedbObject obj, string propertyName, object? value) { if (value is IEnumerable and not string and not byte[]) throw new Exceptions.RedbUnsupportedCollectionException( OwnerNameForRefusal(obj), propertyName, value.GetType()); } private static string OwnerNameForRefusal(IRedbObject obj) { var generic = RedbObjectTypes.GenericOf(obj.GetType()); return generic != null ? Exceptions.RedbNestedCollectionException.Display(generic.GetGenericArguments()[0]) : obj.GetType().Name; } private async Task ProcessArrayElementsWithSubtree(IRedbObject obj, StructureTreeNode arrayStructureNode, long parentValueId, IEnumerable enumerable, List valuesList, List objectsToSave) { long actualParentId = parentValueId; int index = 0; foreach (var item in enumerable) { var elementRecord = new RedbValue { Id = NextTemporaryValueId(), IdObject = obj.Id, IdStructure = arrayStructureNode.Structure.Id, ArrayParentId = actualParentId, // Use found or created ID ArrayIndex = index.ToString() }; if (item != null) { var itemType = item.GetType(); // RECURSION WITH SUBTREES: different types of elements if (await IsRedbObjectStructure(arrayStructureNode.Structure)) { // IRedbObject array element - BULK STRATEGY: take ID directly var redbObj = (IRedbObject)item; var objectId = redbObj.Id; var objHash = redbObj.Hash; // V4 (L.2) elementRecord.Object = objectId; // _Object - special field for FK on _objects elementRecord.Guid = objHash; // RedbObject HASH for ChangeTracking! valuesList.Add(elementRecord); } else if (await IsListItemStructure(arrayStructureNode.Structure)) { // ListItem array element - take ID directly (similarly to IRedbObject) var listItem = (IRedbListItem)item; var listItemId = listItem.Id; elementRecord.ListItem = listItemId; // Write to the ListItem field // O-1/B-3: the id already lives in _listitem; the element needs no separate content // hash (the scalar and dictionary forms never wrote one). ListItem content lives // its own life. valuesList.Add(elementRecord); } else if (IsBusinessClassType(itemType)) { // Business class array element var itemHash = RedbHash.ComputeForProps(item); elementRecord.Guid = itemHash; valuesList.Add(elementRecord); // RECURSION: processing child fields with subtree await ProcessBusinessClassChildrenWithSubtree(obj, elementRecord.Id, item, arrayStructureNode.Children, valuesList, objectsToSave, index); } else { RefuseNestedCollectionValue(obj, arrayStructureNode.Structure.Name, item); // Simple array element var elementDbType = await GetStructureDbType(arrayStructureNode.Structure); // CRITICAL: Calling ProcessNestedObjectsAsync to extract ID from IRedbListItem! var processedValue = await ProcessNestedObjectsAsync(item, elementDbType, false); SetSimpleValueByType(elementRecord, elementDbType, processedValue); valuesList.Add(elementRecord); } } else { valuesList.Add(elementRecord); // null element } ApplyElementKey(arrayStructureNode.Structure, elementRecord, actualParentId); index++; } } /// /// S3: keys an ELEMENT row of a collection whose structure declares an element scope. /// The Collection scope salts the canon with the owning collection id, so only true /// in-collection duplicates collide; the Scheme scope keys the bare canon. References /// canonicalise by target id (the encoder checks _Object/_ListItem first), scalars by /// their typed column, class elements by their content hash. Rows of unkeyed or /// subtree-keyed collections, and rows with no canon (null elements), pass untouched. /// private static void ApplyElementKey(IRedbStructure structure, RedbValue elementRecord, long collectionId) { if (structure.Unique != true || structure.UniqueScope is null) return; var salt = structure.UniqueScope == (long)Core.Attributes.UniqueScope.Collection ? collectionId : (long?)null; elementRecord.Unique = Utils.UniqueKeyEncoder.Compute(elementRecord, salt); } /// /// Computing base array record hash from element hashes /// For RedbObject[] and ListItem[] - combines element hashes /// For others - uses standard array hash /// private async Task ComputeArrayHashFromElements(RedbValue baseArrayRecord, StructureTreeNode arrayStructureNode, List valuesList, object rawValue) { // Check the array element type var isRedbObjectArray = await IsRedbObjectStructure(arrayStructureNode.Structure); var isListItemArray = await IsListItemStructure(arrayStructureNode.Structure); if (isRedbObjectArray || isListItemArray) { // For RedbObject[] and ListItem[] - collect element hashes var elementHashes = valuesList .Where(v => v.ArrayParentId == baseArrayRecord.Id && !string.IsNullOrEmpty(v.ArrayIndex) && v.Guid.HasValue) .OrderBy(v => int.TryParse(v.ArrayIndex, out var idx) ? idx : 0) .Select(v => v.Guid!.Value) .ToList(); if (elementHashes.Any()) { // Combine element hashes into one array hash baseArrayRecord.Guid = RedbHash.CombineHashes(elementHashes); } else { // Empty array baseArrayRecord.Guid = Guid.Empty; } } else { // For business class and primitive arrays - standard hash baseArrayRecord.Guid = RedbHash.ComputeForProps(rawValue); } // S1: a subtree key - mirror the canonical content hash into the key. An EMPTY // array claims no key, like an absent one: "no content" must not collide between // objects. Element-scoped collections (S3) key their ELEMENTS instead. if (arrayStructureNode.Structure.Unique == true && arrayStructureNode.Structure.UniqueScope is null && valuesList.Any(v => v.ArrayParentId == baseArrayRecord.Id)) baseArrayRecord.Unique = Utils.UniqueKeyEncoder.Compute(baseArrayRecord); } /// /// Business class with structure subtree /// FIX: Added parentValueId for nested classes! /// private async Task ProcessBusinessClassWithSubtree(IRedbObject obj, StructureTreeNode classStructureNode, object? rawValue, List valuesList, List objectsToSave, long? parentValueId = null) { if (rawValue == null) { return; } // Compute UUID hash of the business class var classHash = RedbHash.ComputeForProps(rawValue); // Create base Class field record with hash in _Guid // FIX: Set ArrayParentId for nested classes! var classRecord = new RedbValue { Id = NextTemporaryValueId(), IdObject = obj.Id, IdStructure = classStructureNode.Structure.Id, ArrayParentId = parentValueId, // FIX: Link to the parent class! Guid = classHash }; // S1: a subtree key - the canonical content hash IS the value; encode it exactly // like a scalar Guid field so save, recompute and the GetByUnique probe share one // formula. (A class never carries an element scope - the validator rejects it.) if (classStructureNode.Structure.Unique == true && classStructureNode.Structure.UniqueScope is null) classRecord.Unique = Utils.UniqueKeyEncoder.Compute(classRecord); valuesList.Add(classRecord); // Process child fields with the correct subtree! await ProcessBusinessClassChildrenWithSubtree(obj, classRecord.Id, rawValue, classStructureNode.Children, valuesList, objectsToSave); } /// /// Recursive processing of child fields of a business class with subtree /// private async Task ProcessBusinessClassChildrenWithSubtree(IRedbObject obj, long parentValueId, object businessObject, List childrenSubtree, List valuesList, List objectsToSave, int? parentArrayIndex = null) { var businessType = businessObject.GetType(); foreach (var childStructureNode in childrenSubtree) { // PROPERTY EXISTENCE CHECK IN C# CLASS var property = businessType.GetProperty(childStructureNode.Structure.Name); if (property == null || property.GetIndexParameters().Length > 0) { continue; } var childValue = property.GetValue(businessObject); // NULL SEMANTICS if (!ObjectStorageProviderExtensions.ShouldCreateValueRecord(childValue, childStructureNode.Structure.StoreNull ?? false)) { continue; } // RECURSIVE PROCESSING with correct subtrees if (childStructureNode.Structure.CollectionType == Core.Utils.RedbTypeIds.Dictionary) { // FIX: Pass parentValueId for nested Dictionary inside Class await ProcessDictionaryWithSubtree(obj, childStructureNode, childValue, valuesList, objectsToSave, parentValueId); } else if (childStructureNode.Structure.CollectionType == Core.Utils.RedbTypeIds.Array) { // FIX: Pass parentValueId for nested arrays await ProcessArrayWithSubtree(obj, childStructureNode, childValue, valuesList, objectsToSave, parentValueId); } else if (await IsClassTypeStructure(childStructureNode.Structure)) { // FIX: Pass parentValueId for nested classes! await ProcessBusinessClassWithSubtree(obj, childStructureNode, childValue, valuesList, objectsToSave, parentValueId); } else if (await IsRedbObjectStructure(childStructureNode.Structure)) { await ProcessIRedbObjectField(obj, childStructureNode.Structure, childValue, objectsToSave, valuesList, parentValueId, parentArrayIndex); } else { // Create a child field record linked to the parent Class field var childRecord = new RedbValue { Id = NextTemporaryValueId(), IdObject = obj.Id, IdStructure = childStructureNode.Structure.Id, ArrayParentId = parentValueId, ArrayIndex = parentArrayIndex?.ToString() // Inherit ArrayIndex if it's an array element }; RefuseCollectionInSingleValue(obj, childStructureNode.Structure.Name, childValue); var childDbType = await GetStructureDbType(childStructureNode.Structure); SetSimpleValueByType(childRecord, childDbType, childValue); // S2: a [RedbUnique] nested scalar carries the hash of its canonical value // exactly like a root field - same encoder, same index. The validator only // flags structures on collection-free paths, so this is the object's single // row of the structure. if (childStructureNode.Structure.Unique == true) childRecord.Unique = Utils.UniqueKeyEncoder.Compute(childRecord); valuesList.Add(childRecord); } } } /// /// IRedbObject field processing with ID search in the object collector /// private async Task ProcessIRedbObjectField(IRedbObject obj, IRedbStructure structure, object? redbObjectValue, List objectsToSave, List valuesList, long? parentValueId = null, int? parentArrayIndex = null) { if (structure.CollectionType == Core.Utils.RedbTypeIds.Array) { // IRedbObject ARRAY await ProcessIRedbObjectArray(obj, structure, (IEnumerable)redbObjectValue!, objectsToSave, valuesList, parentValueId); } else { // SINGLE IRedbObject await ProcessSingleIRedbObject(obj, structure, (IRedbObject)redbObjectValue!, objectsToSave, valuesList, parentValueId, parentArrayIndex); } } /// /// Single IRedbObject with ID search in the collector /// private async Task ProcessSingleIRedbObject(IRedbObject obj, IRedbStructure structure, IRedbObject redbObjectValue, List objectsToSave, List valuesList, long? parentValueId = null, int? parentArrayIndex = null) { // BULK STRATEGY: Take ID directly from the object (already saved recursively) var objectId = redbObjectValue.Id; var record = new RedbValue { Id = NextTemporaryValueId(), IdObject = obj.Id, IdStructure = structure.Id, Object = objectId, // FIX: _Object - FK to _objects ArrayParentId = parentValueId // FIX: link to parent element record (unique per array element) // ArrayIndex NOT set: parent element record ID is sufficient for disambiguation }; valuesList.Add(record); } /// /// IRedbObject array with ID search in the collector /// private async Task ProcessIRedbObjectArray(IRedbObject obj, IRedbStructure structure, IEnumerable redbObjectArray, List objectsToSave, List valuesList, long? parentValueId = null) { // Create base array record var arrayHash = RedbHash.ComputeForProps((object)redbObjectArray); var baseArrayRecord = new RedbValue { Id = NextTemporaryValueId(), IdObject = obj.Id, IdStructure = structure.Id, ArrayParentId = parentValueId, // FIX: link to parent element Guid = arrayHash }; valuesList.Add(baseArrayRecord); // Process array elements int index = 0; var storedElements = 0; foreach (var item in redbObjectArray) { if (item != null && IsRedbObjectType(item.GetType())) { // BULK STRATEGY: Take ID directly from the object (already saved recursively) var redbObj = (IRedbObject)item; var objectId = redbObj.Id; var elementRecord = new RedbValue { Id = NextTemporaryValueId(), IdObject = obj.Id, IdStructure = structure.Id, ArrayParentId = baseArrayRecord.Id, ArrayIndex = index.ToString(), Object = objectId // FIX: _Object - FK to _objects }; // S3: an element-scoped reference collection keys each link by target id. ApplyElementKey(structure, elementRecord, baseArrayRecord.Id); valuesList.Add(elementRecord); storedElements++; } index++; } // S1: a subtree key on a REFERENCE collection - "unique SET of references". The // content hash mirrors into the key exactly like the other collection builders; // an EMPTY collection claims no key. if (structure.Unique == true && structure.UniqueScope is null && storedElements > 0) baseArrayRecord.Unique = Utils.UniqueKeyEncoder.Compute(baseArrayRecord); } // SetSimpleValueByType already exists in main file ObjectStorageProviderBase.cs /// /// Structure with full information for ChangeTracking /// public class StructureFullInfo { public string DbType { get; set; } = "String"; public bool IsArray { get; set; } public bool StoreNull { get; set; } } /// /// Updates existing value fields from new value (only significant fields). /// protected void UpdateExistingValueFields(RedbValue existingValue, RedbValue newValue, Dictionary structuresInfo) { if (!structuresInfo.TryGetValue(newValue.IdStructure, out var dbType)) { throw new InvalidOperationException( $"Structure Id={newValue.IdStructure} not found in structuresInfo dictionary."); } // The key follows the value: recomputed by the builder for the new value, carried here. existingValue.Unique = newValue.Unique; // If newValue contains Object or ListItem - copy them regardless of DbType if (newValue.Object.HasValue) { existingValue.Object = newValue.Object; existingValue.Guid = newValue.Guid; return; } if (newValue.ListItem.HasValue) { existingValue.ListItem = newValue.ListItem; existingValue.Guid = newValue.Guid; return; } // Update only significant field by DbType switch (dbType) { case "String": existingValue.String = newValue.String; break; case "Long": existingValue.Long = newValue.Long; break; case "Double": existingValue.Double = newValue.Double; break; case "Numeric": // ADDED existingValue.Numeric = newValue.Numeric; break; case "DateTime": // Backward compatibility case "DateTimeOffset": existingValue.DateTimeOffset = newValue.DateTimeOffset; break; case "Boolean": existingValue.Boolean = newValue.Boolean; break; case "Guid": existingValue.Guid = newValue.Guid; break; case "ByteArray": existingValue.ByteArray = newValue.ByteArray; break; case "Object": // ADDED existingValue.Object = newValue.Object; break; case "ListItem": // ADDED existingValue.ListItem = newValue.ListItem; break; } // COLLECTION base row: the structure dbType is the ELEMENT type (Long/Numeric/...), // while the meaningful field of the base row is the canonical content hash in _Guid. // Without this line a CT element edit copied the element column (null -> null) and // left the OLD array hash in the database (CT-2 review, proven by the pin // CtSaveInvariantsTestsBase.ArrayBaseHash_AfterEdit_MatchesTheCanonicalHash). // For dbType == "Guid" (Guid fields, class nodes) the hash is already copied by the switch branch. if (newValue.Guid.HasValue && dbType != "Guid") existingValue.Guid = newValue.Guid; } /// /// Deduplicates value update list by Id to prevent MERGE/UPDATE conflicts /// when the same value ID appears in updates from multiple tree comparison paths /// (e.g. shared RedbObject references). Logs a warning if duplicates are detected. /// protected List DeduplicateValueUpdates(List values, string caller) { if (values.Count <= 1) return values; var grouped = values.GroupBy(v => v.Id).ToList(); if (grouped.Count == values.Count) return values; // No duplicates — fast path var duplicateCount = values.Count - grouped.Count; var duplicateGroups = grouped.Where(g => g.Count() > 1).ToList(); foreach (var g in duplicateGroups) { var entries = g.ToList(); var first = entries[0]; Logger?.LogWarning( "REDB {Caller}: duplicate value _id={ValueId} (IdObject={IdObject}, IdStructure={IdStructure}, " + "ArrayParentId={ArrayParentId}, ArrayIndex={ArrayIndex}) appears {Count} times in pending updates. " + "Keeping last entry.", caller, g.Key, first.IdObject, first.IdStructure, first.ArrayParentId, first.ArrayIndex, entries.Count); } return grouped.Select(g => g.Last()).ToList(); } /// /// Deduplicates value insert list by unique constraint key (IdStructure, IdObject, ArrayParentId, ArrayIndex) /// to prevent duplicate key violations on UIX__values__structure_object* indexes. /// Preserves insertion order, keeps the FIRST entry for each key — because subsequent values /// may reference the first value's Id via _array_parent_id FK (self-referencing). /// protected List DeduplicateValueInserts(List values, string caller) { if (values.Count <= 1) return values; var seen = new HashSet<(long, long, long?, string?)>(values.Count); var result = new List(values.Count); foreach (var v in values) { var key = (v.IdStructure, v.IdObject, v.ArrayParentId, v.ArrayIndex); if (seen.Add(key)) result.Add(v); } if (result.Count == values.Count) return values; // no duplicates — return original var duplicateCount = values.Count - result.Count; Logger?.LogWarning( "REDB {Caller}: {DuplicateCount} duplicate value inserts detected and removed " + "(total {Total} -> {Unique}). Duplicates by (IdStructure, IdObject, ArrayParentId, ArrayIndex).", caller, duplicateCount, values.Count, result.Count); return result; } #region BULK DELETEINSERT OPTIMIZATION #endregion #region CACHE UPDATE // The load path writes nested entries in one walk (GlobalPropsCache.SetGraph); the save path keeps no // separate nested walk here. #endregion } } Path: redb/redb.Core/Providers/Base/ObjectStorageProviderBase.SaveAsyncBatch.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/ObjectStorageProviderBase.SaveAsyncBatch.cs ---- #pragma warning disable CS0618 // implements or uses the deprecated object permissions and roles (RedbDeprecation) using redb.Core.Providers; using redb.Core.Data; using redb.Core.Utils; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using redb.Core.Models.Configuration; using redb.Core.Models.Security; using redb.Core.Caching; using redb.Core.Query; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace redb.Core.Providers.Base { /// /// BATCH SAVE - high-performance saving of multiple objects /// Supports two strategies: DeleteInsert (bulk operations) and ChangeTracking (EF diff) /// public abstract partial class ObjectStorageProviderBase { /// /// Convert IRedbObject to RedbObjectRow for bulk operations /// Uses 'as' optimization for direct access to RedbObject fields. /// protected RedbObjectRow ConvertToObjectRecord(IRedbObject obj) { var redbObj = obj as RedbObject; // Optimization: direct access to fields var record = new RedbObjectRow { Id = redbObj?.id ?? obj.Id, IdScheme = redbObj?.scheme_id ?? obj.SchemeId, IdParent = (redbObj?.parent_id ?? obj.ParentId) == 0 ? null : (redbObj?.parent_id ?? obj.ParentId), IdOwner = redbObj?.owner_id ?? obj.OwnerId, IdWhoChange = redbObj?.who_change_id ?? obj.WhoChangeId, Name = redbObj?.name ?? obj.Name, Hash = redbObj?.hash ?? obj.Hash, ValueUnique = redbObj?.value_unique ?? obj.ValueUnique, DateBegin = redbObj?.date_begin ?? obj.DateBegin, DateComplete = redbObj?.date_complete ?? obj.DateComplete, Key = redbObj?.key ?? obj.Key, ValueLong = redbObj?.value_long ?? obj.ValueLong, ValueString = redbObj?.value_string ?? obj.ValueString, ValueGuid = redbObj?.value_guid ?? obj.ValueGuid, ValueBool = redbObj?.value_bool ?? obj.ValueBool, ValueDouble = redbObj?.value_double ?? obj.ValueDouble, ValueNumeric = redbObj?.value_numeric ?? obj.ValueNumeric, ValueDatetime = redbObj?.value_datetime ?? obj.ValueDatetime, ValueBytes = redbObj?.value_bytes ?? obj.ValueBytes, Note = redbObj?.note ?? obj.Note }; // Handle creation/modification dates based on configuration if (_configuration.AutoSetModifyDate) { if (record.Id == 0) { record.DateCreate = DateTimeOffset.UtcNow; } else { // For existing objects - take the old value var existingDate = redbObj?.date_create ?? obj.DateCreate; // If the date was not set (MinValue), use the current one record.DateCreate = existingDate == DateTimeOffset.MinValue ? DateTimeOffset.UtcNow : existingDate; } record.DateModify = DateTimeOffset.UtcNow; } else { var dateCreate = redbObj?.date_create ?? obj.DateCreate; // If the date was not set (MinValue), use the current one record.DateCreate = dateCreate == DateTimeOffset.MinValue ? DateTimeOffset.UtcNow : dateCreate; var dateModify = redbObj?.date_modify ?? obj.DateModify; record.DateModify = dateModify == DateTimeOffset.MinValue ? DateTimeOffset.UtcNow : dateModify; } // The saved object carries the dates its row gets. For an existing object DateCreate // already holds the stored value (SelectExistingAndTakeCreateDatesAsync), which the // update leaves untouched in the database. obj.DateCreate = record.DateCreate; obj.DateModify = record.DateModify; return record; } /// /// A row of the existing-objects query: an existing object (Id, DateCreate and its scheme's hash), or one of the /// listed schemes (Id 0, DateCreate null), so that a save of new objects only learns the hashes as well. /// private sealed class IdDateCreateRow { public long Id { get; set; } public DateTimeOffset? DateCreate { get; set; } /// The structure hash of the scheme as stored now; null from a dialect that does not read it. public Guid? SchemeHash { get; set; } public long SchemeId { get; set; } } /// /// The existing-objects query: the rows of that exist, and the stored structure hash /// of every scheme of , in one statement. The object part is the query it always was, /// on the object ids; the scheme part reads _schemes by its key. /// private async Task<(List Existing, Dictionary HashByScheme)> SelectExistingAndSchemeHashesAsync( long[] objectIds, IEnumerable objects, System.Threading.CancellationToken cancellationToken) { var schemeIds = objects.Select(o => o.SchemeId).Where(id => id != 0).Distinct().ToArray(); var rows = await _context.QueryAsync( Sql.ObjectStorage_SelectExistingCreateDates(), new object[] { objectIds, schemeIds }, cancellationToken); var hashByScheme = new Dictionary(); foreach (var row in rows) hashByScheme[row.SchemeId] = row.SchemeHash; return (rows.Where(r => r.Id != 0).ToList(), hashByScheme); } /// /// The save's view of each scheme against the database, from the hashes the existing-objects query already /// returns (no round trip of its own): a cached scheme whose hash differs is read again, so a field or a version a /// newer build wrote since is seen by this save. Then the version rule: a class older than the version the scheme /// was synchronised with saves nothing of it (a newer build may have removed fields or changed types). Every /// object of the save counts, new ones included. Returns whether a scheme was read again. /// private async Task RefreshStaleSchemesAsync( IEnumerable objects, Dictionary hashByScheme, System.Threading.CancellationToken cancellationToken) { var readAgain = false; foreach (var group in objects.Where(o => hashByScheme.ContainsKey(o.SchemeId)).GroupBy(o => (o.SchemeId, Type: o.GetType()))) { var generic = RedbObjectTypes.GenericOf(group.Key.Type); if (generic == null) continue; var propsType = generic.GetGenericArguments()[0]; var stored = hashByScheme[group.Key.SchemeId]; var scheme = await _schemeSync.GetSchemeByTypeAsync(propsType, cancellationToken); if (scheme == null || scheme.Id != group.Key.SchemeId) continue; if (stored.HasValue && scheme.StructureHash != stored) { // The invalidation drops the structure trees of the scheme as well (GlobalMetadataCache). Cache.InvalidateScheme(scheme.Id); Cache.InvalidateScheme(scheme.Name); readAgain = true; scheme = await _schemeSync.GetSchemeByIdAsync(scheme.Id, cancellationToken); if (scheme == null) continue; } var classVersion = System.Reflection.CustomAttributeExtensions.GetCustomAttribute(propsType)?.Version ?? 0; var storedVersion = (scheme as RedbScheme)?.Version ?? 0; if (storedVersion > classVersion) throw new Exceptions.RedbPropsClassOlderException(scheme.Name, propsType, classVersion, storedVersion); } return readAgain; } /// /// A scheme of the save was changed by another process since this one cached it, and was read again before /// anything was written: the save builds its value rows again from the current structures and runs once more. /// The check is the first statement of each strategy, after the object locks only. /// private sealed class SchemeReadAgainException : Exception { } /// How many times one save builds its rows again after a scheme changed under it. private const int SchemeReadAgainLimit = 2; /// /// Ids of the objects that exist in the database. Each existing object takes its stored /// creation date: an object built in memory (from JSON, say) and saved onto an existing row /// had DateCreate 0001-01-01 after the save, while the row kept its own date. /// Only the ids the caller set are looked up: an object this save gave its id is new (); /// a save of new objects only sends the scheme part of the statement alone. /// /// /// An object saved under the id of a stored object of another scheme (a different class, or an object in the trash, /// scheme -10): the update kept the stored scheme, deleted its values and wrote the values of the saved class /// into it. Refused before anything is written, from the scheme the existing-objects query already returns. /// private static void RefuseOtherSchemeObjects(List objects, List rows) { if (rows.Count == 0) return; var storedScheme = rows.ToDictionary(r => r.Id, r => r.SchemeId); foreach (var obj in objects) { if (obj.Id != 0 && obj.SchemeId != 0 && storedScheme.TryGetValue(obj.Id, out var stored) && stored != obj.SchemeId) { var type = obj.GetType().IsGenericType ? obj.GetType().GetGenericArguments()[0] : obj.GetType(); throw new Exceptions.RedbSchemeMismatchException(obj.Id, type, obj.SchemeId, stored, $"Object {obj.Id} belongs to scheme {stored}" + (stored == Utils.RedbTypeIds.DeletedScheme ? " (it is in the trash)" : "") + $", but was saved as '{type.FullName ?? type.Name}' which maps to scheme {obj.SchemeId}. " + "Saving it would delete its values and write the values of another class into it; nothing was " + "written. Save a new object (id 0) or load the object under its own class."); } } } protected async Task> SelectExistingAndTakeCreateDatesAsync( List objects, System.Threading.CancellationToken cancellationToken) { if (objects.Count == 0) return new HashSet(); var created = _createdBySave; var ids = objects.Where(o => created == null || !created.Contains(o)).Select(o => o.Id).ToArray(); var (rows, hashByScheme) = await SelectExistingAndSchemeHashesAsync(ids, objects, cancellationToken); RefuseOtherSchemeObjects(objects, rows); var createdById = rows.ToDictionary(r => r.Id, r => r.DateCreate!.Value); // The value rows of this save were built from the trees of the schemes as they were cached: built again. if (await RefreshStaleSchemesAsync(objects, hashByScheme, cancellationToken)) throw new SchemeReadAgainException(); foreach (var obj in objects) { if (createdById.TryGetValue(obj.Id, out var dateCreate)) obj.DateCreate = dateCreate; } return createdById.Keys.ToHashSet(); } // ===== PUBLIC BATCH SAVE METHODS ===== /// /// BATCH SAVE: Save multiple objects (new + updates) /// Uses _securityContext to get the user /// public async Task> SaveAsync(IEnumerable objects, CancellationToken cancellationToken = default) { var effectiveUser = _securityContext.GetEffectiveUser(); return await SaveAsync(objects, effectiveUser, cancellationToken); } /// /// BATCH SAVE with explicit user /// Supports two strategy modes: /// - DeleteInsert: delete ALL values → BulkInsert/BulkUpdate of objects → BulkInsert of values /// - ChangeTracking: tree-based diff → two-phase EF SaveChanges /// public async Task> SaveAsync(IEnumerable objects, IRedbUser user, CancellationToken cancellationToken = default) { // CT-4 (решение владельца 2026-09-04, «как у EF»): контракт «один scope - один // поток» защищён операционным детектором уровня EF DbContext. Командный страж // соединения ловит только НАЛОЖИВШИЕСЯ команды; два перемежающихся async-сохранения // могли молча перемешать pending-состояние ChangeTracking и транзакции. Вход - // синхронно, до первого await, поэтому второй параллельный заход детерминированно // получает исключение. if (System.Threading.Interlocked.CompareExchange(ref _saveOperationInFlight, 1, 0) != 0) throw new InvalidOperationException( "A second SaveAsync started on this IRedbService scope before a previous one " + "completed. Один scope - это одно соединение и одно операционное состояние " + "(как DbContext в EF): параллельные сохранения ведите через отдельные scoped-сервисы."); try { return await SaveBatchCoreAsync(objects, user, cancellationToken); } finally { _createdBySave = null; System.Threading.Interlocked.Exchange(ref _saveOperationInFlight, 0); } } private int _saveOperationInFlight; /// /// The objects of the running save that got their id from it (AssignMissingIds). They are new by definition and /// are never looked up as existing: an id the key cache handed out twice (a block cached before a restore or an /// import) then fails on the primary key instead of updating the row that has the id. Set and cleared by the /// batch save; one save at a time per scope (CT-4). /// private HashSet? _createdBySave; private sealed class IdHashRow { public long Id { get; set; } public Guid? Hash { get; set; } } /// /// F1 (CT hash shortcut): ids of existing objects whose freshly recomputed content hash /// equals the persisted _objects._hash. Root hashes come free with the phase-1 /// existence check; one extra SELECT runs only when the collected graph brought nested /// existing objects. An object with no in-memory hash or no persisted hash is never listed /// (legacy hashes computed by an older canon simply fail the comparison and take the full /// path, migrating on save). /// private async Task?> SelectUnchangedByHashAsync( List allObjectsToSave, Dictionary dbHashById, CancellationToken cancellationToken) { var candidates = allObjectsToSave.Where(o => o.Id > 0 && o.Hash.HasValue).ToList(); if (candidates.Count == 0) return null; var missingIds = candidates.Where(o => !dbHashById.ContainsKey(o.Id)) .Select(o => o.Id).Distinct().ToArray(); if (missingIds.Length > 0) { var rows = await _context.QueryAsync( Sql.ObjectStorage_SelectIdHashPairs(), new object[] { missingIds }, cancellationToken); foreach (var row in rows) dbHashById[row.Id] = row.Hash; } var unchanged = new HashSet(); foreach (var obj in candidates) { if (dbHashById.TryGetValue(obj.Id, out var dbHash) && dbHash.HasValue && dbHash.Value == obj.Hash!.Value) unchanged.Add(obj.Id); } return unchanged.Count > 0 ? unchanged : null; } private async Task> SaveBatchCoreAsync(IEnumerable objects, IRedbUser user, CancellationToken cancellationToken) { var objList = objects.ToList(); if (objList.Count == 0) return new List(); foreach (var obj in objList) RefuseUnloadedReference(obj); // === PHASE 1: VALIDATION AND PREPARATION (BATCH OPTIMIZATION) === // STEP 1: Hash recomputation (in-memory, no DB queries) // Supports: RedbObject with Props, RedbObject with Props=null, RedbObject (non-generic) foreach (var obj in objList) RecomputeHash(obj); // STEP 2: BATCH existence check (1 query instead of N!) // F1: under ChangeTracking the same query also returns the persisted hash of each // existing root, so the hash shortcut costs no extra round-trip for the typical save. // Other strategies keep the id-only query - they never consult the hashes. var ctShortcutActive = _configuration.PropsSaveStrategy == PropsSaveStrategy.ChangeTracking && _configuration.AutoRecomputeHash; var existingIds = objList.Where(o => o.Id != 0).Select(o => o.Id).ToArray(); var dbHashById = new Dictionary(existingIds.Length); HashSet existingIdsSet; if (existingIds.Length == 0) { existingIdsSet = new HashSet(); } else if (ctShortcutActive) { var idHashRows = await _context.QueryAsync( Sql.ObjectStorage_SelectIdHashPairs(), new object[] { existingIds }, cancellationToken); foreach (var row in idHashRows) dbHashById[row.Id] = row.Hash; existingIdsSet = dbHashById.Keys.ToHashSet(); } else { var loadedIds = await _context.QueryScalarListAsync( Sql.ObjectStorage_SelectExistingIds(), new object[] { existingIds }, cancellationToken); existingIdsSet = loadedIds.ToHashSet(); } // Processing of missing objects foreach (var obj in objList.Where(o => o.Id != 0 && !existingIdsSet.Contains(o.Id))) { switch (_configuration.MissingObjectStrategy) { case MissingObjectStrategy.AutoSwitchToInsert: obj.Id = 0; break; case MissingObjectStrategy.ReturnNull: throw new InvalidOperationException($"Object with id {obj.Id} not found. Strategy: ReturnNull is not supported."); case MissingObjectStrategy.ThrowException: default: throw new InvalidOperationException($"Object with id {obj.Id} not found."); } } // STEP 3: BATCH auto-detection of schemes (caching by type) var schemeCache = new Dictionary(); long? objectSchemeId = null; // Cache for non-generic RedbObject scheme foreach (var obj in objList.Where(o => o.SchemeId == 0 && _configuration.AutoSyncSchemesOnSave)) { var objType = obj.GetType(); var genericObjType = Utils.RedbObjectTypes.GenericOf(objType); if (genericObjType != null) { var propsType = genericObjType.GetGenericArguments()[0]; // Check cache if (schemeCache.TryGetValue(propsType, out var cachedSchemeId)) { obj.SchemeId = cachedSchemeId; continue; } // Load/sync the scheme (select generic overload without parameters) var getSchemeMethod = typeof(ISchemeSyncProvider) .GetMethods() .FirstOrDefault(m => m.Name == nameof(ISchemeSyncProvider.GetSchemeByTypeAsync) && m.IsGenericMethod && m.GetParameters() is [{ ParameterType.Name: nameof(CancellationToken) }])? .MakeGenericMethod(propsType); if (getSchemeMethod != null) { var existingSchemeTask = (Task?)getSchemeMethod.Invoke(_schemeSync, new object[] { cancellationToken }); if (existingSchemeTask != null) { await existingSchemeTask.ConfigureAwait(false); var existingScheme = existingSchemeTask.GetType().GetProperty("Result")?.GetValue(existingSchemeTask) as IRedbScheme; if (existingScheme != null) { obj.SchemeId = existingScheme.Id; schemeCache[propsType] = existingScheme.Id; } else if (_configuration.AutoSyncSchemesOnSave) { var syncMethod = typeof(ISchemeSyncProvider) .GetMethods() .FirstOrDefault(m => m.Name == nameof(ISchemeSyncProvider.SyncSchemeAsync) && m.IsGenericMethod && m.GetParameters() is [{ ParameterType.Name: nameof(CancellationToken) }])? .MakeGenericMethod(propsType); if (syncMethod != null) { var syncTask = (Task?)syncMethod.Invoke(_schemeSync, new object[] { cancellationToken }); if (syncTask != null) { await syncTask.ConfigureAwait(false); var scheme = syncTask.GetType().GetProperty("Result")?.GetValue(syncTask) as IRedbScheme; if (scheme != null) { obj.SchemeId = scheme.Id; schemeCache[propsType] = scheme.Id; } } } } } } } else if (objType == typeof(RedbObject)) { // Non-generic RedbObject - use Object scheme if (objectSchemeId == null) { var objectScheme = await _schemeSync.EnsureObjectSchemeAsync("RedbObject"); objectSchemeId = objectScheme.Id; } obj.SchemeId = objectSchemeId.Value; } } // STEP 4: BATCH permissions check if (_configuration.DefaultCheckPermissionsOnSave) { // Load unique schemes once var uniqueSchemeIds = objList.Select(o => o.SchemeId).Distinct().ToArray(); var schemesList = await _context.QueryAsync( Sql.ObjectStorage_SelectSchemesByIds(), new object[] { uniqueSchemeIds }, cancellationToken); var schemesDict = schemesList.ToDictionary(s => s.Id, s => s); // Check INSERT permissions for new objects var newObjectsByScheme = objList.Where(o => o.Id == 0).GroupBy(o => o.SchemeId); foreach (var group in newObjectsByScheme) { if (schemesDict.TryGetValue(group.Key, out var schemeContract)) { var canInsert = await _permissionProvider.CanUserInsertScheme(schemeContract, user); if (!canInsert) { throw new UnauthorizedAccessException($"User {user.Id} has no create permission for objects in scheme {group.Key}"); } } } // Check UPDATE permissions for existing objects foreach (var obj in objList.Where(o => o.Id != 0)) { var canUpdate = await _permissionProvider.CanUserEditObject(obj, user); if (!canUpdate) { throw new UnauthorizedAccessException($"User {user.Id} has no update permission for object {obj.Id}"); } } } // === PHASE 2: COLLECTION OF ALL OBJECTS (MAIN + NESTED) === var allObjectsToSave = new List(); var allValuesToSave = new List(); var processedObjectIds = new HashSet(); var seenInstances = new HashSet(ReferenceEqualityComparer.Instance); var referenceStubs = new List(); foreach (var obj in objList) { await CollectAllObjectsRecursively(obj, allObjectsToSave, processedObjectIds, seenInstances, referenceStubs); } await ResolveReferenceHashesAsync(referenceStubs, cancellationToken); await EnsureNoHeldShapesAsync(allObjectsToSave, cancellationToken); // Interceptors, EF-style (discussion #12, review pass): Saving runs right after the // graph is collected and BEFORE ids, hashes and the unchanged-set are computed - so an // interceptor may MUTATE Props (EF's own SavingChanges contract) and everything below // is derived from what it left. Ran later, an edit here would desynchronize the stored // hash from the content and let the F1 shortcut silently skip the edited object. The // price is EF's too: objects this save creates still show Id == 0 (temporary-key // semantics) - their final ids arrive in SavedAsync. An exception here cancels the // save cleanly: no id was burned, nothing touched the database. // One snapshot for the whole save: Saving and Saved reach the same interceptors even when a run-time // subscription comes or goes meanwhile, and the change feed is collected exactly when they listen. InterceptorChangeSink = null; List? newObjectRefs = null; var interceptors = SnapshotSaveInterceptors(); if (interceptors.Count > 0) { if (_configuration.PropsSaveStrategy == PropsSaveStrategy.ChangeTracking) InterceptorChangeSink = new List(); // "Created by this save" = arrived without an id; the references keep carrying // their final ids once assigned below (SavedAsync reads them then). newObjectRefs = allObjectsToSave.Where(o => o.Id == 0).ToList(); await InvokeSavingInterceptorsAsync(interceptors, new Interception.RedbSavingContext { RootObjects = objList, AllObjects = allObjectsToSave, EffectiveUser = user, Strategy = _configuration.PropsSaveStrategy, NewObjects = newObjectRefs, }, cancellationToken); } // The objects that existed before this save, taken before AssignMissingIds gives the new ones their ids: // only these rows are locked in phase 4. Locking the ids of objects this save creates locked rows that do // not exist yet, and on SQL Server the lock statement then read the rows of concurrent writers. var existingObjectIds = allObjectsToSave.Where(o => o.Id > 0).Select(o => o.Id).ToArray(); _createdBySave = new HashSet(allObjectsToSave.Where(o => o.Id == 0), ReferenceEqualityComparer.Instance); // === PHASE 3: BATCH PROCESSING (REUSING PROTECTED METHODS) === await AssignMissingIds(allObjectsToSave, user, cancellationToken); // V4 (L.2): hashes are final only once ids exist - the parent's hash carries "id:hash" of // every reference, so an object created in this save (id 0 until now) would leave "0:" // in its parent's persisted hash: unreproducible on reload, a props-cache miss for ever // and a hash shift on the first re-save. Children first, then their parents, across the // graph; an existing nested object re-saved through its parent gets its content hash // refreshed the same way - its row is rewritten anyway (review). if (_configuration.AutoRecomputeHash) RecomputeHashesPostOrder(allObjectsToSave); await EnsureSchemesForAllTypes(allObjectsToSave, cancellationToken); // F1 (CT hash shortcut, perf wave 1): under ChangeTracking, existing objects whose // recomputed hash equals the persisted one skip the whole value pipeline - building // value records, the existing-values SELECT, both trees and the diff. Their _objects // row is still updated as before (name/date_modify live their own life). Guarded by // AutoRecomputeHash: with recomputation off the in-memory hash cannot be trusted. // Objects without a hash (either side) never shortcut. ISet? ctUnchangedByHash = null; if (ctShortcutActive) ctUnchangedByHash = await SelectUnchangedByHashAsync(allObjectsToSave, dbHashById, cancellationToken); // A scheme another process changed since this one cached it is noticed by the first statement of the strategy, // before anything is written (RefreshStaleSchemesAsync): the rows are then built again from the scheme // as read now, and the strategy runs once more. for (var readAgain = 0; ; readAgain++) { try { await ProcessAllObjectsPropertiesRecursively(allObjectsToSave, allValuesToSave, ctUnchangedByHash, cancellationToken); // === PHASE 4: STRATEGY SELECTION AND TRANSACTIONAL SAVE === // Wrapped in deadlock retry: ORDER BY _id prevents most deadlocks, // but cross-table edge cases may still occur in cluster environments. var strategy = _configuration.PropsSaveStrategy; // EF pattern: if already in transaction (explicit or ambient TransactionScope) — execute inline var diagIsIn = _context.IsInTransaction; // var diagAmbient = System.Transactions.Transaction.Current?.TransactionInformation.LocalIdentifier ?? ""; // System.Console.WriteLine( // $"[Diag-TX-SAVE] DECISION IsInTransaction={diagIsIn} ambient={diagAmbient} " + // $"branch={(diagIsIn ? "INLINE" : "BEGIN-NEW")} thread={System.Environment.CurrentManagedThreadId} " + // $"objsToSave={allObjectsToSave.Count}"); if (diagIsIn) { // Lock existing objects within the caller's transaction if (existingObjectIds.Length > 0) { await _context.ExecuteAsync( Sql.ObjectStorage_LockObjectsForUpdate(), new object[] { existingObjectIds }, cancellationToken); } // The caller owns the transaction, and a unique violation must not leave it aborted // (PostgreSQL 25P02: every follow-up statement of a catch-and-recover pattern died, // SaveByUniqueAsync's own retry included - bug report п.2, 2026-09-02). The batch // runs under a savepoint; the violation rolls back TO it - the transaction stays // alive - and only then the typed exception leaves. Other failures propagate as // before: they are not the documented recoverable case. await _context.ExecuteAsync(Sql.Transaction_SavepointBegin(), System.Array.Empty(), cancellationToken); try { await ExecuteBatchByStrategy(strategy, allObjectsToSave, allValuesToSave, ctUnchangedByHash, cancellationToken); if (Sql.Transaction_SavepointRelease() is { } release) await _context.ExecuteAsync(release, System.Array.Empty(), cancellationToken); } catch (Exception ex) when (Data.DbErrorClassifier.IsUniqueViolation(ex)) { // Roll back BEFORE translating: the translation itself queries the database. // Deliberately WITHOUT ct (s3.4): the rollback must land even on a cancelled token. await _context.ExecuteAsync(Sql.Transaction_SavepointRollback()); throw await TranslateUniqueViolationAsync(ex, null); } catch (Exception ex) when (IsStaleKeyCache(ex, _createdBySave!.Count > 0)) { await _context.ExecuteAsync(Sql.Transaction_SavepointRollback()); throw StaleKeyCacheFailure(ex, _createdBySave!); } catch (SchemeReadAgainException) { // Nothing was written under the savepoint; the rows are built again and the batch runs anew. await _context.ExecuteAsync(Sql.Transaction_SavepointRollback()); throw; } } else { // Top-level: wrap in DeadlockRetry + Transaction + FOR UPDATE await DeadlockRetryHelper.ExecuteWithRetryAsync(async () => { await using var transaction = await _context.BeginTransactionAsync(cancellationToken: cancellationToken); try { // FOR UPDATE: lock ALL existing objects to prevent race condition if (existingObjectIds.Length > 0) { await _context.ExecuteAsync( Sql.ObjectStorage_LockObjectsForUpdate(), new object[] { existingObjectIds }, cancellationToken); } await ExecuteBatchByStrategy(strategy, allObjectsToSave, allValuesToSave, ctUnchangedByHash, cancellationToken); // The point of no return (s3.3): the LAST ct read - after a successful commit // nothing below ever consults the token again. cancellationToken.ThrowIfCancellationRequested(); await transaction.CommitAsync(); } catch (Exception ex) { await Data.RollbackAfterFailure.RollbackAsync(transaction, ex); if (Data.DbErrorClassifier.IsUniqueViolation(ex)) throw await TranslateUniqueViolationAsync(ex, null); if (IsStaleKeyCache(ex, _createdBySave!.Count > 0)) throw StaleKeyCacheFailure(ex, _createdBySave!); throw; } }, cancellationToken: cancellationToken); } break; } catch (SchemeReadAgainException) { if (readAgain >= SchemeReadAgainLimit) throw new InvalidOperationException( $"A scheme of this save kept changing during the save ({readAgain + 1} times, another process synchronising it); nothing was written."); allValuesToSave.Clear(); } } // === PHASE 5: LOADERS FOR THE SAVED GRAPH, CACHE UPDATE === // The caller's graph lives on after the save, hand-made references included: their stubs get the loader // of this database, as the load path gives its boundary stubs - a stub without a loader cannot answer its // Props (it answered null from a cache hit, with no query and no exception). With the props cache on, the // graph is published once the transaction commits (CachePublication). // Loaded ones only: an unloaded instance in the cache cannot be validated without a lazy load inside the // probe - which deadlocks with the load that probes. var savedGeneric = allObjectsToSave .Where(o => Utils.RedbObjectTypes.GenericOf(o.GetType()) != null && o is RedbObject { IsPropsLoaded: true }) .ToList(); if (savedGeneric.Count > 0) { var loader = CreateLazyPropsLoader(); foreach (var savedObj in savedGeneric) Utils.LazyReferenceInstaller.Install(savedObj, loader); } if (_configuration.EnablePropsCache && PropsCache.Instance != null) { // Not a graph holding a hand-made reference without its header ({ id = 42 }): served from the cache, its // lazy load would fill Props only. The next load reads it from the database with the header. var toCache = savedGeneric .Where(o => o.Hash.HasValue && !Utils.LoadedGraphInspector.HasHeaderlessReference( o.GetType().GetMethod("GetPropsDirectly")?.Invoke(o, null))) .ToList(); if (toCache.Count > 0) { Caching.CachePublication.AfterCommit(_context, () => { foreach (var savedObj in toCache) Caching.CacheDelegates.Set(PropsCache.Instance!, savedObj); }); } } var savedIds = objList.Select(o => o.Id).ToList(); // Saved runs AFTER the commit: the data is in, and (EF-style) an exception from an // interceptor propagates to the caller - but cannot un-commit anything. if (interceptors.Count > 0) { var changes = InterceptorChangeSink; InterceptorChangeSink = null; await InvokeSavedInterceptorsAsync(interceptors, new Interception.RedbSavedContext { RootObjects = objList, AllObjects = allObjectsToSave, EffectiveUser = user, Strategy = _configuration.PropsSaveStrategy, SavedIds = savedIds, // The references captured before id assignment now carry their final ids. NewObjectIds = newObjectRefs!.Select(o => o.Id).ToHashSet(), UnchangedByHash = ctUnchangedByHash as IReadOnlySet, Changes = changes, }, CancellationToken.None); // past the commit - cancelling the notification would lie (s3.3) } return savedIds; } /// /// The object hash as the save writes it: from Props when they are loaded, from the base /// fields when the object has none (Props null, or the non-generic RedbObject). /// private static void RecomputeHash(IRedbObject obj) { var objType = obj.GetType(); // The type or a base type: a TreeRedbObject hashes its Props like the RedbObject it is. var isGeneric = Utils.RedbObjectTypes.GenericOf(objType) != null; if (isGeneric) { // Raw Props: a collected object is loaded by definition, but never risk the getter. var propsValue = objType.GetMethod("GetPropsDirectly")?.Invoke(obj, null); if (propsValue != null) { var currentHash = RedbHash.ComputeFor(obj); if (currentHash.HasValue) obj.Hash = currentHash.Value; } else { obj.Hash = RedbHash.ComputeForBaseFields(obj); } } else { obj.Hash = RedbHash.ComputeForBaseFields(obj); } } /// /// V4 (L.2): a reference written by hand as { id = x } carries no hash, while the /// parent hashes "id:hash" of every reference and writes that hash into the reference row /// (_Guid). One query resolves the persisted hashes, so the first save writes the /// same parent hash every reload will compute - no first-resave shift, no perpetual /// props-cache miss (review). /// private async Task ResolveReferenceHashesAsync(List referenceStubs, CancellationToken cancellationToken) { if (referenceStubs.Count == 0) return; var ids = referenceStubs.Select(s => s.Id).Distinct().ToArray(); var rows = await _context.QueryAsync(Sql.ObjectStorage_SelectObjectsByIds(), new object[] { ids }, cancellationToken); var hashById = new Dictionary(); foreach (var row in rows) hashById[row.Id] = row.Hash; foreach (var stub in referenceStubs) { if (hashById.TryGetValue(stub.Id, out var hash)) stub.Hash = hash; } } /// /// Executes batch save by strategy. OpenSource: only DeleteInsert. /// Pro: override to support ChangeTracking. /// F1: lists existing objects excluded from the value /// pipeline by the hash shortcut - only the ChangeTracking strategy consults it (their /// _objects row still updates; their values were never built and must not be diffed). /// protected virtual async Task ExecuteBatchByStrategy( PropsSaveStrategy strategy, List allObjectsToSave, List allValuesToSave, ISet? ctUnchangedByHash = null, CancellationToken cancellationToken = default) { if (strategy == PropsSaveStrategy.ChangeTracking) { throw new NotSupportedException( "PropsSaveStrategy.ChangeTracking (batch) is not implemented in this provider. " + "Use PropsSaveStrategy.DeleteInsert."); } await SaveBatchWithDeleteInsertStrategy(allObjectsToSave, allValuesToSave, cancellationToken); } // ===== VALUE ROW IDS ===== // A value row built for a save carries a temporary id until the save knows which rows it inserts: the builders // link a child to its parent row by id, and ChangeTracking aligns the rows of an existing object to their stored // ids, so only the rows inserted in the end need a key. Drawing a key for every built row spent one key per row // of every changed object on every save. The range is far from stored value ids and from the reserved negative // ids of the type and system rows (about -9.2e18). private const long TemporaryValueIdTop = -1_000_000_000_000_000L; private const long TemporaryValueIdBottom = -2_000_000_000_000_000L; private long _lastTemporaryValueId = TemporaryValueIdTop; /// A unique temporary id for a value row being built; see . protected long NextTemporaryValueId() { var id = System.Threading.Interlocked.Decrement(ref _lastTemporaryValueId); if (id <= TemporaryValueIdBottom) { System.Threading.Interlocked.CompareExchange(ref _lastTemporaryValueId, TemporaryValueIdTop, id); id = System.Threading.Interlocked.Decrement(ref _lastTemporaryValueId); } return id; } /// Whether is a temporary value row id that still needs a key. protected internal static bool IsTemporaryValueId(long id) => id < TemporaryValueIdTop && id > TemporaryValueIdBottom; /// /// Gives the rows about to be inserted their keys, in one draw of as many keys as there are rows with a temporary /// id, and points every parent link of the save ( and , the /// rows updated) from the temporary id to the key. A link to a temporary id that no inserted row holds is a defect /// of the save, and stops it before anything is written. /// protected internal async Task AssignValueIdsAsync(IReadOnlyCollection inserted, IEnumerable others, CancellationToken cancellationToken) { var temporary = inserted.Where(v => IsTemporaryValueId(v.Id)).ToList(); if (temporary.Count == 0) return; var keys = await _context.Keys.NextObjectIdBatchAsync(temporary.Count, cancellationToken); var map = new Dictionary(temporary.Count); for (var i = 0; i < temporary.Count; i++) { map[temporary[i].Id] = keys[i]; temporary[i].Id = keys[i]; } foreach (var value in inserted.Concat(others)) { if (value.ArrayParentId is not { } parent || !IsTemporaryValueId(parent)) continue; value.ArrayParentId = map.TryGetValue(parent, out var key) ? key : throw new InvalidOperationException( $"A value row (object {value.IdObject}, structure {value.IdStructure}) points to a parent row the save does not insert."); // A collection-scoped element key is salted with the owning collection row id, which was the temporary // one when the key was built: salt it again with the key. Only a key salted that way matches the probe. if (value.Unique is { } unique && value.ArrayIndex != null && Utils.UniqueKeyEncoder.Compute(value, parent) == unique) value.Unique = Utils.UniqueKeyEncoder.Compute(value, key); } } // ===== THE STRUCTURES A CLASS KNOWS ===== /// /// What a Props class knows of its scheme as read from the database: the structures its /// properties match; the structures it lacks below one it knows (a field a /// newer build added inside a nested class, an array or a dictionary), with their paths. /// is false on the normal path: the scheme is the class. /// protected internal sealed record ClassStructures( HashSet Known, IReadOnlyList<(long Id, string Path)> UnknownUnderKnown, bool AnyUnknown, IReadOnlyList ShapeMismatches); // Per scheme instance (the cached scheme is replaced when it changes) and Props type: computed once. Both keys // are weak: a Props type of a collectible AssemblyLoadContext (a module) must not be pinned by this cache. private static readonly System.Runtime.CompilerServices.ConditionalWeakTable>>> ClassStructuresByScheme = new(); /// /// The structures the class of knows of its scheme, from the cached scheme (no round /// trip). Null when the object has no Props type or the cached scheme is another one: the save then treats the /// class as knowing the whole scheme, as before. /// protected internal async Task ClassStructuresOfAsync(IRedbObject obj, CancellationToken cancellationToken) { var generic = RedbObjectTypes.GenericOf(obj.GetType()); if (generic == null) return null; var propsType = generic.GetGenericArguments()[0]; var scheme = await _schemeSync.GetSchemeByTypeAsync(propsType, cancellationToken); if (scheme == null || scheme.Id != obj.SchemeId) return null; var byType = ClassStructuresByScheme.GetValue(scheme, _ => new()); var lazy = byType.GetValue(propsType, type => new Lazy>(() => ComputeAsync(type, scheme.Structures))); try { return await lazy.Value; } catch { // A failed computation (the database unreachable) is not kept: the next save computes again. byType.Remove(propsType); throw; } async Task ComputeAsync(Type type, IReadOnlyCollection structures) { var mismatches = _schemeSync is SchemeSyncProviderBase sync ? await sync.ShapeMismatchesAsync(type, structures) : (IReadOnlyList)[]; var known = SchemeSyncProviderBase.ClassStructureIds(type, structures); if (known.Count == structures.Count) return new ClassStructures(known, [], false, mismatches); var byId = structures.ToDictionary(s => s.Id); string PathOf(IRedbStructure s) => s.IdParent is { } p && byId.TryGetValue(p, out var parent) ? PathOf(parent) + "." + s.Name : s.Name; bool UnderKnown(IRedbStructure s) { for (var p = s.IdParent; p is { } id && byId.TryGetValue(id, out var parent); p = parent.IdParent) if (known.Contains(id)) return true; return false; } var underKnown = structures.Where(s => !known.Contains(s.Id) && UnderKnown(s)) .Select(s => (s.Id, PathOf(s))).OrderBy(x => x.Item2, StringComparer.Ordinal).ToList(); return new ClassStructures(known, underKnown, true, mismatches); } } /// /// Refuses a save of a class whose property has another type or collection kind than the structure stored for /// it (a type change the sync held under the version rule): the value would go into the wrong column and be /// lost. From the cached class structures, so no round trip; it holds whether or not this process synced. /// protected internal async Task EnsureNoHeldShapesAsync(IEnumerable objects, CancellationToken cancellationToken) { foreach (var group in objects.Where(o => o.SchemeId != 0).GroupBy(o => (o.SchemeId, Type: o.GetType()))) { var classStructures = await ClassStructuresOfAsync(group.First(), cancellationToken); if (classStructures is not { ShapeMismatches.Count: > 0 }) continue; var scheme = await _schemeSync.GetSchemeByTypeAsync(RedbObjectTypes.GenericOf(group.Key.Type)!.GetGenericArguments()[0], cancellationToken); throw new Exceptions.RedbPropertyTypeHeldException( scheme?.Name ?? group.Key.SchemeId.ToString(System.Globalization.CultureInfo.InvariantCulture), RedbObjectTypes.GenericOf(group.Key.Type)!.GetGenericArguments()[0], classStructures.ShapeMismatches); } } /// /// Refuses the save when the stored objects have values under a structure the class knows that the class /// does not know: replacing that nested class or collection would delete them. One query, run only when the /// scheme in the database has such structures (an older class next to a newer build). /// protected internal async Task EnsureNothingUnknownUnderKnownAsync( ClassStructures classStructures, IRedbObject sample, IReadOnlyCollection objectIds, CancellationToken cancellationToken) { if (classStructures.UnknownUnderKnown.Count == 0 || objectIds.Count == 0) return; var present = new HashSet(); foreach (var (structureId, _) in classStructures.UnknownUnderKnown) foreach (var chunk in objectIds.Chunk(1000)) { var count = await _context.ExecuteScalarAsync( $"SELECT COUNT(*) FROM _values WHERE _id_structure = {structureId} AND _id_object IN ({string.Join(",", chunk)})", System.Array.Empty(), cancellationToken); if (count > 0) { present.Add(structureId); break; } } if (present.Count == 0) return; var scheme = await _schemeSync.GetSchemeByIdAsync(sample.SchemeId, cancellationToken); var propsType = RedbObjectTypes.GenericOf(sample.GetType())!.GetGenericArguments()[0]; throw new Exceptions.RedbPropsClassOlderException( scheme?.Name ?? sample.SchemeId.ToString(System.Globalization.CultureInfo.InvariantCulture), propsType, classStructures.UnknownUnderKnown.Where(u => present.Contains(u.Id)).Select(u => u.Path).ToList()); } /// /// DeleteInsert's delete of the old values: all values of the objects whose class knows its whole scheme (the /// normal path, unchanged); for a class that knows less, only the values of the structures it knows, after the /// refusal check above. A newer build's top-level field is kept. /// private async Task DeleteValuesTheClassKnowsAsync(List existingObjects, CancellationToken cancellationToken) { var whole = new List(); var partial = new List<(ClassStructures Classes, List Ids)>(); foreach (var group in existingObjects.GroupBy(o => (o.SchemeId, Type: o.GetType()))) { var classStructures = await ClassStructuresOfAsync(group.First(), cancellationToken); var ids = group.Select(o => o.Id).Distinct().ToList(); if (classStructures is not { AnyUnknown: true }) { whole.AddRange(ids); continue; } await EnsureNothingUnknownUnderKnownAsync(classStructures, group.First(), ids, cancellationToken); partial.Add((classStructures, ids)); } if (whole.Count > 0) await _context.Bulk.BulkDeleteValuesByObjectIdsAsync(whole, cancellationToken); foreach (var (classes, ids) in partial) { if (classes.Known.Count == 0) continue; var structureIds = string.Join(",", classes.Known); foreach (var chunk in ids.Chunk(1000)) await _context.ExecuteAsync( $"DELETE FROM _values WHERE _id_object IN ({string.Join(",", chunk)}) AND _id_structure IN ({structureIds})", System.Array.Empty(), cancellationToken); } } // ===== DELETEINSERT STRATEGY ===== /// /// DeleteInsert batch strategy: delete ALL values, BulkInsert/BulkUpdate of objects, BulkInsert of values. /// protected async Task SaveBatchWithDeleteInsertStrategy( List allObjectsToSave, List allValuesToSave, CancellationToken cancellationToken = default) { // Step 1: Determine which objects ACTUALLY exist in the DB var existingIdsSet = await SelectExistingAndTakeCreateDatesAsync(allObjectsToSave, cancellationToken); var existingIdsInDb = existingIdsSet.ToList(); // Step 2: Delete the old values of the structures each object's class knows. A field a newer build of the // class added is kept; one under a nested class or collection the class knows refuses the save. if (existingIdsInDb.Any()) { await DeleteValuesTheClassKnowsAsync( allObjectsToSave.Where(o => existingIdsSet.Contains(o.Id)).ToList(), cancellationToken); } // Step 3: Separation and BulkInsert of new objects var newObjects = allObjectsToSave.Where(o => !existingIdsSet.Contains(o.Id)).ToList(); var existingObjects = allObjectsToSave.Where(o => existingIdsSet.Contains(o.Id)).ToList(); if (newObjects.Any()) { var newRecords = newObjects.Select(ConvertToObjectRecord).ToList(); await _context.Bulk.BulkInsertObjectsAsync(newRecords, cancellationToken); } // Step 4: BulkUpdate of existing objects if (existingObjects.Any()) { // P7 (UNIQUE stage 1): release the keys of EVERY existing object in the batch before the // row updates run - an in-batch key exchange otherwise trips the unique index mid-way. // Every existing object, not only those taking a key: the one giving its key up (new key // NULL) must release it before the one taking it is written. The statement touches rows // that hold a key only. Same transaction as the updates, so no outside reader sees a gap. var existingIdsToRelease = existingObjects.Select(o => o.Id).ToList(); if (existingIdsToRelease.Count > 0) await _context.ExecuteAsync(Sql.ObjectStorage_ClearValueUniqueByIds(existingIdsToRelease), System.Array.Empty(), cancellationToken); var existingRecords = existingObjects.Select(ConvertToObjectRecord).ToList(); await _context.Bulk.BulkUpdateObjectsAsync(existingRecords, cancellationToken); } // Step 5: BulkInsert of all values if (allValuesToSave.Any()) { await AssignValueIdsAsync(allValuesToSave, [], cancellationToken); var deduplicated = DeduplicateValueInserts(allValuesToSave, "SaveBatchWithDeleteInsertStrategy"); var sortedValues = ValuesTopologicalSort.SortByFkDependency(deduplicated); await _context.Bulk.BulkInsertValuesAsync(sortedValues, cancellationToken); } } } } Path: redb/redb.Core/Providers/Base/ObjectStorageProviderBase.StaleKeyCache.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/ObjectStorageProviderBase.StaleKeyCache.cs ---- using System; using System.Collections.Generic; using redb.Core.Data; using redb.Core.Models.Contracts; namespace redb.Core.Providers.Base { public abstract partial class ObjectStorageProviderBase { /// /// An insert of a save failed on the primary key of _objects or _values with an id the key cache /// handed out: value rows always take theirs from the cache, objects only when the save gave them their id. The /// cached ids predate rows the database got since, typically by a restore or an import while this application /// kept running. /// private static bool IsStaleKeyCache(Exception ex, bool createdObjects) { if (!DbErrorClassifier.IsObjectOrValueKeyViolation(ex)) return false; var text = DbErrorClassifier.DescribeUniqueViolation(ex).ConstraintName ?? ""; var onValues = text.Contains("values", StringComparison.OrdinalIgnoreCase); return onValues || createdObjects; } /// /// Drops the cached key block of this database, so the next save takes a fresh range from the sequence, and /// gives the objects of the failed save their id 0 back, so saving them again creates them (an id kept from /// the failed save would address the row that has it). No retry: the error leaves, the caller saves again. /// private Exception StaleKeyCacheFailure(Exception ex, IEnumerable created) { (_context.Keys as RedbKeyGeneratorBase)?.ClearCache(); foreach (var obj in created) obj.Id = 0; return new InvalidOperationException( "The save was not written: an id this application took from its key cache is already used in the " + "database. The cached ids predate rows the database got since, typically by a restore or an import " + "into a database a running application uses. The key cache of this database was reset; save again. " + "Restart applications that use a database after restoring or importing into it.", ex); } } } Path: redb/redb.Core/Providers/Base/ObjectStorageProviderBase.Unique.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/ObjectStorageProviderBase.Unique.cs ---- using System; using System.Linq; using System.Linq.Expressions; using System.Threading.Tasks; using redb.Core.Data; using redb.Core.Exceptions; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using redb.Core.Utils; namespace redb.Core.Providers.Base { /// /// Unique-key side of the storage provider: the typed exception for a violated key, and the /// point lookup by key. The key itself is computed in the scalar value builders /// (); the index lives in the database. /// public abstract partial class ObjectStorageProviderBase { /// /// Builds the typed exception for a unique violation the save just hit. Enrichment — which /// structure, scheme, property — is best-effort and runs after the transaction rolled back; /// a failure to enrich must never mask the violation itself. /// protected async Task TranslateUniqueViolationAsync(Exception ex, long? schemeId) { var (constraint, detail, structureId, kind) = DbErrorClassifier.DescribeUniqueViolation(ex); string? schemeName = null; string? propertyName = null; try { if (structureId.HasValue) { var structure = await _context.QueryFirstOrDefaultAsync( Sql.Structures_SelectById(), structureId.Value); if (structure != null) { propertyName = structure.Name; schemeId = structure.IdScheme; } } if (schemeId.HasValue) schemeName = (await _schemeSync.GetSchemeByIdAsync(schemeId.Value))?.Name; } catch { // Best effort only: the ids we already have still tell the story. } return new RedbUniqueViolationException(schemeId, schemeName, structureId, propertyName, constraint, detail, ex, kind); } /// /// The object of whose [RedbUnique] property holds /// , or null. One index probe: the value is canonicalised and /// hashed exactly as the save path does it, and the partial unique index answers. /// A null value returns null — NULL never takes part in uniqueness. /// public async Task?> GetByUniqueAsync( Expression> keyProperty, object? value, int depth = 10, CancellationToken cancellationToken = default) where TProps : class, new() => await GetByUniqueAsync(GetKeyPropertyName(keyProperty), value, depth, cancellationToken); /// public async Task?> GetByUniqueAsync( string propertyName, object? value, int depth = 10, CancellationToken cancellationToken = default) where TProps : class, new() { if (value is null) return null; var scheme = await _schemeSync.GetSchemeByTypeAsync() ?? throw new InvalidOperationException( $"No scheme for '{typeof(TProps).Name}'; synchronise it first."); var metadata = await GetStructuresWithMetadataAsync(scheme.Id); // S2: the name is a path - "Code" for a root key, "Identity.Passport" for a nested one. var structure = default(StructureMetadata); foreach (var segment in propertyName.Split('.')) { var parentId = structure?.Id; structure = metadata.FirstOrDefault(m => m.IdParent == parentId && m.Name == segment) ?? throw new RedbUniqueKeyDefinitionException(typeof(TProps).Name, propertyName, $"no property '{segment}' at this position of the path in the scheme"); } if (!structure!.Unique) throw new RedbUniqueKeyDefinitionException(typeof(TProps).Name, propertyName, "the property is not marked [RedbUnique]"); // S3: a Collection-scoped key is unique only within its collection - a global // by-value probe has no meaning there. if (structure.UniqueScope == (long)Core.Attributes.UniqueScope.Collection) throw new RedbUniqueKeyDefinitionException(typeof(TProps).Name, propertyName, "the key is scoped to its collection (Scope = Collection); a global lookup " + "by element value has no meaning - query the collection instead"); // The same canonicalisation the save path runs: value -> typed column -> canonical form -> hash. var probe = new RedbValue(); if (structure.UniqueScope == (long)Core.Attributes.UniqueScope.Scheme) { // S3, Scheme-scoped ELEMENT key: the caller passes an element value. References // canonicalise by target id, exactly like the save path keyed the element rows. if (value is IRedbObject refValue) probe.Object = refValue.Id; else if (value is IRedbListItem listItemValue) probe.ListItem = listItemValue.Id; else SetSimpleValueByType(probe, structure.DbType, value); } else { // S1: for a subtree key (a class, array or dictionary) the caller passes the // subtree VALUE; its canonical content hash - the same one the save wrote into // the base row's _Guid - is the probed value. Reference collections are out of // the by-value lookup: their stored hash combines the elements' persisted // hashes, which a detached value cannot reproduce. var probeDbType = structure.DbType; var probeValue = value; var isSubtreeKey = structure.CollectionType != null || structure.TypeSemantic == "Object"; if (isSubtreeKey && value is not Guid) { var contentHash = Utils.RedbHash.ComputeForProps(value); if (contentHash is null) return null; probeValue = contentHash; probeDbType = "Guid"; } SetSimpleValueByType(probe, probeDbType, probeValue); } var key = UniqueKeyEncoder.Compute(probe); if (key is null) return null; var objectId = await _context.ExecuteScalarAsync( Sql.Values_SelectObjectIdByUnique(), new object[] { structure.Id, key.Value }, cancellationToken); return objectId.HasValue ? await LoadAsync(objectId.Value, depth, cancellationToken) : null; } /// /// The single point where resolves "who owns this /// key right now" - one probe of UIX__objects__scheme_unique. Virtual as a /// deterministic interleave seam for the race tests (delete + recreate between the resolve /// and the save); production overrides are not expected. /// protected virtual Task ResolveObjectIdByUniqueKeyAsync(long schemeId, string? valueUnique, CancellationToken cancellationToken = default) => _context.ExecuteScalarAsync( Sql.ObjectStorage_SelectIdBySchemeValueUnique(), new object[] { schemeId, valueUnique! }, cancellationToken); /// /// Upsert by the object key (UNIQUE stage 1, P1): resolve the row by /// (scheme, ValueUnique), then save onto it - the values ride the ordinary save /// pipeline in the same transaction as the row. Not a single-statement native upsert on /// purpose: writing the _objects row via ON CONFLICT/MERGE would bypass the values /// pipeline; resolving first costs one indexed probe and reuses everything. A lost /// OBJECT-KEY race retries once onto the current winner's row - both the creation race /// (the key appeared between the lookup and our insert) and the vanish race (the resolved /// row was deleted and the key recreated elsewhere; BR-8, 2026-09-02) - which keeps a /// concurrent accept of one key idempotent: exactly one object per key, last writer's /// content. A [RedbUnique] PROPERTY violation is never retried: it is not the object /// key's business and surfaces as-is (). /// public async Task SaveByUniqueAsync(RedbObject obj, CancellationToken cancellationToken = default) where TProps : class, new() { if (string.IsNullOrEmpty(obj.ValueUnique)) throw new RedbUniqueKeyDefinitionException(typeof(TProps).Name, nameof(Models.Contracts.IRedbObject.ValueUnique), "SaveByUniqueAsync needs a non-empty ValueUnique to resolve the object by"); var scheme = await _schemeSync.EnsureSchemeFromTypeAsync(); var existingId = await ResolveObjectIdByUniqueKeyAsync(scheme.Id, obj.ValueUnique, cancellationToken); if (existingId.HasValue) obj.id = existingId.Value; try { return await SaveAsync(obj, cancellationToken); } catch (RedbUniqueViolationException uve) when (uve.Kind != RedbUniqueViolationKind.Property) { // Lost an object-key race: either the key appeared between the lookup and our // insert (creation race), or the resolved row vanished and the key was recreated // elsewhere - our save then inserted via AutoSwitchToInsert and hit the key index // (BR-8, 2026-09-02). Take the current winner's row and write onto it, once. // Kind=Property never lands here: a field collision cannot be fixed by // re-resolving the object key. var winner = await ResolveObjectIdByUniqueKeyAsync(scheme.Id, obj.ValueUnique, cancellationToken); if (!winner.HasValue) throw; // the key vanished again (deleted mid-race) - surface the original failure if (existingId.HasValue && winner.Value == existingId.Value) throw; // the same row still owns the key: the violation is not our object key - do not loop obj.id = winner.Value; return await SaveAsync(obj, cancellationToken); } } private static string GetKeyPropertyName(Expression> keyProperty) { // S2: the selector may walk into a nested class - the member chain becomes the // dotted structure path ("Identity.Passport"). var body = keyProperty.Body is UnaryExpression unary ? unary.Operand : keyProperty.Body; var segments = new Stack(); while (body is MemberExpression member) { segments.Push(member.Member.Name); body = member.Expression!; } if (segments.Count == 0 || body is not ParameterExpression) throw new ArgumentException( "The expression must select a property path, e.g. p => p.Code or p => p.Identity.Passport.", nameof(keyProperty)); return string.Join(".", segments); } } } Path: redb/redb.Core/Providers/Base/ObjectStorageProviderBase.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/ObjectStorageProviderBase.cs ---- #pragma warning disable CS0618 // implements or uses the deprecated object permissions and roles (RedbDeprecation) using redb.Core.Providers; using redb.Core.Data; using redb.Core.Utils; using redb.Core.Extensions; using redb.Core.Serialization; using redb.Core.Query; using redb.Core.Services; using System.Text.Json; using System.Text.Json.Serialization; using System.Text.Encodings.Web; using System.Threading; using System.Threading.Tasks; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using redb.Core.Models.Configuration; using System.Reflection; using System.Collections.Generic; using System.Linq; using redb.Core.Exceptions; using System; using redb.Core.Caching; using Microsoft.Extensions.Logging; namespace redb.Core.Providers.Base { /// /// Base abstract class for ObjectStorageProvider with database-agnostic business logic. /// SQL queries are abstracted via ISqlDialect for PostgreSQL/MSSQL/etc support. /// public abstract partial class ObjectStorageProviderBase : IObjectStorageProvider { protected readonly IRedbContext _context; private readonly IRedbObjectSerializer _serializer; private readonly IPermissionProvider _permissionProvider; private readonly IRedbSecurityContext _securityContext; private readonly ISchemeSyncProvider _schemeSync; private readonly RedbServiceConfiguration _configuration; private readonly IListProvider? _listProvider; private readonly ISqlDialect _sql; private readonly ILogger? _logger; /// /// Domain-bound metadata cache for this provider. /// protected GlobalMetadataCache Cache => _schemeSync.Cache; /// /// Domain-bound props cache for this provider. /// protected GlobalPropsCache PropsCache => _schemeSync.PropsCache; /// /// Creates a new ObjectStorageProviderBase instance. /// protected ObjectStorageProviderBase( IRedbContext context, IRedbObjectSerializer serializer, IPermissionProvider permissionProvider, IRedbSecurityContext securityContext, ISchemeSyncProvider schemeSync, RedbServiceConfiguration configuration, ISqlDialect sql, IListProvider? listProvider = null, ILogger? logger = null, Interception.RedbSaveInterceptorPipeline? saveInterceptors = null) { _context = context; _serializer = serializer; _permissionProvider = permissionProvider; _securityContext = securityContext; _schemeSync = schemeSync; _configuration = configuration ?? new RedbServiceConfiguration(); _sql = sql; _listProvider = listProvider; _logger = logger; _saveInterceptors = saveInterceptors ?? Interception.RedbSaveInterceptorPipeline.Empty; } /// /// Save-pipeline interceptors (discussion #12, п.3-4): DI registrations plus run-time subscriptions. Every save /// and delete takes ONE snapshot at its start and uses it for both of its hooks, so a subscription that comes /// or goes meanwhile never gets a Saved without its Saving. An empty snapshot = zero cost: nothing is collected. /// private readonly Interception.RedbSaveInterceptorPipeline _saveInterceptors; /// The interceptors of the operation that starts now. Empty when nobody listens. protected IReadOnlyList SnapshotSaveInterceptors() => _saveInterceptors.Snapshot(); /// /// The change feed for the current save, or null when nobody listens. The base opens it /// before the strategy runs (ChangeTracking only); the Pro diff fills it; the base hands /// it to . Single-threaded by the /// one-scope-one-save contract (CT-4). /// protected List? InterceptorChangeSink; protected static async Task InvokeSavingInterceptorsAsync( IReadOnlyList interceptors, Interception.RedbSavingContext ctx, CancellationToken cancellationToken) { foreach (var interceptor in interceptors) await interceptor.SavingAsync(ctx, cancellationToken); } protected static async Task InvokeSavedInterceptorsAsync( IReadOnlyList interceptors, Interception.RedbSavedContext ctx, CancellationToken cancellationToken) { foreach (var interceptor in interceptors) await interceptor.SavedAsync(ctx, cancellationToken); } private static async Task InvokeDeletingInterceptorsAsync( IReadOnlyList interceptors, Interception.RedbDeletingContext ctx, CancellationToken cancellationToken) { foreach (var interceptor in interceptors) await interceptor.DeletingAsync(ctx, cancellationToken); } private static async Task InvokeDeletedInterceptorsAsync( IReadOnlyList interceptors, Interception.RedbDeletedContext ctx, CancellationToken cancellationToken) { foreach (var interceptor in interceptors) await interceptor.DeletedAsync(ctx, cancellationToken); } // Protected properties for derived classes protected IRedbContext Context => _context; protected IRedbObjectSerializer Serializer => _serializer; protected ISchemeSyncProvider SchemeSyncProvider => _schemeSync; protected RedbServiceConfiguration Configuration => _configuration; protected IListProvider? ListProvider => _listProvider; protected ISqlDialect Sql => _sql; protected IPermissionProvider PermissionProvider => _permissionProvider; protected IRedbSecurityContext SecurityContext => _securityContext; protected ILogger? Logger => _logger; /// /// Creates a LazyPropsLoader instance. Override in derived classes for custom implementations (e.g., ProLazyPropsLoader). /// protected abstract ILazyPropsLoader CreateLazyPropsLoader(); // ===== BASIC METHODS (use _securityContext and configuration) ===== /// /// Load object from EAV by ID (uses _securityContext and config.DefaultCheckPermissionsOnLoad) /// Returns null if object not found and config.ThrowOnObjectNotFound = false /// public async Task?> LoadAsync(long objectId, int depth = 10, CancellationToken cancellationToken = default) where TProps : class, new() { var effectiveUser = _securityContext.GetEffectiveUser(); return await LoadAsync(objectId, effectiveUser, depth, cancellationToken); } /// /// Load object from EAV (uses _securityContext and config.DefaultCheckPermissionsOnLoad) /// Returns null if object not found and config.ThrowOnObjectNotFound = false /// public async Task?> LoadAsync(IRedbObject obj, int depth = 10, CancellationToken cancellationToken = default) where TProps : class, new() { var effectiveUser = _securityContext.GetEffectiveUser(); return await LoadAsync(obj.Id, effectiveUser, depth, cancellationToken); } /// /// Load object from EAV with explicitly specified user (uses config.DefaultCheckPermissionsOnLoad) /// Returns null if object not found and config.ThrowOnObjectNotFound = false /// public async Task?> LoadAsync(IRedbObject obj, IRedbUser user, int depth = 10, CancellationToken cancellationToken = default) where TProps : class, new() { return await LoadAsync(obj.Id, user, depth, cancellationToken); } // ===== OVERLOADS WITH EXPLICIT USER ===== /// /// MAIN loading method - all other LoadAsync methods call it /// Returns null if object not found and config.ThrowOnObjectNotFound = false /// /// /// Checks whether a loaded object's scheme matches the scheme maps to. /// Returns true when it matches (or when the type has no known scheme yet — nothing to compare /// against). On a mismatch the behaviour depends on ThrowOnSchemeMismatch: by default returns /// false so the caller returns null (a soft-deleted object, scheme -10, reads as /// null); when the flag is set, throws . /// Either way garbage never reaches the cache — the check runs before any caching. /// private async Task IsSchemeValidForLoadAsync(long objectId, long actualSchemeId) where TProps : class, new() { // Expected scheme_id for TProps: fast per-domain projection first, then a lazy resolve that // also warms the projection. Null → the type has no scheme yet; accept rather than block loads. var expected = Cache.GetSchemeIdByClrType(typeof(TProps)); if (expected == null) { var scheme = await _schemeSync.GetSchemeByTypeAsync(); expected = scheme?.Id; } if (!expected.HasValue || expected.Value == actualSchemeId) return true; if (_configuration.ThrowOnSchemeMismatch) throw new Exceptions.RedbSchemeMismatchException(objectId, typeof(TProps), expected.Value, actualSchemeId); return false; // soft default: caller returns null instead of garbage } public async Task?> LoadAsync(long objectId, IRedbUser user, int depth = 10, CancellationToken cancellationToken = default) where TProps : class, new() { // Permission check according to configuration if (_configuration.DefaultCheckPermissionsOnLoad) { var canRead = await _permissionProvider.CanUserSelectObject(objectId, user.Id); if (!canRead) { throw new UnauthorizedAccessException($"User {user.Id} has no read permission for object {objectId}"); } } // === EAGER LOADING: Full loading via get_object_json with cache === // OPTIMIZATION for SkipHashValidationOnCacheCheck: check cache first without DB query. // NEVER inside an active transaction (explicit or ambient): a load there is the read of // a read-modify-write - the caller has just taken LockForUpdateAsync and expects the // database's current row, and a pre-lock cached copy is exactly the lost update the // lock exists to prevent (bug report п.1, 2026-09-02). Inside a transaction the load // falls through to the hash-validated path: one indexed SELECT _id,_hash under the lock. if (_configuration.EnablePropsCache && _configuration.SkipHashValidationOnCacheCheck && PropsCache.Instance != null && !_context.IsInTransaction) { var cachedObj = PropsCache.GetWithoutHashValidation(objectId); if (cachedObj != null) { // Cache HIT WITHOUT DB query - return cached object return cachedObj; } } // Cache MISS or hash check enabled - query ID + Hash (+ scheme, for the scheme-match guard // below) to distinguish "object not found" and "hash=null". The probe stays this narrow // on purpose: _hash covers the whole row (header included, see RedbHash), so a match // vouches for the cached object as a whole - no need to read _note/_value_bytes here. var eagerBaseObj = await _context.QueryFirstOrDefaultAsync( Sql.ObjectStorage_SelectIdHashScheme(), new object[] { objectId }, cancellationToken); if (eagerBaseObj == null) { if (_configuration.ThrowOnObjectNotFound) throw new InvalidOperationException($"Object with ID {objectId} not found"); return null; } // Guard against loading an object under the wrong Props type (garbage + cache poisoning). // Mismatch → null by default (soft-deleted scheme -10 reads as null), or throws under the flag. if (!await IsSchemeValidForLoadAsync(objectId, eagerBaseObj.IdScheme)) return null; // Object found, but hash may be null var objectHash = eagerBaseObj.Hash; // Check cache only if hash is NOT null AND validation is not skipped if (_configuration.EnablePropsCache && !_configuration.SkipHashValidationOnCacheCheck && PropsCache.Instance != null && objectHash.HasValue) { var cachedObj = PropsCache.Get(objectId, objectHash.Value); if (cachedObj != null && !await IsCachedGraphCurrentAsync(cachedObj, sync: false, cancellationToken)) { PropsCache.Remove(objectId); cachedObj = null; } if (cachedObj != null) { // Cache HIT - the hash vouches for header and Props alike (cluster review, // 2026-09-11: a save on another node moves _hash whichever part it touched) return cachedObj; } } // Cache MISS - load via get_object_json return await LoadEagerAsync(objectId, depth, cancellationToken); } public Task LoadJsonAsync(long objectId, int depth = 10, CancellationToken cancellationToken = default) => LoadJsonAsync(objectId, _securityContext.GetEffectiveUser(), depth, cancellationToken); public async Task LoadJsonAsync(long objectId, IRedbUser user, int depth = 10, CancellationToken cancellationToken = default) { if (_configuration.DefaultCheckPermissionsOnLoad) { var canRead = await _permissionProvider.CanUserSelectObject(objectId, user.Id); if (!canRead) throw new UnauthorizedAccessException($"User {user.Id} has no read permission for object {objectId}"); } // Straight to the in-database materializer. No PropsCache (it is keyed by CLR type, // and there is none here) and no scheme guard (nothing to compare a scheme against); // Pro keeps this path too - _values stays the source of truth on every tier. var json = await _context.ExecuteJsonAsync(Sql.ObjectStorage_GetObjectJson(), new object[] { objectId, depth }, cancellationToken); if (string.IsNullOrEmpty(json)) { if (_configuration.ThrowOnObjectNotFound) throw new InvalidOperationException($"Object with ID {objectId} not found"); return null; } return json; } /// /// Virtual method for EAGER loading of Props. /// Open Source: uses get_object_json /// Pro: overrides for PVT approach /// protected virtual async Task?> LoadEagerAsync(long objectId, int depth, CancellationToken cancellationToken) where TProps : class, new() { var json = await _context.ExecuteJsonAsync( Sql.ObjectStorage_GetObjectJson(), new object[] { objectId, depth }, cancellationToken); return MaterializeLoadedJson(objectId, json); } /// /// Synchronous twin of for the thread-pool-free . /// Open Source: get_object_json. Pro: overrides with its materializer run synchronously. /// protected virtual RedbObject? LoadEager(long objectId, int depth) where TProps : class, new() { var json = _context.ExecuteJson(Sql.ObjectStorage_GetObjectJson(), objectId, depth); return MaterializeLoadedJson(objectId, json); } /// /// The CPU half of an eager load, shared by the async path and the sync (thread-pool-free) /// path: deserialize, install lazy loaders, cache. /// private RedbObject? MaterializeLoadedJson(long objectId, string? json) where TProps : class, new() { if (string.IsNullOrEmpty(json)) { if (_configuration.ThrowOnObjectNotFound) throw new InvalidOperationException($"Object with ID {objectId} not found"); return null; } // Deserialize JSON into RedbObject var loadedObj = _serializer.Deserialize(json); // V4 (L.3): boundary stubs get their loader - BEFORE the cache Set, so the Set marks // every stub of the now shared graph and drops its origin: a shared instance loads on // the reader's scope only (owner decision 2026-09-15). Utils.LazyReferenceInstaller.Install(loadedObj, CreateLazyPropsLoader()); // Put main object + ALL nested RedbObject into cache - once the transaction commits: until then the // graph is the reader's own (CachePublication). if (_configuration.EnablePropsCache && PropsCache.Instance != null && loadedObj.hash.HasValue) { Caching.CachePublication.AfterCommit(_context, () => { // One walk: the graph is marked shared and every nested RedbObject is cached by its own id // (they are already in memory after deserialization). PropsCache.SetGraph(loadedObj); }); } return loadedObj; } /// /// Synchronous eager load for the thread-pool-free lazy path (the sync getter of /// RedbListItem.Object): the same sequence as the main LoadAsync - permission check, /// props-cache probes, id/hash/scheme row, get_object_json - but every database call runs /// on the calling thread down to ADO.NET, so a saturated thread pool cannot slow or /// deadlock the load. /// public virtual RedbObject? Load(long objectId, int depth = 10) where TProps : class, new() { var user = _securityContext.GetEffectiveUser(); if (_configuration.DefaultCheckPermissionsOnLoad) { if (!_permissionProvider.CanUserSelectObjectSync(objectId, user.Id)) throw new UnauthorizedAccessException($"User {user.Id} has no read permission for object {objectId}"); } // Same cache discipline as the async path, including the in-transaction bypass. if (_configuration.EnablePropsCache && _configuration.SkipHashValidationOnCacheCheck && PropsCache.Instance != null && !_context.IsInTransaction) { var cachedObj = PropsCache.GetWithoutHashValidation(objectId); if (cachedObj != null) return cachedObj; } var eagerBaseObj = _context.QueryFirstOrDefault( Sql.ObjectStorage_SelectIdHashScheme(), objectId); if (eagerBaseObj == null) { if (_configuration.ThrowOnObjectNotFound) throw new InvalidOperationException($"Object with ID {objectId} not found"); return null; } // Scheme guard, cache-only: the async path would resolve a cold CLR-type projection // through the scheme-sync provider; here the only caller is the linked-object loader, // which picked TProps FROM the object's scheme id, so on a cold projection the pair // matches by construction and the load is accepted. var expected = Cache.GetSchemeIdByClrType(typeof(TProps)); if (expected.HasValue && expected.Value != eagerBaseObj.IdScheme) { if (_configuration.ThrowOnSchemeMismatch) throw new Exceptions.RedbSchemeMismatchException(objectId, typeof(TProps), expected.Value, eagerBaseObj.IdScheme); return null; } var objectHash = eagerBaseObj.Hash; if (_configuration.EnablePropsCache && !_configuration.SkipHashValidationOnCacheCheck && PropsCache.Instance != null && objectHash.HasValue) { var cachedObj = PropsCache.Get(objectId, objectHash.Value); if (cachedObj != null && !IsCachedGraphCurrentAsync(cachedObj, sync: true, CancellationToken.None).GetAwaiter().GetResult()) { PropsCache.Remove(objectId); cachedObj = null; } if (cachedObj != null) return cachedObj; } return LoadEager(objectId, depth); } /// /// Whether a cached object whose own hash matched its row may be served with the graph it holds. Its hash does /// not move when an object it references changes or leaves for the trash, on this node or any other, so the /// loaded references are checked against their rows: a missing row, a row of the trash scheme and a moved /// hash all make the graph stale. With every database call runs on the calling thread /// and the task is complete on return. /// protected virtual Task IsCachedGraphCurrentAsync(IRedbObject cached, bool sync, CancellationToken cancellationToken) { // Only the references matter: the caller has already compared this object's own hash with its row. var references = GetLoadedReferences(cached); references.Remove(cached.Id); if (references.Count == 0) return Task.FromResult(true); var ids = references.Keys.ToArray(); var sql = Sql.ObjectStorage_SelectObjectsByIds(); if (sync) return Task.FromResult(IsGraphCurrent(references, _context.Query(sql, new object[] { ids }))); return IsGraphCurrentAsync(sql, ids, references, cancellationToken); } private async Task IsGraphCurrentAsync(string sql, long[] ids, Dictionary references, CancellationToken cancellationToken) { var rows = await _context.QueryAsync(sql, new object[] { ids }, cancellationToken); return IsGraphCurrent(references, rows); } private static bool IsGraphCurrent(Dictionary references, List rows) { var byId = new Dictionary(rows.Count); foreach (var row in rows) byId[row.Id] = row; return IsGraphCurrent(references, byId); } private static bool IsGraphCurrent(Dictionary references, Dictionary byId) { foreach (var (id, hash) in references) { if (!byId.TryGetValue(id, out var row)) return false; // the target is gone if (row.IdScheme == RedbTypeIds.DeletedScheme) return false; // the target left for the trash if (row.Hash != hash) return false; // the target changed } return true; } /// /// The ids of the cached graphs that hold at least one stale reference. All graphs are checked in one query: /// the bulk load hands over every object a cache hit returned, and one statement per object would be the /// price of every list read under the props cache. /// private async Task> FindStaleCachedGraphsAsync(IEnumerable cachedObjects, CancellationToken cancellationToken) { var perRoot = new Dictionary>(); var all = new Dictionary(); foreach (var obj in cachedObjects) { var references = GetLoadedReferences(obj); references.Remove(obj.Id); if (references.Count == 0) continue; perRoot[obj.Id] = references; foreach (var (id, hash) in references) all[id] = hash; } var stale = new HashSet(); if (all.Count == 0) return stale; var ids = all.Keys.ToArray(); var rows = await _context.QueryAsync( Sql.ObjectStorage_SelectObjectsByIds(), new object[] { ids }, cancellationToken); var byId = new Dictionary(rows.Count); foreach (var row in rows) byId[row.Id] = row; foreach (var (rootId, references) in perRoot) if (!IsGraphCurrent(references, byId)) stale.Add(rootId); return stale; } /// /// The loaded objects a cached graph vouches for beyond its root, by id with the hash each was loaded with. /// The walk comes from : it visits the loaded part of Props, never a stub and /// never a leaf getter (a list item's Object getter would load its target on read). /// private static Dictionary GetLoadedReferences(IRedbObject root) => LoadedGraphInspector.CollectLoadedReferences( root.GetType().GetMethod("GetPropsDirectly", Type.EmptyTypes)?.Invoke(root, null)); /// /// Save single object via interface. Type determined internally. /// public async Task SaveAsync(IRedbObject obj, CancellationToken cancellationToken = default) { var effectiveUser = _securityContext.GetEffectiveUser(); return await SaveAsync(obj, effectiveUser, cancellationToken); } /// /// Save single object via interface with explicit user. /// public async Task SaveAsync(IRedbObject obj, IRedbUser user, CancellationToken cancellationToken = default) { var results = await SaveAsync(new[] { obj }, user, cancellationToken); return results.FirstOrDefault(); } public async Task SaveAsync(IRedbObject obj, CancellationToken cancellationToken = default) where TProps : class, new() { var effectiveUser = _securityContext.GetEffectiveUser(); return await SaveAsync(obj, effectiveUser, cancellationToken); } public async Task DeleteAsync(IRedbObject obj, CancellationToken cancellationToken = default) { var effectiveUser = _securityContext.GetEffectiveUser(); return await DeleteAsync(obj, effectiveUser, cancellationToken); } /// /// Deletes an object from the database using atomic ExecuteDeleteAsync. /// Thread-safe and handles concurrent delete attempts gracefully. /// public async Task DeleteAsync(IRedbObject obj, IRedbUser user, CancellationToken cancellationToken = default) { // Permission check according to configuration if (_configuration.DefaultCheckPermissionsOnDelete) { var canDelete = await _permissionProvider.CanUserDeleteObject(obj, user); if (!canDelete) { throw new UnauthorizedAccessException($"User {user.Id} has no delete permission for object {obj.Id}"); } } // Interceptors (owner decision: deletes are covered too). Deleting before the SQL - // an exception cancels the delete; Deleted after it, only when a row actually went. var interceptors = SnapshotSaveInterceptors(); if (interceptors.Count > 0) { await InvokeDeletingInterceptorsAsync(interceptors, new Interception.RedbDeletingContext { ObjectIds = [obj.Id], KnownObjects = [obj], EffectiveUser = user, }, cancellationToken); } // Atomic delete via SQL - single query, no race condition var deletedCount = await _context.ExecuteAsync( Sql.ObjectStorage_DeleteById(), new object[] { obj.Id }, cancellationToken); if (deletedCount == 0) { return false; // Object did not exist or was already deleted } if (interceptors.Count > 0) { await InvokeDeletedInterceptorsAsync(interceptors, new Interception.RedbDeletedContext { ObjectIds = [obj.Id], KnownObjects = [obj], EffectiveUser = user, DeletedCount = deletedCount, }, CancellationToken.None); // the row is gone - cancelling the notification would lie (s3.3) } // === CACHE INVALIDATION === if (_configuration.EnablePropsCache && PropsCache.Instance != null) { PropsCache.Remove(obj.Id); } // === ID RESET STRATEGY === if (_configuration.IdResetStrategy == redb.Core.Models.Configuration.ObjectIdResetStrategy.AutoResetOnDelete) { obj.ResetId(); // Automatically reset ID } return true; } // ===== DELETION BY ID ===== /// /// Delete object by ID (uses _securityContext) /// public async Task DeleteAsync(long objectId, CancellationToken cancellationToken = default) { var effectiveUser = _securityContext.GetEffectiveUser(); return await DeleteAsync(objectId, effectiveUser, cancellationToken); } /// /// Delete object by ID with explicit user /// public async Task DeleteAsync(long objectId, IRedbUser user, CancellationToken cancellationToken = default) { var deletedCount = await DeleteAsync(new[] { objectId }, user, cancellationToken); return deletedCount > 0; } // ===== BULK DELETION BY ID ===== /// /// Bulk deletion of objects by ID (uses _securityContext) /// public async Task DeleteAsync(IEnumerable objectIds, CancellationToken cancellationToken = default) { var effectiveUser = _securityContext.GetEffectiveUser(); return await DeleteAsync(objectIds, effectiveUser, cancellationToken); } /// /// Bulk deletion of objects by ID with explicit user /// public async Task DeleteAsync(IEnumerable objectIds, IRedbUser user, CancellationToken cancellationToken = default) => await DeleteByIdsCoreAsync(objectIds.ToList(), user, knownObjects: [], cancellationToken); /// /// The id-batch funnel. carries the instances when the /// caller had them (the delete-by-object overload), so interceptors see more than ids. /// private async Task DeleteByIdsCoreAsync(List ids, IRedbUser user, IReadOnlyList knownObjects, CancellationToken cancellationToken) { if (ids.Count == 0) return 0; // Permission check according to configuration if (_configuration.DefaultCheckPermissionsOnDelete) { foreach (var id in ids) { var canDelete = await _permissionProvider.CanUserDeleteObject(id, user.Id); if (!canDelete) { throw new UnauthorizedAccessException($"User {user.Id} has no delete permission for object {id}"); } } } var interceptors = SnapshotSaveInterceptors(); if (interceptors.Count > 0) { await InvokeDeletingInterceptorsAsync(interceptors, new Interception.RedbDeletingContext { ObjectIds = ids, KnownObjects = knownObjects, EffectiveUser = user, }, cancellationToken); } // Bulk delete via SQL (single query with ANY), counting every object of the batch it deleted. var deletedCount = await ObjectDeleteByIds.RunAsync(_context, Sql, ids.ToArray(), cancellationToken); // === CACHE INVALIDATION (ALWAYS) === if (PropsCache.Instance != null) { foreach (var id in ids) { PropsCache.Remove(id); } } if (interceptors.Count > 0 && deletedCount > 0) { await InvokeDeletedInterceptorsAsync(interceptors, new Interception.RedbDeletedContext { ObjectIds = ids, KnownObjects = knownObjects, EffectiveUser = user, DeletedCount = deletedCount, }, CancellationToken.None); // rows are gone - cancelling the notification would lie (s3.3) } return deletedCount; } // ===== BULK DELETION BY INTERFACE ===== /// /// Bulk deletion of objects by interface (uses _securityContext) /// public async Task DeleteAsync(IEnumerable objects, CancellationToken cancellationToken = default) { var effectiveUser = _securityContext.GetEffectiveUser(); return await DeleteAsync(objects, effectiveUser, cancellationToken); } /// /// Bulk deletion of objects by interface with explicit user /// public async Task DeleteAsync(IEnumerable objects, IRedbUser user, CancellationToken cancellationToken = default) { var objList = objects.ToList(); if (objList.Count == 0) return 0; var ids = objList.Select(o => o.Id).ToList(); // The id funnel, with the instances handed through so interceptors see the objects. var deletedCount = await DeleteByIdsCoreAsync(ids, user, objList, cancellationToken); // === ID RESET STRATEGY === if (_configuration.IdResetStrategy == redb.Core.Models.Configuration.ObjectIdResetStrategy.AutoResetOnDelete) { foreach (var obj in objList) { obj.ResetId(); } } return deletedCount; } // ===== SOFT DELETE (BACKGROUND DELETION) ===== /// /// Mark objects for soft-deletion (uses _securityContext). /// Creates a trash container and moves objects and their descendants under it. /// public async Task SoftDeleteAsync(IEnumerable objectIds, long? trashParentId = null, CancellationToken cancellationToken = default) { var effectiveUser = _securityContext.GetEffectiveUser(); return await SoftDeleteAsync(objectIds, effectiveUser, trashParentId, cancellationToken); } /// /// Mark objects for soft-deletion with explicit user. /// Creates a trash container and moves objects and their descendants under it. /// public async Task SoftDeleteAsync(IEnumerable objectIds, IRedbUser user, long? trashParentId = null, CancellationToken cancellationToken = default) { var ids = objectIds.ToArray(); // mark_for_deletion writes behind a query: an outer transaction has written from here on. Data.TransactionWrites.Mark(_context); if (ids.Length == 0) return new DeletionMark(0, 0); // Check permissions if configured if (_configuration.DefaultCheckPermissionsOnDelete) { foreach (var id in ids) { var canDelete = await _permissionProvider.CanUserDeleteObject(id, user.Id); if (!canDelete) { throw new UnauthorizedAccessException($"User {user.Id} does not have permission to delete object {id}"); } } } // Call the SQL function to mark objects for deletion. One transaction around it, joining // the caller's when there is one: the SQLite mark is several statements, and a failure // between them is rolled back by the transaction's owner, never left open on the handle. // Run again on a deadlock when this transaction is our own (DeadlockRetryHelper). var results = await DeadlockRetryHelper.ExecuteWithRetryAsync(_context, () => _context.ExecuteAtomicAsync( () => _context.QueryAsync( Sql.SoftDelete_MarkForDeletion(), new object[] { ids, user.Id, trashParentId! }, cancellationToken), cancellationToken), cancellationToken: cancellationToken); var result = results.FirstOrDefault() ?? throw new InvalidOperationException("mark_for_deletion function returned no result"); // Invalidate cache for all marked objects if (_configuration.EnablePropsCache && PropsCache.Instance != null) { foreach (var id in ids) { PropsCache.Remove(id); } } _logger?.LogInformation( "Soft-deleted {Count} objects (including descendants). TrashId={TrashId}, User={UserId}", result.marked_count, result.trash_id, user.Id); return new DeletionMark(result.trash_id, (int)result.marked_count); } /// /// Mark objects for soft-deletion (uses _securityContext). /// Creates a trash container and moves objects and their descendants under it. /// public Task SoftDeleteAsync(IEnumerable objects, long? trashParentId = null, CancellationToken cancellationToken = default) { return SoftDeleteAsync(objects.Select(o => o.Id), trashParentId, cancellationToken); } /// /// Mark objects for soft-deletion with explicit user. /// Creates a trash container and moves objects and their descendants under it. /// public Task SoftDeleteAsync(IEnumerable objects, IRedbUser user, long? trashParentId = null, CancellationToken cancellationToken = default) { return SoftDeleteAsync(objects.Select(o => o.Id), user, trashParentId, cancellationToken); } /// /// Delete objects with background purge and progress reporting. /// Marks objects for deletion, then purges them in batches with progress callback. /// public async Task DeleteWithPurgeAsync( IEnumerable objectIds, int batchSize = 10, IProgress? progress = null, CancellationToken cancellationToken = default, long? trashParentId = null) { // Step 1: Mark for deletion (fast, atomic) var mark = await SoftDeleteAsync(objectIds, trashParentId, cancellationToken); if (mark.MarkedCount == 0) return; // Step 2: Purge in batches with progress await PurgeTrashAsync(mark.TrashId, mark.MarkedCount, batchSize, progress, cancellationToken); } /// /// Purge a trash container created by SoftDeleteAsync. /// Physically deletes objects in batches with progress callback. /// public async Task PurgeTrashAsync( long trashId, int totalCount, int batchSize = 10, IProgress? progress = null, CancellationToken cancellationToken = default) { var effectiveUser = _securityContext.GetEffectiveUser(); var deleted = 0; var startedAt = DateTimeOffset.UtcNow; // The purge function writes behind a query: an outer transaction has written from here on. Data.TransactionWrites.Mark(_context); // Unified cancellation semantics (owner decision, 2026-09-08): cancellation is OCE // here like everywhere else - the historical soft return is gone. The token gates // every batch boundary and rides into the purge command itself; a farewell progress // report with PurgeStatus.Cancelled still fires so a UI shows where the purge // stopped. Each purge_trash batch commits on its own, so nothing is lost - the // remainder stays queued in the database and the background worker (or a retry) // picks it up. try { while (true) { cancellationToken.ThrowIfCancellationRequested(); // Call purge_trash SQL function - one transaction per batch (see SoftDeleteAsync), run again on a // deadlock when the batch's transaction is our own (DeadlockRetryHelper). var results = await DeadlockRetryHelper.ExecuteWithRetryAsync(_context, () => _context.ExecuteAtomicAsync( () => _context.QueryAsync( Sql.SoftDelete_PurgeTrash(), new object[] { trashId, batchSize }, cancellationToken), cancellationToken), cancellationToken: cancellationToken); var result = results.FirstOrDefault(); if (result == null) break; if (result.deleted_count == 0) { if (result.remaining_count == 0) break; // Objects remain but none was deleted. Either every one of them is referenced by a // live object - the batch marked the container 'failed' - or another purger (the // background worker beside this call, another node) deleted the batch chosen here // meanwhile: the container stays 'running' and the next batch takes what is left. var state = await GetDeletionProgressAsync(trashId, cancellationToken); if (state == null || state.Status != PurgeStatus.Running) await ThrowTrashReferencedAsync( trashId, result.remaining_count, deleted, startedAt, effectiveUser.Id, progress, cancellationToken); continue; } deleted += (int)result.deleted_count; var remaining = (int)result.remaining_count; var status = remaining == 0 ? PurgeStatus.Completed : PurgeStatus.Running; progress?.Report(new PurgeProgress( trashId, deleted, remaining, status, startedAt, effectiveUser.Id)); if (remaining == 0) { // A dialect whose purge statement cannot remove the finished container itself (SQLite). if (Sql.SoftDelete_DeleteCompletedTrashContainer() is { } removeContainer) await _context.ExecuteAsync(removeContainer, new object[] { trashId }, cancellationToken); break; } } } catch (OperationCanceledException) { progress?.Report(new PurgeProgress( trashId, deleted, totalCount - deleted, PurgeStatus.Cancelled, startedAt, effectiveUser.Id)); throw; } // LogDebug, not LogInformation — each Identity-level DELETE produces its own // trash container with 1 object, so this fires per-operation and floods INF // logs with "Deleted=1" entries (worker restart compounds it via // RecoverOrphanedTasksAsync draining the accumulated backlog one-by-one). // Operators who need per-purge visibility enable DBG for this category. _logger?.LogDebug( "PurgeTrash completed. TrashId={TrashId}, Deleted={Deleted}, User={UserId}", trashId, deleted, effectiveUser.Id); } /// /// A purge that ended with objects no batch may delete: live objects reference them. redb does /// not unlink those references (that would hide the caller's bug inside another object's data), /// so the purge surfaces them - both sides named - after the container was marked 'failed'. /// private async Task ThrowTrashReferencedAsync( long trashId, long remaining, int deleted, DateTimeOffset startedAt, long userId, IProgress? progress, CancellationToken cancellationToken) { var pairs = await _context.QueryAsync( Sql.SoftDelete_SelectLiveReferrersOfTrash(), new object[] { trashId }, cancellationToken); progress?.Report(new PurgeProgress( trashId, deleted, (int)remaining, PurgeStatus.Failed, startedAt, userId)); _logger?.LogWarning( "PurgeTrash failed. TrashId={TrashId}, Deleted={Deleted}, Remaining={Remaining}: objects are referenced by live objects", trashId, deleted, remaining); throw new RedbObjectReferencedException( trashId, remaining, pairs.Select(p => p.referenced_id).Distinct().ToList(), pairs.Select(p => p.referencing_id).Distinct().ToList()); } /// /// Gets deletion progress for a specific trash container from database. /// Returns null if trash container not found or already deleted. /// public async Task GetDeletionProgressAsync(long trashId, CancellationToken cancellationToken = default) { var results = await _context.QueryAsync( Sql.SoftDelete_GetDeletionProgress(), new object[] { trashId }, cancellationToken); var row = results.FirstOrDefault(); if (row == null) return null; return new PurgeProgress( row.trash_id, (int)row.deleted, (int)(row.total - row.deleted), ParsePurgeStatus(row.status), row.started_at, row.owner_id); } /// /// Gets all active (pending/running) deletions for a user from database. /// public async Task> GetUserActiveDeletionsAsync(long userId, CancellationToken cancellationToken = default) { var results = await _context.QueryAsync( Sql.SoftDelete_GetUserActiveDeletions(), new object[] { userId }, cancellationToken); return results.Select(row => new PurgeProgress( row.trash_id, (int)row.deleted, (int)(row.total - row.deleted), ParsePurgeStatus(row.status), row.started_at, row.owner_id)).ToList(); } private static PurgeStatus ParsePurgeStatus(string status) => status switch { "pending" => PurgeStatus.Pending, "running" => PurgeStatus.Running, "completed" => PurgeStatus.Completed, "failed" => PurgeStatus.Failed, "cancelled" => PurgeStatus.Cancelled, _ => PurgeStatus.Pending }; /// /// Gets orphaned deletion tasks for recovery at startup. /// CLUSTER-SAFE: Returns 'pending' OR 'running' with stale _date_modify. /// public async Task> GetOrphanedDeletionTasksAsync(int timeoutMinutes = 30, CancellationToken cancellationToken = default) { var results = await _context.QueryAsync( Sql.SoftDelete_GetOrphanedTasks(), new object[] { timeoutMinutes }, cancellationToken); return results.Select(row => new OrphanedTask( row.trash_id, (int)row.total, (int)row.deleted, row.status, row.owner_id)).ToList(); } /// /// Atomically claim an orphaned task for processing. /// CLUSTER-SAFE: Uses atomic UPDATE to prevent race conditions. /// public async Task TryClaimOrphanedTaskAsync(long trashId, int timeoutMinutes = 30, CancellationToken cancellationToken = default) { var affected = await _context.ExecuteAsync( Sql.SoftDelete_ClaimOrphanedTask(), new object[] { trashId, timeoutMinutes }, cancellationToken); return affected > 0; } /// /// Internal DTO for orphaned task query results. /// private class OrphanedTaskRow { public long trash_id { get; set; } public long total { get; set; } public long deleted { get; set; } public string status { get; set; } = ""; public long owner_id { get; set; } } // ===== BULK LOADING BY ID ===== /// /// Bulk load objects by ID (uses _securityContext) /// Supports polymorphic loading of objects from different schemes /// public async Task> LoadAsync(IEnumerable objectIds, int depth = 10, CancellationToken cancellationToken = default) { var effectiveUser = _securityContext.GetEffectiveUser(); return await LoadAsync(objectIds, effectiveUser, depth, cancellationToken); } /// /// Bulk loading of objects by ID with explicit user /// Supports two modes: EAGER (get_object_json) and LAZY (_objects + LoadPropsForManyAsync) /// public async Task> LoadAsync(IEnumerable objectIds, IRedbUser user, int depth = 10, CancellationToken cancellationToken = default) { var ids = objectIds.ToList(); if (ids.Count == 0) return new List(); var result = new List(); var idsToLoad = new List(); // === STEP 1: Cache check (if enabled) === // One query resolves the hash and scheme of every id (the polymorphic load needs the schemes anyway), and // the cache answers by hash. SkipHashValidationOnCacheCheck changes nothing here: it used to switch the // cache off for the batch (every object rematerialized), and without it the batch asked the database once // per id. This is the road of the list-item preload and of LoadLinkedObjectsAsync. if (_configuration.EnablePropsCache && PropsCache.Instance != null) { var rows = await _context.QueryAsync( Sql.ObjectStorage_SelectObjectsByIds(), new object[] { ids.ToArray() }, cancellationToken); var rowById = new Dictionary(rows.Count); foreach (var row in rows) rowById[row.Id] = row; var hits = new List<(long Id, IRedbObject Obj)>(); foreach (var id in ids) { IRedbObject? cachedObj = null; if (rowById.TryGetValue(id, out var row) && row.Hash.HasValue) { // Get type through AutomaticTypeRegistry var propsType = Cache.GetClrType(row.IdScheme); if (propsType != null) { // Typed Get(id, hash): the delegate is built once per props type. cachedObj = Caching.CacheDelegates.Get(PropsCache, propsType, id, row.Hash.Value); } } if (cachedObj != null) hits.Add((id, cachedObj)); // Cache HIT, checked for a stale graph below else idsToLoad.Add(id); // Cache MISS, or the object does not exist - the load reports that } // A cached graph keeps the references it was loaded with, and a target that changed or left for the // trash moves neither this object's hash nor its cache entry. One query checks every reference of // every hit; a stale graph is dropped and its object is read again. if (hits.Count > 0) { var stale = await FindStaleCachedGraphsAsync(hits.Select(h => h.Obj), cancellationToken); foreach (var (id, obj) in hits) { if (stale.Contains(id)) { PropsCache.Remove(id); idsToLoad.Add(id); } else { result.Add(obj); } } } } else { idsToLoad = ids; } if (idsToLoad.Count == 0) { return result; // All from cache! } // === STEP 2: Permission check === if (_configuration.DefaultCheckPermissionsOnLoad) { foreach (var id in idsToLoad) { var canRead = await _permissionProvider.CanUserSelectObject(id, user.Id); if (!canRead) { throw new UnauthorizedAccessException($"User {user.Id} has no read permission for object {id}"); } } } // === STEP 3: Loading missing objects === // V4 (L.0): the old per-call lazy switch is gone. Free loads eagerly via // get_object_json; Pro overrides LoadObjectsEagerAsync to its batch materializer. var loadedObjects = await LoadObjectsEagerAsync(idsToLoad, depth, cancellationToken); result.AddRange(loadedObjects); // === STEP 4: Check if all objects are found === if (_configuration.ThrowOnObjectNotFound) { var loadedIds = result.Select(o => o.Id).ToHashSet(); var missingIds = ids.Where(id => !loadedIds.Contains(id)).ToList(); if (missingIds.Count > 0) { throw new InvalidOperationException($"Objects with ID [{string.Join(", ", missingIds)}] not found"); } } return result; } /// /// LAZY loading: base fields from _objects + LoadPropsForManyAsync /// protected for access from Pro version /// protected async Task> LoadObjectsLazyAsync(List objectIds, int depth, CancellationToken cancellationToken = default) { if (objectIds.Count == 0) return new List(); // Load base fields from _objects via SQL var baseObjects = await _context.QueryAsync( Sql.ObjectStorage_SelectObjectsByIds(), new object[] { objectIds.ToArray() }, cancellationToken); if (baseObjects.Count == 0) return new List(); // Group by scheme_id for polymorphic deserialization var result = new List(); var objectsByScheme = baseObjects.GroupBy(o => o.IdScheme); foreach (var schemeGroup in objectsByScheme) { var schemeId = schemeGroup.Key; var objectsForScheme = schemeGroup.ToList(); // Resolve scheme_id → Type: lazy, self-healing, cross-domain-safe (loads the scheme by // id and derives via the global ClrSchemeTypeIndex if this domain hasn't seen it yet). // Null means the scheme genuinely has no CLR type → a legitimately non-generic object. var propsType = await Cache.ResolveClrTypeAsync(schemeId, SchemeSyncProvider); if (propsType == null) { // Non-generic RedbObject (Object scheme) - create without Props foreach (var baseObj in objectsForScheme) { result.Add(CreateNonGenericRedbObject(baseObj)); } continue; } // Create typed RedbObject var createMethod = typeof(ObjectStorageProviderBase) .GetMethod(nameof(CreateRedbObjectsFromBaseObjects), System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)? .MakeGenericMethod(propsType); if (createMethod != null) { var createTask = (Task)createMethod.Invoke(this, new object[] { objectsForScheme, depth })!; await createTask; var typedObjects = createTask.GetType().GetProperty("Result")?.GetValue(createTask) as System.Collections.IEnumerable; if (typedObjects != null) { foreach (var obj in typedObjects) { if (obj is IRedbObject redbObj) { result.Add(redbObj); } } } } } return result; } /// /// Create non-generic RedbObject from RedbObjectRow (Object scheme, no Props). /// private RedbObject CreateNonGenericRedbObject(RedbObjectRow baseObj) { var obj = new RedbObject(); baseObj.ApplyHeaderTo(obj); return obj; } /// /// Creates RedbObject<TProps> from base RedbObjectRow fields with LazyPropsLoader and LoadPropsForManyAsync /// private async Task>> CreateRedbObjectsFromBaseObjects(List baseObjects, int depth) where TProps : class, new() { var redbObjects = baseObjects.Select(baseObj => { var obj = baseObj.ToRedbObject(); obj._lazyLoader = CreateLazyPropsLoader(); return obj; }).ToList(); // Bulk load Props via LoadPropsForManyAsync at the requested depth (V4: no sync-over-async) var lazyLoader = CreateLazyPropsLoader(); await lazyLoader.LoadPropsForManyAsync(redbObjects, propsDepth: depth); // Cache loaded objects - once the transaction commits (CachePublication). if (_configuration.EnablePropsCache && PropsCache.Instance != null) { Caching.CachePublication.AfterCommit(_context, () => { foreach (var obj in redbObjects.Where(o => o.hash.HasValue)) PropsCache.Set(obj); }); } return redbObjects; } /// /// EAGER loading: get_object_json for all IDs /// Open Source: uses get_object_json /// Pro: overrides for PVT approach /// protected virtual async Task> LoadObjectsEagerAsync(List objectIds, int depth, CancellationToken cancellationToken) { if (objectIds.Count == 0) return new List(); // Use unnest for bulk get_object_json call var idsArray = objectIds.ToArray(); // Execute get_object_json for each ID via SQL var objectsJsonList = await _context.ExecuteJsonListAsync( Sql.ObjectStorage_GetObjectsJsonBulk(), new object[] { idsArray, depth }, cancellationToken); var result = new List(); foreach (var objectJson in objectsJsonList) { if (string.IsNullOrEmpty(objectJson)) continue; // Extract scheme_id from JSON for polymorphic deserialization using var jsonDoc = System.Text.Json.JsonDocument.Parse(objectJson); var schemeId = jsonDoc.RootElement.GetProperty("scheme_id").GetInt64(); // Get type through AutomaticTypeRegistry var propsType = Cache.GetClrType(schemeId); if (propsType == null) { // Non-generic RedbObject (Object scheme) - deserialize base fields only var baseObj = System.Text.Json.JsonSerializer.Deserialize(objectJson); if (baseObj != null) { result.Add(baseObj); } continue; } // Dynamic deserialization var redbObj = _serializer.DeserializeRedbDynamic(objectJson, propsType); if (redbObj != null) { Utils.LazyReferenceInstaller.Install(redbObj, CreateLazyPropsLoader()); // V4 (L.3) // Cache main + nested objects if (_configuration.EnablePropsCache && PropsCache.Instance != null && redbObj.Hash.HasValue) { // The object and its nested objects in one walk. Caching.CacheDelegates.SetGraph(PropsCache, redbObj); } result.Add(redbObj); } } return result; } // ===== LAZY REFERENCE RELOAD (V4, LAZY Л2 §4.6) ===== /// public async Task LoadReferencesAsync(RedbObject parent, Func?>?> references, CancellationToken cancellationToken = default) where TProps : class, new() where TRef : class, new() { var props = parent?.GetPropsDirectly(); if (props == null) return; var stubs = (references(props) ?? Enumerable.Empty?>()) .Where(r => r is { id: > 0 } && !r.IsPropsLoaded) .Select(r => r!) .ToList(); if (stubs.Count == 0) return; // One batch: the loader checks the props cache first, then fetches the misses together. // Depth 1, exactly like a stub's first Props access: the reloaded objects' own references // are stubs again - laziness stays transitive through the batch form (§4.7). await CreateLazyPropsLoader().LoadPropsForManyAsync(stubs, propsDepth: 1, cancellationToken: cancellationToken); } /// public Task LoadReferencesAsync(RedbObject parent, Func?> reference, CancellationToken cancellationToken = default) where TProps : class, new() where TRef : class, new() => LoadReferencesAsync(parent, p => new[] { reference(p) }, cancellationToken); // ===== LOAD WITH PARENT CHAIN ===== /// /// Load object by ID with parent chain to root (uses _securityContext). /// public async Task?> LoadWithParentsAsync(long objectId, int depth = 10, CancellationToken cancellationToken = default) where TProps : class, new() { var effectiveUser = _securityContext.GetEffectiveUser(); return await LoadWithParentsAsync(objectId, effectiveUser, depth, cancellationToken); } /// /// Load object with parent chain to root (uses _securityContext). /// public async Task?> LoadWithParentsAsync(IRedbObject obj, int depth = 10, CancellationToken cancellationToken = default) where TProps : class, new() { var effectiveUser = _securityContext.GetEffectiveUser(); return await LoadWithParentsAsync(obj.Id, effectiveUser, depth, cancellationToken); } /// /// Load object by ID with parent chain to root with explicit user. /// public async Task?> LoadWithParentsAsync(IRedbObject obj, IRedbUser user, int depth = 10, CancellationToken cancellationToken = default) where TProps : class, new() { return await LoadWithParentsAsync(obj.Id, user, depth, cancellationToken); } /// /// MAIN LoadWithParentsAsync - loads single object with parent chain. /// Delegates to bulk method for implementation reuse. /// public async Task?> LoadWithParentsAsync(long objectId, IRedbUser user, int depth = 10, CancellationToken cancellationToken = default) where TProps : class, new() { var list = await LoadWithParentsAsync(new[] { objectId }, user, depth, cancellationToken); return list.FirstOrDefault(); } /// /// Bulk load objects with parent chains (uses _securityContext). /// public async Task>> LoadWithParentsAsync(IEnumerable objectIds, int depth = 10, CancellationToken cancellationToken = default) where TProps : class, new() { var effectiveUser = _securityContext.GetEffectiveUser(); return await LoadWithParentsAsync(objectIds, effectiveUser, depth, cancellationToken); } /// /// MAIN bulk LoadWithParentsAsync - loads objects with parent chains to root. /// Uses recursive CTE to get all ancestor IDs, then bulk loads all objects. /// Parents are loaded polymorphically (each with its real Props type). /// public async Task>> LoadWithParentsAsync(IEnumerable objectIds, IRedbUser user, int depth = 10, CancellationToken cancellationToken = default) where TProps : class, new() { var ids = objectIds.ToList(); if (ids.Count == 0) return new List>(); // 1. Get IDs of all objects and their ancestors via recursive CTE var allIds = await _context.QueryScalarListAsync(_sql.Tree_SelectIdsWithAncestors(), new object[] { ids.ToArray(), TreeProviderBase.MaxAncestorDepth }, cancellationToken); // 2. Load all objects polymorphically (target + parents with real types) var loadedObjects = await LoadAsync(allIds, user, depth, cancellationToken); // 3. Convert to ITreeRedbObject (polymorphic - each keeps its real Props type) var treeObjects = new Dictionary(); foreach (var obj in loadedObjects) { treeObjects[obj.Id] = Utils.TreeObjectConverter.ToTreeObjectDynamic(obj); } // 4. Build Parent relationships (polymorphic) Utils.TreeObjectConverter.BuildParentRelationships(treeObjects.Values); // 5. Return only requested objects that match TProps type return ids .Where(id => treeObjects.ContainsKey(id) && treeObjects[id] is TreeRedbObject) .Select(id => (TreeRedbObject)treeObjects[id]) .ToList(); } /// /// Bulk polymorphic load with parent chains (uses _securityContext). /// public async Task> LoadWithParentsAsync(IEnumerable objectIds, int depth = 10, CancellationToken cancellationToken = default) { var effectiveUser = _securityContext.GetEffectiveUser(); return await LoadWithParentsAsync(objectIds, effectiveUser, depth, cancellationToken); } /// /// MAIN bulk polymorphic LoadWithParentsAsync. /// Preserves actual Props types for each object. /// public async Task> LoadWithParentsAsync(IEnumerable objectIds, IRedbUser user, int depth = 10, CancellationToken cancellationToken = default) { var ids = objectIds.ToList(); if (ids.Count == 0) return new List(); // 1. Get IDs of all objects and their ancestors var allIds = await _context.QueryScalarListAsync(_sql.Tree_SelectIdsWithAncestors(), new object[] { ids.ToArray(), TreeProviderBase.MaxAncestorDepth }, cancellationToken); // 2. Load all objects var loadedObjects = await LoadAsync(allIds, user, depth, cancellationToken); // 3. Convert to ITreeRedbObject and build dictionary var treeObjects = new Dictionary(); foreach (var obj in loadedObjects) { treeObjects[obj.Id] = Utils.TreeObjectConverter.ToTreeObjectDynamic(obj); } // 4. Build Parent relationships Utils.TreeObjectConverter.BuildParentRelationships(treeObjects.Values); // 5. Return only requested objects return ids .Where(id => treeObjects.ContainsKey(id)) .Select(id => treeObjects[id]) .ToList(); } public async Task SaveAsync(IRedbObject obj, IRedbUser user, CancellationToken cancellationToken = default) where TProps : class, new() { // Route through Batch pipeline — same TX + FOR UPDATE + DeadlockRetry for all strategies var results = await SaveAsync(new[] { (IRedbObject)obj }, user, cancellationToken); return results.FirstOrDefault(); } /// public Task LockForUpdateAsync(params long[] objectIds) => LockForUpdateAsync(objectIds, CancellationToken.None); /// public async Task LockForUpdateAsync(long[] objectIds, CancellationToken cancellationToken) { if (objectIds == null || objectIds.Length == 0) return 0; // SELECT _id ... FOR UPDATE/UPDLOCK: the rows that exist come back (and are locked); // the count is the caller\x27s signal. A deleted id locks nothing and MUST NOT be taken // for locked (BR-9, 2026-09-02: with the default AutoSwitchToInsert a CAS save after // a silent no-op lock resurrects the deleted object). var locked = await _context.QueryScalarListAsync( _sql.ObjectStorage_LockObjectsForUpdate(), new object[] { objectIds }, cancellationToken).ConfigureAwait(false); return locked.Count; } /// public Task LockForUpdateRequiredAsync(params long[] objectIds) => LockForUpdateRequiredAsync(objectIds, CancellationToken.None); /// public async Task LockForUpdateRequiredAsync(long[] objectIds, CancellationToken cancellationToken) { if (objectIds == null || objectIds.Length == 0) return; if (!_context.IsInTransaction) throw new InvalidOperationException( "LockForUpdateRequiredAsync must run inside an active transaction: a row lock " + "lives only until its transaction ends, so a lock taken outside one guarantees " + "nothing. Wrap the lock and the work it protects in ExecuteAtomicAsync or " + "BeginTransactionAsync."); var requested = objectIds.Distinct().ToArray(); var locked = await _context.QueryScalarListAsync( _sql.ObjectStorage_LockObjectsForUpdate(), new object[] { requested }, cancellationToken).ConfigureAwait(false); if (locked.Count == requested.Length) return; throw new RedbLockNotAcquiredException( requested, requested.Except(locked).OrderBy(x => x).ToArray()); } // CT-3 (ревью 2026-09-03, снесено 2026-09-04): здесь жил мёртвый одиночный путь // сохранения свойств (SavePropertiesAsync со своим Delete/Insert и ВТОРЫМ, расходящимся // алгоритмом ChangeTracking) - точка входа не имела ни одного вызова. Все сохранения V4 // идут батч-конвейером SaveAsync; Free заявляет ChangeTracking как NotSupported в // ExecuteBatchByStrategy, живой CT - в redb.Core.Pro. Вместе с кластером удалены его // хелперы (Methods.cs целиком) и пара мёртвых SQL-методов диалектов. /// /// Get scheme structures with full metadata including _store_null /// private async Task> GetStructuresWithMetadataAsync(long schemeId) { // Load structures with type info via SQL join var rows = await _context.QueryAsync( Sql.ObjectStorage_SelectStructuresWithMetadata(), schemeId); return rows.Select(r => new StructureMetadata { Id = r.Id, IdParent = r.IdParent, Name = r.Name, DbType = r.DbType, IsArray = r.CollectionType != null, CollectionType = r.CollectionType, KeyType = r.KeyType, StoreNull = r.StoreNull, Unique = r.Unique, UniqueScope = r.UniqueScope, TypeSemantic = r.TypeSemantic }).ToList(); } /// /// Helper class for mapping structure metadata query results. /// private class StructureMetadataRow { public long Id { get; set; } public long? IdParent { get; set; } public string Name { get; set; } = string.Empty; public string DbType { get; set; } = "String"; public long? CollectionType { get; set; } public long? KeyType { get; set; } public bool StoreNull { get; set; } public bool Unique { get; set; } public long? UniqueScope { get; set; } public string TypeSemantic { get; set; } = "string"; } /// /// AUTOSAVE: Processes nested RedbObjects, saving them recursively /// private async Task ProcessNestedObjectsAsync(object rawValue, string dbType, bool isArray) { if (rawValue == null) return null; // Process arrays if (isArray && rawValue is System.Collections.IEnumerable enumerable && rawValue is not string) { var processedList = new List(); foreach (var item in enumerable) { if (IsRedbObjectWithoutId(item)) { var nestedObj = (IRedbObject)item; var savedId = await SaveAsync(nestedObj); processedList.Add(savedId); } else if (IsRedbObjectWithId(item)) { processedList.Add(((IRedbObject)item).Id); } else if (item is IRedbListItem listItemInArray) { // Process IRedbListItem in array - extract Id processedList.Add(listItemInArray.Id); } else { processedList.Add(item); } } return processedList; } // Process single objects if (IsRedbObjectWithoutId(rawValue)) { var nestedObj = (IRedbObject)rawValue; var savedId = await SaveAsync(nestedObj); return savedId; } if (IsRedbObjectWithId(rawValue)) { return ((IRedbObject)rawValue).Id; } // Process IRedbListItem - extract Id if (rawValue is IRedbListItem listItem) { return listItem.Id; } return rawValue; } /// /// Checks if object is IRedbObject with Id = 0 (needs saving) /// private static bool IsRedbObjectWithoutId(object? value) { if (value is IRedbObject redbObj) { return redbObj.Id == 0; } return false; } /// /// Checks if object is IRedbObject with Id != 0 (already saved) /// private static bool IsRedbObjectWithId(object? value) { if (value is IRedbObject redbObj) { return redbObj.Id != 0; } return false; } /// /// UPDATED VERSION: Removed JSON arrays, only simple types /// private static void SetSimpleValueByType(RedbValue valueRecord, string dbType, object? processedValue) { if (processedValue == null) return; // ARRAYS NOT PROCESSED - they go through SaveArrayFieldAsync // Direct assignment of typed values switch (dbType) { case "String": case "Text": // A plain ToString() of a DateOnly uses the CURRENT culture, so a value written under one // culture failed or silently mis-parsed under another: the invariant round-trip form. valueRecord.String = processedValue switch { DateOnly dateOnly => Core.Utils.RedbTemporalFormat.ToText(dateOnly), _ => processedValue?.ToString() }; break; case "Long": case "bigint": // TimeOnly and TimeSpan carry db_type "Long" (_types seed): their Ticks. if (processedValue is TimeSpan timeSpan) valueRecord.Long = timeSpan.Ticks; else if (processedValue is TimeOnly timeOnly) valueRecord.Long = timeOnly.Ticks; else if (processedValue is long longVal) valueRecord.Long = longVal; else if (processedValue is int intVal) valueRecord.Long = intVal; else if (long.TryParse(processedValue?.ToString(), out var parsedLong)) valueRecord.Long = parsedLong; break; case "Double": if (processedValue is double doubleVal) valueRecord.Double = doubleVal; else if (processedValue is float floatVal) valueRecord.Double = floatVal; else if (double.TryParse(processedValue?.ToString(), out var parsedDouble)) valueRecord.Double = parsedDouble; break; case "Numeric": // Precise decimal numbers for financial calculations if (processedValue is decimal decimalVal) valueRecord.Numeric = decimalVal; else if (processedValue is double doubleVal2) valueRecord.Numeric = redb.Core.Utils.RedbDecimal.FromDouble(doubleVal2); else if (processedValue is float floatVal2) valueRecord.Numeric = redb.Core.Utils.RedbDecimal.FromSingle(floatVal2); else if (decimal.TryParse(processedValue?.ToString(), out var parsedDecimal)) valueRecord.Numeric = parsedDecimal; break; case "Boolean": if (processedValue is bool boolVal) valueRecord.Boolean = boolVal; else if (bool.TryParse(processedValue?.ToString(), out var parsedBool)) valueRecord.Boolean = parsedBool; break; // db_type "DateTime" belongs to DateOnly (the CLR DateTime type carries db_type // "DateTimeOffset" and is handled in the branch below, discriminated by the // runtime type of the value). case "DateTime": if (processedValue is DateOnly dateOnlyValue) { // Midnight of that date, as a zone-less clock reading. Was previously // DateTime.TryParse(dateOnly.ToString()) — a round-trip through the // current culture's short date pattern. valueRecord.DateTimeOffset = Core.Utils.DateTimeConverter.NormalizeForStorage( dateOnlyValue.ToDateTime(TimeOnly.MinValue)); } else if (processedValue is DateTime dateTime) { // Use centralized converter: DateTime → UTC valueRecord.DateTimeOffset = Core.Utils.DateTimeConverter.NormalizeForStorage(dateTime); } else if (Core.Utils.RedbTemporalFormat.TryParseDateOnly(processedValue?.ToString(), out var parsedDateOnly)) { valueRecord.DateTimeOffset = Core.Utils.DateTimeConverter.NormalizeForStorage( parsedDateOnly.ToDateTime(TimeOnly.MinValue)); } break; case "DateTimeOffset": if (processedValue is DateTimeOffset dateTimeOffset) valueRecord.DateTimeOffset = dateTimeOffset; else if (processedValue is DateTime dt) valueRecord.DateTimeOffset = Core.Utils.DateTimeConverter.NormalizeForStorage(dt); // DateOnly stores midnight of that date as a zone-less reading. It carries // db_type "DateTimeOffset" so that every JSON projection, PVT builder and the // SQLite native extension handle it through the branch they already have. else if (processedValue is DateOnly dateOnlyForOffset) valueRecord.DateTimeOffset = Core.Utils.DateTimeConverter.NormalizeForStorage( dateOnlyForOffset.ToDateTime(TimeOnly.MinValue)); else if (DateTimeOffset.TryParse(processedValue?.ToString(), System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.RoundtripKind, out var parsedDate)) valueRecord.DateTimeOffset = parsedDate; break; case "ByteArray": if (processedValue is byte[] byteArray) valueRecord.ByteArray = byteArray; break; case "Object": // Object references are stored in separate _object field if (processedValue is long objectId) valueRecord.Object = objectId; else if (long.TryParse(processedValue?.ToString(), out var parsedObjId)) valueRecord.Object = parsedObjId; break; case "ListItem": // ListItem references are stored in separate _listitem field if (processedValue is IRedbListItem listItem) { valueRecord.ListItem = listItem.Id; } else if (processedValue is long listItemId) { valueRecord.ListItem = listItemId; } else if (long.TryParse(processedValue?.ToString(), out var parsedListId)) { valueRecord.ListItem = parsedListId; } else { throw new InvalidOperationException( $"ListItem value cannot be processed: value='{processedValue}', type='{processedValue?.GetType().FullName}'."); } break; case "Guid": if (processedValue is Guid guidVal) valueRecord.Guid = guidVal; else if (Guid.TryParse(processedValue?.ToString(), out var parsedGuid)) valueRecord.Guid = parsedGuid; break; default: valueRecord.String = processedValue?.ToString(); break; } } /// /// Converts IRedbStructure to StructureMetadata getting type info from cache /// private async Task> ConvertStructuresToMetadataAsync(IEnumerable structures) { var result = new List(); foreach (var structure in structures) { // Get type info by IdType via cache or DB var typeInfo = await GetTypeInfoAsync(structure.IdType); result.Add(new StructureMetadata { Id = structure.Id, IdParent = structure.IdParent, Name = structure.Name, DbType = typeInfo.DbType, IsArray = structure.CollectionType != null, StoreNull = structure.StoreNull ?? false, Unique = structure.Unique ?? false, TypeSemantic = typeInfo.TypeSemantic }); } return result; } /// /// Gets type info by IdType. /// private async Task<(string DbType, string TypeSemantic)> GetTypeInfoAsync(long typeId) { // Direct SQL query for type info var typeEntity = await _context.QueryFirstOrDefaultAsync( Sql.ObjectStorage_SelectTypeById(), typeId); return typeEntity != null ? (typeEntity.DbType ?? "String", typeEntity.Type1 ?? "string") : ("String", "string"); } /// /// OPTIMIZATION: Get scheme from cache WITHOUT hash validation /// Used inside SaveAsync transactions where scheme is guaranteed not to change /// protected async Task GetSchemeFromCacheOrDbAsync(long schemeId) { // First check cache WITHOUT DB query for hash validation var cachedScheme = Cache.GetScheme(schemeId); if (cachedScheme != null) { return cachedScheme; // Cache HIT - return without validation } // Cache MISS - load via provider (it will cache) return await _schemeSync.GetSchemeByIdAsync(schemeId); } } /// /// Structure metadata with extended info including _store_null /// internal class StructureMetadata { public long Id { get; set; } public long? IdParent { get; set; } // Add field for structure hierarchy public string Name { get; set; } = string.Empty; public string DbType { get; set; } = "String"; public bool IsArray { get; set; } public long? CollectionType { get; set; } // Array, Dictionary, etc. public long? KeyType { get; set; } // Key type for Dictionary public bool StoreNull { get; set; } /// The field is a [RedbUnique] key: its root scalar values carry a hash in _unique. public bool Unique { get; set; } /// S3: element-key scope of a collection key (null = default reading). public long? UniqueScope { get; set; } public string TypeSemantic { get; set; } = "string"; /// /// True if this is a Dictionary field /// public bool IsDictionary => CollectionType == RedbTypeIds.Dictionary; } /// /// DTO for mark_for_deletion SQL function result. /// internal class MarkForDeletionResult { public long trash_id { get; set; } public long marked_count { get; set; } } /// /// DTO for purge_trash SQL function result. /// internal class PurgeTrashResult { public long deleted_count { get; set; } public long remaining_count { get; set; } } /// /// DTO for the live-referrers-of-trash query: a trashed object and a live object referencing it. /// internal class TrashReferrerRow { public long referenced_id { get; set; } public long referencing_id { get; set; } } /// /// DTO for deletion progress SQL query result. /// internal class TrashProgressRow { public long trash_id { get; set; } public long total { get; set; } public long deleted { get; set; } public string status { get; set; } = "pending"; public DateTimeOffset started_at { get; set; } public long owner_id { get; set; } } } Path: redb/redb.Core/Providers/Base/ObjectStorageProviderExtensions.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/ObjectStorageProviderExtensions.cs ---- using redb.Core.Data; using redb.Core.Utils; using System.Text.Json.Serialization; using System.Reflection; namespace redb.Core.Providers.Base { /// /// Extensions for PostgresObjectStorageProvider under the new saving paradigm /// public static class ObjectStorageProviderExtensions { // ===== NEW METHODS FOR FIELD PROCESSING UNDER THE NEW PARADIGM ===== /// /// Determine if a record should be created in _values based on value and _store_null /// internal static bool ShouldCreateValueRecord(object? rawValue, bool storeNull) { // If the value is not NULL - always create a record if (rawValue != null) return true; // If the value is NULL - create a record only if _store_null = true return storeNull; } /// /// Check if the type is a Class type (business class, not a primitive) /// internal static bool IsClassType(string typeSemantic) { // FIXED: Class type has Type1 = "Object" (looking at TypeSemantic from _types._type) // Business classes are mapped to type "Class" with _type="Object" return typeSemantic == "Object"; } /// /// Check if the type is a RedbObject<> reference /// internal static bool IsRedbObjectReference(string typeSemantic) { return typeSemantic == "RedbObjectRow"; } } } Path: redb/redb.Core/Providers/Base/PermissionProviderBase.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/PermissionProviderBase.cs ---- using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using redb.Core.Data; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using redb.Core.Models.Enums; using redb.Core.Models.Permissions; using redb.Core.Models.Security; using redb.Core.Query; using Microsoft.Extensions.Logging; namespace redb.Core.Providers.Base; /// /// Base implementation of permission provider with common business logic. /// Database-specific providers inherit from this class and provide ISqlDialect. /// /// IMPORTANT: Uses DB-specific SQL function for effective permissions! /// PostgreSQL: get_user_permissions_for_object() /// MSSQL: Must provide equivalent CTE/JOIN query /// public abstract class PermissionProviderBase : IPermissionProvider { protected readonly IRedbContext Context; protected readonly IRedbSecurityContext SecurityContext; protected readonly ISqlDialect Sql; protected readonly ILogger? Logger; // Permission cache for SQL results. Shared by the process, keyed by database first: ids are per database, and two // databases hand out the same user and object ids (the system admin is id 1 in every one), so a key of user and // object alone served one database's permission for another (review 2026-09-24, C-1). private static readonly ConcurrentDictionary PermissionCache = new(); private static readonly TimeSpan CacheLifetime = TimeSpan.FromMinutes(5); private static long _cacheRequests; private static long _cacheHits; // A provider built outside a service has no database name; its entries stay its own rather than guess one. private readonly string _instanceDomain = "instance:" + Guid.NewGuid().ToString("N"); /// /// The database this provider reads (the service's cache domain), set by the service that owns it. Part of every /// permission cache key. /// internal string? CacheDomain { get; set; } private string KeyPrefix => (CacheDomain ?? _instanceDomain) + "|"; private string CacheKey(long userId, long objectId) => $"{KeyPrefix}{userId}_{objectId}"; protected PermissionProviderBase( IRedbContext context, IRedbSecurityContext securityContext, ISqlDialect sql, ILogger? logger = null) { Context = context ?? throw new ArgumentNullException(nameof(context)); SecurityContext = securityContext ?? throw new ArgumentNullException(nameof(securityContext)); Sql = sql ?? throw new ArgumentNullException(nameof(sql)); Logger = logger; } // ============================================================ // === EFFECTIVE PERMISSION VIA SQL === // ============================================================ /// /// Get effective permission via SQL (uses DB function or query). /// Override in derived class for DB-specific optimizations. /// protected virtual async Task GetEffectivePermissionViaSqlAsync(long objectId, long userId, CancellationToken cancellationToken = default) { var cacheKey = CacheKey(userId, objectId); Interlocked.Increment(ref _cacheRequests); if (PermissionCache.TryGetValue(cacheKey, out var cached)) { var isExpired = DateTimeOffset.UtcNow - cached.cachedAt > CacheLifetime; if (!isExpired) { Interlocked.Increment(ref _cacheHits); return cached.result; } } var result = await Context.QueryFirstOrDefaultAsync( Sql.Permissions_GetEffectiveForObject(), new object[] { objectId, userId }, cancellationToken); if (result != null) { PermissionCache[cacheKey] = (result, DateTimeOffset.UtcNow); } return result; } /// /// Synchronous twin of for the /// thread-pool-free lazy path: same cache, same SQL, executed on the calling thread. /// protected virtual UserPermissionResult? GetEffectivePermissionViaSql(long objectId, long userId) { var cacheKey = CacheKey(userId, objectId); Interlocked.Increment(ref _cacheRequests); if (PermissionCache.TryGetValue(cacheKey, out var cached)) { var isExpired = DateTimeOffset.UtcNow - cached.cachedAt > CacheLifetime; if (!isExpired) { Interlocked.Increment(ref _cacheHits); return cached.result; } } var result = Context.QueryFirstOrDefault( Sql.Permissions_GetEffectiveForObject(), objectId, userId); if (result != null) { PermissionCache[cacheKey] = (result, DateTimeOffset.UtcNow); } return result; } /// public virtual bool CanUserSelectObjectSync(long objectId, long userId) { if (userId == 0) return true; var permission = GetEffectivePermissionViaSql(objectId, userId); if (permission == null) throw new InvalidOperationException($"Cannot get permissions for object {objectId} and user {userId}."); return permission.CanSelect; } /// /// Invalidate permission cache. Called after permission changes. /// /// /// Only this database's entries: a permission change in one database says nothing about another. Other /// processes (nodes of a cluster) are not reached and keep their entries until CacheLifetime runs out. /// protected void InvalidatePermissionCache(long? userId = null, long? objectId = null) { var prefix = KeyPrefix; if (userId.HasValue && objectId.HasValue) { PermissionCache.TryRemove(CacheKey(userId.Value, objectId.Value), out _); return; } var userPrefix = userId.HasValue ? $"{prefix}{userId}_" : prefix; var objectSuffix = objectId.HasValue ? $"_{objectId}" : null; var keysToRemove = PermissionCache.Keys .Where(k => k.StartsWith(userPrefix, StringComparison.Ordinal) && (objectSuffix == null || k.EndsWith(objectSuffix, StringComparison.Ordinal))) .ToList(); foreach (var key in keysToRemove) PermissionCache.TryRemove(key, out _); } /// /// Get cache statistics for monitoring. /// public static string GetCacheStatistics() { var hitRate = _cacheRequests > 0 ? (double)_cacheHits / _cacheRequests * 100 : 0; return $"Permission cache: Requests={_cacheRequests}, Hits={_cacheHits}, " + $"Hit Rate={hitRate:F1}%, Entries={PermissionCache.Count}"; } // ============================================================ // === BASE METHODS (using SecurityContext) === // ============================================================ /// public virtual IQueryable GetReadableObjectIds() { var effectiveUser = ((RedbSecurityContext)SecurityContext).GetEffectiveUser(); return GetReadableObjectIds(effectiveUser.Id); } /// public virtual async Task CanUserEditObject(IRedbObject obj, CancellationToken cancellationToken = default) { var effectiveUser = ((RedbSecurityContext)SecurityContext).GetEffectiveUser(); return await CanUserEditObject(obj.Id, effectiveUser.Id); } /// public virtual async Task CanUserSelectObject(IRedbObject obj, CancellationToken cancellationToken = default) { var effectiveUser = ((RedbSecurityContext)SecurityContext).GetEffectiveUser(); return await CanUserSelectObject(obj.Id, effectiveUser.Id); } /// public virtual async Task CanUserInsertScheme(IRedbScheme scheme, CancellationToken cancellationToken = default) { var effectiveUser = ((RedbSecurityContext)SecurityContext).GetEffectiveUser(); return await CanUserInsertScheme(scheme.Id, effectiveUser.Id); } /// public virtual async Task CanUserDeleteObject(IRedbObject obj, CancellationToken cancellationToken = default) { var effectiveUser = ((RedbSecurityContext)SecurityContext).GetEffectiveUser(); return await CanUserDeleteObject(obj.Id, effectiveUser.Id); } // ============================================================ // === METHODS WITH EXPLICIT USER === // ============================================================ /// public virtual IQueryable GetReadableObjectIds(IRedbUser user) { return GetReadableObjectIds(user.Id); } /// public virtual IQueryable GetReadableObjectIds(long userId) { var ids = GetReadableObjectIdsAsync(userId).GetAwaiter().GetResult(); return ids.AsQueryable(); } /// /// Async version of GetReadableObjectIds. /// protected virtual async Task> GetReadableObjectIdsAsync(long userId, CancellationToken cancellationToken = default) { return await Context.QueryAsync(Sql.Permissions_SelectReadableObjectIds(), new object[] { userId }, cancellationToken); } /// public virtual async Task CanUserEditObject(long objectId, long userId, CancellationToken cancellationToken = default) { if (userId == 0) return true; // System user can do everything var permission = await GetEffectivePermissionViaSqlAsync(objectId, userId); if (permission == null) throw new InvalidOperationException($"Cannot get permissions for object {objectId} and user {userId}."); return permission.CanUpdate; } /// public virtual async Task CanUserSelectObject(long objectId, long userId, CancellationToken cancellationToken = default) { if (userId == 0) return true; var permission = await GetEffectivePermissionViaSqlAsync(objectId, userId); if (permission == null) throw new InvalidOperationException($"Cannot get permissions for object {objectId} and user {userId}."); return permission.CanSelect; } /// public virtual async Task> GetSelectableObjectIdsAsync(IReadOnlyCollection objectIds, long userId, CancellationToken cancellationToken = default) { if (userId == 0) return objectIds.ToHashSet(); // The cache of the single check answers first; the rest is one query, by the same rule (Permissions_GetEffectiveForObjects), // and lands in the same cache. var now = DateTimeOffset.UtcNow; var permissions = new Dictionary(); var missing = new List(); foreach (var objectId in objectIds.Distinct()) { Interlocked.Increment(ref _cacheRequests); if (PermissionCache.TryGetValue(CacheKey(userId, objectId), out var cached) && now - cached.cachedAt <= CacheLifetime) { Interlocked.Increment(ref _cacheHits); permissions[objectId] = cached.result; } else { missing.Add(objectId); } } if (missing.Count > 0) { var rows = await Context.QueryAsync( Sql.Permissions_GetEffectiveForObjects(), new object[] { missing.ToArray(), userId }, cancellationToken); foreach (var row in rows) if (permissions.TryAdd(row.ObjectId, row)) // the first row of an object, as the single query's LIMIT 1 PermissionCache[CacheKey(userId, row.ObjectId)] = (row, now); } var selectable = new HashSet(); foreach (var objectId in objectIds) { if (!permissions.TryGetValue(objectId, out var permission)) throw new InvalidOperationException($"Cannot get permissions for object {objectId} and user {userId}."); if (permission.CanSelect) selectable.Add(objectId); } return selectable; } /// public virtual async Task CanUserInsertScheme(long schemeId, long userId, CancellationToken cancellationToken = default) { if (userId == 0) return true; var permission = await GetEffectivePermissionViaSqlAsync(schemeId, userId); if (permission == null) throw new InvalidOperationException($"Cannot get permissions for scheme {schemeId} and user {userId}."); return permission.CanInsert; } /// public virtual async Task CanUserDeleteObject(long objectId, long userId, CancellationToken cancellationToken = default) { if (userId == 0) return true; var permission = await GetEffectivePermissionViaSqlAsync(objectId, userId); if (permission == null) throw new InvalidOperationException($"Cannot get permissions for object {objectId} and user {userId}."); return permission.CanDelete; } // ============================================================ // === OVERLOADS WITH OBJECTS === // ============================================================ /// public virtual async Task CanUserEditObject(IRedbObject obj, IRedbUser user, CancellationToken cancellationToken = default) => await CanUserEditObject(obj.Id, user.Id, cancellationToken); /// public virtual async Task CanUserSelectObject(IRedbObject obj, IRedbUser user, CancellationToken cancellationToken = default) => await CanUserSelectObject(obj.Id, user.Id, cancellationToken); /// public virtual async Task CanUserInsertScheme(IRedbScheme scheme, IRedbUser user, CancellationToken cancellationToken = default) => await CanUserInsertScheme(scheme.Id, user.Id, cancellationToken); /// public virtual async Task CanUserDeleteObject(IRedbObject obj, IRedbUser user, CancellationToken cancellationToken = default) => await CanUserDeleteObject(obj.Id, user.Id, cancellationToken); /// public virtual async Task CanUserEditObject(RedbObject obj, CancellationToken cancellationToken = default) { var effectiveUser = ((RedbSecurityContext)SecurityContext).GetEffectiveUser(); return await CanUserEditObject(obj.Id, effectiveUser.Id); } /// public virtual async Task CanUserSelectObject(RedbObject obj, CancellationToken cancellationToken = default) { var effectiveUser = ((RedbSecurityContext)SecurityContext).GetEffectiveUser(); return await CanUserSelectObject(obj.Id, effectiveUser.Id); } /// public virtual async Task CanUserDeleteObject(RedbObject obj, CancellationToken cancellationToken = default) { var effectiveUser = ((RedbSecurityContext)SecurityContext).GetEffectiveUser(); return await CanUserDeleteObject(obj.Id, effectiveUser.Id); } /// public virtual async Task CanUserEditObject(RedbObject obj, IRedbUser user, CancellationToken cancellationToken = default) => await CanUserEditObject(obj.Id, user.Id, cancellationToken); /// public virtual async Task CanUserSelectObject(RedbObject obj, IRedbUser user, CancellationToken cancellationToken = default) => await CanUserSelectObject(obj.Id, user.Id, cancellationToken); /// public virtual async Task CanUserInsertScheme(RedbObject obj, IRedbUser user, CancellationToken cancellationToken = default) => await CanUserInsertScheme(obj.SchemeId, user.Id, cancellationToken); /// public virtual async Task CanUserDeleteObject(RedbObject obj, IRedbUser user, CancellationToken cancellationToken = default) => await CanUserDeleteObject(obj.Id, user.Id, cancellationToken); // ============================================================ // === CRUD PERMISSIONS === // ============================================================ /// public virtual async Task CreatePermissionAsync(PermissionRequest request, IRedbUser? currentUser = null, CancellationToken cancellationToken = default) { var newId = await Context.NextObjectIdAsync(); var newPermission = new RedbPermission { Id = newId, IdUser = request.UserId, IdRole = request.RoleId, IdRef = request.ObjectId, Select = request.CanSelect, Insert = request.CanInsert, Update = request.CanUpdate, Delete = request.CanDelete }; await Context.ExecuteAsync(Sql.Permissions_Insert(), new object[] { newId, (object?)request.UserId ?? DBNull.Value, (object?)request.RoleId ?? DBNull.Value, request.ObjectId, request.CanSelect, request.CanInsert, request.CanUpdate, request.CanDelete }, cancellationToken); InvalidatePermissionCache(request.UserId, request.ObjectId); if (request.ObjectId != 0) InvalidatePermissionCache(null, request.ObjectId); await OnPermissionCreatedAsync(newPermission, currentUser); return newPermission; } /// public virtual async Task UpdatePermissionAsync(IRedbPermission permission, PermissionRequest request, IRedbUser? currentUser = null, CancellationToken cancellationToken = default) { var result = await Context.ExecuteAsync(Sql.Permissions_Update(), new object[] { request.CanSelect, request.CanInsert, request.CanUpdate, request.CanDelete, permission.Id }, cancellationToken); if (result == 0) throw new ArgumentException($"Permission with ID {permission.Id} not found"); InvalidatePermissionCache(permission.IdUser, permission.IdRef); var updated = new RedbPermission { Id = permission.Id, IdUser = permission.IdUser, IdRole = permission.IdRole, IdRef = permission.IdRef, Select = request.CanSelect, Insert = request.CanInsert, Update = request.CanUpdate, Delete = request.CanDelete }; await OnPermissionUpdatedAsync(updated, currentUser); return updated; } /// public virtual async Task DeletePermissionAsync(IRedbPermission permission, IRedbUser? currentUser = null, CancellationToken cancellationToken = default) { var result = await Context.ExecuteAsync(Sql.Permissions_Delete(), new object[] { permission.Id }, cancellationToken); InvalidatePermissionCache(permission.IdUser, permission.IdRef); if (permission.IdRef != 0) InvalidatePermissionCache(null, permission.IdRef); if (result > 0) await OnPermissionDeletedAsync(permission, currentUser); return result > 0; } // ============================================================ // === PERMISSION SEARCH === // ============================================================ /// public virtual async Task> GetPermissionsByUserAsync(IRedbUser user, CancellationToken cancellationToken = default) { var permissions = await Context.QueryAsync(Sql.Permissions_SelectByUser(), new object[] { user.Id }, cancellationToken); return permissions.Cast().ToList(); } /// public virtual async Task> GetPermissionsByRoleAsync(IRedbRole role, CancellationToken cancellationToken = default) { var permissions = await Context.QueryAsync(Sql.Permissions_SelectByRole(), new object[] { role.Id }, cancellationToken); return permissions.Cast().ToList(); } /// public virtual async Task> GetPermissionsByObjectAsync(IRedbObject obj, CancellationToken cancellationToken = default) { var permissions = await Context.QueryAsync(Sql.Permissions_SelectByObject(), new object[] { obj.Id }, cancellationToken); return permissions.Cast().ToList(); } /// public virtual async Task GetPermissionByIdAsync(long permissionId, CancellationToken cancellationToken = default) { return await Context.QueryFirstOrDefaultAsync(Sql.Permissions_SelectById(), new object[] { permissionId }, cancellationToken); } // ============================================================ // === PERMISSION MANAGEMENT === // ============================================================ /// public virtual async Task GrantPermissionAsync(IRedbUser user, IRedbObject obj, PermissionAction actions, IRedbUser? currentUser = null, CancellationToken cancellationToken = default) { return await GrantPermissionInternalAsync(user.Id, null, obj.Id, actions, currentUser); } /// public virtual async Task GrantPermissionAsync(IRedbRole role, IRedbObject obj, PermissionAction actions, IRedbUser? currentUser = null, CancellationToken cancellationToken = default) { return await GrantPermissionInternalAsync(null, role.Id, obj.Id, actions, currentUser); } /// /// Internal method to grant permission. /// protected virtual async Task GrantPermissionInternalAsync(long? userId, long? roleId, long objectId, PermissionAction actions, IRedbUser? currentUser = null, CancellationToken cancellationToken = default) { var existingPermission = await Context.QueryFirstOrDefaultAsync( Sql.Permissions_SelectByUserRoleObject(), new object[] { (object?)userId ?? DBNull.Value, (object?)roleId ?? DBNull.Value, objectId }, cancellationToken); if (existingPermission != null) { var newSelect = existingPermission.Select == true || actions.HasFlag(PermissionAction.Select); var newInsert = existingPermission.Insert == true || actions.HasFlag(PermissionAction.Insert); var newUpdate = existingPermission.Update == true || actions.HasFlag(PermissionAction.Update); var newDelete = existingPermission.Delete == true || actions.HasFlag(PermissionAction.Delete); await Context.ExecuteAsync(Sql.Permissions_Update(), new object[] { newSelect, newInsert, newUpdate, newDelete, existingPermission.Id }, cancellationToken); } else { var newId = await Context.NextObjectIdAsync(); await Context.ExecuteAsync(Sql.Permissions_Insert(), new object[] { newId, (object?)userId ?? DBNull.Value, (object?)roleId ?? DBNull.Value, objectId, actions.HasFlag(PermissionAction.Select), actions.HasFlag(PermissionAction.Insert), actions.HasFlag(PermissionAction.Update), actions.HasFlag(PermissionAction.Delete) }, cancellationToken); } InvalidatePermissionCache(userId, objectId); return true; } /// public virtual async Task RevokePermissionAsync(IRedbUser user, IRedbObject obj, IRedbUser? currentUser = null, CancellationToken cancellationToken = default) { return await RevokePermissionInternalAsync(user.Id, null, obj.Id, currentUser); } /// public virtual async Task RevokePermissionAsync(IRedbRole role, IRedbObject obj, IRedbUser? currentUser = null, CancellationToken cancellationToken = default) { return await RevokePermissionInternalAsync(null, role.Id, obj.Id, currentUser); } /// /// Internal method to revoke permission. /// protected virtual async Task RevokePermissionInternalAsync(long? userId, long? roleId, long objectId, IRedbUser? currentUser = null, CancellationToken cancellationToken = default) { var result = await Context.ExecuteAsync(Sql.Permissions_DeleteByUserRoleObject(), new object[] { (object?)userId ?? DBNull.Value, (object?)roleId ?? DBNull.Value, objectId }, cancellationToken); InvalidatePermissionCache(userId, objectId); return result > 0; } /// public virtual async Task RevokeAllUserPermissionsAsync(IRedbUser user, IRedbUser? currentUser = null, CancellationToken cancellationToken = default) { InvalidatePermissionCache(user.Id, null); return await Context.ExecuteAsync(Sql.Permissions_DeleteByUser(), new object[] { user.Id }, cancellationToken); } /// public virtual async Task RevokeAllRolePermissionsAsync(IRedbRole role, IRedbUser? currentUser = null, CancellationToken cancellationToken = default) { InvalidatePermissionCache(); return await Context.ExecuteAsync(Sql.Permissions_DeleteByRole(), new object[] { role.Id }, cancellationToken); } // ============================================================ // === EFFECTIVE PERMISSIONS === // ============================================================ /// public virtual async Task GetEffectivePermissionsAsync(IRedbUser user, IRedbObject obj, CancellationToken cancellationToken = default) { return await GetEffectivePermissionsAsync(user.Id, obj.Id); } /// /// Get effective permissions for user and object. /// protected virtual async Task GetEffectivePermissionsAsync(long userId, long objectId, CancellationToken cancellationToken = default) { // Get user's direct permissions var userPermissions = await Context.QueryAsync( Sql.Permissions_SelectByUser() + $" AND (_id_ref = {Sql.FormatParameter(2)} OR _id_ref = 0)", new object[] { userId, objectId }, cancellationToken); // Get user's roles var userRoles = await Context.QueryAsync(Sql.Permissions_SelectUserRoleIds(), new object[] { userId }, cancellationToken); var roleIds = userRoles.Select(ur => ur.IdRole).ToList(); // Get role permissions List rolePermissions = []; if (roleIds.Count > 0) { rolePermissions = await Context.QueryAsync( Sql.Permissions_SelectAllColumns() + $" WHERE {Sql.FormatArrayContains("_id_role", Sql.FormatParameter(1))} AND (_id_ref = {Sql.FormatParameter(2)} OR _id_ref = 0)", new object[] { roleIds.ToArray(), objectId }, cancellationToken); } return BuildEffectivePermissionResult(userId, objectId, userPermissions, rolePermissions); } /// public virtual async Task> GetEffectivePermissionsBatchAsync(IRedbUser user, IRedbObject[] objects, CancellationToken cancellationToken = default) { var objectIds = objects.Select(o => o.Id).ToArray(); var results = await GetEffectivePermissionsBatchAsync(user.Id, objectIds); var finalResults = new Dictionary(); foreach (var obj in objects) { if (results.TryGetValue(obj.Id, out var result)) finalResults[obj] = result; } return finalResults; } /// /// Batch get effective permissions. /// protected virtual async Task> GetEffectivePermissionsBatchAsync(long userId, long[] objectIds, CancellationToken cancellationToken = default) { if (objectIds == null || objectIds.Length == 0) return new Dictionary(); var userPermissions = await Context.QueryAsync( Sql.Permissions_SelectAllColumns() + $" WHERE _id_user = {Sql.FormatParameter(1)} AND {Sql.FormatArrayContains("_id_ref", Sql.FormatParameter(2))}", new object[] { userId, objectIds }, cancellationToken); var userRoles = await Context.QueryAsync(Sql.Permissions_SelectUserRoleIds(), new object[] { userId }, cancellationToken); var roleIds = userRoles.Select(ur => ur.IdRole).ToList(); List rolePermissions = []; if (roleIds.Count > 0) { rolePermissions = await Context.QueryAsync( Sql.Permissions_SelectAllColumns() + $" WHERE {Sql.FormatArrayContains("_id_role", Sql.FormatParameter(1))} AND {Sql.FormatArrayContains("_id_ref", Sql.FormatParameter(2))}", new object[] { roleIds.ToArray(), objectIds }, cancellationToken); } var userPermissionsByObject = userPermissions.GroupBy(p => p.IdRef).ToDictionary(g => g.Key, g => g.ToList()); var rolePermissionsByObject = rolePermissions.GroupBy(p => p.IdRef).ToDictionary(g => g.Key, g => g.ToList()); var result = new Dictionary(); foreach (var objectId in objectIds) { var userPerms = userPermissionsByObject.GetValueOrDefault(objectId, []); var rolePerms = rolePermissionsByObject.GetValueOrDefault(objectId, []); result[objectId] = BuildEffectivePermissionResult(userId, objectId, userPerms, rolePerms); } return result; } /// public virtual async Task> GetAllEffectivePermissionsAsync(IRedbUser user, CancellationToken cancellationToken = default) { return await GetAllEffectivePermissionsAsync(user.Id); } /// /// Get all effective permissions for user. /// protected virtual async Task> GetAllEffectivePermissionsAsync(long userId, CancellationToken cancellationToken = default) { var userPermissions = await Context.QueryAsync(Sql.Permissions_SelectByUser(), new object[] { userId }, cancellationToken); var userRoles = await Context.QueryAsync(Sql.Permissions_SelectUserRoleIds(), new object[] { userId }, cancellationToken); var roleIds = userRoles.Select(ur => ur.IdRole).ToList(); List rolePermissions = []; if (roleIds.Count > 0) { rolePermissions = await Context.QueryAsync( Sql.Permissions_SelectAllColumns() + $" WHERE {Sql.FormatArrayContains("_id_role", Sql.FormatParameter(1))}", new object[] { roleIds.ToArray() }, cancellationToken); } var allObjectIds = userPermissions.Select(p => p.IdRef) .Concat(rolePermissions.Select(p => p.IdRef)) .Distinct() .ToList(); var userPermissionsByObject = userPermissions.GroupBy(p => p.IdRef).ToDictionary(g => g.Key, g => g.ToList()); var rolePermissionsByObject = rolePermissions.GroupBy(p => p.IdRef).ToDictionary(g => g.Key, g => g.ToList()); var result = new List(); foreach (var objectId in allObjectIds) { var userPerms = userPermissionsByObject.GetValueOrDefault(objectId, []); var rolePerms = rolePermissionsByObject.GetValueOrDefault(objectId, []); var effectiveResult = BuildEffectivePermissionResult(userId, objectId, userPerms, rolePerms); if (effectiveResult.HasAnyPermission) result.Add(effectiveResult); } return result.OrderBy(r => r.ObjectId).ToList(); } /// /// Build EffectivePermissionResult from user and role permissions. /// private static EffectivePermissionResult BuildEffectivePermissionResult( long userId, long objectId, List userPermissions, List rolePermissions) { var result = new EffectivePermissionResult { UserId = userId, ObjectId = objectId, PermissionSourceId = objectId, PermissionType = "Combined", CanSelect = userPermissions.Any(p => p.Select == true) || rolePermissions.Any(p => p.Select == true), CanInsert = userPermissions.Any(p => p.Insert == true) || rolePermissions.Any(p => p.Insert == true), CanUpdate = userPermissions.Any(p => p.Update == true) || rolePermissions.Any(p => p.Update == true), CanDelete = userPermissions.Any(p => p.Delete == true) || rolePermissions.Any(p => p.Delete == true) }; if (userPermissions.Count != 0 && rolePermissions.Count != 0) { result.PermissionType = "UserAndRole"; } else if (userPermissions.Count != 0) { result.PermissionType = "User"; result.PermissionUserId = userId; } else if (rolePermissions.Count != 0) { result.PermissionType = "Role"; result.RoleId = rolePermissions[0].IdRole; } return result; } // ============================================================ // === STATISTICS === // ============================================================ /// public virtual async Task GetPermissionCountAsync(CancellationToken cancellationToken = default) { return await Context.ExecuteScalarAsync(Sql.Permissions_Count(), System.Array.Empty(), cancellationToken); } /// public virtual async Task GetUserPermissionCountAsync(IRedbUser user, CancellationToken cancellationToken = default) { return await GetUserPermissionCountAsync(user.Id); } /// /// Get permission count for user. /// protected virtual async Task GetUserPermissionCountAsync(long userId, CancellationToken cancellationToken = default) { var directPermissions = await Context.ExecuteScalarAsync(Sql.Permissions_CountByUser(), new object[] { userId }, cancellationToken); var userRoles = await Context.QueryAsync(Sql.Permissions_SelectUserRoleIds(), new object[] { userId }, cancellationToken); var roleIds = userRoles.Select(ur => ur.IdRole).ToList(); int rolePermissions = 0; if (roleIds.Count > 0) { rolePermissions = await Context.ExecuteScalarAsync( Sql.Permissions_CountFrom() + $" WHERE {Sql.FormatArrayContains("_id_role", Sql.FormatParameter(1))}", new object[] { roleIds.ToArray() }, cancellationToken); } return directPermissions + rolePermissions; } /// public virtual async Task GetRolePermissionCountAsync(IRedbRole role, CancellationToken cancellationToken = default) { return await Context.ExecuteScalarAsync(Sql.Permissions_CountByRole(), new object[] { role.Id }, cancellationToken); } // ============================================================ // === LIFECYCLE HOOKS === // ============================================================ /// /// Called after permission is created. Override in Pro for audit. /// protected virtual Task OnPermissionCreatedAsync(IRedbPermission permission, IRedbUser? currentUser, CancellationToken cancellationToken = default) { return Task.CompletedTask; } /// /// Called after permission is updated. Override in Pro for audit. /// protected virtual Task OnPermissionUpdatedAsync(IRedbPermission permission, IRedbUser? currentUser, CancellationToken cancellationToken = default) { return Task.CompletedTask; } /// /// Called after permission is deleted. Override in Pro for audit. /// protected virtual Task OnPermissionDeletedAsync(IRedbPermission permission, IRedbUser? currentUser, CancellationToken cancellationToken = default) { return Task.CompletedTask; } } Path: redb/redb.Core/Providers/Base/QueryableProviderBase.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/QueryableProviderBase.cs ---- #pragma warning disable CS0618 // implements or uses the deprecated object permissions and roles (RedbDeprecation) using redb.Core.Data; using redb.Core.Models.Configuration; using redb.Core.Models.Contracts; using redb.Core.Models.Security; using redb.Core.Query; using redb.Core.Query.QueryExpressions; using redb.Core.Serialization; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace redb.Core.Providers.Base { /// /// Base class for IQueryableProvider implementations. /// Contains all common logic for creating LINQ queries. /// DB-specific implementations provide concrete query providers via factory methods. /// public abstract class QueryableProviderBase : IQueryableProvider { protected readonly IRedbContext Context; protected readonly IRedbObjectSerializer Serializer; protected readonly ISchemeSyncProvider SchemeSync; protected readonly ILogger? Logger; protected readonly IRedbSecurityContext SecurityContext; protected readonly RedbServiceConfiguration Configuration; protected readonly ILazyPropsLoader? LazyPropsLoader; protected readonly string CacheDomain; /// The list provider of the service, set by RedbServiceBase: see WithListItems. internal IListProvider? ListItems { get; set; } // Hands the list provider to the query providers of a new query, for the groupings it may run: the key of a // grouping by a list item is read through it (Query.Grouping.ListItemGroupKeys). private IRedbQueryable WithListItems(IRedbQueryable query) where TProps : class, new() { if (query is redb.Core.Query.RedbQueryable flat && flat.QueryProvider is redb.Core.Query.Grouping.IListItemKeySource flatKeys) flatKeys.ListItems = ListItems; if (query is redb.Core.Query.Base.TreeQueryableBase tree && tree.TreeProvider is redb.Core.Query.Grouping.IListItemKeySource treeKeys) treeKeys.ListItems = ListItems; return query; } protected QueryableProviderBase( IRedbContext context, IRedbObjectSerializer serializer, ISchemeSyncProvider schemeSync, IRedbSecurityContext securityContext, ILazyPropsLoader? lazyPropsLoader = null, RedbServiceConfiguration? configuration = null, string? cacheDomain = null, ILogger? logger = null) { Context = context ?? throw new ArgumentNullException(nameof(context)); Serializer = serializer ?? throw new ArgumentNullException(nameof(serializer)); SchemeSync = schemeSync ?? throw new ArgumentNullException(nameof(schemeSync)); SecurityContext = securityContext ?? throw new ArgumentNullException(nameof(securityContext)); LazyPropsLoader = lazyPropsLoader; Configuration = configuration ?? new RedbServiceConfiguration(); CacheDomain = cacheDomain ?? Configuration.GetEffectiveCacheDomain(); Logger = logger; } // ===== ABSTRACT FACTORY METHODS ===== /// /// Create DB-specific query provider for flat queries. /// protected abstract IRedbQueryable CreateQuery(long schemeId, long? userId, bool checkPermissions) where TProps : class, new(); /// /// Create DB-specific query provider for tree queries. /// protected abstract IRedbQueryable CreateTreeQuery( long schemeId, long? userId, bool checkPermissions, long? rootObjectId, int? maxDepth) where TProps : class, new(); /// /// Create empty tree query (for null rootObject case). /// protected abstract IRedbQueryable CreateEmptyTreeQuery(long schemeId, long? userId, bool checkPermissions) where TProps : class, new(); /// /// Create tree query for multiple root objects. /// protected abstract IRedbQueryable CreateMultiRootTreeQuery( long schemeId, long? userId, bool checkPermissions, List rootObjects, int? maxDepth) where TProps : class, new(); /// /// Create tree query for multiple root object IDs. /// protected abstract IRedbQueryable CreateMultiRootTreeQueryByIds( long schemeId, long? userId, bool checkPermissions, IEnumerable rootObjectIds, int? maxDepth) where TProps : class, new(); // ===== FLAT QUERIES ===== public IRedbQueryable Query() where TProps : class, new() { var scheme = GetSchemeSync(); var effectiveUser = SecurityContext.GetEffectiveUser(); return WithListItems(CreateQuery(scheme.Id, effectiveUser.Id, Configuration.DefaultCheckPermissionsOnQuery)); } public IRedbQueryable Query(IRedbUser user) where TProps : class, new() { var scheme = GetSchemeSync(); return WithListItems(CreateQuery(scheme.Id, user.Id, Configuration.DefaultCheckPermissionsOnQuery)); } /// /// Get scheme synchronously - first from cache, then via Task.Run to avoid SynchronizationContext deadlock. /// Cache is warmed up by InitializeAsync() at startup, so Task.Run path is rarely used. /// private IRedbScheme GetSchemeSync() where TProps : class { // Try cache first (fast, no async, no DB call) var scheme = SchemeSync.GetSchemeFromCache(); if (scheme != null) return scheme; // Fallback: use Task.Run to avoid Blazor/ASP.NET SynchronizationContext deadlock. // This runs GetSchemeByTypeAsync on ThreadPool where there's no SynchronizationContext. // Note: GetSchemeByTypeAsync will cache the result, so subsequent calls will hit cache. scheme = Task.Run(() => SchemeSync.GetSchemeByTypeAsync()).GetAwaiter().GetResult(); if (scheme == null) throw new InvalidOperationException($"Scheme for type '{typeof(TProps).Name}' not found. Ensure InitializeAsync() was called at startup."); // Read once and cached for the process: a process that reads schemes another one owns (a Tsak worker // whose module does not sync them) meets this on every first query, and nothing is wrong with it. Logger?.LogDebug( "Scheme '{SchemeName}' was not in the cache and was read from the database on first use.", scheme.Name); return scheme; } // ===== TREE QUERIES ===== public IRedbQueryable TreeQuery() where TProps : class, new() { var scheme = GetSchemeSync(); var effectiveUser = SecurityContext.GetEffectiveUser(); return WithListItems(CreateTreeQuery(scheme.Id, effectiveUser.Id, Configuration.DefaultCheckPermissionsOnQuery, null, null)); } public IRedbQueryable TreeQuery(IRedbUser user) where TProps : class, new() { var scheme = GetSchemeSync(); return WithListItems(CreateTreeQuery(scheme.Id, user.Id, Configuration.DefaultCheckPermissionsOnQuery, null, null)); } // ===== SYNC TREE QUERIES WITH ROOT OBJECT ===== public IRedbQueryable TreeQuery(long rootObjectId, int? maxDepth = null) where TProps : class, new() { var scheme = GetSchemeSync(); var effectiveUser = SecurityContext.GetEffectiveUser(); return WithListItems(CreateTreeQuery(scheme.Id, effectiveUser.Id, Configuration.DefaultCheckPermissionsOnQuery, rootObjectId, maxDepth)); } public IRedbQueryable TreeQuery(IRedbObject? rootObject, int? maxDepth = null) where TProps : class, new() { var scheme = GetSchemeSync(); var effectiveUser = SecurityContext.GetEffectiveUser(); if (rootObject == null) return WithListItems(CreateEmptyTreeQuery(scheme.Id, effectiveUser.Id, Configuration.DefaultCheckPermissionsOnQuery)); return WithListItems(CreateTreeQuery(scheme.Id, effectiveUser.Id, Configuration.DefaultCheckPermissionsOnQuery, rootObject.Id, maxDepth)); } public IRedbQueryable TreeQuery(IEnumerable rootObjects, int? maxDepth = null) where TProps : class, new() { var rootList = rootObjects?.ToList() ?? []; var scheme = GetSchemeSync(); var effectiveUser = SecurityContext.GetEffectiveUser(); if (!rootList.Any()) return WithListItems(CreateEmptyTreeQuery(scheme.Id, effectiveUser.Id, Configuration.DefaultCheckPermissionsOnQuery)); if (rootList.Count == 1) return WithListItems(CreateTreeQuery(scheme.Id, effectiveUser.Id, Configuration.DefaultCheckPermissionsOnQuery, rootList[0].Id, maxDepth)); return WithListItems(CreateMultiRootTreeQuery(scheme.Id, effectiveUser.Id, Configuration.DefaultCheckPermissionsOnQuery, rootList, maxDepth)); } public IRedbQueryable TreeQuery(IEnumerable rootObjectIds, int? maxDepth = null) where TProps : class, new() { var idsList = rootObjectIds?.ToList() ?? []; var scheme = GetSchemeSync(); var effectiveUser = SecurityContext.GetEffectiveUser(); if (!idsList.Any()) return WithListItems(CreateEmptyTreeQuery(scheme.Id, effectiveUser.Id, Configuration.DefaultCheckPermissionsOnQuery)); if (idsList.Count == 1) return WithListItems(CreateTreeQuery(scheme.Id, effectiveUser.Id, Configuration.DefaultCheckPermissionsOnQuery, idsList[0], maxDepth)); return WithListItems(CreateMultiRootTreeQueryByIds(scheme.Id, effectiveUser.Id, Configuration.DefaultCheckPermissionsOnQuery, idsList, maxDepth)); } public IRedbQueryable TreeQuery(long rootObjectId, IRedbUser user, int? maxDepth = null) where TProps : class, new() { var scheme = GetSchemeSync(); return WithListItems(CreateTreeQuery(scheme.Id, user.Id, Configuration.DefaultCheckPermissionsOnQuery, rootObjectId, maxDepth)); } public IRedbQueryable TreeQuery(IRedbObject? rootObject, IRedbUser user, int? maxDepth = null) where TProps : class, new() { var scheme = GetSchemeSync(); if (rootObject == null) return WithListItems(CreateEmptyTreeQuery(scheme.Id, user.Id, Configuration.DefaultCheckPermissionsOnQuery)); return WithListItems(CreateTreeQuery(scheme.Id, user.Id, Configuration.DefaultCheckPermissionsOnQuery, rootObject.Id, maxDepth)); } public IRedbQueryable TreeQuery(IEnumerable rootObjects, IRedbUser user, int? maxDepth = null) where TProps : class, new() { var rootList = rootObjects?.ToList() ?? []; var scheme = GetSchemeSync(); if (!rootList.Any()) return WithListItems(CreateEmptyTreeQuery(scheme.Id, user.Id, Configuration.DefaultCheckPermissionsOnQuery)); if (rootList.Count == 1) return WithListItems(CreateTreeQuery(scheme.Id, user.Id, Configuration.DefaultCheckPermissionsOnQuery, rootList[0].Id, maxDepth)); return WithListItems(CreateMultiRootTreeQuery(scheme.Id, user.Id, Configuration.DefaultCheckPermissionsOnQuery, rootList, maxDepth)); } public IRedbQueryable TreeQuery(IEnumerable rootObjectIds, IRedbUser user, int? maxDepth = null) where TProps : class, new() { var idsList = rootObjectIds?.ToList() ?? []; var scheme = GetSchemeSync(); if (!idsList.Any()) return WithListItems(CreateEmptyTreeQuery(scheme.Id, user.Id, Configuration.DefaultCheckPermissionsOnQuery)); if (idsList.Count == 1) return WithListItems(CreateTreeQuery(scheme.Id, user.Id, Configuration.DefaultCheckPermissionsOnQuery, idsList[0], maxDepth)); return WithListItems(CreateMultiRootTreeQueryByIds(scheme.Id, user.Id, Configuration.DefaultCheckPermissionsOnQuery, idsList, maxDepth)); } } } Path: redb/redb.Core/Providers/Base/RoleProviderBase.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/RoleProviderBase.cs ---- #pragma warning disable CS0618 // implements or uses the deprecated object permissions and roles (RedbDeprecation) using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using redb.Core.Data; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using redb.Core.Models.Roles; using redb.Core.Query; using Microsoft.Extensions.Logging; namespace redb.Core.Providers.Base; /// /// Base implementation of role provider with common business logic. /// Database-specific providers inherit from this class and provide ISqlDialect. /// /// Usage: /// public class PostgresRoleProvider : RoleProviderBase /// { /// public PostgresRoleProvider(IRedbContext context, IRedbSecurityContext security) /// : base(context, security, new PostgreSqlDialect()) { } /// } /// public abstract class RoleProviderBase : IRoleProvider { protected readonly IRedbContext Context; protected readonly IRedbSecurityContext SecurityContext; protected readonly ISqlDialect Sql; protected readonly ILogger? Logger; protected RoleProviderBase( IRedbContext context, IRedbSecurityContext securityContext, ISqlDialect sql, ILogger? logger = null) { Context = context ?? throw new ArgumentNullException(nameof(context)); SecurityContext = securityContext ?? throw new ArgumentNullException(nameof(securityContext)); Sql = sql ?? throw new ArgumentNullException(nameof(sql)); Logger = logger; } // ============================================================ // === CRUD ROLES === // ============================================================ /// public virtual async Task CreateRoleAsync(CreateRoleRequest request, IRedbUser? currentUser = null, CancellationToken cancellationToken = default) { ValidateRoleName(request.Name); // Check name uniqueness var existingRole = await GetRoleByNameInternalAsync(request.Name); if (existingRole != null) throw new InvalidOperationException($"Role with name '{request.Name}' already exists"); // Create new role var newRoleId = await Context.NextObjectIdAsync(); await InsertRoleInternalAsync(newRoleId, request.Name); var newRole = new RedbRole { Id = newRoleId, Name = request.Name }; // Assign users to role if specified if (request.UserLogins?.Length > 0) { await AssignUsersByLoginsAsync(newRole, request.UserLogins); } else if (request.Users?.Length > 0) { await AssignUsersByObjectsAsync(newRole, request.Users); } // Lifecycle hook for derived classes await OnRoleCreatedAsync(newRole, currentUser); return newRole; } /// public virtual async Task UpdateRoleAsync(IRedbRole role, string newName, IRedbUser? currentUser = null, CancellationToken cancellationToken = default) { ValidateRoleName(newName); var dbRole = await GetRoleByIdInternalAsync(role.Id); if (dbRole == null) throw new ArgumentException($"Role with ID {role.Id} not found"); // Check name uniqueness if changed if (dbRole.Name != newName) { var existingRole = await Context.ExecuteScalarAsync( Sql.Roles_ExistsByNameExcluding(), new object[] { newName, role.Id }, cancellationToken); if (existingRole.HasValue) throw new InvalidOperationException($"Role with name '{newName}' already exists"); await Context.ExecuteAsync(Sql.Roles_UpdateName(), new object[] { newName, role.Id }, cancellationToken); dbRole.Name = newName; } await OnRoleUpdatedAsync(dbRole, currentUser); return dbRole; } /// public virtual async Task DeleteRoleAsync(IRedbRole role, IRedbUser? currentUser = null, CancellationToken cancellationToken = default) { var dbRole = await GetRoleByIdInternalAsync(role.Id); if (dbRole == null) return false; // Cascade delete user-role associations await Context.ExecuteAsync(Sql.UsersRoles_DeleteByRole(), new object[] { role.Id }, cancellationToken); // Cascade delete role permissions await Context.ExecuteAsync(Sql.Permissions_DeleteByRole(), new object[] { role.Id }, cancellationToken); // Delete role itself var result = await Context.ExecuteAsync(Sql.Roles_Delete(), new object[] { role.Id }, cancellationToken); if (result > 0) await OnRoleDeletedAsync(role, currentUser); return result > 0; } // ============================================================ // === SEARCH ROLES === // ============================================================ /// public virtual async Task GetRoleByIdAsync(long roleId, CancellationToken cancellationToken = default) { return await GetRoleByIdInternalAsync(roleId); } /// public virtual async Task GetRoleByNameAsync(string roleName, CancellationToken cancellationToken = default) { return await GetRoleByNameInternalAsync(roleName); } /// public virtual async Task LoadRoleAsync(long roleId, CancellationToken cancellationToken = default) { var role = await GetRoleByIdAsync(roleId); if (role == null) throw new ArgumentException($"Role with ID {roleId} not found"); return role; } /// public virtual async Task LoadRoleAsync(string roleName, CancellationToken cancellationToken = default) { var role = await GetRoleByNameAsync(roleName); if (role == null) throw new ArgumentException($"Role with name '{roleName}' not found"); return role; } /// public virtual async Task> GetRolesAsync(CancellationToken cancellationToken = default) { var roles = await Context.QueryAsync(Sql.Roles_SelectAll(), System.Array.Empty(), cancellationToken); return roles.Cast().ToList(); } // ============================================================ // === USER-ROLE MANAGEMENT === // ============================================================ /// public virtual async Task AssignUserToRoleAsync(IRedbUser user, IRedbRole role, IRedbUser? currentUser = null, CancellationToken cancellationToken = default) { // Check user exists var userExists = await Context.ExecuteScalarAsync(Sql.Users_ExistsById(), new object[] { user.Id }, cancellationToken); if (!userExists.HasValue) throw new ArgumentException($"User with ID {user.Id} not found"); // Check role exists var roleExists = await Context.ExecuteScalarAsync(Sql.Roles_ExistsById(), new object[] { role.Id }, cancellationToken); if (!roleExists.HasValue) throw new ArgumentException($"Role with ID {role.Id} not found"); // Check if already assigned var existingAssignment = await Context.ExecuteScalarAsync(Sql.UsersRoles_Exists(), new object[] { user.Id, role.Id }, cancellationToken); if (existingAssignment.HasValue) return true; // Already assigned // Create assignment var userRoleId = await Context.NextObjectIdAsync(); var result = await Context.ExecuteAsync(Sql.UsersRoles_Insert(), new object[] { userRoleId, user.Id, role.Id }, cancellationToken); return result > 0; } /// public virtual async Task RemoveUserFromRoleAsync(IRedbUser user, IRedbRole role, IRedbUser? currentUser = null, CancellationToken cancellationToken = default) { var result = await Context.ExecuteAsync(Sql.UsersRoles_Delete(), new object[] { user.Id, role.Id }, cancellationToken); return result > 0; } /// public virtual async Task SetUserRolesAsync(IRedbUser user, IRedbRole[] roles, IRedbUser? currentUser = null, CancellationToken cancellationToken = default) { // Check user exists var userExists = await Context.ExecuteScalarAsync(Sql.Users_ExistsById(), new object[] { user.Id }, cancellationToken); if (!userExists.HasValue) throw new ArgumentException($"User with ID {user.Id} not found"); // Delete all existing user roles await Context.ExecuteAsync(Sql.UsersRoles_DeleteByUser(), new object[] { user.Id }, cancellationToken); // Add new roles if (roles is { Length: > 0 }) { foreach (var role in roles) { var roleExists = await Context.ExecuteScalarAsync(Sql.Roles_ExistsById(), new object[] { role.Id }, cancellationToken); if (roleExists.HasValue) { var userRoleId = await Context.NextObjectIdAsync(); await Context.ExecuteAsync(Sql.UsersRoles_Insert(), new object[] { userRoleId, user.Id, role.Id }, cancellationToken); } } } return true; } /// public virtual async Task> GetUserRolesAsync(IRedbUser user, CancellationToken cancellationToken = default) { var roles = await Context.QueryAsync(Sql.UsersRoles_SelectRolesByUser(), new object[] { user.Id }, cancellationToken); return roles.Cast().ToList(); } /// public virtual async Task> GetRoleUsersAsync(IRedbRole role, CancellationToken cancellationToken = default) { var users = await Context.QueryAsync(Sql.UsersRoles_SelectUsersByRole(), new object[] { role.Id }, cancellationToken); return users.Cast().ToList(); } /// public virtual async Task UserHasRoleAsync(IRedbUser user, IRedbRole role, CancellationToken cancellationToken = default) { var exists = await Context.ExecuteScalarAsync(Sql.UsersRoles_Exists(), new object[] { user.Id, role.Id }, cancellationToken); return exists.HasValue; } // ============================================================ // === VALIDATION === // ============================================================ /// public virtual async Task IsRoleNameAvailableAsync(string roleName, IRedbRole? excludeRole = null, CancellationToken cancellationToken = default) { if (excludeRole != null) { var exists = await Context.ExecuteScalarAsync( Sql.Roles_ExistsByNameExcluding(), new object[] { roleName, excludeRole.Id }, cancellationToken); return !exists.HasValue; } else { var exists = await Context.ExecuteScalarAsync(Sql.Roles_ExistsByName(), new object[] { roleName }, cancellationToken); return !exists.HasValue; } } // ============================================================ // === STATISTICS === // ============================================================ /// public virtual async Task GetRoleCountAsync(CancellationToken cancellationToken = default) { return await Context.ExecuteScalarAsync(Sql.Roles_Count(), System.Array.Empty(), cancellationToken); } /// public virtual async Task GetRoleUserCountAsync(IRedbRole role, CancellationToken cancellationToken = default) { return await Context.ExecuteScalarAsync(Sql.UsersRoles_CountByRole(), new object[] { role.Id }, cancellationToken); } /// public virtual async Task> GetRoleStatisticsAsync(CancellationToken cancellationToken = default) { var roles = await Context.QueryAsync(Sql.Roles_SelectAll(), System.Array.Empty(), cancellationToken); var result = new Dictionary(); foreach (var role in roles) { var count = await Context.ExecuteScalarAsync(Sql.UsersRoles_CountByRole(), new object[] { role.Id }, cancellationToken); result[role] = count; } return result; } // ============================================================ // === CONFIGURATION MANAGEMENT === // ============================================================ /// public virtual async Task GetRoleConfigurationIdAsync(long roleId, CancellationToken cancellationToken = default) { return await Context.ExecuteScalarAsync(Sql.Roles_SelectConfigurationId(), new object[] { roleId }, cancellationToken); } /// public virtual async Task SetRoleConfigurationAsync(long roleId, long? configId, CancellationToken cancellationToken = default) { var result = await Context.ExecuteAsync(Sql.Roles_UpdateConfiguration(), new object[] { (object?)configId ?? DBNull.Value, roleId }, cancellationToken); if (result == 0) throw new ArgumentException($"Role with ID {roleId} not found"); } // ============================================================ // === PROTECTED VIRTUAL METHODS (for override in derived classes) === // ============================================================ /// /// Insert role into database. Override for DB-specific optimizations (e.g., RETURNING). /// protected virtual async Task InsertRoleInternalAsync(long roleId, string name, CancellationToken cancellationToken = default) { await Context.ExecuteAsync(Sql.Roles_Insert(), new object[] { roleId, name }, cancellationToken); } /// /// Get role by ID from database. /// protected virtual async Task GetRoleByIdInternalAsync(long roleId, CancellationToken cancellationToken = default) { return await Context.QueryFirstOrDefaultAsync(Sql.Roles_SelectById(), new object[] { roleId }, cancellationToken); } /// /// Get role by name from database. /// protected virtual async Task GetRoleByNameInternalAsync(string name, CancellationToken cancellationToken = default) { return await Context.QueryFirstOrDefaultAsync(Sql.Roles_SelectByName(), new object[] { name }, cancellationToken); } // ============================================================ // === LIFECYCLE HOOKS (for Pro features like audit) === // ============================================================ /// /// Called after role is created. Override in Pro to add audit logging. /// protected virtual Task OnRoleCreatedAsync(IRedbRole role, IRedbUser? currentUser, CancellationToken cancellationToken = default) { return Task.CompletedTask; } /// /// Called after role is updated. Override in Pro to add audit logging. /// protected virtual Task OnRoleUpdatedAsync(IRedbRole role, IRedbUser? currentUser, CancellationToken cancellationToken = default) { return Task.CompletedTask; } /// /// Called after role is deleted. Override in Pro to add audit logging. /// protected virtual Task OnRoleDeletedAsync(IRedbRole role, IRedbUser? currentUser, CancellationToken cancellationToken = default) { return Task.CompletedTask; } // ============================================================ // === PRIVATE HELPERS === // ============================================================ private void ValidateRoleName(string? name) { if (string.IsNullOrWhiteSpace(name)) throw new ArgumentException("Role name is required"); if (name.Length < 2) throw new ArgumentException("Role name must be at least 2 characters"); } private async Task AssignUsersByLoginsAsync(IRedbRole role, string[] userLogins, CancellationToken cancellationToken = default) { foreach (var userLogin in userLogins) { var userId = await Context.ExecuteScalarAsync(Sql.Users_SelectIdByLogin(), new object[] { userLogin }, cancellationToken); if (!userId.HasValue) throw new ArgumentException($"User with login '{userLogin}' not found"); var userRoleId = await Context.NextObjectIdAsync(); await Context.ExecuteAsync(Sql.UsersRoles_Insert(), new object[] { userRoleId, userId.Value, role.Id }, cancellationToken); } } private async Task AssignUsersByObjectsAsync(IRedbRole role, IRedbUser[] users, CancellationToken cancellationToken = default) { foreach (var user in users) { var userExists = await Context.ExecuteScalarAsync(Sql.Users_ExistsById(), new object[] { user.Id }, cancellationToken); if (!userExists.HasValue) throw new ArgumentException($"User with ID {user.Id} ('{user.Login}') not found"); var userRoleId = await Context.NextObjectIdAsync(); await Context.ExecuteAsync(Sql.UsersRoles_Insert(), new object[] { userRoleId, user.Id, role.Id }, cancellationToken); } } } Path: redb/redb.Core/Providers/Base/SchemeSyncProviderBase.ByteArrayStorage.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.ByteArrayStorage.cs ---- using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using redb.Core.Utils; namespace redb.Core.Providers.Base; /// /// Migration of byte[] properties to scalar storage (V4, work Б1 — owner decision 2026-08-31). /// /// /// Before V4 the scheme sync classified a byte[] property as an ARRAY of Byte: a base row /// with the array hash in _Guid plus one element row per byte in _Long. The scalar /// machinery — the ByteArray type, the _values._ByteArray BLOB column, base64 in the JSON /// builders, the Pro materializer — existed all along and was unreachable from class models. V4 /// classifies byte[] as the scalar it is; this file converts what the old classification /// left behind, at synchronisation, self-healing and idempotent: the bytes are assembled from the /// element rows in index order into the base row's _ByteArray, the element rows are deleted, /// and the structure becomes ByteArray with no collection. /// /// public abstract partial class SchemeSyncProviderBase { /// /// True when the structure is the pre-V4 shape of a byte[] property (Array of Byte) and /// the CLR side now wants the scalar ByteArray. /// private static bool IsLegacyByteArrayShape(IRedbStructure structure, long newTypeId, bool isArray) => structure.IdType == RedbTypeIds.Byte && structure.CollectionType == RedbTypeIds.Array && newTypeId == RedbTypeIds.ByteArray && !isArray; /// /// Converts every object's per-byte element rows into one scalar _ByteArray value on the /// base row, then retypes the structure. Runs inside scheme synchronisation; a crash half-way /// leaves the structure untouched (type flips last), so the next start converts again — and a /// base row that already carries its bytes with no element rows left (the crash landed between /// the delete and the type flip, or a second node finished first) is recognised and kept. /// private async Task ConvertByteArrayStorageAsync(RedbStructure structure, CancellationToken cancellationToken = default) { // The old layout: base row with the array hash in _Guid; element rows with // _array_parent_id = base._id, _array_index = "0".."n", the byte in _Long. // // A base row is NOT "the row with no parent": a byte[] nested in a class (or in an // array-of-class element) has _array_parent_id = the class row, a row of ANOTHER structure, // and a pseudo _array_index. Membership tells the two apart: an element row points at a row // of THIS structure, a base row never does. var rows = await Context.QueryAsync(Sql.Values_SelectByStructure(), new object[] { structure.Id }, cancellationToken); var ownIds = rows.Select(r => r.Id).ToHashSet(); bool IsElement(RedbValue r) => r.ArrayParentId is { } parent && ownIds.Contains(parent); var elements = rows.Where(IsElement).ToLookup(r => r.ArrayParentId!.Value); var baseRows = rows.Where(r => !IsElement(r)).ToList(); var converted = 0; var alreadyConverted = 0; foreach (var baseRow in baseRows) { var parts = elements[baseRow.Id] .OrderBy(e => int.TryParse(e.ArrayIndex, out var i) ? i : int.MaxValue) .ToList(); if (parts.Count == 0 && baseRow.ByteArray != null) { // Bytes assembled and elements gone, only the type flip is missing: a previous run // got that far. Overwriting with an empty payload here is how a retry loses data. alreadyConverted++; continue; } var bytes = new byte[parts.Count]; for (var i = 0; i < parts.Count; i++) bytes[i] = unchecked((byte)(parts[i].Long ?? 0)); await Context.ExecuteAsync(Sql.Values_SetByteArrayScalar(), new object[] { bytes, baseRow.Id }, cancellationToken); converted++; } // Set-based: the element rows of a megabyte payload are a million ids, too many to inline. var removed = elements.Count == 0 ? 0 : await Context.ExecuteAsync(Sql.Values_DeleteByteArrayElements(), new object[] { structure.Id }, cancellationToken); Logger?.LogInformation( "REDB byte[] storage: structure {StructureId} ('{Name}') converted from Array-of-Byte to " + "scalar _ByteArray: {Objects} object value(s) assembled, {Kept} already converted, " + "{Elements} element row(s) removed.", structure.Id, structure.Name, converted, alreadyConverted, removed); } } Path: redb/redb.Core/Providers/Base/SchemeSyncProviderBase.Drop.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.Drop.cs ---- using Microsoft.Extensions.Logging; using redb.Core.Models; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using redb.Core.Utils; namespace redb.Core.Providers.Base; public abstract partial class SchemeSyncProviderBase { /// public Task DropUnknownStructuresAsync(bool dryRun = true, CancellationToken cancellationToken = default) where TProps : class => GuardSchemeSyncAsync(() => DropUnknownStructuresCoreAsync(dryRun, cancellationToken), cancellationToken); private async Task DropUnknownStructuresCoreAsync(bool dryRun, CancellationToken cancellationToken) where TProps : class { var scheme = await GetSchemeByTypeAsync(cancellationToken) ?? throw new InvalidOperationException( $"No scheme is stored for {typeof(TProps).FullName}: synchronise it before dropping its structures."); var stored = await Context.QueryFirstOrDefaultAsync(Sql.Schemes_SelectById(), new object[] { scheme.Id }, cancellationToken); var classVersion = GetRedbSchemeAttribute()?.Version ?? 0; var storedVersion = stored?.Version ?? 0; if (classVersion < storedVersion) throw new Exceptions.RedbPropsClassOlderException(scheme.Name, typeof(TProps), classVersion, storedVersion); var structures = await Context.QueryAsync(Sql.Structures_SelectByScheme(), new object[] { scheme.Id }, cancellationToken); var known = ClassStructureIds(typeof(TProps), structures.Cast().ToList()); var byId = structures.ToDictionary(s => s.Id); string PathOf(RedbStructure s) => s.IdParent is { } p && byId.TryGetValue(p, out var parent) ? PathOf(parent) + "." + s.Name : s.Name; var unknown = structures.Where(s => !known.Contains(s.Id)).ToList(); var items = new List(); foreach (var s in unknown.OrderBy(PathOf, StringComparer.Ordinal)) { var values = await Context.ExecuteScalarAsync( $"SELECT COUNT(*) FROM _values WHERE _id_structure = {s.Id}", Array.Empty(), cancellationToken) ?? 0; items.Add(new RedbDropReportItem(PathOf(s), s.Id, values, false)); } if (!dryRun && unknown.Count > 0) { BeforeSchemeWrite(); await Context.ExecuteAsync(Sql.Structures_DeleteByIds(unknown.Select(s => s.Id).ToList()), Array.Empty(), cancellationToken); await Context.ExecuteAsync(Sql.Schemes_SyncMetadataCache(), new object[] { scheme.Id }, cancellationToken); var remaining = await Context.QueryAsync(Sql.Structures_SelectBySchemeShort(), new object[] { scheme.Id }, cancellationToken); await Context.ExecuteAsync(Sql.Schemes_UpdateHash(), new object[] { SchemeHashCalculator.ComputeSchemeStructureHash(remaining), scheme.Id }, cancellationToken); Cache.InvalidateScheme(scheme.Id); Cache.InvalidateScheme(scheme.Name); items = items.Select(i => i with { Deleted = true }).ToList(); } var report = new RedbDropReport(scheme.Name, scheme.Id, classVersion, storedVersion, dryRun, items); if (items.Count > 0) Logger?.LogWarning("REDB DropUnknownStructuresAsync: {Report}", report.ToString()); return report; } } Path: redb/redb.Core/Providers/Base/SchemeSyncProviderBase.Rename.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.Rename.cs ---- using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Threading; using System.Threading.Tasks; using redb.Core.Attributes; using redb.Core.Caching; using redb.Core.Exceptions; using redb.Core.Models.Entities; using Microsoft.Extensions.Logging; namespace redb.Core.Providers.Base; /// /// Rename side of the scheme sync: on properties. /// /// A property whose name is not stored but whose previous name is takes the stored structure: one UPDATE of the name /// through the dialect, the id and every value stay. The previous names are kept in _structures._renamed_from /// (a JSON array, oldest first), so that a class that predates the rename stops at its sync instead of adding the old /// name again and, under the strict sync, deleting the renamed structure with its values. /// /// /// The names a rename changes reach everything derived from them through the steps of the sync that follow it: the /// scheme hash ( hashes the names) is recomputed and the scheme and structure /// tree caches are dropped when it moves, and the metadata cache table is rebuilt by the writing pass. /// /// public abstract partial class SchemeSyncProviderBase { /// /// Checks one level of a class (the root of the scheme, or the class of a nested property) against the previous /// names stored at that level: a stored structure that the class does not claim, by its name or by a /// , while the class declares one of its previous names, means the class is older /// than the rename. Runs before anything is written at the level. /// private static void CheckRenamedAway(string schemeName, Type type, IReadOnlyList properties, long? parentId, List existingStructures) { var declared = properties.Select(p => p.Name).ToHashSet(StringComparer.Ordinal); CheckOneStepSwap(type, properties); var claimed = new HashSet(declared, StringComparer.Ordinal); foreach (var property in properties) foreach (var rename in property.GetCustomAttributes(false)) claimed.Add(rename.OldName); var level = existingStructures.Where(s => s.IdParent == parentId).ToList(); foreach (var stored in level) { if (stored.RenamedFrom == null || claimed.Contains(stored.Name)) continue; var previous = ReadRenamedFrom(stored); var hit = previous.LastOrDefault(declared.Contains); if (hit != null) throw RedbRenameConflictException.RenamedAway(schemeName, $"{type.Name}.{hit}", stored.Name, stored.Id); } foreach (var property in properties) { var name = property.Name; var path = $"{type.Name}.{name}"; var chain = DeclaredRenames(property); var current = level.FirstOrDefault(s => s.Name == name); var oldNames = chain.Where(n => n != name).Distinct(StringComparer.Ordinal).ToList(); var ownOldNames = oldNames.Where(n => !declared.Contains(n)).ToList(); // A previous name another property of the class carries again (a freed name taken by a new property) is // read only once the rename is applied: while the database stores such a name and neither the current name // nor a previous name no other property carries, the stored structure could belong to either property. if (current == null && !level.Any(s => ownOldNames.Contains(s.Name))) { var reused = oldNames.FirstOrDefault(n => declared.Contains(n) && level.Any(s => s.Name == n)); if (reused != null) throw new InvalidOperationException( $"[RedbRename(\"{reused}\")] on '{path}': the class '{type.FullName ?? type.Name}' also declares a " + $"property '{reused}', and the database stores '{reused}' but not '{name}'. The stored structure " + $"could belong to either property. Apply the rename with a class that does not declare " + $"'{reused}' again, then add the new property."); } // The first name of the property is part of the hash canon (RedbHash.HashSortKey): the history the database // keeps must start with the first [RedbRename] the class declares, or the stored hashes were computed in // another order than the class computes them now. var matched = current ?? level.Where(s => ownOldNames.Contains(s.Name)).OrderBy(s => s.Id).FirstOrDefault(); if (matched == null) continue; var history = ReadRenamedFrom(matched); if (history.Count > 0 && (chain.Count == 0 || chain[0] != history[0])) throw RedbRenameConflictException.FirstNameMismatch(schemeName, path, matched.Id, history, chain.Count == 0 ? null : chain[0]); } } /// /// Refuses two properties of one class level that swap names in one step: the last /// of each (the attribute declared last; the attributes are read in declaration order, the order the first-name /// check verifies against the stored history) names the current name of the other. Each of the two renames needs /// its target name free, and the target is the other property's name until that one is renamed, so the pair can /// only mean both renames at once; the sync would find both current names stored and rename nothing, leaving the /// values under the names they had. A swap through a temporary name leaves other last names and passes. Read from /// the class alone. /// private static void CheckOneStepSwap(Type type, IReadOnlyList properties) { var lastNames = new Dictionary(StringComparer.Ordinal); foreach (var property in properties) { var last = DeclaredRenames(property).LastOrDefault(); if (last != null && last != property.Name) lastNames[property.Name] = last; } foreach (var (name, last) in lastNames) { if (string.CompareOrdinal(name, last) > 0 || !lastNames.TryGetValue(last, out var back) || back != name) continue; throw new InvalidOperationException( $"[RedbRename(\"{last}\")] on '{type.Name}.{name}' and [RedbRename(\"{name}\")] on '{type.Name}.{last}': " + $"the class '{type.FullName ?? type.Name}' swaps the two names in one step, which the sync cannot apply. " + $"Swap them through a temporary name, one deployment per rename: '{name}' to a temporary name, then " + $"'{last}' to '{name}', then the temporary name to '{last}'."); } } /// The names of the s of a property, in declaration order. private static List DeclaredRenames(PropertyInfo property) => property.GetCustomAttributes(false).Select(a => a.OldName).ToList(); /// /// The stored structure of a property: under its name, or under one of its previous names, which is then renamed /// in place. Null when the property is new. /// private async Task MatchStructureAsync(string schemeName, Type type, PropertyInfo property, IReadOnlyList properties, long? parentId, List existingStructures, CancellationToken cancellationToken = default) { var name = property.Name; var path = $"{type.Name}.{name}"; var current = existingStructures.FirstOrDefault(s => s.Name == name && s.IdParent == parentId); var chain = DeclaredRenames(property); // A previous name another property carries again belongs to that property once the rename is applied; the // level check (CheckRenamedAway) has already refused the state in which it is not. var oldNames = chain .Where(n => n != name && properties.All(p => p.Name != n)) .Distinct(StringComparer.Ordinal) .ToList(); if (oldNames.Count == 0) return current; var stored = existingStructures .Where(s => s.IdParent == parentId && oldNames.Contains(s.Name)) .OrderBy(s => s.Id) .ToList(); if (stored.Count == 0) return current; if (current != null) throw RedbRenameConflictException.BothStored(schemeName, path, stored[0].Name, current.Id, stored[0].Id); if (stored.Count > 1) throw RedbRenameConflictException.SeveralStored(schemeName, path, stored.Select(s => (s.Name, s.Id)).ToList()); var renamed = stored[0]; var renamedFrom = StructureHistoryAfterRename(ReadRenamedFrom(renamed), chain, renamed.Name); BeforeSchemeWrite(); await Context.ExecuteAsync(Sql.Structures_Rename(), new object[] { name, renamedFrom, renamed.Id }, cancellationToken); Logger?.LogInformation( "REDB schema sync: scheme '{SchemeName}': structure {StructureId} renamed from '{OldName}' to '{NewName}' ([RedbRename]).", schemeName, renamed.Id, renamed.Name, name); renamed.Name = name; renamed.RenamedFrom = renamedFrom; return renamed; } /// The previous names of a structure, oldest first; empty when it was never renamed. private static List ReadRenamedFrom(RedbStructure structure) => ReadRenamedFrom(structure.RenamedFrom, $"_structures._renamed_from of structure {structure.Id} ('{structure.Name}')"); /// The previous names of a scheme, oldest first; empty when it was never renamed. private static List ReadRenamedFrom(RedbScheme scheme) => ReadRenamedFrom(scheme.RenamedFrom, $"_schemes._renamed_from of scheme {scheme.Id} ('{scheme.Name}')"); private static List ReadRenamedFrom(string? json, string what) { if (string.IsNullOrEmpty(json)) return []; try { return System.Text.Json.JsonSerializer.Deserialize>(json) ?? []; } catch (System.Text.Json.JsonException ex) { throw new InvalidOperationException( $"{what} is not a JSON array of names: '{json}'. Correct or clear the column by hand.", ex); } } /// /// The history of a structure after one more rename, oldest first. A structure renamed before keeps its history and /// gets the name it is renamed from appended. A structure renamed for the first time gets the declared chain up to /// that name: a database created with a class that already carried [RedbRename] has no history of the names before /// it, and the first name of the chain is what the hash canon sorts by. The current name is never removed, so the /// first entry stays the first name even when a property is renamed back. /// private static string StructureHistoryAfterRename(List previous, List chain, string renamedFrom) { var list = previous.Count > 0 ? new List(previous) : chain.TakeWhile(n => n != renamedFrom).Distinct(StringComparer.Ordinal).ToList(); if (!list.Contains(renamedFrom)) list.Add(renamedFrom); return System.Text.Json.JsonSerializer.Serialize(list); } /// The history after one more rename: the previous list with the name renamed from appended. private static string AppendRenamedFrom(List previous, string renamedFrom, string newName) { var list = previous.Where(n => n != newName).ToList(); if (!list.Contains(renamedFrom)) list.Add(renamedFrom); return System.Text.Json.JsonSerializer.Serialize(list); } /// /// The previous scheme names a class declares (), newest first: the /// lookup tries the most recent name before older ones. Empty and repeated names and the target name are skipped. /// private static List GetDeclaredPreviousSchemeNames(Type type, string targetName) { var declared = type.GetCustomAttribute()?.RenamedFrom; if (declared == null || declared.Length == 0) return []; return declared .Where(n => !string.IsNullOrWhiteSpace(n) && n != targetName) .Distinct(StringComparer.Ordinal) .Reverse() .ToList(); } /// /// Renames a scheme in place and records the name it had in _schemes._renamed_from. The id stays, so every /// object and structure stays with it. /// private async Task RenameSchemeAsync(RedbScheme scheme, string previousName, string targetName, Type type, CancellationToken cancellationToken) { BeforeSchemeWrite(); Logger?.LogInformation( "Renaming scheme '{OldName}' to '{NewName}' (ID: {SchemeId}, InTransaction: {InTx})", previousName, targetName, scheme.Id, Context.CurrentTransaction != null); var renamedFrom = AppendRenamedFrom(ReadRenamedFrom(scheme), previousName, targetName); var rowsAffected = await Context.ExecuteAsync(Sql.Schemes_Rename(), new object[] { targetName, renamedFrom, scheme.Id }, cancellationToken); if (rowsAffected == 0) { Logger?.LogWarning("Rename UPDATE affected 0 rows for scheme ID {SchemeId}. SQL: {Sql}", scheme.Id, Sql.Schemes_Rename()); } scheme.Name = targetName; scheme.RenamedFrom = renamedFrom; // Three keys: the id, the name it was found under, and the target name (in case a stale entry sits there). The // process-global name -> Type index is refreshed immediately rather than waiting for the next assembly rescan. Cache.InvalidateScheme(scheme.Id); Cache.InvalidateScheme(previousName); Cache.InvalidateScheme(targetName); ClrSchemeTypeIndex.Register(targetName, type); } /// /// Before a scheme is created: a stored scheme whose previous names hold the name about to be created, while no class /// of this application declares that scheme under its current name, means the class is older than the rename. /// A class that does declare it is a new scheme taking a freed name, which is allowed. /// private async Task CheckSchemeRenamedAwayAsync(Type type, string targetName, CancellationToken cancellationToken) { var renamed = await Context.QueryAsync(Sql.Schemes_SelectRenamed(), Array.Empty(), cancellationToken); foreach (var scheme in renamed) { if (!ReadRenamedFrom(scheme).Contains(targetName)) continue; if (ClrSchemeTypeIndex.Resolve(scheme.Name) != null) continue; throw RedbRenameConflictException.SchemeRenamedAway(type, targetName, scheme.Name, scheme.Id); } } } Path: redb/redb.Core/Providers/Base/SchemeSyncProviderBase.SchemaLock.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.SchemaLock.cs ---- using System; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; namespace redb.Core.Providers.Base; /// /// The schema lock around a scheme sync. Nodes of a cluster sync the same schemes at once: they start together, /// their modules share Props classes, a new version of a module adds a field on every node at the same moment. /// Two of them inserting the same structure failed on the unique keys of _schemes and _structures, /// two rebuilding the metadata cache of one scheme on its rows. /// /// /// A sync first runs as a check: the same code, reading only. The first write it reaches stops it, and the sync /// runs again under the schema lock of the service, now writing; a node that waited for the lock finds the work done /// and writes nothing. A scheme already in step (nearly every start) never reaches a write and never takes the lock. /// /// public abstract partial class SchemeSyncProviderBase { /// /// Runs work under the schema lock of the service that owns this provider (reentrant). Set by the service right /// after it builds the provider; left null, the sync writes without a lock, as a provider built on its own did. /// public Func, CancellationToken, Task>? RunUnderSchemaLock { get; set; } /// /// Receives the schema problems a sync meets (duplicate root structures it leaves alone): the service logs them as /// errors and lists them in . Left null, the provider logs them itself. /// public Action? SchemaProblemFound { get; set; } private void ReportSchemaProblem(Models.RedbSchemaProblem problem) { if (SchemaProblemFound != null) SchemaProblemFound(problem); else Logger?.LogError("{Problem}", problem.Message); } private enum SyncPass { Check, Write } // The pass of the sync running in this flow; null outside one. A sync nested in another (SyncSchemeAsync calling // SyncStructuresFromTypeAsync) belongs to the outer pass. private readonly AsyncLocal _syncPass = new(); /// Thrown at the first write of a check pass; never leaves . private sealed class SchemeWriteNeededException : Exception { } private bool IsCheckPass => _syncPass.Value == SyncPass.Check; /// Called before every write of a sync: a check pass stops here. private void BeforeSchemeWrite() { if (IsCheckPass) throw new SchemeWriteNeededException(); ForgetCachedSchemesIfRolledBack(); } // Transactions whose rollback already clears the scheme caches: one registration per transaction. private static readonly System.Runtime.CompilerServices.ConditionalWeakTable RollbackResetRegistered = new(); /// /// A sync that writes inside a transaction caches the schemes and structures it creates before the transaction /// ends. If it rolls back, those entries point at rows that do not exist (and ids that are never handed out /// again): the next save of the type would reference a missing scheme. The caches of this database are dropped /// on that rollback and refill from the database. /// private void ForgetCachedSchemesIfRolledBack() { if (Data.TransactionHooks.TransactionOf(Context) is not { } transaction) return; if (!RollbackResetRegistered.TryAdd(transaction, transaction)) return; Data.TransactionHooks.OnCompleted(Context, committed => { if (committed) return; Cache.ClearDomainIncludingClrTypes(); }); } private async Task GuardSchemeSyncAsync(Func> sync, CancellationToken cancellationToken) { // Inside a transaction of the caller the lock would be released before the caller commits, and the next node // would not see the rows written under it: such a sync runs as before, unguarded. if (_syncPass.Value != null || RunUnderSchemaLock == null || Context.IsInTransaction) return await sync(); _syncPass.Value = SyncPass.Check; try { return await sync(); } catch (SchemeWriteNeededException) { } T result = default!; await RunUnderSchemaLock(async () => { _syncPass.Value = SyncPass.Write; result = await sync(); }, cancellationToken); return result; } } Path: redb/redb.Core/Providers/Base/SchemeSyncProviderBase.Unique.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.Unique.cs ---- using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using redb.Core.Attributes; using redb.Core.Exceptions; using redb.Core.Models; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using redb.Core.Utils; namespace redb.Core.Providers.Base; /// /// Unique-key side of scheme synchronisation: validating [RedbUnique], keeping /// _structures._unique in step with the attribute, and recomputing _values._unique /// when the keys of a populated structure cannot be trusted. /// /// /// Recomputation triggers (UNIQUE plan, work 2.8): the attribute appeared on a populated structure; /// the structure's _unique_version is behind ; rows exist /// with a value but no key — the trace of a SQL-side writer (a type migration, a Pro data migration), /// which releases keys instead of faking them; and the explicit /// . Duplicates are reported, never thrown: the first row /// of a group keeps the key, the rest stay outside the index (§4.2 — otherwise "unique" would be /// formally on and factually off, silently). /// /// public abstract partial class SchemeSyncProviderBase { private static readonly HashSet AllowedUniqueKeyTypes = [ typeof(string), typeof(char), typeof(long), typeof(int), typeof(short), typeof(byte), typeof(Guid), typeof(bool), typeof(double), typeof(float), typeof(decimal), typeof(DateTime), typeof(DateTimeOffset), typeof(DateOnly), typeof(TimeOnly), typeof(TimeSpan), // byte[] is a root scalar since Б1 (owner decision 2026-08-31): stored whole in _ByteArray. typeof(byte[]), ]; /// /// Validates the attribute's placement and brings _structures._unique in line with it. /// Rejection happens here, at synchronisation — not at insert, where a misplaced key would /// degrade into an index that silently never fires (§4.4). /// private async Task SyncUniqueFlagAsync( Type ownerType, PropertyInfo property, RedbStructure structure, bool isArray, bool isDictionary, Type baseType, bool pathHasCollection, CancellationToken cancellationToken = default) { var uniqueAttribute = property.GetCustomAttribute(); var wantUnique = uniqueAttribute != null; // S3: a non-default Scope switches a collection key from the subtree-content reading // to ELEMENT keys; NULL in _structures._unique_scope means the default reading. var wantScope = uniqueAttribute?.Scope is { } s && s != UniqueScope.Default ? (long?)s : null; if (wantUnique) { if (wantScope != null && !isArray && !isDictionary) throw new RedbUniqueKeyDefinitionException(ownerType.Name, property.Name, "Scope applies to collections only: on a scalar or a nested class the bare " + "attribute already carries the strongest reading"); // S2: a scalar inside a nested class is a legal key as long as no ancestor on the // path is a collection - on a collection-free path the object holds exactly one row // of the structure, so the per-structure index reads the same as for a root key. if (pathHasCollection) throw new RedbUniqueKeyDefinitionException(ownerType.Name, property.Name, "the property sits inside an element of a collection of classes; every element " + "of every object shares one structure, so uniqueness would mean one value " + "across all elements of all objects"); // S1: a class, array or dictionary property is a SUBTREE key - the canonical content // hash the storage maintains on the base row becomes the key, so "unique" reads as // "no two objects hold this exact content". Scalars keep the per-type canon rules. var isSubtreeKey = isArray || isDictionary || IsBusinessClass(baseType); if (!isSubtreeKey) { var t = Nullable.GetUnderlyingType(baseType) ?? baseType; if (t.IsEnum) throw new RedbUniqueKeyDefinitionException(ownerType.Name, property.Name, "an enum is stored as its name in text and is not a key type; key a string or an integer property instead"); if (!AllowedUniqueKeyTypes.Contains(t)) throw new RedbUniqueKeyDefinitionException(ownerType.Name, property.Name, $"type '{t.Name}' cannot be a key"); } } var current = structure.Unique == true; if (current == wantUnique && structure.UniqueScope == wantScope) return; BeforeSchemeWrite(); if (wantUnique) { // Version stays NULL until the keys are actually computed: EnsureUniqueKeysAsync sees the // missing stamp and recomputes, populated structure or not (§4.2). A SCOPE change also // clears the stamp and the stored keys: the same values key differently per scope. if (current && structure.UniqueScope != wantScope) await Context.ExecuteAsync(Sql.Values_ClearUniqueByStructure(), new object[] { structure.Id }, cancellationToken); await Context.ExecuteAsync(Sql.Structures_UpdateUnique(), new object[] { true, DBNull.Value, (object?)wantScope ?? DBNull.Value, structure.Id }, cancellationToken); structure.Unique = true; structure.UniqueVersion = null; structure.UniqueScope = wantScope; } else { // The attribute is gone: the flag and every stored key go with it — a key that no longer // guards anything must not keep rejecting values. await Context.ExecuteAsync(Sql.Structures_UpdateUnique(), new object[] { false, DBNull.Value, DBNull.Value, structure.Id }, cancellationToken); await Context.ExecuteAsync(Sql.Values_ClearUniqueByStructure(), new object[] { structure.Id }, cancellationToken); structure.Unique = false; structure.UniqueVersion = null; structure.UniqueScope = null; } } /// /// Runs after the structures of a scheme are in their final shape: recomputes the keys of every /// key structure whose stored keys cannot be trusted, and stamps the encoder version. /// private async Task EnsureUniqueKeysAsync(IRedbScheme scheme, IReadOnlyList structures, CancellationToken cancellationToken = default) { // S2: nested keys included - the validator only ever sets Unique on collection-free // paths, so every flagged structure holds one row per object, root or nested. foreach (var structure in structures.Where(s => s.Unique == true)) { // S3: element-scoped keys live on the ELEMENT rows; the unhashed-row probe below is // keyed to non-element rows, so element scopes recompute on a version/scope change // and via the explicit RecomputeUniqueAsync - a SQL-side wipe of element keys heals // on the explicit call, not automatically. var isElementScoped = structure.UniqueScope != null; // S1: a collection's dbType is the ELEMENT type, but its key lives on the BASE row, // whose canonical content hash sits in _Guid; class nodes are typed Guid already. var column = structure.CollectionType != null ? "_Guid" : await GetTypedColumnAsync(structure.IdType); if (!isElementScoped && column == null) continue; // no canonical column - nothing to hash; the validator refuses such keys anyway var needsRecompute = structure.UniqueVersion != UniqueKeyEncoder.Version; if (!needsRecompute && !isElementScoped) { var unhashed = await Context.ExecuteScalarAsync( Sql.Values_ExistsUnhashedByStructure(column!), new object[] { structure.Id }, cancellationToken); needsRecompute = unhashed.HasValue; } if (!needsRecompute) continue; BeforeSchemeWrite(); var report = await RecomputeUniqueForStructureAsync(scheme, structure); if (report.HasDuplicates && Logger != null) { Logger.LogWarning( "REDB unique key: scheme '{Scheme}', property '{Property}' has {Groups} duplicate group(s), " + "{Losers} row(s) left OUTSIDE the unique index (their _unique is NULL). The first row of each " + "group holds the key. Query them: SELECT * FROM _values WHERE _id_structure = {StructureId} " + "AND _unique IS NULL AND {Column} IS NOT NULL. Uniqueness is enforced for every keyed row; " + "the duplicates are the application's to resolve.", report.SchemeName, report.PropertyName, report.Duplicates.Count, report.LosingRows, structure.Id, column); } } } /// /// Recomputes _values._unique for one key structure from the stored typed values — the /// same representation the save path hashes, so both agree. Winners (first row per key, lowest /// id) get the key; duplicates stay NULL and are reported. Self-healing by design: a crash /// half-way leaves unhashed rows, which is itself a recompute trigger. /// private async Task RecomputeUniqueForStructureAsync(IRedbScheme scheme, RedbStructure structure, CancellationToken cancellationToken = default) { // S3: element-scoped keys sit on the ELEMENT rows and, for the Collection scope, are // salted with the owning collection id - the same formula the save path runs. var isElementScoped = structure.UniqueScope != null; var collectionSalted = structure.UniqueScope == (long)UniqueScope.Collection; var rows = await Context.QueryAsync( isElementScoped ? Sql.Values_SelectElementRowsByStructure() : Sql.Values_SelectRootScalarsByStructure(), new object[] { structure.Id }, cancellationToken); var hashed = 0; var winners = new List<(long ValueId, Guid Key)>(); var toClear = new List(); var duplicates = new List(); foreach (var group in rows .Select(r => (Row: r, Key: UniqueKeyEncoder.Compute(r, collectionSalted ? r.ArrayParentId : null))) .GroupBy(x => x.Key)) { if (group.Key is null) { // NULL value: no key. Clear leftovers (e.g. the value was nulled by SQL). toClear.AddRange(group.Where(x => x.Row.Unique != null).Select(x => x.Row.Id)); continue; } var ordered = group.OrderBy(x => x.Row.Id).ToList(); var winner = ordered[0]; hashed++; if (winner.Row.Unique != group.Key) winners.Add((winner.Row.Id, group.Key.Value)); if (ordered.Count > 1) { toClear.AddRange(ordered.Skip(1).Where(x => x.Row.Unique != null).Select(x => x.Row.Id)); duplicates.Add(new UniqueDuplicateGroup { Key = group.Key.Value, ValueIds = ordered.Select(x => x.Row.Id).ToList(), ObjectIds = ordered.Select(x => x.Row.IdObject).ToList(), }); } } // Clears first: an exchange of keys between rows must release before it takes. foreach (var id in toClear) await Context.ExecuteAsync(Sql.Values_UpdateUnique(), new object[] { DBNull.Value, id }, cancellationToken); foreach (var (valueId, key) in winners) { try { await Context.ExecuteAsync(Sql.Values_UpdateUnique(), new object[] { key, valueId }, cancellationToken); } catch (Exception ex) when (Data.DbErrorClassifier.IsUniqueViolation(ex)) { // A concurrent writer took the key between our read and this write. The row stays // unhashed - outside the index, visible to the next recompute trigger. Logger?.LogWarning(ex, "REDB unique key recompute: value {ValueId} of structure {StructureId} lost the key to a " + "concurrent writer; the row stays outside the index until resolved.", valueId, structure.Id); } } await Context.ExecuteAsync(Sql.Structures_UpdateUnique(), new object[] { true, (long)UniqueKeyEncoder.Version, (object?)structure.UniqueScope ?? DBNull.Value, structure.Id }, cancellationToken); structure.UniqueVersion = UniqueKeyEncoder.Version; return new UniqueRecomputeReport { SchemeId = scheme.Id, SchemeName = scheme.Name, StructureId = structure.Id, PropertyName = structure.Name, TotalRows = rows.Count, HashedRows = hashed, Duplicates = duplicates, }; } /// /// Explicit recomputation of the keys of one [RedbUnique] property (UNIQUE plan 2.8, /// trigger "г"). Same algorithm the automatic triggers use; returns the report instead of /// logging it. /// public async Task RecomputeUniqueAsync(string propertyName, CancellationToken cancellationToken = default) where TProps : class { var scheme = await GetSchemeByTypeAsync() ?? throw new InvalidOperationException($"No scheme for '{typeof(TProps).Name}'; synchronise it first."); var structures = await Context.QueryAsync(Sql.Structures_SelectByScheme(), new object[] { scheme.Id }, cancellationToken); // S2: the name is a path - "Code" for a root key, "Identity.Passport" for a nested one. RedbStructure? structure = null; foreach (var segment in propertyName.Split('.')) { var parentId = structure?.Id; structure = structures.FirstOrDefault(s => s.IdParent == parentId && s.Name == segment); if (structure == null) throw new RedbUniqueKeyDefinitionException(typeof(TProps).Name, propertyName, $"no property '{segment}' at this position of the path in the scheme"); } if (structure!.Unique != true) throw new RedbUniqueKeyDefinitionException(typeof(TProps).Name, propertyName, "the property is not marked [RedbUnique]"); return await RecomputeUniqueForStructureAsync(scheme, structure); } /// The _values typed column a type's canonical value lives in; null for non-scalars. private async Task GetTypedColumnAsync(long typeId, CancellationToken cancellationToken = default) { var type = await Context.QueryFirstOrDefaultAsync(Sql.ObjectStorage_SelectTypeById(), new object[] { typeId }, cancellationToken); return type?.DbType switch { "String" or "Text" => "_String", "Long" or "bigint" => "_Long", "Guid" => "_Guid", "Double" => "_Double", "DateTime" or "DateTimeOffset" => "_DateTimeOffset", "Boolean" => "_Boolean", "ByteArray" => "_ByteArray", "Numeric" => "_Numeric", _ => null, }; } } 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; } } Path: redb/redb.Core/Providers/Base/TreeProviderBase.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/TreeProviderBase.cs ---- #pragma warning disable CS0618 // implements or uses the deprecated object permissions and roles (RedbDeprecation) using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using redb.Core.Data; using redb.Core.Models; using redb.Core.Models.Configuration; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using redb.Core.Models.Security; using redb.Core.Query; using redb.Core.Serialization; using redb.Core.Utils; using redb.Core.Caching; using Microsoft.Extensions.Logging; namespace redb.Core.Providers.Base; /// /// Base class for tree provider with all platform-agnostic logic. /// SQL queries are delegated to ISqlDialect. /// public abstract class TreeProviderBase : ITreeProvider { protected readonly IRedbContext Context; protected readonly IObjectStorageProvider ObjectStorage; protected readonly IPermissionProvider PermissionProvider; protected readonly IRedbObjectSerializer Serializer; protected readonly IRedbSecurityContext SecurityContext; protected readonly RedbServiceConfiguration Configuration; protected readonly ISchemeSyncProvider SchemeSyncProvider; protected readonly ISqlDialect Sql; protected GlobalMetadataCache Cache => SchemeSyncProvider.Cache; protected readonly ILogger? Logger; /// /// The save-pipeline interceptors of the service, the same the object storage runs: DeleteSubtreeAsync fires /// DeletingAsync and DeletedAsync as DeleteAsync does. /// private readonly Interception.RedbSaveInterceptorPipeline _saveInterceptors; protected TreeProviderBase( IRedbContext context, IObjectStorageProvider objectStorage, IPermissionProvider permissionProvider, IRedbObjectSerializer serializer, IRedbSecurityContext securityContext, ISchemeSyncProvider schemeSyncProvider, ISqlDialect sql, RedbServiceConfiguration? configuration = null, ILogger? logger = null, Interception.RedbSaveInterceptorPipeline? saveInterceptors = null) { _saveInterceptors = saveInterceptors ?? Interception.RedbSaveInterceptorPipeline.Empty; Context = context ?? throw new ArgumentNullException(nameof(context)); ObjectStorage = objectStorage ?? throw new ArgumentNullException(nameof(objectStorage)); PermissionProvider = permissionProvider ?? throw new ArgumentNullException(nameof(permissionProvider)); Serializer = serializer ?? throw new ArgumentNullException(nameof(serializer)); SecurityContext = securityContext ?? throw new ArgumentNullException(nameof(securityContext)); SchemeSyncProvider = schemeSyncProvider ?? throw new ArgumentNullException(nameof(schemeSyncProvider)); Sql = sql ?? throw new ArgumentNullException(nameof(sql)); Configuration = configuration ?? new RedbServiceConfiguration(); Logger = logger; } // ============================================================ // === INTERFACE IMPLEMENTATION === // ============================================================ public async Task InitializeTypeRegistryAsync(CancellationToken cancellationToken = default) { if (!Cache.IsClrTypeRegistryInitialized) { await Cache.InitializeClrTypeRegistryAsync(SchemeSyncProvider); } } // ===== BASE METHODS (use _securityContext and configuration) ===== /// /// Load tree by root object ID (uses _securityContext). /// public async Task> LoadTreeAsync(long rootObjectId, int? maxDepth = null, CancellationToken cancellationToken = default) where TProps : class, new() { var effectiveUser = SecurityContext.GetEffectiveUser(); var actualMaxDepth = maxDepth ?? Configuration.DefaultMaxTreeDepth; return await LoadTreeWithUserAsync(rootObjectId, actualMaxDepth, effectiveUser.Id, Configuration.DefaultCheckPermissionsOnLoad); } public async Task> LoadTreeAsync(IRedbObject rootObj, int? maxDepth = null, CancellationToken cancellationToken = default) where TProps : class, new() { var effectiveUser = SecurityContext.GetEffectiveUser(); var actualMaxDepth = maxDepth ?? Configuration.DefaultMaxTreeDepth; return await LoadTreeWithUserAsync(rootObj.Id, actualMaxDepth, effectiveUser.Id, Configuration.DefaultCheckPermissionsOnLoad); } public async Task>> GetChildrenAsync(IRedbObject parentObj, CancellationToken cancellationToken = default) where TProps : class, new() { var effectiveUser = SecurityContext.GetEffectiveUser(); return await GetChildrenWithUserAsync(parentObj.Id, effectiveUser.Id, Configuration.DefaultCheckPermissionsOnLoad); } public async Task>> GetPathToRootAsync(IRedbObject obj, CancellationToken cancellationToken = default) where TProps : class, new() { var effectiveUser = SecurityContext.GetEffectiveUser(); return await GetPathToRootWithUserAsync(obj.Id, effectiveUser.Id, Configuration.DefaultCheckPermissionsOnLoad); } public async Task>> GetDescendantsAsync(IRedbObject parentObj, int? maxDepth = null, CancellationToken cancellationToken = default) where TProps : class, new() { var effectiveUser = SecurityContext.GetEffectiveUser(); var actualMaxDepth = maxDepth ?? Configuration.DefaultMaxTreeDepth; return await GetDescendantsWithUserAsync(parentObj.Id, actualMaxDepth, effectiveUser.Id, Configuration.DefaultCheckPermissionsOnLoad); } public async Task MoveObjectAsync(IRedbObject obj, IRedbObject? newParentObj, CancellationToken cancellationToken = default) { var effectiveUser = SecurityContext.GetEffectiveUser(); await MoveObjectWithUserAsync(obj.Id, newParentObj?.Id, effectiveUser.Id, Configuration.DefaultCheckPermissionsOnSave); } public async Task CreateChildAsync(TreeRedbObject obj, IRedbObject parentObj, CancellationToken cancellationToken = default) where TProps : class, new() { var effectiveUser = SecurityContext.GetEffectiveUser(); return await CreateChildWithUserAsync(obj, parentObj.Id, effectiveUser.Id, Configuration.DefaultCheckPermissionsOnSave); } public async Task DeleteSubtreeAsync(IRedbObject parentObj, CancellationToken cancellationToken = default) { var effectiveUser = SecurityContext.GetEffectiveUser(); return await DeleteSubtreeWithUserAsync(parentObj.Id, effectiveUser); } // ===== OVERLOADS WITH EXPLICIT USER ===== /// /// Load tree by root object ID with explicit user. /// public async Task> LoadTreeAsync(long rootObjectId, IRedbUser user, int? maxDepth = null, CancellationToken cancellationToken = default) where TProps : class, new() { var actualMaxDepth = maxDepth ?? Configuration.DefaultMaxTreeDepth; return await LoadTreeWithUserAsync(rootObjectId, actualMaxDepth, user.Id, Configuration.DefaultCheckPermissionsOnLoad); } public async Task> LoadTreeAsync(IRedbObject rootObj, IRedbUser user, int? maxDepth = null, CancellationToken cancellationToken = default) where TProps : class, new() { var actualMaxDepth = maxDepth ?? Configuration.DefaultMaxTreeDepth; return await LoadTreeWithUserAsync(rootObj.Id, actualMaxDepth, user.Id, Configuration.DefaultCheckPermissionsOnLoad); } public async Task>> GetChildrenAsync(IRedbObject parentObj, IRedbUser user, CancellationToken cancellationToken = default) where TProps : class, new() => await GetChildrenWithUserAsync(parentObj.Id, user.Id, Configuration.DefaultCheckPermissionsOnLoad); public async Task>> GetPathToRootAsync(IRedbObject obj, IRedbUser user, CancellationToken cancellationToken = default) where TProps : class, new() => await GetPathToRootWithUserAsync(obj.Id, user.Id, Configuration.DefaultCheckPermissionsOnLoad); public async Task>> GetDescendantsAsync(IRedbObject parentObj, IRedbUser user, int? maxDepth = null, CancellationToken cancellationToken = default) where TProps : class, new() { var actualMaxDepth = maxDepth ?? Configuration.DefaultMaxTreeDepth; return await GetDescendantsWithUserAsync(parentObj.Id, actualMaxDepth, user.Id, Configuration.DefaultCheckPermissionsOnLoad); } public async Task MoveObjectAsync(IRedbObject obj, IRedbObject? newParentObj, IRedbUser user, CancellationToken cancellationToken = default) => await MoveObjectWithUserAsync(obj.Id, newParentObj?.Id, user.Id, Configuration.DefaultCheckPermissionsOnSave, cancellationToken); public async Task CreateChildAsync(TreeRedbObject obj, IRedbObject parentObj, IRedbUser user, CancellationToken cancellationToken = default) where TProps : class, new() => await CreateChildWithUserAsync(obj, parentObj.Id, user.Id, Configuration.DefaultCheckPermissionsOnSave); public async Task DeleteSubtreeAsync(IRedbObject parentObj, IRedbUser user, CancellationToken cancellationToken = default) => await DeleteSubtreeWithUserAsync(parentObj.Id, user, cancellationToken); // ===== POLYMORPHIC METHODS ===== public async Task LoadPolymorphicTreeAsync(IRedbObject rootObj, int? maxDepth = null, CancellationToken cancellationToken = default) { var effectiveUser = SecurityContext.GetEffectiveUser(); var actualMaxDepth = maxDepth ?? Configuration.DefaultMaxTreeDepth; return await LoadPolymorphicTreeWithUserAsync(rootObj.Id, actualMaxDepth, effectiveUser.Id, Configuration.DefaultCheckPermissionsOnLoad); } public async Task> GetPolymorphicChildrenAsync(IRedbObject parentObj, CancellationToken cancellationToken = default) { var effectiveUser = SecurityContext.GetEffectiveUser(); return await GetPolymorphicChildrenWithUserAsync(parentObj.Id, effectiveUser.Id, Configuration.DefaultCheckPermissionsOnLoad); } public async Task> GetPolymorphicPathToRootAsync(IRedbObject obj, CancellationToken cancellationToken = default) { var effectiveUser = SecurityContext.GetEffectiveUser(); return await GetPolymorphicPathToRootWithUserAsync(obj.Id, effectiveUser.Id, Configuration.DefaultCheckPermissionsOnLoad); } public async Task> GetPolymorphicDescendantsAsync(IRedbObject parentObj, int? maxDepth = null, CancellationToken cancellationToken = default) { var effectiveUser = SecurityContext.GetEffectiveUser(); var actualMaxDepth = maxDepth ?? Configuration.DefaultMaxTreeDepth; return await GetPolymorphicDescendantsWithUserAsync(parentObj.Id, actualMaxDepth, effectiveUser.Id, Configuration.DefaultCheckPermissionsOnLoad); } // ===== POLYMORPHIC METHODS WITH EXPLICIT USER ===== public async Task LoadPolymorphicTreeAsync(IRedbObject rootObj, IRedbUser user, int? maxDepth = null, CancellationToken cancellationToken = default) { var actualMaxDepth = maxDepth ?? Configuration.DefaultMaxTreeDepth; return await LoadPolymorphicTreeWithUserAsync(rootObj.Id, actualMaxDepth, user.Id, Configuration.DefaultCheckPermissionsOnLoad); } public async Task> GetPolymorphicChildrenAsync(IRedbObject parentObj, IRedbUser user, CancellationToken cancellationToken = default) => await GetPolymorphicChildrenWithUserAsync(parentObj.Id, user.Id, Configuration.DefaultCheckPermissionsOnLoad, cancellationToken); public async Task> GetPolymorphicPathToRootAsync(IRedbObject obj, IRedbUser user, CancellationToken cancellationToken = default) => await GetPolymorphicPathToRootWithUserAsync(obj.Id, user.Id, Configuration.DefaultCheckPermissionsOnLoad, cancellationToken); public async Task> GetPolymorphicDescendantsAsync(IRedbObject parentObj, IRedbUser user, int? maxDepth = null, CancellationToken cancellationToken = default) { var actualMaxDepth = maxDepth ?? Configuration.DefaultMaxTreeDepth; return await GetPolymorphicDescendantsWithUserAsync(parentObj.Id, actualMaxDepth, user.Id, Configuration.DefaultCheckPermissionsOnLoad); } // ============================================================ // === PROTECTED VIRTUAL METHODS (can be overridden in derived classes) === // ============================================================ protected virtual async Task> LoadTreeWithUserAsync( long rootId, int maxDepth = 10, long? userId = null, bool checkPermissions = false, CancellationToken cancellationToken = default) where TProps : class, new() { var baseObject = await ObjectStorage.LoadAsync(rootId, 1); if (baseObject == null) throw new InvalidOperationException($"Object with ID {rootId} not found"); var treeObject = ConvertToTreeObject(baseObject); // The nodes come in walk order, a parent before its children. var byId = new Dictionary> { [rootId] = treeObject }; foreach (var node in await LoadTypedSubtreeAsync(rootId, maxDepth, userId, checkPermissions, cancellationToken)) { var parent = byId[node.parent_id!.Value]; node.Parent = parent; parent.Children.Add(node); byId[node.id] = node; } return treeObject; } protected virtual async Task>> GetChildrenWithUserAsync( long parentId, long? userId = null, bool checkPermissions = false, CancellationToken cancellationToken = default) where TProps : class, new() { var scheme = await SchemeSyncProvider.GetSchemeByTypeAsync(); if (scheme == null) throw new InvalidOperationException($"Scheme for type {typeof(TProps).Name} not found. Use SyncSchemeAsync<{typeof(TProps).Name}>() to create scheme."); var jsonResults = await Context.ExecuteJsonListAsync(Sql.Tree_SelectChildrenJson(), new object[] { parentId, scheme.Id }, cancellationToken); var children = new List>(); foreach (var json in jsonResults) { if (string.IsNullOrEmpty(json)) continue; try { var redbObj = Serializer.Deserialize(json); if (redbObj == null) continue; if (checkPermissions && userId.HasValue) { var canSelect = await PermissionProvider.CanUserSelectObject(redbObj); if (!canSelect) continue; } var treeObj = ConvertToTreeObject(redbObj); children.Add(treeObj); } catch { throw; } } return children; } protected virtual async Task>> GetPathToRootWithUserAsync( long objectId, long? userId = null, bool checkPermissions = false, CancellationToken cancellationToken = default) where TProps : class, new() { // One statement for the chain, one batch for the objects. The path ends where the load of an ancestor one by // one used to stop: at an ancestor of another scheme (or the RedbSchemeMismatchException under // ThrowOnSchemeMismatch), one the reader may not see, or one that is missing. var reader = SecurityContext.GetEffectiveUser(); var chain = await SelectAncestorsAsync(objectId, cancellationToken); if (chain.Count == 0) { if (Configuration.ThrowOnObjectNotFound) throw new InvalidOperationException($"Object with ID {objectId} not found"); return []; } var expectedScheme = Cache.GetSchemeIdByClrType(typeof(TProps)) ?? (await SchemeSyncProvider.GetSchemeByTypeAsync())?.Id; // Asked one by one from the object up and only until the first refusal, as before: an ancestor above it is // never asked (the single check throws for an object with no permission row). A path is a few levels. var kept = new List(); foreach (var row in chain) { if (expectedScheme.HasValue && row.IdScheme != expectedScheme.Value) { if (Configuration.ThrowOnSchemeMismatch) throw new Exceptions.RedbSchemeMismatchException(row.Id, typeof(TProps), expectedScheme.Value, row.IdScheme); break; } if (Configuration.DefaultCheckPermissionsOnLoad && !await PermissionProvider.CanUserSelectObject(row.Id, reader.Id, cancellationToken)) break; kept.Add(row); } if (kept.Count == chain.Count && chain[^1].IdParent is { } dangling && chain[^1].Depth < MaxAncestorDepth && Configuration.ThrowOnObjectNotFound) throw new InvalidOperationException($"Object with ID {dangling} not found"); if (expectedScheme.HasValue) EnsureClrTypeRegistered(expectedScheme.Value); var loaded = await LoadNodesAsync(kept.Select(r => r.Id).ToList(), reader, 1, cancellationToken); var path = new List>(); foreach (var row in kept) { if (!loaded.TryGetValue(row.Id, out var obj)) break; path.Insert(0, ConvertToTreeObject(AsTyped(obj))); } for (int i = 0; i < path.Count - 1; i++) { path[i + 1].Parent = path[i]; } return path; } protected virtual async Task>> GetDescendantsWithUserAsync( long parentId, int maxDepth = 50, long? userId = null, bool checkPermissions = false, CancellationToken cancellationToken = default) where TProps : class, new() { // In walk order: a child, everything below it, then the next child. return await LoadTypedSubtreeAsync(parentId, maxDepth, userId, checkPermissions, cancellationToken); } protected virtual async Task MoveObjectWithUserAsync(long objectId, long? newParentId, long userId, bool checkPermissions = true, CancellationToken cancellationToken = default) { if (checkPermissions) { // Use direct ID-based permission check (no need to load full object with Props) var canEdit = await PermissionProvider.CanUserEditObject(objectId, userId); if (!canEdit) throw new UnauthorizedAccessException($"User {userId} does not have permission to edit object {objectId}"); } if (newParentId.HasValue) { var parentExists = await Context.ExecuteScalarAsync(Sql.Tree_ObjectExists(), new object[] { newParentId.Value }, cancellationToken); if (!parentExists.HasValue) throw new ArgumentException($"Parent object {newParentId} does not exist"); await ValidateNoCyclicReference(objectId, newParentId.Value); } var rowsAffected = await Context.ExecuteAsync( Sql.Tree_UpdateParent(), new object[] { newParentId.HasValue ? (object)newParentId.Value : DBNull.Value, DateTimeOffset.UtcNow, userId, objectId }, cancellationToken); if (rowsAffected == 0) throw new ArgumentException($"Object {objectId} not found"); // The move bypasses the save path: the database drops the object's hash (Tree_UpdateParent) and the cached copy // goes with it - under SkipHashValidationOnCacheCheck a load never asks the database and would keep answering // with the old parent until the entry expired. if (Configuration.EnablePropsCache && SchemeSyncProvider.PropsCache.Instance != null) SchemeSyncProvider.PropsCache.Remove(objectId); } protected virtual async Task CreateChildWithUserAsync( TreeRedbObject obj, long parentId, long? userId = null, bool checkPermissions = false, CancellationToken cancellationToken = default) where TProps : class, new() { if (obj.id == 0) { obj.id = await Context.NextObjectIdAsync(); AssignedIdRollback.ResetOnRollback(Context, new IRedbObject[] { obj }); } obj.parent_id = parentId == 0 ? null : parentId; var effectiveUser = SecurityContext.GetEffectiveUser(); return await ObjectStorage.SaveAsync(obj, effectiveUser); } protected virtual async Task DeleteSubtreeWithUserAsync(long parentId, IRedbUser user, CancellationToken cancellationToken = default) { var checkPermissions = Configuration.DefaultCheckPermissionsOnDelete; if (checkPermissions) { var canDelete = await PermissionProvider.CanUserDeleteObject(parentId, user.Id); if (!canDelete) throw new UnauthorizedAccessException($"User {user.Id} does not have permission to delete subtree of object {parentId}"); } // Every descendant of any scheme, down to the same 100 levels the walk one parent at a time went to. var objectIds = (await SelectSubtreeAsync(parentId, null, 100, cancellationToken)).Select(r => r.Id).ToList(); objectIds.Add(parentId); // One transaction for both statements. They used to run in sequence, and a failure in the // second (a live FK reference pointing into the subtree) left the first committed: the // objects survived with their values already gone (DataLoss p.2). // The count is the objects of the subtree this call deleted. It used to be the size of the subtree collected // above, so an object another session deleted in between was counted too. var ids = objectIds.ToArray(); // The same contract as DeleteAsync: one DeletingAsync before the delete (an interceptor that throws stops it), // one DeletedAsync after it when something was deleted, both with the whole collected subtree. var interceptors = _saveInterceptors.Snapshot(); if (interceptors.Count > 0) { var deleting = new Interception.RedbDeletingContext { ObjectIds = objectIds, KnownObjects = [], EffectiveUser = user }; foreach (var interceptor in interceptors) await interceptor.DeletingAsync(deleting, cancellationToken); } var deleted = 0; await Context.ExecuteAtomicAsync(async () => { await Context.ExecuteAsync(Sql.Tree_DeleteValuesByObjectIds(), new object[] { ids }, cancellationToken); var countSql = Sql.ObjectStorage_CountObjectsByIds(); if (countSql != null) deleted = checked((int)await Context.ExecuteScalarAsync(countSql, new object[] { ids }, cancellationToken)); var affected = await Context.ExecuteAsync(Sql.Tree_DeleteObjectsByIds(), new object[] { ids }, cancellationToken); if (countSql == null) deleted = affected; }, cancellationToken); // Every object of the subtree leaves the Props cache, as DeleteAsync removes the objects it deletes. if (SchemeSyncProvider.PropsCache.Instance != null) foreach (var id in ids) SchemeSyncProvider.PropsCache.Remove(id); if (interceptors.Count > 0 && deleted > 0) { var deletedContext = new Interception.RedbDeletedContext { ObjectIds = objectIds, KnownObjects = [], EffectiveUser = user, DeletedCount = deleted, }; foreach (var interceptor in interceptors) await interceptor.DeletedAsync(deletedContext, CancellationToken.None); // the rows are gone } return deleted; } // ============================================================ // === POLYMORPHIC IMPLEMENTATION === // ============================================================ protected virtual async Task LoadDynamicObjectAsync(long objectId, IRedbUser? user = null, CancellationToken cancellationToken = default) { if (Configuration.DefaultCheckPermissionsOnLoad && user != null) { var canRead = await PermissionProvider.CanUserSelectObject(objectId, user.Id); if (!canRead) throw new UnauthorizedAccessException($"User {user.Id} does not have permission to read object {objectId}"); } var result = await Context.QueryFirstOrDefaultAsync(Sql.Tree_SelectSchemeAndJson(), new object[] { objectId }, cancellationToken); if (result == null || string.IsNullOrEmpty(result.JsonData)) throw new InvalidOperationException($"Object with ID {objectId} not found"); var propsType = Cache.GetClrType(result.SchemeId) ?? typeof(object); return Serializer.DeserializeDynamic(result.JsonData, propsType); } protected virtual async Task LoadPolymorphicTreeWithUserAsync( long rootId, int maxDepth = 10, long? userId = null, bool checkPermissions = false, CancellationToken cancellationToken = default) { var user = userId.HasValue ? await GetUserByIdAsync(userId.Value) : null; var baseObject = await LoadDynamicObjectAsync(rootId, user); var treeObject = ConvertToPolymorphicTreeObjectWithProps(baseObject); // The nodes come in walk order, a parent before its children. var byId = new Dictionary { [rootId] = treeObject }; foreach (var node in await LoadPolymorphicSubtreeAsync(rootId, maxDepth, userId, checkPermissions, cancellationToken)) { var parent = byId[node.ParentId!.Value]; node.Parent = parent; parent.Children.Add(node); byId[node.Id] = node; } return treeObject; } protected virtual async Task> GetPolymorphicChildrenWithUserAsync( long parentId, long? userId = null, bool checkPermissions = false, CancellationToken cancellationToken = default) { var results = await Context.QueryAsync(Sql.Tree_SelectPolymorphicChildren(), new object[] { parentId }, cancellationToken); var children = new List(); foreach (var result in results) { if (string.IsNullOrEmpty(result.JsonData)) continue; try { if (checkPermissions && userId.HasValue) { var canSelect = await PermissionProvider.CanUserSelectObject(result.ObjectId, userId.Value); if (!canSelect) continue; } var propsType = Cache.GetClrType(result.SchemeId) ?? typeof(object); var typedObject = Serializer.DeserializeDynamic(result.JsonData, propsType); var treeObj = ConvertToPolymorphicTreeObjectWithProps(typedObject); children.Add(treeObj); } catch { throw; } } return children; } protected virtual async Task> GetPolymorphicPathToRootWithUserAsync( long objectId, long? userId = null, bool checkPermissions = false, CancellationToken cancellationToken = default) { // One statement for the chain, one batch for the objects. The path ends where the load of an ancestor one by // one used to stop, at one the user may not see; a missing ancestor is an error, as it was. var chain = await SelectAncestorsAsync(objectId, cancellationToken); if (chain.Count == 0) throw new InvalidOperationException($"Object with ID {objectId} not found"); if (chain[^1].IdParent is { } dangling && chain[^1].Depth < MaxAncestorDepth) throw new InvalidOperationException($"Object with ID {dangling} not found"); var user = userId.HasValue ? await GetUserByIdAsync(userId.Value) : null; var check = userId.HasValue && (checkPermissions || Configuration.DefaultCheckPermissionsOnLoad); // Asked one by one from the object up and only until the first refusal, as before (see the typed path). var kept = new List(); foreach (var row in chain) { if (check && !await PermissionProvider.CanUserSelectObject(row.Id, userId!.Value, cancellationToken)) break; kept.Add(row); } var loaded = await LoadNodesAsync(kept.Select(r => r.Id).ToList(), user ?? SecurityContext.GetEffectiveUser(), Configuration.DefaultLoadDepth, cancellationToken); var path = new List(); foreach (var row in kept) { if (!loaded.TryGetValue(row.Id, out var obj)) break; path.Insert(0, ConvertToPolymorphicTreeObjectWithProps(obj)); } for (int i = 0; i < path.Count - 1; i++) { path[i + 1].Parent = path[i]; } return path; } protected virtual async Task> GetPolymorphicDescendantsWithUserAsync( long parentId, int maxDepth = 50, long? userId = null, bool checkPermissions = false, CancellationToken cancellationToken = default) { // In walk order: a child, everything below it, then the next child. return await LoadPolymorphicSubtreeAsync(parentId, maxDepth, userId, checkPermissions, cancellationToken); } // ============================================================ // === PRIVATE HELPER METHODS === // ============================================================ // ============================================================ // === WALKS IN ONE STATEMENT === // A subtree or a chain of ancestors used to be read one parent at a time, a query or two per node (11 thousand // nodes: 27-44 s). It is now one statement for the shape (Tree_SelectSubtreeRows, Tree_SelectAncestorRows), one // permission batch when permissions are checked, and one batch load of the objects. // ============================================================ /// A row of or . protected sealed class TreeWalkRow { public long Id { get; set; } public long? IdParent { get; set; } public long IdScheme { get; set; } public int Depth { get; set; } } /// How far up a chain of ancestors is read: well past any real tree, short of a runaway cycle. internal const int MaxAncestorDepth = 10_000; /// /// The descendants of an object down to , children of a parent in their order. A node /// met twice means a cycle in _id_parent: an error, where the walk one parent at a time went round it to the depth. /// private async Task> SelectSubtreeAsync(long rootId, long? schemeId, int maxDepth, CancellationToken cancellationToken) { if (maxDepth <= 0) return []; var rows = await Context.QueryAsync(Sql.Tree_SelectSubtreeRows(), new object[] { rootId, (object?)schemeId ?? DBNull.Value, maxDepth }, cancellationToken); var seen = new HashSet { rootId }; foreach (var row in rows) if (!seen.Add(row.Id)) throw new InvalidOperationException( $"Cyclic reference in the tree under object {rootId}: object {row.Id} is reached twice. " + "Fix _id_parent of the objects on the cycle."); return rows; } /// /// An object (depth 0) and its ancestors, nearest first. An object met twice means a cycle in _id_parent: an error, /// where the walk up used to stop at it silently. /// private async Task> SelectAncestorsAsync(long objectId, CancellationToken cancellationToken) { var rows = await Context.QueryAsync(Sql.Tree_SelectAncestorRows(), new object[] { objectId, MaxAncestorDepth }, cancellationToken); var seen = new HashSet(); foreach (var row in rows) if (!seen.Add(row.Id)) throw new InvalidOperationException( $"Cyclic reference in the tree: object {row.Id} is its own ancestor (path from object {objectId}). " + "Fix _id_parent of the objects on the cycle."); if (rows.Count > 0 && rows[^1].Depth >= MaxAncestorDepth && rows[^1].IdParent.HasValue) throw new InvalidOperationException( $"The chain of ancestors of object {objectId} is longer than {MaxAncestorDepth} levels."); return rows; } /// /// The rows reachable from the root through rows that pass , in walk order: a child, /// everything below it, then the next child. A row that does not pass is left out with its whole subtree, as the /// walk one parent at a time never descended into it. /// private static List Reachable(long rootId, List rows, Func keep) { var children = rows.ToLookup(r => r.IdParent!.Value); var result = new List(rows.Count); var stack = new Stack>(); stack.Push(children[rootId].GetEnumerator()); while (stack.Count > 0) { var siblings = stack.Peek(); if (!siblings.MoveNext()) { stack.Pop(); continue; } if (!keep(siblings.Current)) continue; result.Add(siblings.Current); stack.Push(children[siblings.Current.Id].GetEnumerator()); } return result; } /// /// The rows of the subtree the user may read, asked level by level: one permission batch per level, for the rows /// under a parent already kept that pass . A row under a refused one is never asked, as /// the walk one parent at a time never asked it (the single check throws for an object with no permission row). /// private async Task> SelectReadableAsync( long rootId, List rows, long userId, Func eligible, CancellationToken cancellationToken) { var children = rows.ToLookup(r => r.IdParent!.Value); var readable = new HashSet(); var parents = new List { rootId }; while (parents.Count > 0) { var level = parents.SelectMany(p => children[p]).Where(eligible).ToList(); if (level.Count == 0) break; var allowed = await PermissionProvider.GetSelectableObjectIdsAsync(level.Select(r => r.Id).ToList(), userId, cancellationToken); parents = level.Where(r => allowed.Contains(r.Id)).Select(r => r.Id).ToList(); readable.UnionWith(parents); } return readable; } /// One batch load of objects (polymorphic: each in the type of its scheme), by id. private async Task> LoadNodesAsync(List ids, IRedbUser user, int depth, CancellationToken cancellationToken) { if (ids.Count == 0) return new Dictionary(); var loaded = await ObjectStorage.LoadAsync(ids, user, depth, cancellationToken); return loaded.ToDictionary(o => o.Id); } /// /// Binds the scheme to in the type registry when nothing is bound to it yet: the /// batch load picks the type of an object by its scheme, and the walk one parent at a time read the children of /// this scheme as directly. /// private void EnsureClrTypeRegistered(long schemeId) where TProps : class, new() { if (Cache.GetClrType(schemeId) == null) Cache.RegisterClrType(typeof(TProps).FullName ?? typeof(TProps).Name, schemeId, typeof(TProps)); } private static RedbObject AsTyped(IRedbObject obj) where TProps : class, new() => obj as RedbObject ?? throw new InvalidOperationException( $"Object {obj.Id} of scheme {obj.SchemeId} loads as {obj.GetType().Name}, not as RedbObject<{typeof(TProps).Name}>: " + "another type is bound to that scheme."); /// /// The descendants of of the scheme of , in walk order, each /// with its parent_id: what the walk one parent at a time returned (GetChildrenWithUserAsync per node), with the /// same reader for the permission check (the effective user, as CanUserSelectObject of an object asks). /// private async Task>> LoadTypedSubtreeAsync( long rootId, int maxDepth, long? userId, bool checkPermissions, CancellationToken cancellationToken) where TProps : class, new() { var scheme = await SchemeSyncProvider.GetSchemeByTypeAsync(); if (scheme == null) throw new InvalidOperationException($"Scheme for type {typeof(TProps).Name} not found. Use SyncSchemeAsync<{typeof(TProps).Name}>() to create scheme."); var rows = await SelectSubtreeAsync(rootId, scheme.Id, maxDepth, cancellationToken); if (rows.Count == 0) return []; var reader = SecurityContext.GetEffectiveUser(); var readable = checkPermissions && userId.HasValue ? await SelectReadableAsync(rootId, rows, reader.Id, _ => true, cancellationToken) : null; var kept = Reachable(rootId, rows, r => readable == null || readable.Contains(r.Id)); EnsureClrTypeRegistered(scheme.Id); var loaded = await LoadNodesAsync(kept.Select(r => r.Id).ToList(), reader, Configuration.DefaultLoadDepth, cancellationToken); // An object gone between the walk and the load is left out with its subtree. return Reachable(rootId, kept, r => loaded.ContainsKey(r.Id)) .Select(r => ConvertToTreeObject(AsTyped(loaded[r.Id]))) .ToList(); } /// /// The descendants of of every scheme, in walk order: what the walk one parent at a time /// returned (GetPolymorphicChildrenWithUserAsync per node). An object whose scheme has no CLR type is left out with /// its subtree, as there. /// private async Task> LoadPolymorphicSubtreeAsync( long rootId, int maxDepth, long? userId, bool checkPermissions, CancellationToken cancellationToken) { var rows = await SelectSubtreeAsync(rootId, null, maxDepth, cancellationToken); if (rows.Count == 0) return []; bool Typed(TreeWalkRow r) => Cache.GetClrType(r.IdScheme) != null; var readable = checkPermissions && userId.HasValue ? await SelectReadableAsync(rootId, rows, userId.Value, Typed, cancellationToken) : null; var kept = Reachable(rootId, rows, r => Typed(r) && (readable == null || readable.Contains(r.Id))); var user = userId.HasValue ? await GetUserByIdAsync(userId.Value) : null; var loaded = await LoadNodesAsync(kept.Select(r => r.Id).ToList(), user ?? SecurityContext.GetEffectiveUser(), Configuration.DefaultLoadDepth, cancellationToken); return Reachable(rootId, kept, r => loaded.ContainsKey(r.Id)) .Select(r => ConvertToPolymorphicTreeObjectWithProps(loaded[r.Id])) .ToList(); } private async Task ValidateNoCyclicReference(long objectId, long newParentId, CancellationToken cancellationToken = default) { // The new parent and its ancestors, one statement. Read row by row, in the order the walk up used to read them. var rows = await Context.QueryAsync( Sql.Tree_SelectAncestorRows(), new object[] { newParentId, MaxAncestorDepth }, cancellationToken); var visited = new HashSet(); foreach (var row in rows) { if (row.Id == objectId) throw new InvalidOperationException($"Cannot move object {objectId}: this would create a cyclic reference"); if (!visited.Add(row.Id)) throw new InvalidOperationException("Cyclic reference detected in existing data structure"); } } private Task GetUserByIdAsync(long userId) { return Task.FromResult(new DummyUser { Id = userId }); } // ============================================================ // === CONVERSION HELPERS === // ============================================================ protected TreeRedbObject ConvertToTreeObject(RedbObject source) where TProps : class, new() { return new TreeRedbObject { id = source.id, parent_id = source.parent_id, scheme_id = source.scheme_id, owner_id = source.owner_id, who_change_id = source.who_change_id, date_create = source.date_create, date_modify = source.date_modify, date_begin = source.date_begin, date_complete = source.date_complete, key = source.key, value_long = source.value_long, value_string = source.value_string, value_guid = source.value_guid, value_bool = source.value_bool, value_double = source.value_double, value_numeric = source.value_numeric, value_datetime = source.value_datetime, value_bytes = source.value_bytes, value_unique = source.value_unique, name = source.name, note = source.note, hash = source.hash, Props = source.Props }; } protected ITreeRedbObject ConvertToPolymorphicTreeObjectWithProps(IRedbObject source) { var redbObj = source as RedbObject; if (redbObj == null) throw new InvalidOperationException($"Object must be of type RedbObject, got: {source.GetType()}"); return new TreeRedbObjectDynamic(source) { id = redbObj.id, parent_id = redbObj.parent_id, scheme_id = redbObj.scheme_id, owner_id = redbObj.owner_id, who_change_id = redbObj.who_change_id, date_create = redbObj.date_create, date_modify = redbObj.date_modify, date_begin = redbObj.date_begin, date_complete = redbObj.date_complete, key = redbObj.key, value_long = redbObj.value_long, value_string = redbObj.value_string, value_guid = redbObj.value_guid, value_bool = redbObj.value_bool, value_double = redbObj.value_double, value_numeric = redbObj.value_numeric, value_datetime = redbObj.value_datetime, value_bytes = redbObj.value_bytes, value_unique = redbObj.value_unique, name = redbObj.name, note = redbObj.note, hash = redbObj.hash }; } // ============================================================ // === HELPER CLASSES === // ============================================================ private class DummyUser : IRedbUser { public long Id { get; set; } public string Login { get; set; } = string.Empty; public string Name { get; set; } = string.Empty; public string Password { get; set; } = string.Empty; public bool Enabled { get; set; } = true; public DateTimeOffset DateRegister { get; set; } = DateTimeOffset.UtcNow; public DateTimeOffset? DateDismiss { get; set; } public string? Phone { get; set; } public string? Email { get; set; } public long? Key { get; set; } public long? CodeInt { get; set; } public string? CodeString { get; set; } public Guid? CodeGuid { get; set; } public string? Note { get; set; } public Guid? Hash { get; set; } } protected class TreeRedbObjectDynamic : TreeRedbObject, ITreeRedbObject { public IRedbObject SourceObject { get; } public TreeRedbObjectDynamic(IRedbObject source) { SourceObject = source; } } } /// /// DTO for scheme + JSON query result. /// public class SchemeWithJson { public long SchemeId { get; set; } public string? JsonData { get; set; } } /// /// DTO for child object query result. /// public class ChildObjectInfo { public long ObjectId { get; set; } public long SchemeId { get; set; } public string? JsonData { get; set; } } Path: redb/redb.Core/Providers/Base/UserProviderBase.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/UserProviderBase.cs ---- using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using redb.Core.Data; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using redb.Core.Models.Users; using redb.Core.Query; using redb.Core.Security; using Microsoft.Extensions.Logging; namespace redb.Core.Providers.Base; /// /// Base implementation of user provider with common business logic. /// Database-specific providers inherit from this class and provide ISqlDialect and IPasswordHasher. /// public abstract class UserProviderBase : IUserProvider { protected readonly IRedbContext Context; protected readonly IRedbSecurityContext SecurityContext; protected readonly ISqlDialect Sql; protected readonly IPasswordHasher PasswordHasher; protected readonly ILogger? Logger; protected UserProviderBase( IRedbContext context, IRedbSecurityContext securityContext, ISqlDialect sql, IPasswordHasher passwordHasher, ILogger? logger = null) { Context = context ?? throw new ArgumentNullException(nameof(context)); SecurityContext = securityContext ?? throw new ArgumentNullException(nameof(securityContext)); Sql = sql ?? throw new ArgumentNullException(nameof(sql)); PasswordHasher = passwordHasher ?? throw new ArgumentNullException(nameof(passwordHasher)); Logger = logger; } // ============================================================ // === CRUD OPERATIONS === // ============================================================ /// public virtual async Task CreateUserAsync(CreateUserRequest request, IRedbUser? currentUser = null, CancellationToken cancellationToken = default) { ValidateCreateRequest(request); if (!await IsLoginAvailableAsync(request.Login)) throw new InvalidOperationException($"Login '{request.Login}' is already taken"); var hashedPassword = PasswordHasher.HashPassword(request.Password); var newUserId = await Context.NextObjectIdAsync(); var newUser = new RedbUser { Id = newUserId, Login = request.Login, Password = hashedPassword, Name = request.Name, Email = request.Email, Phone = request.Phone, Enabled = request.Enabled, DateRegister = request.DateRegister ?? DateTimeOffset.UtcNow, DateDismiss = null, Key = request.Key, CodeInt = request.CodeInt, CodeString = request.CodeString, CodeGuid = request.CodeGuid, Note = request.Note, Hash = Guid.NewGuid() }; await Context.ExecuteAsync(Sql.Users_Insert(), new object[] { newUser.Id, newUser.Login, newUser.Password, newUser.Name, (object?)newUser.Phone ?? DBNull.Value, (object?)newUser.Email ?? DBNull.Value, newUser.Enabled, newUser.DateRegister, (object?)newUser.DateDismiss ?? DBNull.Value, (object?)newUser.Key ?? DBNull.Value, (object?)newUser.CodeInt ?? DBNull.Value, (object?)newUser.CodeString ?? DBNull.Value, (object?)newUser.CodeGuid ?? DBNull.Value, (object?)newUser.Note ?? DBNull.Value, newUser.Hash }, cancellationToken); // Assign roles if (request.RoleNames?.Length > 0) { await AssignRolesByNamesAsync(newUser.Id, request.RoleNames); } else if (request.Roles?.Length > 0) { await AssignRolesByObjectsAsync(newUser.Id, request.Roles); } await OnUserCreatedAsync(newUser, currentUser); return newUser; } /// public virtual async Task UpdateUserAsync(IRedbUser user, UpdateUserRequest request, IRedbUser? currentUser = null, CancellationToken cancellationToken = default) { if (user.Id == 0 || user.Id == -1) throw new InvalidOperationException($"System user with ID {user.Id} cannot be modified"); var dbUser = await Context.QueryFirstOrDefaultAsync(Sql.Users_SelectById(), new object[] { user.Id }, cancellationToken); if (dbUser == null) throw new ArgumentException($"User with ID {user.Id} not found"); var dataChanged = false; if (request.Login != null) { var exists = await Context.ExecuteScalarAsync(Sql.Users_ExistsByLoginExcluding(), new object[] { request.Login, user.Id }, cancellationToken); if (exists.HasValue) throw new InvalidOperationException($"User with login '{request.Login}' already exists"); dbUser.Login = request.Login; dataChanged = true; } if (request.Name != null) { dbUser.Name = request.Name; dataChanged = true; } if (request.Phone != null) { dbUser.Phone = request.Phone; dataChanged = true; } if (request.Email != null) { dbUser.Email = request.Email; dataChanged = true; } if (request.Enabled.HasValue) { dbUser.Enabled = request.Enabled.Value; dataChanged = true; } if (request.DateDismiss.HasValue) { dbUser.DateDismiss = request.DateDismiss.Value; dataChanged = true; } if (request.Key.HasValue) { dbUser.Key = request.Key.Value; dataChanged = true; } if (request.CodeInt.HasValue) { dbUser.CodeInt = request.CodeInt.Value; dataChanged = true; } if (request.CodeString != null) { dbUser.CodeString = string.IsNullOrEmpty(request.CodeString) ? null : request.CodeString; dataChanged = true; } if (request.CodeGuid.HasValue) { dbUser.CodeGuid = request.CodeGuid.Value; dataChanged = true; } if (request.Note != null) { dbUser.Note = string.IsNullOrEmpty(request.Note) ? null : request.Note; dataChanged = true; } // Update roles if (request.RoleNames != null) { await Context.ExecuteAsync(Sql.UsersRoles_DeleteByUser(), new object[] { user.Id }, cancellationToken); await AssignRolesByNamesAsync(user.Id, request.RoleNames); dataChanged = true; } else if (request.Roles != null) { await Context.ExecuteAsync(Sql.UsersRoles_DeleteByUser(), new object[] { user.Id }, cancellationToken); await AssignRolesByObjectsAsync(user.Id, request.Roles); dataChanged = true; } if (dataChanged) { dbUser.Hash = Guid.NewGuid(); await Context.ExecuteAsync(Sql.Users_Update(), new object[] { dbUser.Login, dbUser.Name, (object?)dbUser.Phone ?? DBNull.Value, (object?)dbUser.Email ?? DBNull.Value, dbUser.Enabled, (object?)dbUser.DateDismiss ?? DBNull.Value, (object?)dbUser.Key ?? DBNull.Value, (object?)dbUser.CodeInt ?? DBNull.Value, (object?)dbUser.CodeString ?? DBNull.Value, (object?)dbUser.CodeGuid ?? DBNull.Value, (object?)dbUser.Note ?? DBNull.Value, dbUser.Hash, dbUser.Id }, cancellationToken); } await OnUserUpdatedAsync(dbUser, currentUser); return dbUser; } /// public virtual async Task DeleteUserAsync(IRedbUser user, IRedbUser? currentUser = null, CancellationToken cancellationToken = default) { if (user.Id == 0 || user.Id == 1 || user.Id == -1) throw new InvalidOperationException($"System user with ID {user.Id} cannot be deleted"); var dbUser = await Context.QueryFirstOrDefaultAsync(Sql.Users_SelectById(), new object[] { user.Id }, cancellationToken); if (dbUser == null) return false; if (!dbUser.Enabled && dbUser.DateDismiss != null) return true; // Already soft-deleted // Delete associations await Context.ExecuteAsync(Sql.UsersRoles_DeleteByUser(), new object[] { user.Id }, cancellationToken); await Context.ExecuteAsync(Sql.Permissions_DeleteByUser(), new object[] { user.Id }, cancellationToken); // Soft delete — login STAYS as-is (immutable per protect_system_users trigger). // Name is suffixed for tombstoning visibility. Soft-deleted rows are filtered out // of normal queries by the _enabled=false predicate; their login slot remains // occupied so re-registration with the same login is blocked until an explicit // hard DELETE removes the row. var timestamp = DateTimeOffset.UtcNow.ToString("yyyyMMddHHmmssfff"); var newName = $"{dbUser.Name}_DEL_{timestamp}"; var result = await Context.ExecuteAsync(Sql.Users_SoftDelete(), new object[] { newName, false, DateTimeOffset.UtcNow, user.Id }, cancellationToken); if (result > 0) await OnUserDeletedAsync(user, currentUser); return result > 0; } // ============================================================ // === SEARCH AND RETRIEVAL === // ============================================================ /// public virtual async Task GetUserByIdAsync(long userId, CancellationToken cancellationToken = default) { return await Context.QueryFirstOrDefaultAsync(Sql.Users_SelectById(), new object[] { userId }, cancellationToken); } /// public virtual async Task> GetUsersByIdsAsync(IEnumerable userIds, CancellationToken cancellationToken = default) { var ids = userIds.ToArray(); if (ids.Length == 0) return new List(); var users = await Context.QueryAsync(Sql.Users_SelectByIds(), new object[] { (object)ids }, cancellationToken); return users.Cast().ToList(); } /// public virtual async Task GetUserByLoginAsync(string login, CancellationToken cancellationToken = default) { return await Context.QueryFirstOrDefaultAsync(Sql.Users_SelectByLogin(), new object[] { login }, cancellationToken); } /// public virtual async Task GetUserByEmailAsync(string email, CancellationToken cancellationToken = default) { if (string.IsNullOrWhiteSpace(email)) return null; return await Context.QueryFirstOrDefaultAsync(Sql.Users_SelectByEmail(), new object[] { email }, cancellationToken); } /// public virtual async Task LoadUserAsync(string login, CancellationToken cancellationToken = default) { var user = await GetUserByLoginAsync(login); if (user == null) throw new ArgumentException($"User with login '{login}' not found"); return user; } /// public virtual async Task LoadUserAsync(long userId, CancellationToken cancellationToken = default) { var user = await GetUserByIdAsync(userId); if (user == null) throw new ArgumentException($"User with ID {userId} not found"); return user; } /// public virtual async Task> GetUsersAsync(UserSearchCriteria? criteria = null, CancellationToken cancellationToken = default) { // Build dynamic SQL - this is DB-specific, override in derived class if needed var sql = BuildUserSearchSql(criteria, out var parameters); var users = await Context.QueryAsync(sql, parameters, cancellationToken); return users.Cast().ToList(); } /// public virtual async Task CountUsersAsync(UserSearchCriteria? criteria = null, CancellationToken cancellationToken = default) { var sql = BuildUserCountSql(criteria, out var parameters); return await Context.ExecuteScalarAsync(sql, parameters, cancellationToken); } /// /// Build SQL for user search. Override in derived class for DB-specific syntax. /// protected virtual string BuildUserSearchSql(UserSearchCriteria? criteria, out object[] parameters) { var whereClause = BuildUserWhereClause(criteria, out parameters); var sql = Sql.Users_SelectAllColumns() + whereClause; if (criteria != null) { var sortColumn = criteria.SortBy switch { UserSortField.Id => "_id", UserSortField.Login => "_login", UserSortField.Name => "_name", UserSortField.Email => "_email", UserSortField.DateRegister => "_date_register", UserSortField.DateDismiss => "_date_dismiss", UserSortField.Enabled => "_enabled", UserSortField.Key => "_key", UserSortField.CodeInt => "_code_int", UserSortField.CodeString => "_code_string", UserSortField.Note => "_note", _ => "_name" }; var sortDir = criteria.SortDirection == UserSortDirection.Ascending ? "ASC" : "DESC"; sql += $" ORDER BY {Sql.QuoteIdentifier(sortColumn)} {sortDir}"; sql += " " + Sql.FormatPagination(criteria.Limit > 0 ? criteria.Limit : null, criteria.Offset > 0 ? criteria.Offset : null); } else { sql += $" ORDER BY {Sql.QuoteIdentifier("_name")}"; } return sql; } /// /// Build SQL for counting users matching criteria. /// protected virtual string BuildUserCountSql(UserSearchCriteria? criteria, out object[] parameters) { var whereClause = BuildUserWhereClause(criteria, out parameters); return Sql.Users_CountFrom() + whereClause; } /// /// Build WHERE clause for user queries. Shared by search and count. /// protected virtual string BuildUserWhereClause(UserSearchCriteria? criteria, out object[] parameters) { var conditions = new List(); var paramList = new List(); int paramIndex = 1; if (criteria != null) { if (criteria.ExcludeSystemUsers) conditions.Add("_id > 0"); if (!string.IsNullOrEmpty(criteria.LoginPattern)) { conditions.Add(Sql.FormatCaseInsensitiveLike("_login", Sql.FormatParameter(paramIndex++))); paramList.Add($"%{EscapeLikeWildcards(criteria.LoginPattern)}%"); } if (!string.IsNullOrEmpty(criteria.LoginExact)) { conditions.Add(Sql.FormatCaseInsensitiveLike("_login", Sql.FormatParameter(paramIndex++))); paramList.Add(EscapeLikeWildcards(criteria.LoginExact)); } if (!string.IsNullOrEmpty(criteria.LoginStartsWith)) { conditions.Add(Sql.FormatCaseInsensitiveLike("_login", Sql.FormatParameter(paramIndex++))); paramList.Add($"{EscapeLikeWildcards(criteria.LoginStartsWith)}%"); } if (!string.IsNullOrEmpty(criteria.LoginNotEqual)) { conditions.Add($"NOT ({Sql.FormatCaseInsensitiveLike("_login", Sql.FormatParameter(paramIndex++))})"); paramList.Add(EscapeLikeWildcards(criteria.LoginNotEqual)); } if (!string.IsNullOrEmpty(criteria.NamePattern)) { conditions.Add(Sql.FormatCaseInsensitiveLike("_name", Sql.FormatParameter(paramIndex++))); paramList.Add($"%{EscapeLikeWildcards(criteria.NamePattern)}%"); } if (!string.IsNullOrEmpty(criteria.NameExact)) { conditions.Add(Sql.FormatCaseInsensitiveLike("_name", Sql.FormatParameter(paramIndex++))); paramList.Add(EscapeLikeWildcards(criteria.NameExact)); } if (!string.IsNullOrEmpty(criteria.NameStartsWith)) { conditions.Add(Sql.FormatCaseInsensitiveLike("_name", Sql.FormatParameter(paramIndex++))); paramList.Add($"{EscapeLikeWildcards(criteria.NameStartsWith)}%"); } if (!string.IsNullOrEmpty(criteria.NameNotEqual)) { conditions.Add($"NOT ({Sql.FormatCaseInsensitiveLike("_name", Sql.FormatParameter(paramIndex++))})"); paramList.Add(EscapeLikeWildcards(criteria.NameNotEqual)); } if (!string.IsNullOrEmpty(criteria.EmailPattern)) { conditions.Add(Sql.FormatCaseInsensitiveLike("_email", Sql.FormatParameter(paramIndex++))); paramList.Add($"%{EscapeLikeWildcards(criteria.EmailPattern)}%"); } if (!string.IsNullOrEmpty(criteria.EmailExact)) { conditions.Add(Sql.FormatCaseInsensitiveLike("_email", Sql.FormatParameter(paramIndex++))); paramList.Add(EscapeLikeWildcards(criteria.EmailExact)); } if (!string.IsNullOrEmpty(criteria.EmailStartsWith)) { conditions.Add(Sql.FormatCaseInsensitiveLike("_email", Sql.FormatParameter(paramIndex++))); paramList.Add($"{EscapeLikeWildcards(criteria.EmailStartsWith)}%"); } if (!string.IsNullOrEmpty(criteria.EmailNotEqual)) { conditions.Add($"NOT ({Sql.FormatCaseInsensitiveLike("_email", Sql.FormatParameter(paramIndex++))})"); paramList.Add(EscapeLikeWildcards(criteria.EmailNotEqual)); } if (criteria.Enabled.HasValue) { conditions.Add($"_enabled = {Sql.FormatParameter(paramIndex++)}"); paramList.Add(criteria.Enabled.Value); } if (criteria.RoleId.HasValue) { conditions.Add($"_id IN (SELECT _id_user FROM _users_roles WHERE _id_role = {Sql.FormatParameter(paramIndex++)})"); paramList.Add(criteria.RoleId.Value); } if (criteria.RegisteredFrom.HasValue) { conditions.Add($"_date_register >= {Sql.FormatParameter(paramIndex++)}"); paramList.Add(criteria.RegisteredFrom.Value); } if (criteria.RegisteredTo.HasValue) { conditions.Add($"_date_register <= {Sql.FormatParameter(paramIndex++)}"); paramList.Add(criteria.RegisteredTo.Value); } if (criteria.KeyValue.HasValue) { conditions.Add($"_key = {Sql.FormatParameter(paramIndex++)}"); paramList.Add(criteria.KeyValue.Value); } if (criteria.CodeIntValue.HasValue) { conditions.Add($"_code_int = {Sql.FormatParameter(paramIndex++)}"); paramList.Add(criteria.CodeIntValue.Value); } if (!string.IsNullOrEmpty(criteria.CodeStringPattern)) { conditions.Add(Sql.FormatCaseInsensitiveLike("_code_string", Sql.FormatParameter(paramIndex++))); paramList.Add($"%{EscapeLikeWildcards(criteria.CodeStringPattern)}%"); } if (!string.IsNullOrEmpty(criteria.NotePattern)) { conditions.Add(Sql.FormatCaseInsensitiveLike("_note", Sql.FormatParameter(paramIndex++))); paramList.Add($"%{EscapeLikeWildcards(criteria.NotePattern)}%"); } if (criteria.CodeGuidValue.HasValue) { conditions.Add($"_code_guid = {Sql.FormatParameter(paramIndex++)}"); paramList.Add(criteria.CodeGuidValue.Value); } } parameters = paramList.ToArray(); if (conditions.Count > 0) return " WHERE " + string.Join(" AND ", conditions); if (criteria == null) return " WHERE _id > 0"; return ""; } /// /// True when this dialect treats '[' as a LIKE character-class opener. SQL Server does, so /// MssqlUserProvider overrides this to also escape brackets; PostgreSQL and SQLite treat /// '[' as an ordinary character, where escaping it would change the search itself /// (SQLI-PoC: LIKE bracket). /// protected virtual bool LikeBracketIsWildcard => false; /// /// Escapes LIKE/ILIKE wildcard characters (%, _, \) in user input /// so they are treated as literal characters. Dialects whose LIKE also reads '[' as a /// character-class opener escape that too. /// protected string EscapeLikeWildcards(string value) { var escaped = value.Replace("\\", "\\\\").Replace("%", "\\%").Replace("_", "\\_"); return LikeBracketIsWildcard ? escaped.Replace("[", "[[]") : escaped; } // ============================================================ // === AUTHENTICATION === // ============================================================ /// public virtual async Task ValidateUserAsync(string login, string password, CancellationToken cancellationToken = default) { if (string.IsNullOrWhiteSpace(login) || string.IsNullOrWhiteSpace(password)) return null; try { var user = await Context.QueryFirstOrDefaultAsync(Sql.Users_SelectByLogin(), new object[] { login }, cancellationToken); if (user == null || !user.Enabled) return null; if (!PasswordHasher.VerifyPassword(password, user.Password)) return null; return user; } catch { return null; } } /// public virtual async Task ChangePasswordAsync(IRedbUser user, string currentPassword, string newPassword, IRedbUser? currentUser = null, CancellationToken cancellationToken = default) { if (user == null) throw new ArgumentNullException(nameof(user)); if (string.IsNullOrWhiteSpace(currentPassword)) throw new ArgumentException("Current password cannot be empty"); if (string.IsNullOrWhiteSpace(newPassword)) throw new ArgumentException("New password cannot be empty"); if (user.Id == 0) throw new InvalidOperationException("Cannot change password for system user (ID 0)"); var dbUser = await Context.QueryFirstOrDefaultAsync(Sql.Users_SelectById(), new object[] { user.Id }, cancellationToken); if (dbUser == null) throw new InvalidOperationException($"User with ID {user.Id} not found"); if (!dbUser.Enabled) throw new InvalidOperationException("Cannot change password for disabled user"); // Wrong current password is the most common user error on a "change password" form, and the // method is Task documented as "true if changed" — so it returns false here, it does not // throw. (Programmer/precondition errors above — null args, disabled/system user — still throw.) if (!PasswordHasher.VerifyPassword(currentPassword, dbUser.Password)) return false; if (PasswordHasher.VerifyPassword(newPassword, dbUser.Password)) throw new ArgumentException("New password must be different from current"); var hashedPassword = PasswordHasher.HashPassword(newPassword); await Context.ExecuteAsync(Sql.Users_UpdatePassword(), new object[] { hashedPassword, user.Id }, cancellationToken); return true; } /// public virtual async Task SetPasswordAsync(IRedbUser user, string newPassword, IRedbUser? currentUser = null, CancellationToken cancellationToken = default) { if (user.Id == 0) throw new InvalidOperationException("System user password (ID 0) cannot be changed"); if (currentUser != null && currentUser.Id != 1 && currentUser.Id != user.Id) throw new UnauthorizedAccessException("Only admin can set passwords for other users"); if (string.IsNullOrWhiteSpace(newPassword) || newPassword.Length < 4) throw new ArgumentException("Password must be at least 4 characters"); var exists = await Context.ExecuteScalarAsync(Sql.Users_ExistsById(), new object[] { user.Id }, cancellationToken); if (!exists.HasValue) throw new ArgumentException($"User with ID {user.Id} not found"); var hashedPassword = PasswordHasher.HashPassword(newPassword); var result = await Context.ExecuteAsync(Sql.Users_UpdatePassword(), new object[] { hashedPassword, user.Id }, cancellationToken); return result > 0; } /// public virtual async Task SetPasswordHashAsync(IRedbUser user, string passwordHash, IRedbUser? currentUser = null, CancellationToken cancellationToken = default) { if (user.Id == 0) throw new InvalidOperationException("System user password (ID 0) cannot be changed"); if (currentUser != null && currentUser.Id != 1 && currentUser.Id != user.Id) throw new UnauthorizedAccessException("Only admin can set passwords for other users"); if (string.IsNullOrWhiteSpace(passwordHash)) throw new ArgumentException("Password hash cannot be empty", nameof(passwordHash)); var exists = await Context.ExecuteScalarAsync(Sql.Users_ExistsById(), new object[] { user.Id }, cancellationToken); if (!exists.HasValue) throw new ArgumentException($"User with ID {user.Id} not found"); var result = await Context.ExecuteAsync(Sql.Users_UpdatePassword(), new object[] { passwordHash, user.Id }, cancellationToken); return result > 0; } // ============================================================ // === STATUS MANAGEMENT === // ============================================================ /// public virtual async Task EnableUserAsync(IRedbUser user, IRedbUser? currentUser = null, CancellationToken cancellationToken = default) { if (user.Id == 0 || user.Id == -1) return true; var result = await Context.ExecuteAsync(Sql.Users_UpdateStatus(), new object[] { true, DBNull.Value, user.Id }, cancellationToken); return result >= 0; } /// public virtual async Task DisableUserAsync(IRedbUser user, IRedbUser? currentUser = null, CancellationToken cancellationToken = default) { if (user.Id == 0 || user.Id == -1) throw new InvalidOperationException($"System user with ID {user.Id} cannot be disabled"); if (currentUser != null && currentUser.Id == user.Id) throw new InvalidOperationException("User cannot disable themselves"); var result = await Context.ExecuteAsync(Sql.Users_UpdateStatus(), new object[] { false, DateTimeOffset.UtcNow, user.Id }, cancellationToken); return result >= 0; } // ============================================================ // === VALIDATION === // ============================================================ /// public virtual async Task ValidateUserDataAsync(CreateUserRequest request, CancellationToken cancellationToken = default) { var result = new UserValidationResult(); if (string.IsNullOrWhiteSpace(request.Login)) result.AddError("Login", "Login is required"); else { if (request.Login.Length < 3) result.AddError("Login", "Login must be at least 3 characters"); if (!await IsLoginAvailableAsync(request.Login)) result.AddError("Login", $"Login '{request.Login}' is already taken"); if (request.Login.Contains(' ') || request.Login.Contains('@')) result.AddError("Login", "Login cannot contain spaces or @"); } if (string.IsNullOrWhiteSpace(request.Name)) result.AddError("Name", "Name is required"); if (string.IsNullOrWhiteSpace(request.Password)) result.AddError("Password", "Password is required"); else if (request.Password.Length < 4) result.AddError("Password", "Password must be at least 4 characters"); if (!string.IsNullOrWhiteSpace(request.Email)) { if (!request.Email.Contains('@') || !request.Email.Contains('.')) result.AddError("Email", "Invalid email format"); var emailExists = await Context.ExecuteScalarAsync(Sql.Users_ExistsByEmail(), new object[] { request.Email }, cancellationToken); if (emailExists.HasValue) result.AddError("Email", $"Email '{request.Email}' is already taken"); } if (!string.IsNullOrWhiteSpace(request.Phone) && request.Phone.Length < 7) result.AddError("Phone", "Phone number is too short"); if (request.CodeInt.HasValue) { if (request.CodeInt.Value < 0) result.AddError("CodeInt", "Code cannot be negative"); if (request.CodeInt.Value > 999999999) result.AddError("CodeInt", "Code is too large"); } if (!string.IsNullOrWhiteSpace(request.CodeString)) { if (request.CodeString.Length > 50) result.AddError("CodeString", "Code string is too long (max 50)"); if (request.CodeString.Contains(';') || request.CodeString.Contains('|')) result.AddError("CodeString", "Code string cannot contain ; or |"); } if (!string.IsNullOrWhiteSpace(request.Note) && request.Note.Length > 1000) result.AddError("Note", "Note is too long (max 1000)"); return result; } /// public virtual async Task IsLoginAvailableAsync(string login, long? excludeUserId = null, CancellationToken cancellationToken = default) { if (excludeUserId.HasValue) { var exists = await Context.ExecuteScalarAsync(Sql.Users_ExistsByLoginExcluding(), new object[] { login, excludeUserId.Value }, cancellationToken); return !exists.HasValue; } else { var exists = await Context.ExecuteScalarAsync(Sql.Users_ExistsByLogin(), new object[] { login }, cancellationToken); return !exists.HasValue; } } // ============================================================ // === STATISTICS === // ============================================================ /// public virtual async Task GetUserCountAsync(bool includeDisabled = false, CancellationToken cancellationToken = default) { return await Context.ExecuteScalarAsync(includeDisabled ? Sql.Users_Count() : Sql.Users_CountEnabled(), System.Array.Empty(), cancellationToken); } /// public virtual Task GetActiveUserCountAsync(DateTimeOffset fromDate, DateTimeOffset toDate, CancellationToken cancellationToken = default) { throw new NotImplementedException("GetActiveUserCountAsync requires activity logging"); } // ============================================================ // === CONFIGURATION MANAGEMENT === // ============================================================ /// public virtual async Task GetUserConfigurationIdAsync(long userId, CancellationToken cancellationToken = default) { return await Context.ExecuteScalarAsync(Sql.Users_SelectConfigurationId(), new object[] { userId }, cancellationToken); } /// public virtual async Task SetUserConfigurationAsync(long userId, long? configId, CancellationToken cancellationToken = default) { var result = await Context.ExecuteAsync(Sql.Users_UpdateConfiguration(), new object[] { (object?)configId ?? DBNull.Value, userId }, cancellationToken); if (result == 0) throw new ArgumentException($"User with ID {userId} not found"); } /// public virtual async Task> GetUserRolesAsync(long userId, CancellationToken cancellationToken = default) { var roles = await Context.QueryAsync(Sql.UsersRoles_SelectRolesByUser(), new object[] { userId }, cancellationToken); return roles.Cast().ToList(); } // ============================================================ // === PRIVATE HELPERS === // ============================================================ private void ValidateCreateRequest(CreateUserRequest request) { if (request == null) throw new ArgumentNullException(nameof(request)); if (string.IsNullOrWhiteSpace(request.Login)) throw new ArgumentException("Login cannot be empty"); if (string.IsNullOrWhiteSpace(request.Password)) throw new ArgumentException("Password cannot be empty"); if (string.IsNullOrWhiteSpace(request.Name)) throw new ArgumentException("Name cannot be empty"); } private async Task AssignRolesByNamesAsync(long userId, string[] roleNames, CancellationToken cancellationToken = default) { foreach (var roleName in roleNames) { var role = await Context.QueryFirstOrDefaultAsync(Sql.Roles_SelectIdByName(), new object[] { roleName }, cancellationToken); if (role == null) throw new ArgumentException($"Role '{roleName}' not found"); var userRoleId = await Context.NextObjectIdAsync(); await Context.ExecuteAsync(Sql.UsersRoles_Insert(), new object[] { userRoleId, userId, role.Id }, cancellationToken); } } private async Task AssignRolesByObjectsAsync(long userId, IRedbRole[] roles, CancellationToken cancellationToken = default) { foreach (var role in roles) { var exists = await Context.ExecuteScalarAsync(Sql.Roles_ExistsById(), new object[] { role.Id }, cancellationToken); if (!exists.HasValue) throw new ArgumentException($"Role with ID {role.Id} ('{role.Name}') not found"); var userRoleId = await Context.NextObjectIdAsync(); await Context.ExecuteAsync(Sql.UsersRoles_Insert(), new object[] { userRoleId, userId, role.Id }, cancellationToken); } } // ============================================================ // === LIFECYCLE HOOKS === // ============================================================ protected virtual Task OnUserCreatedAsync(IRedbUser user, IRedbUser? currentUser) => Task.CompletedTask; protected virtual Task OnUserUpdatedAsync(IRedbUser user, IRedbUser? currentUser) => Task.CompletedTask; protected virtual Task OnUserDeletedAsync(IRedbUser user, IRedbUser? currentUser) => Task.CompletedTask; } Path: redb/redb.Core/Providers/Base/ValidationProviderBase.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/ValidationProviderBase.cs ---- using redb.Core.Data; using redb.Core.Extensions; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using redb.Core.Query; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; namespace redb.Core.Providers.Base { /// /// Base class for validation provider. /// Contains common validation logic for schema and type checking. /// public abstract class ValidationProviderBase : IValidationProvider { protected readonly IRedbContext Context; protected readonly ISqlDialect Sql; protected readonly ILogger? Logger; private List? _supportedTypesCache; private Dictionary? _csharpToRedbTypeCache; protected ValidationProviderBase( IRedbContext context, ISqlDialect sql, ILogger? logger = null) { Context = context ?? throw new ArgumentNullException(nameof(context)); Sql = sql ?? throw new ArgumentNullException(nameof(sql)); Logger = logger; } public async Task> GetSupportedTypesAsync(CancellationToken cancellationToken = default) { if (_supportedTypesCache != null) return _supportedTypesCache; var dbTypes = await Context.QueryAsync(Sql.Validation_SelectAllTypes(), System.Array.Empty(), cancellationToken); _supportedTypesCache = dbTypes.Select(t => new SupportedType { Id = t.Id, Name = t.Name, DbType = t.DbType ?? "String", DotNetType = t.Type1 ?? "string", SupportsArrays = t.Name != "Object" && t.Name != "ListItem", SupportsNullability = t.Name != "Object", Description = GetTypeDescription(t.Name) }).ToList(); return _supportedTypesCache; } public async Task ValidateTypeAsync(Type csharpType, string propertyName, CancellationToken cancellationToken = default) { var supportedTypes = await GetSupportedTypesAsync(); var underlyingType = Nullable.GetUnderlyingType(csharpType) ?? csharpType; var mappedTypeName = await MapCSharpTypeToRedbTypeAsync(underlyingType); var supportedType = supportedTypes.FirstOrDefault(t => t.Name == mappedTypeName); if (supportedType == null) { return new ValidationIssue { Severity = ValidationSeverity.Error, PropertyName = propertyName, Message = $"Type '{csharpType.Name}' is not supported in REDB", SuggestedFix = $"Use one of supported types: {string.Join(", ", supportedTypes.Where(t => t.SupportsNullability).Select(t => t.DotNetType))}" }; } if (underlyingType == typeof(decimal)) { return new ValidationIssue { Severity = ValidationSeverity.Warning, PropertyName = propertyName, Message = "Type 'decimal' will be converted to 'double', possible precision loss", SuggestedFix = "Consider using 'double' directly or store as 'string' for precise calculations" }; } if (underlyingType == typeof(float)) { return new ValidationIssue { Severity = ValidationSeverity.Info, PropertyName = propertyName, Message = "Type 'float' will be converted to 'double'", SuggestedFix = "Consider using 'double' directly" }; } return null; } public async Task ValidateSchemaAsync(string schemeName, bool strictDeleteExtra = true, CancellationToken cancellationToken = default) where TProps : class { var result = new SchemaValidationResult { IsValid = true }; var properties = typeof(TProps).GetProperties(BindingFlags.Public | BindingFlags.Instance) .Where(p => !p.ShouldIgnoreForRedb()) .ToArray(); var nullabilityContext = new NullabilityInfoContext(); foreach (var property in properties) { var typeIssue = await ValidateTypeAsync(property.PropertyType, property.Name); if (typeIssue != null) { result.Issues.Add(typeIssue); if (typeIssue.Severity == ValidationSeverity.Error) result.IsValid = false; } var nullabilityInfo = nullabilityContext.Create(property); var isArray = IsArrayType(property.PropertyType); var baseType = isArray ? GetArrayElementType(property.PropertyType) : property.PropertyType; var isRequired = nullabilityInfo.WriteState != NullabilityState.Nullable && Nullable.GetUnderlyingType(baseType) == null; var constraintIssue = ValidatePropertyConstraints(property.PropertyType, property.Name, isRequired, isArray); if (constraintIssue != null) { result.Issues.Add(constraintIssue); if (constraintIssue.Severity == ValidationSeverity.Error) result.IsValid = false; } } var existingScheme = await Context.QueryFirstOrDefaultAsync( Sql.Validation_SelectSchemeByName(), new object[] { schemeName }, cancellationToken); if (existingScheme != null) { result.ChangeReport = await AnalyzeSchemaChangesAsync(existingScheme.Id); if (result.ChangeReport.HasBreakingChanges && strictDeleteExtra) { result.Issues.Add(new ValidationIssue { Severity = ValidationSeverity.Warning, PropertyName = "Schema", Message = "Breaking schema changes detected with strictDeleteExtra=true", SuggestedFix = "Check change report or set strictDeleteExtra=false" }); } } return result; } public async Task ValidateSchemaAsync(IRedbScheme scheme, bool strictDeleteExtra = true, CancellationToken cancellationToken = default) where TProps : class { return await ValidateSchemaAsync(scheme.Name, strictDeleteExtra); } public async Task AnalyzeSchemaChangesAsync(IRedbScheme scheme, CancellationToken cancellationToken = default) where TProps : class { return await AnalyzeSchemaChangesAsync(scheme.Id); } public async Task AnalyzeSchemaChangesAsync(long schemeId, CancellationToken cancellationToken = default) where TProps : class { var report = new SchemaChangeReport(); var properties = typeof(TProps).GetProperties(BindingFlags.Public | BindingFlags.Instance) .Where(p => !p.ShouldIgnoreForRedb()) .ToArray(); var nullabilityContext = new NullabilityInfoContext(); var existingStructures = await Context.QueryAsync( Sql.Validation_SelectStructuresBySchemeId(), new object[] { schemeId }, cancellationToken); var allTypes = await Context.QueryAsync(Sql.Validation_SelectAllTypes(), System.Array.Empty(), cancellationToken); var typesDict = allTypes.ToDictionary(t => t.Id); var existingNames = existingStructures.Select(s => s.Name).ToHashSet(); var newNames = properties.Select(p => p.Name).ToHashSet(); // Added properties foreach (var property in properties.Where(p => !existingNames.Contains(p.Name))) { report.Changes.Add(new StructureChange { Type = ChangeType.Added, PropertyName = property.Name, NewValue = $"{property.PropertyType.Name} ({await MapCSharpTypeToRedbTypeAsync(property.PropertyType)})", IsBreaking = false }); } // Removed properties foreach (var structure in existingStructures.Where(s => !newNames.Contains(s.Name))) { var typeName = typesDict.TryGetValue(structure.IdType, out var t) ? t.Name : "Unknown"; report.Changes.Add(new StructureChange { Type = ChangeType.Removed, PropertyName = structure.Name, OldValue = typeName, IsBreaking = true }); report.HasBreakingChanges = true; } // Modified properties foreach (var property in properties.Where(p => existingNames.Contains(p.Name))) { var existingStructure = existingStructures.First(s => s.Name == property.Name); var structureTypeName = typesDict.TryGetValue(existingStructure.IdType, out var st) ? st.Name : "Unknown"; var nullabilityInfo = nullabilityContext.Create(property); var isArray = IsArrayType(property.PropertyType); var baseType = isArray ? GetArrayElementType(property.PropertyType) : property.PropertyType; var isRequired = nullabilityInfo.WriteState != NullabilityState.Nullable && Nullable.GetUnderlyingType(baseType) == null; var newTypeName = await MapCSharpTypeToRedbTypeAsync(baseType); // Type change check if (structureTypeName != newTypeName) { var change = new StructureChange { Type = ChangeType.TypeChanged, PropertyName = property.Name, OldValue = structureTypeName, NewValue = newTypeName, IsBreaking = !AreTypesCompatible(structureTypeName, newTypeName) }; report.Changes.Add(change); if (change.IsBreaking) report.HasBreakingChanges = true; } // Nullability change check if (existingStructure.AllowNotNull != isRequired) { var change = new StructureChange { Type = ChangeType.NullabilityChanged, PropertyName = property.Name, OldValue = existingStructure.AllowNotNull == true ? "required" : "optional", NewValue = isRequired ? "required" : "optional", IsBreaking = isRequired && existingStructure.AllowNotNull != true }; report.Changes.Add(change); if (change.IsBreaking) report.HasBreakingChanges = true; } // Array change check var wasArray = existingStructure.CollectionType != null; if (wasArray != isArray) { var change = new StructureChange { Type = ChangeType.ArrayChanged, PropertyName = property.Name, OldValue = wasArray ? "array" : "single", NewValue = isArray ? "array" : "single", IsBreaking = true }; report.Changes.Add(change); report.HasBreakingChanges = true; } } return report; } public ValidationIssue? ValidatePropertyConstraints(Type propertyType, string propertyName, bool isRequired, bool isArray) { if (isArray) { var elementType = GetArrayElementType(propertyType); if (typeof(RedbObject<>).IsAssignableFrom(elementType)) { return new ValidationIssue { Severity = ValidationSeverity.Warning, PropertyName = propertyName, Message = "Object arrays require special attention during serialization", SuggestedFix = "Ensure objects in array have correct IDs" }; } } if (isRequired && propertyType.IsClass && propertyType != typeof(string)) { return new ValidationIssue { Severity = ValidationSeverity.Warning, PropertyName = propertyName, Message = "Required reference types (except string) may cause deserialization issues", SuggestedFix = "Consider making the field nullable or provide a default value" }; } return null; } #region Helper Methods private async Task MapCSharpTypeToRedbTypeAsync(Type type) { var underlyingType = Nullable.GetUnderlyingType(type) ?? type; if (_csharpToRedbTypeCache == null) { await InitializeCSharpToRedbTypeMappingAsync(); } if (_csharpToRedbTypeCache!.TryGetValue(underlyingType, out var exactMatch)) return exactMatch; if (underlyingType.IsGenericType && underlyingType.GetGenericTypeDefinition() == typeof(RedbObject<>)) return "Object"; return "String"; } private async Task InitializeCSharpToRedbTypeMappingAsync(CancellationToken cancellationToken = default) { var allTypes = await Context.QueryAsync(Sql.Validation_SelectAllTypes(), System.Array.Empty(), cancellationToken); _csharpToRedbTypeCache = new Dictionary(); // Sort by ID to ensure base types (String, Long, etc.) are processed first 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 if (csharpType != null && !_csharpToRedbTypeCache.ContainsKey(csharpType)) { _csharpToRedbTypeCache[csharpType] = dbType.Name; } } } 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 }; private static bool IsArrayType(Type type) => type.IsArray || (type.IsGenericType && (type.GetGenericTypeDefinition() == typeof(List<>) || type.GetGenericTypeDefinition() == typeof(IList<>) || type.GetGenericTypeDefinition() == typeof(ICollection<>) || type.GetGenericTypeDefinition() == typeof(IEnumerable<>))); private static Type GetArrayElementType(Type arrayType) { if (arrayType.IsArray) return arrayType.GetElementType()!; if (arrayType.IsGenericType) return arrayType.GetGenericArguments()[0]; return typeof(object); } private static bool AreTypesCompatible(string oldType, string newType) { var compatibleMappings = new Dictionary> { ["String"] = ["String"], ["Long"] = ["Long", "Double"], ["Double"] = ["Double"], ["Boolean"] = ["Boolean"], ["DateTime"] = ["DateTime", "String"], ["DateTimeOffset"] = ["DateTimeOffset", "String"], ["DateOnly"] = ["DateOnly", "String"], ["TimeOnly"] = ["TimeOnly", "String"], ["TimeSpan"] = ["TimeSpan", "String"], ["Guid"] = ["Guid", "String"], ["ByteArray"] = ["ByteArray", "String"], ["Object"] = ["Object", "Long"] }; return compatibleMappings.TryGetValue(oldType, out var compatible) && compatible.Contains(newType); } private static string GetTypeDescription(string typeName) => typeName switch { "String" => "String values (text up to 850 chars in _String)", "Long" => "Integer numbers (int, long)", "Double" => "Floating point numbers (double, float, decimal)", "Boolean" => "Boolean values (true/false)", "DateTime" => "Date and time", "DateTimeOffset" => "Date and time with time zone", "Guid" => "Unique identifiers", "ByteArray" => "Binary data", "Object" => "References to other REDB objects", "ListItem" => "List items", "Text" => "Long text values (deprecated, use String)", _ => "Unknown type" }; #endregion } } Path: redb/redb.Core/Providers/ILazyPropsLoader.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/ILazyPropsLoader.cs ---- using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using redb.Core.Models.Entities; namespace redb.Core.Providers { /// /// Interface for lazy loading of RedbObject Props. /// public interface ILazyPropsLoader { /// /// Synchronous Props loading (for Properties getter). /// /// Object ID /// Scheme ID /// Object Props, or null when the target is gone (moved to the trash) - V4 (L.3, LAZY �4.8) TProps? LoadProps(long objectId, long schemeId) where TProps : class, new(); /// /// The database (cache domain) this loader reads. A loader bound to one scope names its database: the reference /// stubs it materializes then carry the one scope-free loader of that database, which loads on the live scope of /// whoever reads them (owner decision 2026-09-15). Null for a loader bound to no database. /// string? CacheDomain => null; /// /// The context (one scope, one connection) this loader is bound to. The stubs and list items it materializes keep /// the service of that scope as their origin: when no redb scope is current for the reader, they load on the origin /// while it lives and the instance is not shared (owner decision 2026-09-15). Null for a loader bound to no scope. /// Data.IRedbContext? ScopeContext => null; /// /// Asynchronous Props loading (for explicit preload LoadPropsAsync). /// /// Object ID /// Scheme ID /// Object Props, or null when the target is gone (moved to the trash) - V4 (L.3, LAZY �4.8) /// Cancels the operation (OCE only; a rollback in flight always completes). Task LoadPropsAsync(long objectId, long schemeId, CancellationToken cancellationToken = default) where TProps : class, new(); /// /// BULK Props loading for multiple objects with caching and parallelism. /// /// List of objects to load Props for /// Cancels the operation (OCE only; a rollback in flight always completes). Task LoadPropsForManyAsync(List> objects, CancellationToken cancellationToken = default) where TProps : class, new(); /// /// OPTIMIZED Props loading with structure_ids filter. /// Loads only specified fields from _values (for Select projections). /// /// List of objects to load Props for /// HashSet of structure_ids for _values filtering (null = all) /// Cancels the operation (OCE only; a rollback in flight always completes). Task LoadPropsForManyAsync( List> objects, HashSet? projectedStructureIds, CancellationToken cancellationToken = default) where TProps : class, new(); /// /// BULK Props loading with custom depth for nested RedbObject. /// /// List of objects to load Props for /// Maximum depth for nested RedbObject loading (null = use config default) /// Cancels the operation (OCE only; a rollback in flight always completes). Task LoadPropsForManyAsync( List> objects, int? propsDepth, CancellationToken cancellationToken = default) where TProps : class, new(); /// /// OPTIMIZED Props loading with structure_ids filter and custom depth. /// /// List of objects to load Props for /// HashSet of structure_ids for _values filtering (null = all) /// Maximum depth for nested RedbObject loading (null = use config default) /// Cancels the operation (OCE only; a rollback in flight always completes). Task LoadPropsForManyAsync( List> objects, HashSet? projectedStructureIds, int? propsDepth, CancellationToken cancellationToken = default) where TProps : class, new(); } } Path: redb/redb.Core/Providers/IListProvider.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/IListProvider.cs ---- using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace redb.Core.Providers { /// /// Provider for working with dictionaries (Lists) and their items (ListItems). /// public interface IListProvider { /// /// Resolves many linked objects in one round-trip on the owning service's connection, for the hand-out preload /// (PreloadListItemLinkedObjects). Returns only the objects that exist; a missing id simply stays lazy on /// its item. Set by the owning . A single loads on the /// live scope of whoever reads it - the provider attaches no loader to items (owner decision 2026-09-15). /// Func, CancellationToken, Task>>? LinkedObjectsBatchLoader { get => null; set { } } // === LIST CRUD === Task GetListAsync(long listId, CancellationToken cancellationToken = default); Task GetListByNameAsync(string name, CancellationToken cancellationToken = default); Task> GetAllListsAsync(CancellationToken cancellationToken = default); /// /// Get list with all its items loaded. /// Task GetListWithItemsAsync(long listId, CancellationToken cancellationToken = default); /// /// Get list by name with all its items loaded. /// Task GetListByNameWithItemsAsync(string name, CancellationToken cancellationToken = default); Task SaveListAsync(IRedbList list, CancellationToken cancellationToken = default); Task DeleteListAsync(long listId, CancellationToken cancellationToken = default); // === ITEM CRUD === Task GetListItemAsync(long itemId, CancellationToken cancellationToken = default); /// /// The list items of the given ids, in one query for those the cache does not hold. An id that names no item is /// absent from the result; the order of the result is not that of the ids. /// Task> GetListItemsByIdsAsync(IEnumerable itemIds, CancellationToken cancellationToken = default); Task> GetListItemsAsync(long listId, CancellationToken cancellationToken = default); Task GetListItemByValueAsync(long listId, string value, CancellationToken cancellationToken = default); Task SaveListItemAsync(IRedbListItem item, CancellationToken cancellationToken = default); Task DeleteListItemAsync(long itemId, CancellationToken cancellationToken = default); /// /// Add multiple items from ready objects. /// Task> AddItemsAsync(IRedbList list, IEnumerable items, CancellationToken cancellationToken = default); /// /// Add multiple items from string values (convenience method). /// Task> AddItemsAsync(IRedbList list, IEnumerable values, IEnumerable? aliases = null, CancellationToken cancellationToken = default); /// /// Save list with all its items (Aggregate Root). /// Task SaveListWithItemsAsync(IRedbList list, CancellationToken cancellationToken = default); // === SPECIFIC METHODS === Task> GetItemsByObjectReferenceAsync(long objectId, CancellationToken cancellationToken = default); Task IsListUsedInStructuresAsync(long listId, CancellationToken cancellationToken = default); Task SyncListFromEnumAsync(string? listName = null, CancellationToken cancellationToken = default) where TEnum : struct, Enum; } } Path: redb/redb.Core/Providers/IMaintenanceProvider.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/IMaintenanceProvider.cs ---- using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace redb.Core.Providers { /// /// Storage maintenance: planner statistics and index health. Born out of the 2026-09-10 /// incident where stale planner statistics after a bulk seed turned every plan into fiction /// (a 30ms tree query ran for a second), and index health was visible only by hand-written /// catalog queries per database. /// /// Everything here is read-only except the two AnalyzeAsync overloads, and both are /// explicit calls. Reorganising the storage (VACUUM, REINDEX, resetting counters) is not /// offered on purpose (owner decision 2026-09-21): the facade reports what the database is /// doing so an operator can hand the findings to a DBA, and a button that locks a production /// table must not be one click away in a dashboard. /// /// public interface IMaintenanceProvider { /// /// Refreshes the planner statistics of the database (PostgreSQL ANALYZE, /// MSSQL sp_updatestats, SQLite PRAGMA analysis_limit; ANALYZE). /// An EXPLICIT call by design: on a large database it can run for minutes, so it must /// never be a silent side effect of a save. Call it after bulk writes - a seed, an /// import, a migration - or every estimate the planner reads will be stale. /// Task AnalyzeAsync(CancellationToken cancellationToken = default); /// /// Refreshes the planner statistics of ONE table (PostgreSQL ANALYZE t, MSSQL /// UPDATE STATISTICS t, SQLite ANALYZE t - every engine supports it), for /// the usual case where the operator knows the table that brought them here and a /// whole-database pass would run for minutes. /// /// Table name, unquoted, as the catalogs report it. /// Schema of the table; null means the engine's default /// (public, dbo) and is the only option on SQLite. /// The name is empty. /// No such table in the database. The name is /// checked against the catalogs and quoted by the dialect before it reaches SQL: it comes /// from a dashboard, and an identifier cannot be a parameter. Task AnalyzeTableAsync(string table, string? schema = null, CancellationToken cancellationToken = default); /// /// Index statistics of the user tables, read from the database catalogs. Fields the /// engine cannot report are null - see each property; nothing is guessed. /// Task> GetIndexStatsAsync(CancellationToken cancellationToken = default); /// /// Table statistics of the user tables: size, rows, the size of their indexes, and when /// the engine last refreshed statistics or reclaimed dead rows. The other half of the /// picture an operator needs - says what the indexes are, /// this says what they sit on. /// Task> GetTableStatsAsync(CancellationToken cancellationToken = default); /// /// Since when the usage counters of have been counting, /// and whether this node is a replica. Without it "this index served no read" says /// nothing: the counters may have been reset or the server restarted a minute ago, and on /// a PostgreSQL replica they count only this node's own reads. /// Task GetStatisticsWindowAsync(CancellationToken cancellationToken = default); } /// /// One index as the database catalog sees it. Honestly nullable: each provider fills what /// its engine can report (PostgreSQL and MSSQL carry usage counters, SQLite does not; /// MSSQL usage counters reset on server restart; needs PostgreSQL 16+). /// public class IndexStatistics { /// Schema of the table; null on engines without schemas (SQLite). public string? Schema { get; set; } /// Table the index belongs to. public string Table { get; set; } = string.Empty; /// Index name. public string Name { get; set; } = string.Empty; /// Whether the index is unique; null when the catalog does not say. public bool? IsUnique { get; set; } /// Key columns in index order. Empty only when the engine could not report them. public IReadOnlyList Columns { get; set; } = Array.Empty(); /// /// Columns carried but not keyed (MSSQL INCLUDE); empty elsewhere. Without this a /// covering index is indistinguishable from a composite one. /// public IReadOnlyList IncludedColumns { get; set; } = Array.Empty(); /// The index backs a primary key. public bool IsPrimaryKey { get; set; } /// The index backs a unique constraint (as opposed to a plain unique index). public bool IsUniqueConstraint { get; set; } /// MSSQL clustered index - the table itself; null on engines without the notion. public bool? IsClustered { get; set; } /// The index serves a foreign key, so dropping it turns key checks into scans. public bool BacksForeignKey { get; set; } /// The index belongs to a table of the redb schema (a name starting with '_'). public bool IsRedbOwned { get; set; } /// /// The index must not be dropped, whatever its usage counters say (owner decision /// 2026-09-21). True for every index of the redb schema and for any index that backs a /// primary key, a unique constraint or a foreign key. says which. /// public bool IsSystemCritical { get; set; } /// Why is set; when it is not. public IndexCriticality CriticalReason { get; set; } /// On-disk size in bytes; null when unavailable (SQLite without dbstat). public long? SizeBytes { get; set; } /// Planner's row estimate for the index; null when unavailable. public long? EstimatedRows { get; set; } /// Point-lookup uses. PostgreSQL reports one combined scan counter here. public long? Seeks { get; set; } /// Range/full scans (MSSQL); null where the engine does not split the counter. public long? Scans { get; set; } /// Maintenance writes into the index (MSSQL); null elsewhere. public long? Updates { get; set; } /// Last time the index served a read; PostgreSQL 16+ and MSSQL only. public DateTimeOffset? LastUsed { get; set; } } /// Why an index must survive regardless of how often it is read. public enum IndexCriticality { /// Nothing structural: the usage counters are the whole story. None = 0, /// A table of the redb type system: schemes, structures, types, their cache, migrations. RedbMetadata = 1, /// A table redb checks permissions against: users, roles, permissions. RedbSecurity = 2, /// A table holding redb data: objects, values, list items. RedbData = 3, /// Backs a primary key. PrimaryKey = 4, /// Enforces uniqueness. Unique = 5, /// Serves a foreign key. ForeignKey = 6 } /// /// One table as the database catalog sees it. Nullable in the same spirit as /// : what the engine does not report stays null. /// public class TableStatistics { /// Schema of the table; null on engines without schemas (SQLite). public string? Schema { get; set; } /// Table name. public string Table { get; set; } = string.Empty; /// The table belongs to the redb schema (a name starting with '_'). public bool IsRedbOwned { get; set; } /// Planner's row estimate; null when unavailable. public long? EstimatedRows { get; set; } /// Size of the table's own data in bytes; null when unavailable. public long? DataSizeBytes { get; set; } /// Total size of the table's indexes in bytes; null when unavailable. public long? IndexesSizeBytes { get; set; } /// Rows dead but not yet reclaimed (PostgreSQL); null elsewhere. public long? DeadRows { get; set; } /// When statistics of this table were last refreshed by an explicit request; null when the engine does not record it. public DateTimeOffset? LastAnalyze { get; set; } /// When the engine refreshed them on its own (PostgreSQL autoanalyze); null elsewhere. public DateTimeOffset? LastAutoAnalyze { get; set; } /// When dead rows were last reclaimed (PostgreSQL vacuum); null elsewhere. public DateTimeOffset? LastVacuum { get; set; } /// /// Whether the engine holds any statistics for this table at all. SQLite records no /// dates, so this is all it can say: ANALYZE has run at least once, or never. /// public bool? HasStatistics { get; set; } } /// /// The window the usage counters of /// cover, and whether this node is a replica. /// public class StatisticsWindow { /// /// Since when the counters have been counting: the last statistics reset (PostgreSQL) or /// the start of the instance (MSSQL). Null where the engine keeps no counters (SQLite) or /// has never reset them. /// public DateTimeOffset? CountersSince { get; set; } /// /// The node is a read-only replica (PostgreSQL in recovery). Its counters describe this /// node alone, so an index unused here may be busy on the primary. Null where the notion /// does not apply. /// public bool? IsReplica { get; set; } } } Path: redb/redb.Core/Providers/IObjectStorageProvider.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/IObjectStorageProvider.cs ---- using redb.Core.Models.Entities; using redb.Core.Models.Contracts; using redb.Core.Services; using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace redb.Core.Providers { /// /// Provider for saving/loading objects in EAV storage. /// Permission checks are managed centrally via configuration. /// public interface IObjectStorageProvider { // ===== BASE METHODS (use _securityContext and configuration) ===== /// /// Load object from EAV by ID (uses _securityContext and config.DefaultCheckPermissionsOnLoad). /// Returns null if object not found and config.ThrowOnObjectNotFound = false. /// Task?> LoadAsync(long objectId, int depth = 10, CancellationToken cancellationToken = default) where TProps : class, new(); /// /// Synchronous for the /// thread-pool-free lazy path (the sync getter of RedbListItem.Object): the whole load runs /// on the calling thread down to ADO.NET, so a saturated thread pool cannot slow or /// deadlock it. The default falls back to blocking on the async form (pool-coupled); /// the in-tree base provider overrides with a true sync path. /// RedbObject? Load(long objectId, int depth = 10) where TProps : class, new() => LoadAsync(objectId, depth).ConfigureAwait(false).GetAwaiter().GetResult(); /// /// Load object from EAV (uses _securityContext and config.DefaultCheckPermissionsOnLoad). /// Returns null if object not found and config.ThrowOnObjectNotFound = false. /// Task?> LoadAsync(IRedbObject obj, int depth = 10, CancellationToken cancellationToken = default) where TProps : class, new(); /// /// Load object from EAV with explicit user by ID (uses config.DefaultCheckPermissionsOnLoad). /// Returns null if object not found and config.ThrowOnObjectNotFound = false. /// Task?> LoadAsync(long objectId, IRedbUser user, int depth = 10, CancellationToken cancellationToken = default) where TProps : class, new(); /// /// Load object from EAV with explicit user (uses config.DefaultCheckPermissionsOnLoad). /// Returns null if object not found and config.ThrowOnObjectNotFound = false. /// Task?> LoadAsync(IRedbObject obj, IRedbUser user, int depth = 10, CancellationToken cancellationToken = default) where TProps : class, new(); /// /// Load the whole object as raw JSON by ID, without a CLR props type — the in-database /// materializer (get_object_json on every provider) serializes the full RedbObject tree /// to the given depth. Permission check per config.DefaultCheckPermissionsOnLoad; the /// typed props cache is not consulted (it is keyed by CLR type). /// Returns null if object not found and config.ThrowOnObjectNotFound = false. /// Task LoadJsonAsync(long objectId, int depth = 10, CancellationToken cancellationToken = default); /// /// Load the whole object as raw JSON by ID with explicit user (see /// ). /// Task LoadJsonAsync(long objectId, IRedbUser user, int depth = 10, CancellationToken cancellationToken = default); /// /// The object whose [RedbUnique] property holds the given value, or null. One probe of the /// partial unique index: the value is canonicalised and hashed exactly as the save path /// does it. Throws RedbUniqueKeyDefinitionException when the property is not a unique key. /// Task?> GetByUniqueAsync(System.Linq.Expressions.Expression> keyProperty, object? value, int depth = 10, CancellationToken cancellationToken = default) where TProps : class, new(); /// Task?> GetByUniqueAsync(string propertyName, object? value, int depth = 10, CancellationToken cancellationToken = default) where TProps : class, new(); /// /// Upsert by the object key (P1): resolves the _objects row by (scheme, ValueUnique) and /// saves onto it - the values ride the ordinary pipeline in the same save. A lost creation /// race retries onto the winner's row, so a concurrent accept of one key is idempotent: /// exactly one object per key, last writer's content. Returns the object id. /// Throws RedbUniqueKeyDefinitionException when ValueUnique is empty. /// Task SaveByUniqueAsync(RedbObject obj, CancellationToken cancellationToken = default) where TProps : class, new(); /// /// Save object to EAV (uses _securityContext and config.DefaultCheckPermissionsOnSave). /// Determines type (generic/non-generic) internally. /// Task SaveAsync(IRedbObject obj, CancellationToken cancellationToken = default); /// /// Save generic object to EAV (uses _securityContext and config.DefaultCheckPermissionsOnSave). /// Task SaveAsync(IRedbObject obj, CancellationToken cancellationToken = default) where TProps : class, new(); /// /// Delete object (uses _securityContext and config.DefaultCheckPermissionsOnDelete). /// Task DeleteAsync(IRedbObject obj, CancellationToken cancellationToken = default); // ===== OVERLOADS WITH EXPLICIT USER (use configuration) ===== /// /// Save object to EAV with explicit user. Determines type internally. /// Task SaveAsync(IRedbObject obj, IRedbUser user, CancellationToken cancellationToken = default); /// /// Save generic object to EAV with explicit user (uses config.DefaultCheckPermissionsOnSave). /// Task SaveAsync(IRedbObject obj, IRedbUser user, CancellationToken cancellationToken = default) where TProps : class, new(); /// /// Delete object with explicit user (uses config.DefaultCheckPermissionsOnDelete). /// Task DeleteAsync(IRedbObject obj, IRedbUser user, CancellationToken cancellationToken = default); // ===== DELETE BY ID ===== /// /// Delete object by ID (uses _securityContext and config.DefaultCheckPermissionsOnDelete). /// /// true if object deleted, false if not found Task DeleteAsync(long objectId, CancellationToken cancellationToken = default); /// /// Delete object by ID with explicit user (uses config.DefaultCheckPermissionsOnDelete). /// /// true if object deleted, false if not found Task DeleteAsync(long objectId, IRedbUser user, CancellationToken cancellationToken = default); // ===== BULK OPERATIONS WITH PERMISSION CHECK ===== /// /// Bulk delete objects by ID (uses _securityContext and config.DefaultCheckPermissionsOnDelete). /// /// Number of deleted objects Task DeleteAsync(IEnumerable objectIds, CancellationToken cancellationToken = default); /// /// Bulk delete objects by ID with explicit user (uses config.DefaultCheckPermissionsOnDelete). /// /// Number of deleted objects Task DeleteAsync(IEnumerable objectIds, IRedbUser user, CancellationToken cancellationToken = default); /// /// Bulk delete objects by interface (uses _securityContext and config.DefaultCheckPermissionsOnDelete). /// /// Number of deleted objects Task DeleteAsync(IEnumerable objects, CancellationToken cancellationToken = default); /// /// Bulk delete objects by interface with explicit user (uses config.DefaultCheckPermissionsOnDelete). /// /// Number of deleted objects Task DeleteAsync(IEnumerable objects, IRedbUser user, CancellationToken cancellationToken = default); /// /// Bulk polymorphic load of objects by ID (uses _securityContext and config.DefaultCheckPermissionsOnLoad). /// Supports objects of different schemes in one request. /// /// List of object IDs to load /// Depth for loading nested objects (EAGER mode only) /// List of polymorphic IRedbObject instances /// Cancels the operation; see the cancellation contract in the plan (OCE only, rollback always completes). Task> LoadAsync(IEnumerable objectIds, int depth = 10, CancellationToken cancellationToken = default); /// /// Bulk polymorphic load of objects by ID with explicit user (uses config.DefaultCheckPermissionsOnLoad). /// Supports objects of different schemes in one request. /// /// List of object IDs to load /// User for permission check /// Depth for loading nested objects (EAGER mode only) /// List of polymorphic IRedbObject instances /// Cancels the operation; see the cancellation contract in the plan (OCE only, rollback always completes). Task> LoadAsync(IEnumerable objectIds, IRedbUser user, int depth = 10, CancellationToken cancellationToken = default); /// /// Bulk save of polymorphic objects (uses _securityContext and config). /// Supports new and existing objects, nested objects. /// Uses two strategies: DeleteInsert (bulk operations) or ChangeTracking (EF diff). /// /// List of IDs of all main objects Task> SaveAsync(IEnumerable objects, CancellationToken cancellationToken = default); /// /// Bulk save of polymorphic objects with explicit user (uses config). /// Supports new and existing objects, nested objects. /// Uses two strategies: DeleteInsert (bulk operations) or ChangeTracking (EF diff). /// /// List of IDs of all main objects Task> SaveAsync(IEnumerable objects, IRedbUser user, CancellationToken cancellationToken = default); // ===== SOFT DELETE (BACKGROUND DELETION) ===== /// /// Mark objects for soft-deletion (uses _securityContext). /// Creates a trash container and moves objects and their descendants under it. /// Actual deletion happens in background via IBackgroundDeletionService. /// /// IDs of objects to mark for deletion /// Optional parent ID for trash container (null = root level) /// Deletion mark with trash container ID and count of marked objects /// Cancels the operation; see the cancellation contract in the plan (OCE only, rollback always completes). Task SoftDeleteAsync(IEnumerable objectIds, long? trashParentId = null, CancellationToken cancellationToken = default); /// /// Mark objects for soft-deletion with explicit user. /// Creates a trash container and moves objects and their descendants under it. /// Actual deletion happens in background via IBackgroundDeletionService. /// /// IDs of objects to mark for deletion /// User performing the operation /// Optional parent ID for trash container (null = root level) /// Deletion mark with trash container ID and count of marked objects /// Cancels the operation; see the cancellation contract in the plan (OCE only, rollback always completes). Task SoftDeleteAsync(IEnumerable objectIds, IRedbUser user, long? trashParentId = null, CancellationToken cancellationToken = default); /// /// Mark objects for soft-deletion (uses _securityContext). /// Creates a trash container and moves objects and their descendants under it. /// /// Objects to mark for deletion /// Optional parent ID for trash container (null = root level) /// Deletion mark with trash container ID and count of marked objects /// Cancels the operation; see the cancellation contract in the plan (OCE only, rollback always completes). Task SoftDeleteAsync(IEnumerable objects, long? trashParentId = null, CancellationToken cancellationToken = default); /// /// Mark objects for soft-deletion with explicit user. /// Creates a trash container and moves objects and their descendants under it. /// /// Objects to mark for deletion /// User performing the operation /// Optional parent ID for trash container (null = root level) /// Deletion mark with trash container ID and count of marked objects /// Cancels the operation; see the cancellation contract in the plan (OCE only, rollback always completes). Task SoftDeleteAsync(IEnumerable objects, IRedbUser user, long? trashParentId = null, CancellationToken cancellationToken = default); /// /// Delete objects with background purge and progress reporting. /// Marks objects for deletion, then purges them in batches with progress callback. /// /// IDs of objects to delete /// Number of objects to delete per batch /// Optional progress reporter /// Cancellation token /// Optional parent ID for trash container (null = root level) Task DeleteWithPurgeAsync( IEnumerable objectIds, int batchSize = 10, IProgress? progress = null, CancellationToken cancellationToken = default, long? trashParentId = null); /// /// Purge a trash container created by SoftDeleteAsync. /// Physically deletes objects in batches with progress callback. /// Call this after SoftDeleteAsync if you want to control purge timing separately. /// /// Trash container ID from DeletionMark.TrashId /// Total objects to delete (from DeletionMark.MarkedCount) /// Number of objects to delete per batch /// Optional progress reporter /// Cancellation token Task PurgeTrashAsync( long trashId, int totalCount, int batchSize = 10, IProgress? progress = null, CancellationToken cancellationToken = default); /// /// Gets deletion progress for a specific trash container from database. /// Returns null if trash container not found or already deleted. /// /// Trash container ID /// Cancels the operation; see the cancellation contract in the plan (OCE only, rollback always completes). Task GetDeletionProgressAsync(long trashId, CancellationToken cancellationToken = default); /// /// Gets all active (pending/running) deletions for a user from database. /// /// User ID /// Cancels the operation; see the cancellation contract in the plan (OCE only, rollback always completes). Task> GetUserActiveDeletionsAsync(long userId, CancellationToken cancellationToken = default); /// /// Gets orphaned deletion tasks for recovery at startup. /// CLUSTER-SAFE: Returns 'pending' OR 'running' with stale _date_modify. /// /// Minutes after which 'running' task is considered orphaned /// Cancels the operation; see the cancellation contract in the plan (OCE only, rollback always completes). Task> GetOrphanedDeletionTasksAsync(int timeoutMinutes = 30, CancellationToken cancellationToken = default); /// /// Atomically claim an orphaned task for processing. /// CLUSTER-SAFE: Uses atomic UPDATE to prevent race conditions. /// /// Trash container ID to claim /// Minutes for stale check /// True if successfully claimed, false if already taken by another instance /// Cancels the operation; see the cancellation contract in the plan (OCE only, rollback always completes). Task TryClaimOrphanedTaskAsync(long trashId, int timeoutMinutes = 30, CancellationToken cancellationToken = default); // ===== BULK OPERATIONS (WITHOUT PERMISSION CHECK) ===== /// /// BULK INSERT: Create many new objects in one operation (does NOT check permissions). /// - Creates schemes if missing (similar to SaveAsync) /// - Generates IDs for objects with id == 0 via GetNextKey /// - Fully processes recursive nested objects, arrays, Class fields /// - Uses BulkInsert for maximum performance /// - If id != 0, relies on DB errors for duplicates (does not check in advance) /// - An object the given ones refer to that is already in the database is a reference: its id is written, the /// object itself is neither inserted nor changed /// - A nested new object keeps the ParentId it carries (null when none was set), as in SaveAsync: a reference /// is not a place in the tree /// Task> AddNewObjectsAsync(IEnumerable> objects, CancellationToken cancellationToken = default) where TProps : class, new(); /// /// BULK INSERT with explicit user: Create many new objects (does NOT check permissions). /// - Sets OwnerId and WhoChangeId for all objects from specified user /// - Rest of logic identical to AddNewObjectsAsync without user /// Task> AddNewObjectsAsync(IEnumerable> objects, IRedbUser user, CancellationToken cancellationToken = default) where TProps : class, new(); // NOTE: Non-generic RedbObject (Object scheme) uses existing methods: // - SaveAsync(IEnumerable) - RedbObject : IRedbObject // - LoadAsync(IEnumerable) - returns List, cast to RedbObject // ===== LOAD WITH PARENT CHAIN ===== /// /// Load object from EAV by ID with parent chain to root (uses _securityContext). /// Returns TreeRedbObject with populated Parent property up to root. /// Returns null if object not found and config.ThrowOnObjectNotFound = false. /// /// Object ID to load /// Depth for loading nested objects in Props /// Cancels the operation; see the cancellation contract in the plan (OCE only, rollback always completes). Task?> LoadWithParentsAsync(long objectId, int depth = 10, CancellationToken cancellationToken = default) where TProps : class, new(); /// /// Load object from EAV with parent chain to root (uses _securityContext). /// Returns TreeRedbObject with populated Parent property up to root. /// Returns null if object not found and config.ThrowOnObjectNotFound = false. /// Task?> LoadWithParentsAsync(IRedbObject obj, int depth = 10, CancellationToken cancellationToken = default) where TProps : class, new(); /// /// Load object from EAV by ID with parent chain to root with explicit user. /// Returns TreeRedbObject with populated Parent property up to root. /// Returns null if object not found and config.ThrowOnObjectNotFound = false. /// Task?> LoadWithParentsAsync(long objectId, IRedbUser user, int depth = 10, CancellationToken cancellationToken = default) where TProps : class, new(); /// /// Load object from EAV with parent chain to root with explicit user. /// Returns TreeRedbObject with populated Parent property up to root. /// Returns null if object not found and config.ThrowOnObjectNotFound = false. /// Task?> LoadWithParentsAsync(IRedbObject obj, IRedbUser user, int depth = 10, CancellationToken cancellationToken = default) where TProps : class, new(); /// /// Bulk load objects by ID with parent chains to root (uses _securityContext). /// Each object has its Parent chain populated up to root. /// Parent objects that are common across multiple chains are shared (same reference). /// /// Object IDs to load /// Depth for loading nested objects in Props /// Cancels the operation; see the cancellation contract in the plan (OCE only, rollback always completes). Task>> LoadWithParentsAsync(IEnumerable objectIds, int depth = 10, CancellationToken cancellationToken = default) where TProps : class, new(); /// /// Bulk load objects by ID with parent chains to root with explicit user. /// Each object has its Parent chain populated up to root. /// Parent objects that are common across multiple chains are shared (same reference). /// Task>> LoadWithParentsAsync(IEnumerable objectIds, IRedbUser user, int depth = 10, CancellationToken cancellationToken = default) where TProps : class, new(); /// /// Bulk polymorphic load of objects by ID with parent chains (uses _securityContext). /// Supports objects of different schemes in one request. /// Each object has its Parent chain populated up to root. /// Task> LoadWithParentsAsync(IEnumerable objectIds, int depth = 10, CancellationToken cancellationToken = default); /// /// Bulk polymorphic load of objects by ID with parent chains with explicit user. /// Supports objects of different schemes in one request. /// Each object has its Parent chain populated up to root. /// Task> LoadWithParentsAsync(IEnumerable objectIds, IRedbUser user, int depth = 10, CancellationToken cancellationToken = default); // ===== LAZY REFERENCE RELOAD (V4, LAZY Л2 §4.6) ===== /// /// Loads a COLLECTION of reference stubs under a loaded parent in ONE batch query - the /// antidote to N+1 on lazy collections. Already-loaded references are skipped; a stub whose /// target left for the trash gets null Props, not an exception. /// Task LoadReferencesAsync(RedbObject parent, Func?>?> references, CancellationToken cancellationToken = default) where TProps : class, new() where TRef : class, new(); /// Single-reference form of . Task LoadReferencesAsync(RedbObject parent, Func?> reference, CancellationToken cancellationToken = default) where TProps : class, new() where TRef : class, new(); // ===== ROW-LEVEL LOCKING ===== /// /// Acquire row-level locks on objects by id within the current transaction and report how /// many of the requested rows exist (and are therefore locked). A deleted or never-created /// id locks nothing and is NOT an error here - the returned count is the signal; compare it /// with your distinct id set (BR-9, 2026-09-02: a silent no-op lock plus the default /// MissingObjectStrategy.AutoSwitchToInsert let a CAS save resurrect a deleted object). /// Must be called inside an active transaction ( /// or ): locks release when the /// transaction ends. Rows are locked in ascending id order, so concurrent lockers do not /// deadlock on each other. PostgreSQL: SELECT ... FOR UPDATE. MSSQL: WITH (UPDLOCK, ROWLOCK). /// SQLite: an existence check only - writers are serialized database-wide. /// /// IDs of objects to lock /// How many distinct requested ids exist in _objects (those rows are locked). Task LockForUpdateAsync(params long[] objectIds); /// /// Paired overload: params is incompatible with a trailing token (B1 amendment). Task LockForUpdateAsync(long[] objectIds, CancellationToken cancellationToken); /// /// Strict form of for CAS patterns (lock -> re-read -> save): /// every requested id must exist. Throws /// naming the missing ids, and refuses with to run /// outside an active transaction, where a "lock" would guarantee nothing. /// /// IDs of objects that must all be locked Task LockForUpdateRequiredAsync(params long[] objectIds); /// /// Paired overload: params is incompatible with a trailing token (B1 amendment). Task LockForUpdateRequiredAsync(long[] objectIds, CancellationToken cancellationToken); } } Path: redb/redb.Core/Providers/IPermissionProvider.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/IPermissionProvider.cs ---- #pragma warning disable CS0618 // implements or uses the deprecated object permissions and roles (RedbDeprecation) using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using redb.Core.Models.Enums; using redb.Core.Models.Permissions; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace redb.Core.Providers { /// /// Provider for access permission management. /// public interface IPermissionProvider { // ===== BASE METHODS (use _securityContext by default) ===== /// /// Get IDs of objects readable by current user. /// IQueryable GetReadableObjectIds(); /// /// Check if current user can edit object. /// [System.Obsolete(RedbDeprecation.PermissionsAndRoles)] Task CanUserEditObject(IRedbObject obj, CancellationToken cancellationToken = default); /// /// Check if current user can read object. /// [System.Obsolete(RedbDeprecation.PermissionsAndRoles)] Task CanUserSelectObject(IRedbObject obj, CancellationToken cancellationToken = default); /// /// Check if current user can create objects in scheme. /// [System.Obsolete(RedbDeprecation.PermissionsAndRoles)] Task CanUserInsertScheme(IRedbScheme scheme, CancellationToken cancellationToken = default); /// /// Check if current user can delete object. /// [System.Obsolete(RedbDeprecation.PermissionsAndRoles)] Task CanUserDeleteObject(IRedbObject obj, CancellationToken cancellationToken = default); // ===== OVERLOADS WITH EXPLICIT USER ===== /// /// Get IDs of objects readable by user. /// IQueryable GetReadableObjectIds(IRedbUser user); /// /// Check if user can edit object. /// [System.Obsolete(RedbDeprecation.PermissionsAndRoles)] Task CanUserEditObject(IRedbObject obj, IRedbUser user, CancellationToken cancellationToken = default); /// /// Check if user can read object. /// [System.Obsolete(RedbDeprecation.PermissionsAndRoles)] Task CanUserSelectObject(IRedbObject obj, IRedbUser user, CancellationToken cancellationToken = default); /// /// Check if user can create objects in scheme. /// [System.Obsolete(RedbDeprecation.PermissionsAndRoles)] Task CanUserInsertScheme(IRedbScheme scheme, IRedbUser user, CancellationToken cancellationToken = default); /// /// Check if user can delete object. /// [System.Obsolete(RedbDeprecation.PermissionsAndRoles)] Task CanUserDeleteObject(IRedbObject obj, IRedbUser user, CancellationToken cancellationToken = default); // ===== METHODS WITH REDBOBJECT ===== /// /// Check if current user can edit object. /// [System.Obsolete(RedbDeprecation.PermissionsAndRoles)] Task CanUserEditObject(RedbObject obj, CancellationToken cancellationToken = default); /// /// Check if current user can read object. /// [System.Obsolete(RedbDeprecation.PermissionsAndRoles)] Task CanUserSelectObject(RedbObject obj, CancellationToken cancellationToken = default); /// /// Check if current user can delete object. /// [System.Obsolete(RedbDeprecation.PermissionsAndRoles)] Task CanUserDeleteObject(RedbObject obj, CancellationToken cancellationToken = default); /// /// Check if user can edit object. /// [System.Obsolete(RedbDeprecation.PermissionsAndRoles)] Task CanUserEditObject(RedbObject obj, IRedbUser user, CancellationToken cancellationToken = default); /// /// Check if user can read object. /// [System.Obsolete(RedbDeprecation.PermissionsAndRoles)] Task CanUserSelectObject(RedbObject obj, IRedbUser user, CancellationToken cancellationToken = default); /// /// Check if user can create objects in object's scheme. /// [System.Obsolete(RedbDeprecation.PermissionsAndRoles)] Task CanUserInsertScheme(RedbObject obj, IRedbUser user, CancellationToken cancellationToken = default); /// /// Check if user can delete object. /// [System.Obsolete(RedbDeprecation.PermissionsAndRoles)] Task CanUserDeleteObject(RedbObject obj, IRedbUser user, CancellationToken cancellationToken = default); // ===== CRUD METHODS FOR PERMISSIONS ===== /// /// Create new permission. /// /// Permission data /// Current user (for audit) /// Created permission /// Cancels the operation (OCE only; a rollback in flight always completes). [System.Obsolete(RedbDeprecation.PermissionsAndRoles)] Task CreatePermissionAsync(PermissionRequest request, IRedbUser? currentUser = null, CancellationToken cancellationToken = default); /// /// Update permission. /// /// Permission to update /// New permission data /// Current user (for audit) /// Updated permission /// Cancels the operation (OCE only; a rollback in flight always completes). [System.Obsolete(RedbDeprecation.PermissionsAndRoles)] Task UpdatePermissionAsync(IRedbPermission permission, PermissionRequest request, IRedbUser? currentUser = null, CancellationToken cancellationToken = default); /// /// Delete permission. /// /// Permission to delete /// Current user (for audit) /// true if permission deleted /// Cancels the operation (OCE only; a rollback in flight always completes). [System.Obsolete(RedbDeprecation.PermissionsAndRoles)] Task DeletePermissionAsync(IRedbPermission permission, IRedbUser? currentUser = null, CancellationToken cancellationToken = default); // ===== PERMISSION SEARCH ===== /// /// Get user permissions. /// /// User /// List of user permissions /// Cancels the operation (OCE only; a rollback in flight always completes). [System.Obsolete(RedbDeprecation.PermissionsAndRoles)] Task> GetPermissionsByUserAsync(IRedbUser user, CancellationToken cancellationToken = default); /// /// Get role permissions. /// /// Role /// List of role permissions /// Cancels the operation (OCE only; a rollback in flight always completes). [System.Obsolete(RedbDeprecation.PermissionsAndRoles)] Task> GetPermissionsByRoleAsync(IRedbRole role, CancellationToken cancellationToken = default); /// /// Get permissions for object. /// /// Object /// List of permissions for object /// Cancels the operation (OCE only; a rollback in flight always completes). [System.Obsolete(RedbDeprecation.PermissionsAndRoles)] Task> GetPermissionsByObjectAsync(IRedbObject obj, CancellationToken cancellationToken = default); /// /// Get permission by ID. /// /// Permission ID /// Permission or null if not found /// Cancels the operation (OCE only; a rollback in flight always completes). [System.Obsolete(RedbDeprecation.PermissionsAndRoles)] Task GetPermissionByIdAsync(long permissionId, CancellationToken cancellationToken = default); // ===== PERMISSION MANAGEMENT ===== /// /// Grant permission to user. /// /// User /// Object /// Permission actions /// Current user (for audit) /// true if permission granted /// Cancels the operation (OCE only; a rollback in flight always completes). [System.Obsolete(RedbDeprecation.PermissionsAndRoles)] Task GrantPermissionAsync(IRedbUser user, IRedbObject obj, PermissionAction actions, IRedbUser? currentUser = null, CancellationToken cancellationToken = default); /// /// Grant permission to role. /// /// Role /// Object /// Permission actions /// Current user (for audit) /// true if permission granted /// Cancels the operation (OCE only; a rollback in flight always completes). [System.Obsolete(RedbDeprecation.PermissionsAndRoles)] Task GrantPermissionAsync(IRedbRole role, IRedbObject obj, PermissionAction actions, IRedbUser? currentUser = null, CancellationToken cancellationToken = default); /// /// Revoke permission from user. /// /// User /// Object /// Current user (for audit) /// true if permission revoked /// Cancels the operation (OCE only; a rollback in flight always completes). [System.Obsolete(RedbDeprecation.PermissionsAndRoles)] Task RevokePermissionAsync(IRedbUser user, IRedbObject obj, IRedbUser? currentUser = null, CancellationToken cancellationToken = default); /// /// Revoke permission from role. /// /// Role /// Object /// Current user (for audit) /// true if permission revoked /// Cancels the operation (OCE only; a rollback in flight always completes). [System.Obsolete(RedbDeprecation.PermissionsAndRoles)] Task RevokePermissionAsync(IRedbRole role, IRedbObject obj, IRedbUser? currentUser = null, CancellationToken cancellationToken = default); /// /// Revoke all user permissions. /// /// User /// Current user (for audit) /// Number of revoked permissions /// Cancels the operation (OCE only; a rollback in flight always completes). [System.Obsolete(RedbDeprecation.PermissionsAndRoles)] Task RevokeAllUserPermissionsAsync(IRedbUser user, IRedbUser? currentUser = null, CancellationToken cancellationToken = default); /// /// Revoke all role permissions. /// /// Role /// Current user (for audit) /// Number of revoked permissions /// Cancels the operation (OCE only; a rollback in flight always completes). [System.Obsolete(RedbDeprecation.PermissionsAndRoles)] Task RevokeAllRolePermissionsAsync(IRedbRole role, IRedbUser? currentUser = null, CancellationToken cancellationToken = default); // ===== EFFECTIVE PERMISSIONS ===== /// /// Get effective user permissions for object (including inheritance and roles). /// /// User /// Object /// Effective user permissions /// Cancels the operation (OCE only; a rollback in flight always completes). [System.Obsolete(RedbDeprecation.PermissionsAndRoles)] Task GetEffectivePermissionsAsync(IRedbUser user, IRedbObject obj, CancellationToken cancellationToken = default); /// /// Get effective user permissions for multiple objects (batch). /// /// User /// Array of objects /// Dictionary object -> effective permissions /// Cancels the operation (OCE only; a rollback in flight always completes). [System.Obsolete(RedbDeprecation.PermissionsAndRoles)] Task> GetEffectivePermissionsBatchAsync(IRedbUser user, IRedbObject[] objects, CancellationToken cancellationToken = default); /// /// Get all effective user permissions. /// /// User /// List of all effective user permissions /// Cancels the operation (OCE only; a rollback in flight always completes). [System.Obsolete(RedbDeprecation.PermissionsAndRoles)] Task> GetAllEffectivePermissionsAsync(IRedbUser user, CancellationToken cancellationToken = default); // ===== STATISTICS ===== /// /// Get total permission count. /// /// Total number of permissions [System.Obsolete(RedbDeprecation.PermissionsAndRoles)] Task GetPermissionCountAsync(CancellationToken cancellationToken = default); /// /// Get user permission count. /// /// User /// Number of user permissions /// Cancels the operation (OCE only; a rollback in flight always completes). [System.Obsolete(RedbDeprecation.PermissionsAndRoles)] Task GetUserPermissionCountAsync(IRedbUser user, CancellationToken cancellationToken = default); /// /// Get role permission count. /// /// Role /// Number of role permissions /// Cancels the operation (OCE only; a rollback in flight always completes). [System.Obsolete(RedbDeprecation.PermissionsAndRoles)] Task GetRolePermissionCountAsync(IRedbRole role, CancellationToken cancellationToken = default); //=== Low-level access [System.Obsolete(RedbDeprecation.PermissionsAndRoles)] Task CanUserEditObject(long objectId, long userId, CancellationToken cancellationToken = default); [System.Obsolete(RedbDeprecation.PermissionsAndRoles)] Task CanUserSelectObject(long objectId, long userId, CancellationToken cancellationToken = default); /// /// Synchronous for the /// thread-pool-free lazy path (the sync getter of RedbListItem.Object). The default falls /// back to blocking on the async form; the in-tree base provider overrides with a true /// sync SQL call on the calling thread. /// [System.Obsolete(RedbDeprecation.PermissionsAndRoles)] bool CanUserSelectObjectSync(long objectId, long userId) => CanUserSelectObject(objectId, userId).ConfigureAwait(false).GetAwaiter().GetResult(); [System.Obsolete(RedbDeprecation.PermissionsAndRoles)] Task CanUserInsertScheme(long schemeId, long userId, CancellationToken cancellationToken = default); [System.Obsolete(RedbDeprecation.PermissionsAndRoles)] Task CanUserDeleteObject(long objectId, long userId, CancellationToken cancellationToken = default); /// /// The objects of the user may read, by the rule of /// for each, answered at once. The tree loads /// check a whole subtree this way. The default asks the single check per object; the in-tree base provider /// answers with one query. /// async Task> GetSelectableObjectIdsAsync(IReadOnlyCollection objectIds, long userId, CancellationToken cancellationToken = default) { var selectable = new HashSet(); foreach (var objectId in objectIds) if (await CanUserSelectObject(objectId, userId, cancellationToken)) selectable.Add(objectId); return selectable; } } } Path: redb/redb.Core/Providers/IQueryProvider.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/IQueryProvider.cs ---- using redb.Core.Query; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using redb.Core.Models.Contracts; namespace redb.Core.Providers { /// /// Provider for creating LINQ queries (high-level API). /// public interface IQueryableProvider { /// /// Create type-safe query by type (synchronous). /// IRedbQueryable Query() where TProps : class, new(); /// /// Create type-safe query by type with specified user (synchronous). /// IRedbQueryable Query(IRedbUser user) where TProps : class, new(); // ===== TREE LINQ QUERIES ===== /// /// Create type-safe tree query by type (synchronous). /// Supports hierarchical operators: WhereHasAncestor, WhereHasDescendant, WhereLevel, WhereRoots, WhereLeaves. /// IRedbQueryable TreeQuery() where TProps : class, new(); /// /// Create type-safe tree query by type with specified user (synchronous). /// Supports hierarchical operators: WhereHasAncestor, WhereHasDescendant, WhereLevel, WhereRoots, WhereLeaves. /// IRedbQueryable TreeQuery(IRedbUser user) where TProps : class, new(); // ===== TREE LINQ WITH SUBTREE LIMITATION ===== // ===== SYNCHRONOUS VERSIONS ===== /// /// Create tree query limited to subtree (synchronous, by ID). /// Search will be performed only among descendants of specified rootObjectId. /// IRedbQueryable TreeQuery(long rootObjectId, int? maxDepth = null) where TProps : class, new(); /// /// Create tree query limited to subtree (synchronous). /// If rootObject = null, returns empty queryable (more convenient for client code). /// IRedbQueryable TreeQuery(IRedbObject? rootObject, int? maxDepth = null) where TProps : class, new(); /// /// Create tree query limited to subtrees of object list (synchronous). /// If list empty, returns empty queryable (more convenient for client code). /// IRedbQueryable TreeQuery(IEnumerable rootObjects, int? maxDepth = null) where TProps : class, new(); /// /// Create tree query limited to subtrees by ID list (synchronous). /// If list empty, returns empty queryable. /// IRedbQueryable TreeQuery(IEnumerable rootObjectIds, int? maxDepth = null) where TProps : class, new(); /// /// Create tree query limited to subtree with specified user (synchronous, by ID). /// Search will be performed only among descendants of specified rootObjectId. /// IRedbQueryable TreeQuery(long rootObjectId, IRedbUser user, int? maxDepth = null) where TProps : class, new(); /// /// Create tree query limited to subtree with specified user (synchronous). /// If rootObject = null, returns empty queryable (more convenient for client code). /// IRedbQueryable TreeQuery(IRedbObject? rootObject, IRedbUser user, int? maxDepth = null) where TProps : class, new(); /// /// Create tree query limited to subtrees of object list with specified user (synchronous). /// If list empty, returns empty queryable (more convenient for client code). /// IRedbQueryable TreeQuery(IEnumerable rootObjects, IRedbUser user, int? maxDepth = null) where TProps : class, new(); /// /// Create tree query limited to subtrees by ID list with specified user (synchronous). /// If list empty, returns empty queryable. /// IRedbQueryable TreeQuery(IEnumerable rootObjectIds, IRedbUser user, int? maxDepth = null) where TProps : class, new(); } } Path: redb/redb.Core/Providers/IRoleProvider.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/IRoleProvider.cs ---- using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using redb.Core.Models.Contracts; using redb.Core.Models.Roles; namespace redb.Core.Providers { /// /// Provider for user role management. /// Provides CRUD operations for roles and user-role relationship management. /// [System.Obsolete(RedbDeprecation.PermissionsAndRoles)] public interface IRoleProvider { // === ROLE CRUD === /// /// Create new role. /// /// Role creation data /// Current user (for audit) /// Created role /// Cancels the operation (OCE only; a rollback in flight always completes). Task CreateRoleAsync(CreateRoleRequest request, IRedbUser? currentUser = null, CancellationToken cancellationToken = default); /// /// Update role. /// /// Role to update /// New role name /// Current user (for audit) /// Updated role /// Cancels the operation (OCE only; a rollback in flight always completes). Task UpdateRoleAsync(IRedbRole role, string newName, IRedbUser? currentUser = null, CancellationToken cancellationToken = default); /// /// Delete role. /// All related permissions are also deleted (cascade). /// /// Role to delete /// Current user (for audit) /// true if role deleted /// Cancels the operation (OCE only; a rollback in flight always completes). Task DeleteRoleAsync(IRedbRole role, IRedbUser? currentUser = null, CancellationToken cancellationToken = default); // === ROLE SEARCH === /// /// Get role by ID. /// /// Role ID /// Role or null if not found /// Cancels the operation (OCE only; a rollback in flight always completes). Task GetRoleByIdAsync(long roleId, CancellationToken cancellationToken = default); /// /// Get role by name. /// /// Role name /// Role or null if not found /// Cancels the operation (OCE only; a rollback in flight always completes). Task GetRoleByNameAsync(string roleName, CancellationToken cancellationToken = default); /// /// Load role by ID (throws exception if not found). /// /// Role ID /// Role /// If role not found /// Cancels the operation (OCE only; a rollback in flight always completes). Task LoadRoleAsync(long roleId, CancellationToken cancellationToken = default); /// /// Load role by name (throws exception if not found). /// /// Role name /// Role /// If role not found /// Cancels the operation (OCE only; a rollback in flight always completes). Task LoadRoleAsync(string roleName, CancellationToken cancellationToken = default); /// /// Get all roles. /// /// List of all roles Task> GetRolesAsync(CancellationToken cancellationToken = default); // === USER-ROLE MANAGEMENT === /// /// Assign role to user. /// /// User /// Role /// Current user (for audit) /// true if role assigned /// Cancels the operation (OCE only; a rollback in flight always completes). Task AssignUserToRoleAsync(IRedbUser user, IRedbRole role, IRedbUser? currentUser = null, CancellationToken cancellationToken = default); /// /// Remove role from user. /// /// User /// Role /// Current user (for audit) /// true if role removed /// Cancels the operation (OCE only; a rollback in flight always completes). Task RemoveUserFromRoleAsync(IRedbUser user, IRedbRole role, IRedbUser? currentUser = null, CancellationToken cancellationToken = default); /// /// Set user roles (replace all existing). /// /// User /// Array of roles /// Current user (for audit) /// true if roles set /// Cancels the operation (OCE only; a rollback in flight always completes). Task SetUserRolesAsync(IRedbUser user, IRedbRole[] roles, IRedbUser? currentUser = null, CancellationToken cancellationToken = default); /// /// Get user roles. /// /// User /// List of user roles /// Cancels the operation (OCE only; a rollback in flight always completes). Task> GetUserRolesAsync(IRedbUser user, CancellationToken cancellationToken = default); /// /// Get role users. /// /// Role /// List of users with this role /// Cancels the operation (OCE only; a rollback in flight always completes). Task> GetRoleUsersAsync(IRedbRole role, CancellationToken cancellationToken = default); /// /// Check if user has role. /// /// User /// Role /// true if user has role /// Cancels the operation (OCE only; a rollback in flight always completes). Task UserHasRoleAsync(IRedbUser user, IRedbRole role, CancellationToken cancellationToken = default); // === VALIDATION === /// /// Check role name availability. /// /// Role name to check /// Role to exclude (for update) /// true if role name available /// Cancels the operation (OCE only; a rollback in flight always completes). Task IsRoleNameAvailableAsync(string roleName, IRedbRole? excludeRole = null, CancellationToken cancellationToken = default); // === STATISTICS === /// /// Get role count. /// /// Number of roles Task GetRoleCountAsync(CancellationToken cancellationToken = default); /// /// Get user count in role. /// /// Role /// Number of users in role /// Cancels the operation (OCE only; a rollback in flight always completes). Task GetRoleUserCountAsync(IRedbRole role, CancellationToken cancellationToken = default); /// /// Get role statistics (role -> user count). /// /// Dictionary role -> user count Task> GetRoleStatisticsAsync(CancellationToken cancellationToken = default); // === CONFIGURATION MANAGEMENT === /// /// Get role configuration ID. /// /// Role ID /// Configuration ID or null if not set /// Cancels the operation (OCE only; a rollback in flight always completes). Task GetRoleConfigurationIdAsync(long roleId, CancellationToken cancellationToken = default); /// /// Set role configuration. /// /// Role ID /// Configuration ID (RedbObject<UserConfigurationProps>) or null to reset /// Cancels the operation (OCE only; a rollback in flight always completes). Task SetRoleConfigurationAsync(long roleId, long? configId, CancellationToken cancellationToken = default); } } Path: redb/redb.Core/Providers/ISchemeSyncProvider.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/ISchemeSyncProvider.cs ---- using System; using System.Threading; using System.Threading.Tasks; using redb.Core.Caching; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using System.Collections.Generic; namespace redb.Core.Providers { /// /// Provider for scheme and structure management (Code-First). /// public interface ISchemeSyncProvider { /// /// Domain-bound metadata cache for this provider. /// GlobalMetadataCache Cache { get; } /// /// Domain-bound list cache for this provider. /// GlobalListCache ListCache { get; } /// /// Domain-bound props/object cache for this provider. /// GlobalPropsCache PropsCache { get; } // ===== METHODS WITH CONTRACTS ===== /// /// Create/get scheme by name from Props type. /// If schemeName = null, uses TProps class name. /// Task EnsureSchemeFromTypeAsync(CancellationToken cancellationToken = default) where TProps : class; /// /// Synchronize scheme structures from Props type (by default deletes extra fields). /// Task> SyncStructuresFromTypeAsync(IRedbScheme scheme, bool strictDeleteExtra = true, CancellationToken cancellationToken = default) where TProps : class; /// /// Simplified scheme synchronization method with auto-detection of name and alias. /// Scheme name and alias determined from RedbSchemeAttribute. /// Task SyncSchemeAsync(CancellationToken cancellationToken = default) where TProps : class; /// /// The structures of 's scheme that the class does not declare (fields it removed, /// or a newer build added), with their stored values. The sync keeps them unless the class raised /// ; this call deletes them on request, under the scheme lock, /// values included. With (the default) it only reports. Refused with /// when the class's version is lower than the database's. /// Task DropUnknownStructuresAsync(bool dryRun = true, CancellationToken cancellationToken = default) where TProps : class; // ===== SCHEME SEARCH ===== /// /// Get scheme by ID. /// Task GetSchemeByIdAsync(long schemeId, CancellationToken cancellationToken = default); /// /// Synchronous for the thread-pool-free load path (the synchronous /// Load<T> and lazy getters): every database call runs on the calling thread. There is no /// blocking fallback over the async form - it would bring the thread pool back into exactly that path. /// IRedbScheme? GetSchemeById(long schemeId) => throw new NotSupportedException( $"{GetType().Name} does not implement the synchronous GetSchemeById that the synchronous load path needs."); /// /// Get scheme by name. /// Task GetSchemeByNameAsync(string schemeName, CancellationToken cancellationToken = default); /// /// Get scheme by C# class type. /// Uses class name for scheme search. /// Task GetSchemeByTypeAsync(CancellationToken cancellationToken = default) where TProps : class; /// /// Get scheme from cache synchronously (no DB call). /// Returns null if not in cache. Use after InitializeAsync() to ensure cache is warm. /// IRedbScheme? GetSchemeFromCache() where TProps : class; /// /// Get scheme from cache synchronously (no DB call). /// Returns null if not in cache. /// IRedbScheme? GetSchemeFromCache(string schemeName); /// /// Get scheme by C# class type. /// Uses class name for scheme search. /// Task GetSchemeByTypeAsync(Type type, CancellationToken cancellationToken = default); /// /// Load scheme by C# class type (throws exception if not found). /// Task LoadSchemeByTypeAsync(CancellationToken cancellationToken = default) where TProps : class; /// /// Load scheme by C# class type (throws exception if not found). /// Task LoadSchemeByTypeAsync(Type type, CancellationToken cancellationToken = default); /// /// Get all schemes. /// Task> GetSchemesAsync(CancellationToken cancellationToken = default); /// /// Get scheme structures. /// Task> GetStructuresAsync(IRedbScheme scheme, CancellationToken cancellationToken = default); /// /// Get scheme structures by C# class type. /// Task> GetStructuresByTypeAsync(CancellationToken cancellationToken = default) where TProps : class; /// /// Get scheme structures by C# class type. /// Task> GetStructuresByTypeAsync(Type type, CancellationToken cancellationToken = default); // ===== SCHEME EXISTENCE CHECKS ===== /// /// Check if scheme exists for C# class type. /// Task SchemeExistsForTypeAsync(CancellationToken cancellationToken = default) where TProps : class; /// /// Check if scheme exists for C# class type. /// Task SchemeExistsForTypeAsync(Type type, CancellationToken cancellationToken = default); /// /// Check if scheme exists by name. /// Task SchemeExistsByNameAsync(string schemeName, CancellationToken cancellationToken = default); // ===== UTILITY METHODS ===== /// /// Get scheme name for C# class type. /// Considers attributes and namespaces. /// string GetSchemeNameForType() where TProps : class; /// /// Get scheme name for C# class type. /// Considers attributes and namespaces. /// string GetSchemeNameForType(Type type); /// /// Get scheme alias for C# class type. /// Extracts from RedbSchemeAttribute. /// string? GetSchemeAliasForType() where TProps : class; /// /// Get scheme alias for C# class type. /// Extracts from RedbSchemeAttribute. /// string? GetSchemeAliasForType(Type type); // ===== OBJECT SCHEME (NON-GENERIC) ===== /// /// Get or create scheme for Object type (without Props). /// Used for non-generic RedbObject that stores only base _objects fields. /// Scheme will have _type = Object (not Class). /// /// Scheme name (e.g. "RedbObject" or custom name) /// Cancels the operation (OCE only; a rollback in flight always completes). Task EnsureObjectSchemeAsync(string name, CancellationToken cancellationToken = default); /// /// Get scheme for Object type by name. /// Returns null if not found. /// Task GetObjectSchemeAsync(string name, CancellationToken cancellationToken = default); // ===== TYPE MIGRATION ===== /// /// Migrate data when changing structure type (e.g. String -> Long). /// Moves data from old type column to new type column. /// /// Structure ID to migrate /// Old type name (e.g. "String") /// New type name (e.g. "Long") /// If true, only returns count without actual migration /// Migration result with affected rows count /// Cancels the operation (OCE only; a rollback in flight always completes). Task MigrateStructureTypeAsync(long structureId, string oldTypeName, string newTypeName, bool dryRun = false, CancellationToken cancellationToken = default); /// /// Recompute the stored unique keys of one [RedbUnique] property and report duplicates /// (rows left outside the unique index). The automatic triggers run the same algorithm at /// scheme synchronisation; this is the explicit form (UNIQUE plan 2.8). /// Task RecomputeUniqueAsync(string propertyName, CancellationToken cancellationToken = default) where TProps : class; // ===== STRUCTURE TREE CACHE ===== /// /// Get structure tree for scheme (cached). /// Task> GetStructureTreeAsync(long schemeId, CancellationToken cancellationToken = default); /// /// Get subtree starting from parent structure (cached). /// Task> GetSubtreeAsync(long schemeId, long? parentStructureId, CancellationToken cancellationToken = default); /// /// Invalidate structure tree cache for scheme. /// void InvalidateStructureTreeCache(long schemeId); /// /// Get structure tree cache statistics. /// (int TreesCount, int SubtreesCount, long MemoryEstimate) GetStructureTreeCacheStats(); } /// /// Result of data type migration. /// public class TypeMigrationResult { public int AffectedRows { get; set; } public int SuccessCount { get; set; } public int ErrorCount { get; set; } public string? Errors { get; set; } } } Path: redb/redb.Core/Providers/ITreeProvider.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/ITreeProvider.cs ---- using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace redb.Core.Providers { /// /// Provider for tree structure operations. /// Permission checks managed centrally via configuration (similar to IObjectStorageProvider). /// public interface ITreeProvider { // ===== BASE METHODS (use _securityContext and configuration) ===== /// /// Load tree/subtree by root object ID (uses _securityContext and config.DefaultCheckPermissionsOnLoad). /// Loads root object and all its children recursively. /// Task> LoadTreeAsync(long rootObjectId, int? maxDepth = null, CancellationToken cancellationToken = default) where TProps : class, new(); /// /// Load tree/subtree (uses _securityContext and config.DefaultCheckPermissionsOnLoad). /// Task> LoadTreeAsync(IRedbObject rootObj, int? maxDepth = null, CancellationToken cancellationToken = default) where TProps : class, new(); /// /// Get direct children of object (uses _securityContext and config.DefaultCheckPermissionsOnLoad). /// Task>> GetChildrenAsync(IRedbObject parentObj, CancellationToken cancellationToken = default) where TProps : class, new(); /// /// Get path from object to root (uses _securityContext and config.DefaultCheckPermissionsOnLoad). /// Task>> GetPathToRootAsync(IRedbObject obj, CancellationToken cancellationToken = default) where TProps : class, new(); /// /// Get all object descendants (uses _securityContext and config.DefaultCheckPermissionsOnLoad). /// Task>> GetDescendantsAsync(IRedbObject parentObj, int? maxDepth = null, CancellationToken cancellationToken = default) where TProps : class, new(); /// /// Move object in tree (uses _securityContext and config.DefaultCheckPermissionsOnSave). /// Task MoveObjectAsync(IRedbObject obj, IRedbObject? newParentObj, CancellationToken cancellationToken = default); /// /// Create child object (uses _securityContext and config.DefaultCheckPermissionsOnSave). /// Task CreateChildAsync(TreeRedbObject obj, IRedbObject parentObj, CancellationToken cancellationToken = default) where TProps : class, new(); /// /// Delete object subtree recursively (uses _securityContext and config.DefaultCheckPermissionsOnDelete). /// Task DeleteSubtreeAsync(IRedbObject parentObj, CancellationToken cancellationToken = default); // ===== OVERLOADS WITH EXPLICIT USER (use configuration) ===== /// /// Load tree/subtree by root object ID with explicit user (uses config.DefaultCheckPermissionsOnLoad). /// Task> LoadTreeAsync(long rootObjectId, IRedbUser user, int? maxDepth = null, CancellationToken cancellationToken = default) where TProps : class, new(); /// /// Load tree/subtree with explicit user (uses config.DefaultCheckPermissionsOnLoad). /// Task> LoadTreeAsync(IRedbObject rootObj, IRedbUser user, int? maxDepth = null, CancellationToken cancellationToken = default) where TProps : class, new(); /// /// Get direct children of object with explicit user (uses config.DefaultCheckPermissionsOnLoad). /// Task>> GetChildrenAsync(IRedbObject parentObj, IRedbUser user, CancellationToken cancellationToken = default) where TProps : class, new(); /// /// Get path from object to root with explicit user (uses config.DefaultCheckPermissionsOnLoad). /// Task>> GetPathToRootAsync(IRedbObject obj, IRedbUser user, CancellationToken cancellationToken = default) where TProps : class, new(); /// /// Get all object descendants with explicit user (uses config.DefaultCheckPermissionsOnLoad). /// Task>> GetDescendantsAsync(IRedbObject parentObj, IRedbUser user, int? maxDepth = null, CancellationToken cancellationToken = default) where TProps : class, new(); /// /// Move object in tree with explicit user (uses config.DefaultCheckPermissionsOnSave). /// Task MoveObjectAsync(IRedbObject obj, IRedbObject? newParentObj, IRedbUser user, CancellationToken cancellationToken = default); /// /// Create child object with explicit user (uses config.DefaultCheckPermissionsOnSave). /// Task CreateChildAsync(TreeRedbObject obj, IRedbObject parentObj, IRedbUser user, CancellationToken cancellationToken = default) where TProps : class, new(); /// /// Delete object subtree recursively with explicit user (uses config.DefaultCheckPermissionsOnDelete). /// Task DeleteSubtreeAsync(IRedbObject parentObj, IRedbUser user, CancellationToken cancellationToken = default); // ===== POLYMORPHIC METHODS (for mixed trees) ===== /// /// Load polymorphic tree/subtree - supports objects of different schemes in one tree. /// Uses _securityContext and config.DefaultCheckPermissionsOnLoad. /// Task LoadPolymorphicTreeAsync(IRedbObject rootObj, int? maxDepth = null, CancellationToken cancellationToken = default); /// /// Get all direct children of object regardless of their schemes. /// Uses _securityContext and config.DefaultCheckPermissionsOnLoad. /// Task> GetPolymorphicChildrenAsync(IRedbObject parentObj, CancellationToken cancellationToken = default); /// /// Get polymorphic path from object to root - objects can be of different schemes. /// Uses _securityContext and config.DefaultCheckPermissionsOnLoad. /// Task> GetPolymorphicPathToRootAsync(IRedbObject obj, CancellationToken cancellationToken = default); /// /// Get all polymorphic descendants of object regardless of their schemes. /// Uses _securityContext and config.DefaultCheckPermissionsOnLoad. /// Task> GetPolymorphicDescendantsAsync(IRedbObject parentObj, int? maxDepth = null, CancellationToken cancellationToken = default); // ===== POLYMORPHIC METHODS WITH EXPLICIT USER ===== /// /// Load polymorphic tree/subtree with explicit user. /// Uses config.DefaultCheckPermissionsOnLoad. /// Task LoadPolymorphicTreeAsync(IRedbObject rootObj, IRedbUser user, int? maxDepth = null, CancellationToken cancellationToken = default); /// /// Get all direct children of object regardless of their schemes with explicit user. /// Uses config.DefaultCheckPermissionsOnLoad. /// Task> GetPolymorphicChildrenAsync(IRedbObject parentObj, IRedbUser user, CancellationToken cancellationToken = default); /// /// Get polymorphic path from object to root with explicit user. /// Uses config.DefaultCheckPermissionsOnLoad. /// Task> GetPolymorphicPathToRootAsync(IRedbObject obj, IRedbUser user, CancellationToken cancellationToken = default); /// /// Get all polymorphic descendants of object with explicit user. /// Uses config.DefaultCheckPermissionsOnLoad. /// Task> GetPolymorphicDescendantsAsync(IRedbObject parentObj, IRedbUser user, int? maxDepth = null, CancellationToken cancellationToken = default); // ===== POLYMORPHISM INITIALIZATION ===== /// /// Initialize AutomaticTypeRegistry for polymorphic operation support. /// Should be called at application startup. /// Task InitializeTypeRegistryAsync(CancellationToken cancellationToken = default); } } Path: redb/redb.Core/Providers/IUserProvider.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/IUserProvider.cs ---- using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using redb.Core.Models.Contracts; using redb.Core.Models.Users; namespace redb.Core.Providers { /// /// Provider for user management. /// Provides CRUD operations and business logic for working with users. /// public interface IUserProvider { // === CRUD OPERATIONS === /// /// Create new user. /// /// User creation data /// Current user (for audit) /// Created user /// Cancels the operation (OCE only; a rollback in flight always completes). Task CreateUserAsync(CreateUserRequest request, IRedbUser? currentUser = null, CancellationToken cancellationToken = default); /// /// Update user data. /// /// User to update /// New user data /// Current user (for audit) /// Updated user /// Cancels the operation (OCE only; a rollback in flight always completes). Task UpdateUserAsync(IRedbUser user, UpdateUserRequest request, IRedbUser? currentUser = null, CancellationToken cancellationToken = default); /// /// Delete user (soft delete - deactivation). /// System users (ID 0, 1) cannot be deleted. /// /// User to delete /// Current user (for audit) /// true if user deleted /// Cancels the operation (OCE only; a rollback in flight always completes). Task DeleteUserAsync(IRedbUser user, IRedbUser? currentUser = null, CancellationToken cancellationToken = default); // === SEARCH AND RETRIEVAL === /// /// Get user by ID. /// /// User ID /// User or null if not found /// Cancels the operation (OCE only; a rollback in flight always completes). Task GetUserByIdAsync(long userId, CancellationToken cancellationToken = default); /// /// Get multiple users by IDs in a single query. /// Task> GetUsersByIdsAsync(IEnumerable userIds, CancellationToken cancellationToken = default); /// /// Get user by login. /// /// User login /// User or null if not found /// Cancels the operation (OCE only; a rollback in flight always completes). Task GetUserByLoginAsync(string login, CancellationToken cancellationToken = default); /// /// Get the first user whose _email matches the supplied address /// (case-insensitive). Email is NOT enforced unique at the schema level — /// one address may legitimately be reused after a prior account is soft-deleted /// or whoever owned it changed their address. Callers that need a uniqueness /// invariant (e.g. federation-conflict probes) should still verify the result /// against their own policy. /// /// Email address to search by. Whitespace and surrounding /// punctuation are NOT trimmed — pass a canonicalised value. /// First matching active user, or null when no row matches. /// Cancels the operation (OCE only; a rollback in flight always completes). Task GetUserByEmailAsync(string email, CancellationToken cancellationToken = default); /// /// Load user by login (throws exception if not found). /// /// User login /// User /// If user not found /// Cancels the operation (OCE only; a rollback in flight always completes). Task LoadUserAsync(string login, CancellationToken cancellationToken = default); /// /// Load user by ID (throws exception if not found). /// /// User ID /// User /// If user not found /// Cancels the operation (OCE only; a rollback in flight always completes). Task LoadUserAsync(long userId, CancellationToken cancellationToken = default); /// /// Get list of users with filtering. /// /// Search criteria (can be null) /// List of users /// Cancels the operation (OCE only; a rollback in flight always completes). Task> GetUsersAsync(UserSearchCriteria? criteria = null, CancellationToken cancellationToken = default); /// /// Count users matching criteria without loading data. /// Task CountUsersAsync(UserSearchCriteria? criteria = null, CancellationToken cancellationToken = default); // === AUTHENTICATION === /// /// Validate user login and password. /// /// Login /// Password (plain text) /// User if credentials valid, null if invalid /// Cancels the operation (OCE only; a rollback in flight always completes). Task ValidateUserAsync(string login, string password, CancellationToken cancellationToken = default); /// /// Change user password. /// /// User /// Current password (for verification) /// New password /// Current user (for audit) /// true if password changed /// Cancels the operation (OCE only; a rollback in flight always completes). Task ChangePasswordAsync(IRedbUser user, string currentPassword, string newPassword, IRedbUser? currentUser = null, CancellationToken cancellationToken = default); /// /// Set new password for user (without checking old password). /// For administrators only. /// /// User /// New password /// Current user (for audit) /// true if password set /// Cancels the operation (OCE only; a rollback in flight always completes). Task SetPasswordAsync(IRedbUser user, string newPassword, IRedbUser? currentUser = null, CancellationToken cancellationToken = default); /// /// Store a password hash computed elsewhere, for example an administrator password given in /// configuration as a hash rather than in plain text. The hash is written as is, so it must be /// one the configured verifies: with the /// default hasher, a BCrypt hash ($2a$, $2b$ or $2y$). /// Same access rules as . /// /// User /// Password hash /// Current user (for audit) /// true if the hash was stored /// Cancels the operation (OCE only; a rollback in flight always completes). Task SetPasswordHashAsync(IRedbUser user, string passwordHash, IRedbUser? currentUser = null, CancellationToken cancellationToken = default) => throw new NotSupportedException($"{GetType().Name} does not support setting a password hash."); // === STATUS MANAGEMENT === /// /// Activate user. /// /// User /// Current user (for audit) /// true if user activated /// Cancels the operation (OCE only; a rollback in flight always completes). Task EnableUserAsync(IRedbUser user, IRedbUser? currentUser = null, CancellationToken cancellationToken = default); /// /// Deactivate user. /// System users (ID 0, 1) cannot be deactivated. /// /// User /// Current user (for audit) /// true if user deactivated /// Cancels the operation (OCE only; a rollback in flight always completes). Task DisableUserAsync(IRedbUser user, IRedbUser? currentUser = null, CancellationToken cancellationToken = default); // === VALIDATION === /// /// Validate user data correctness. /// /// Data to validate /// Validation result /// Cancels the operation (OCE only; a rollback in flight always completes). Task ValidateUserDataAsync(CreateUserRequest request, CancellationToken cancellationToken = default); /// /// Check login availability. /// /// Login to check /// User ID to exclude (for update) /// true if login available /// Cancels the operation (OCE only; a rollback in flight always completes). Task IsLoginAvailableAsync(string login, long? excludeUserId = null, CancellationToken cancellationToken = default); // === STATISTICS === /// /// Get user count. /// /// Include deactivated users /// Number of users /// Cancels the operation (OCE only; a rollback in flight always completes). Task GetUserCountAsync(bool includeDisabled = false, CancellationToken cancellationToken = default); /// /// Get active user count for period. /// /// Start date /// End date /// Number of active users /// Cancels the operation (OCE only; a rollback in flight always completes). Task GetActiveUserCountAsync(DateTimeOffset fromDate, DateTimeOffset toDate, CancellationToken cancellationToken = default); // === CONFIGURATION MANAGEMENT === /// /// Get user configuration ID. /// /// User ID /// Configuration ID or null if not set /// Cancels the operation (OCE only; a rollback in flight always completes). Task GetUserConfigurationIdAsync(long userId, CancellationToken cancellationToken = default); /// /// Set user configuration. /// /// User ID /// Configuration ID (RedbObject<UserConfigurationProps>) or null to reset /// Cancels the operation (OCE only; a rollback in flight always completes). Task SetUserConfigurationAsync(long userId, long? configId, CancellationToken cancellationToken = default); /// /// Get user roles. /// Used for building effective configuration. /// /// User ID /// List of user roles /// Cancels the operation (OCE only; a rollback in flight always completes). Task> GetUserRolesAsync(long userId, CancellationToken cancellationToken = default); } } Path: redb/redb.Core/Providers/IValidationProvider.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/IValidationProvider.cs ---- using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using redb.Core.Models.Contracts; namespace redb.Core.Providers { /// /// Schema validation result. /// public class SchemaValidationResult { public bool IsValid { get; set; } public List Issues { get; set; } = new(); public SchemaChangeReport? ChangeReport { get; set; } } /// /// Validation issue. /// public class ValidationIssue { public ValidationSeverity Severity { get; set; } public string PropertyName { get; set; } = string.Empty; public string Message { get; set; } = string.Empty; public string? SuggestedFix { get; set; } } /// /// Validation issue severity level. /// public enum ValidationSeverity { Info, Warning, Error } /// /// Schema change report. /// public class SchemaChangeReport { public List Changes { get; set; } = new(); public bool HasBreakingChanges { get; set; } } /// /// Structure change. /// public class StructureChange { public ChangeType Type { get; set; } public string PropertyName { get; set; } = string.Empty; public string? OldValue { get; set; } public string? NewValue { get; set; } public bool IsBreaking { get; set; } } /// /// Change type. /// public enum ChangeType { Added, Removed, Modified, TypeChanged, NullabilityChanged, ArrayChanged } /// /// Supported type information. /// public class SupportedType { public string Name { get; set; } = string.Empty; public string DbType { get; set; } = string.Empty; public string DotNetType { get; set; } = string.Empty; public long Id { get; set; } public bool SupportsArrays { get; set; } = true; public bool SupportsNullability { get; set; } = true; public string? Description { get; set; } } /// /// Provider for schema and type validation. /// public interface IValidationProvider { /// /// Get all supported types. /// Task> GetSupportedTypesAsync(CancellationToken cancellationToken = default); /// /// Validate C# type correspondence with REDB supported types. /// Task ValidateTypeAsync(Type csharpType, string propertyName, CancellationToken cancellationToken = default); /// /// Validate schema before synchronization. /// Task ValidateSchemaAsync(string schemeName, bool strictDeleteExtra = true, CancellationToken cancellationToken = default) where TProps : class; /// /// Validate schema before synchronization (with contract). /// Task ValidateSchemaAsync(IRedbScheme scheme, bool strictDeleteExtra = true, CancellationToken cancellationToken = default) where TProps : class; /// /// Check schema change compatibility. /// Task AnalyzeSchemaChangesAsync(IRedbScheme scheme, CancellationToken cancellationToken = default) where TProps : class; /// /// Validate property constraints and arrays. /// ValidationIssue? ValidatePropertyConstraints(Type propertyType, string propertyName, bool isRequired, bool isArray); } } Path: redb/redb.Core/Query/Aggregation/Agg.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/Query/Aggregation/Agg.cs ---- namespace redb.Core.Query.Aggregation; /// /// Static helper for creating aggregate expressions in Select /// Allows writing: .Select(x => new { Total = Agg.Sum(x.Props.Price) }) /// public static class Agg { /// /// Sum of field values /// /// /// .Select(x => new { Total = Agg.Sum(x.Props.Price) }) /// .Select(x => new { ItemsTotal = Agg.Sum(x.Props.Items.Select(i => i.Price)) }) /// public static decimal Sum(decimal value) => throw new NotSupportedException("Agg.Sum must be processed in ProjectionFieldExtractor"); public static decimal Sum(decimal? value) => throw new NotSupportedException("Agg.Sum must be processed in ProjectionFieldExtractor"); public static long Sum(long value) => throw new NotSupportedException("Agg.Sum must be processed in ProjectionFieldExtractor"); public static long Sum(long? value) => throw new NotSupportedException("Agg.Sum must be processed in ProjectionFieldExtractor"); public static int Sum(int value) => throw new NotSupportedException("Agg.Sum must be processed in ProjectionFieldExtractor"); public static int Sum(int? value) => throw new NotSupportedException("Agg.Sum must be processed in ProjectionFieldExtractor"); public static double Sum(double value) => throw new NotSupportedException("Agg.Sum must be processed in ProjectionFieldExtractor"); public static double Sum(double? value) => throw new NotSupportedException("Agg.Sum must be processed in ProjectionFieldExtractor"); /// /// Sum of values from a collection (for arrays) /// public static decimal Sum(IEnumerable values) => throw new NotSupportedException("Agg.Sum must be processed in ProjectionFieldExtractor"); public static decimal Sum(IEnumerable values) => throw new NotSupportedException("Agg.Sum must be processed in ProjectionFieldExtractor"); public static long Sum(IEnumerable values) => throw new NotSupportedException("Agg.Sum must be processed in ProjectionFieldExtractor"); public static int Sum(IEnumerable values) => throw new NotSupportedException("Agg.Sum must be processed in ProjectionFieldExtractor"); public static double Sum(IEnumerable values) => throw new NotSupportedException("Agg.Sum must be processed in ProjectionFieldExtractor"); /// /// Average value of a field /// public static decimal Average(decimal value) => throw new NotSupportedException("Agg.Average must be processed in ProjectionFieldExtractor"); public static decimal Average(decimal? value) => throw new NotSupportedException("Agg.Average must be processed in ProjectionFieldExtractor"); public static double Average(long value) => throw new NotSupportedException("Agg.Average must be processed in ProjectionFieldExtractor"); public static double Average(int value) => throw new NotSupportedException("Agg.Average must be processed in ProjectionFieldExtractor"); public static double Average(double value) => throw new NotSupportedException("Agg.Average must be processed in ProjectionFieldExtractor"); /// /// Average value from a collection (for arrays) /// public static decimal Average(IEnumerable values) => throw new NotSupportedException("Agg.Average must be processed in ProjectionFieldExtractor"); public static double Average(IEnumerable values) => throw new NotSupportedException("Agg.Average must be processed in ProjectionFieldExtractor"); public static double Average(IEnumerable values) => throw new NotSupportedException("Agg.Average must be processed in ProjectionFieldExtractor"); public static double Average(IEnumerable values) => throw new NotSupportedException("Agg.Average must be processed in ProjectionFieldExtractor"); /// /// Minimum value of a field /// public static T Min(T value) => throw new NotSupportedException("Agg.Min must be processed in ProjectionFieldExtractor"); /// /// Minimum value from a collection /// public static T Min(IEnumerable values) => throw new NotSupportedException("Agg.Min must be processed in ProjectionFieldExtractor"); /// /// Maximum value of a field /// public static T Max(T value) => throw new NotSupportedException("Agg.Max must be processed in ProjectionFieldExtractor"); /// /// Maximum value from a collection /// public static T Max(IEnumerable values) => throw new NotSupportedException("Agg.Max must be processed in ProjectionFieldExtractor"); /// /// Count of elements in a collection /// public static int Count(IEnumerable values) => throw new NotSupportedException("Agg.Count must be processed in ProjectionFieldExtractor"); /// /// Count of records (COUNT(*)) /// public static int Count() => throw new NotSupportedException("Agg.Count must be processed in AggregateAsync"); // ===== GROUPBY OVERLOADS ===== /// /// Sum in a group: Agg.Sum(g, x => x.Stock) /// public static TValue Sum(Grouping.IRedbGrouping group, System.Linq.Expressions.Expression> selector) => throw new NotSupportedException("Agg.Sum for GroupBy"); /// /// Average in a group: Agg.Average(g, x => x.Age) /// public static double Average(Grouping.IRedbGrouping group, System.Linq.Expressions.Expression> selector) => throw new NotSupportedException("Agg.Average for GroupBy"); /// /// Minimum in a group: Agg.Min(g, x => x.Price) /// public static TValue Min(Grouping.IRedbGrouping group, System.Linq.Expressions.Expression> selector) => throw new NotSupportedException("Agg.Min for GroupBy"); /// /// Maximum in a group: Agg.Max(g, x => x.Price) /// public static TValue Max(Grouping.IRedbGrouping group, System.Linq.Expressions.Expression> selector) => throw new NotSupportedException("Agg.Max for GroupBy"); /// /// Count in a group: Agg.Count(g) /// public static int Count(Grouping.IRedbGrouping group) => throw new NotSupportedException("Agg.Count for GroupBy"); /// /// Count of the members of a group that satisfy a condition: Agg.Count(g, c => c.IsVerified). /// Works in SelectAsync and in Having, for GroupBy, GroupByArray and their tree forms. The condition may /// compare fields with constants or with each other, combine comparisons with &&, || and !, test a /// field for null and use a boolean field alone. /// public static int Count( Grouping.IRedbGrouping group, System.Linq.Expressions.Expression> predicate) => throw new NotSupportedException("Agg.Count for GroupBy"); } Path: redb/redb.Core/Query/Aggregation/AggregateFunction.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/Query/Aggregation/AggregateFunction.cs ---- namespace redb.Core.Query.Aggregation; /// /// Aggregate function types for EAV fields. /// public enum AggregateFunction { /// Sum of numeric values Sum, /// Arithmetic average Average, /// Minimum value Min, /// Maximum value Max, /// Record count Count } Path: redb/redb.Core/Query/Aggregation/AggregateRequest.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/Query/Aggregation/AggregateRequest.cs ---- using System.Collections.Generic; using redb.Core.Query.Utils; namespace redb.Core.Query.Aggregation; /// /// Request for batch aggregation of multiple fields. /// public class AggregateRequest { /// Field path (e.g. "Price" or "Items[].Price") public string FieldPath { get; set; } = ""; /// Aggregation function public AggregateFunction Function { get; set; } /// Result alias public string? Alias { get; set; } /// /// Condition of a conditional count (Agg.Count(g, x => x.IsVerified)): a boolean expression in the JSON /// form HAVING uses ($and/$or/$not, $eq/$ne/$gt/$gte/$lt/$lte, $isnull/$notnull, /// $field, $const). Null for an aggregate without a condition. Only /// carries one. /// public string? ConditionJson { get; set; } /// /// True when the path names a field of the object itself (x.Id, x.Name) and not a Props field. /// The path alone cannot tell: x.Props.Name and x.Name both read "Name". A path marked "0$:" is a /// base field whatever this says. /// public bool IsBaseField { get; set; } /// /// Whether an aggregate argument reads a field of the object itself: a member chain that starts /// at a parameter typed as the object and does not pass through its Props. x.Id does, /// x.Props.Id and anything under a parameter typed as Props do not. /// public static bool ReadsObjectField(System.Linq.Expressions.Expression? expression) { var current = StripConvert(expression); if (current is not System.Linq.Expressions.MemberExpression) return false; var throughProps = false; while (current is System.Linq.Expressions.MemberExpression member) { if (member.Member.Name == "Props") throughProps = true; current = StripConvert(member.Expression); } return !throughProps && current is System.Linq.Expressions.ParameterExpression parameter && typeof(redb.Core.Models.Contracts.IRedbObject).IsAssignableFrom(parameter.Type); } private static System.Linq.Expressions.Expression? StripConvert(System.Linq.Expressions.Expression? expression) { while (expression is System.Linq.Expressions.UnaryExpression { NodeType: System.Linq.Expressions.ExpressionType.Convert or System.Linq.Expressions.ExpressionType.ConvertChecked } unary) { expression = unary.Operand; } return expression; } } /// /// Batch aggregation result. /// public class AggregateResult { /// Results by aliases public Dictionary Values { get; set; } = new(); /// Get value by alias public T? Get(string alias) where T : struct { if (Values.TryGetValue(alias, out var value) && value != null) { return (T)TemporalDecoder.ChangeType(value, typeof(T)); } return null; } /// Get value by alias (nullable) public T? GetNullable(string alias) where T : struct { if (Values.TryGetValue(alias, out var value)) { if (value == null) return null; return (T)TemporalDecoder.ChangeType(value, typeof(T)); } return null; } } Path: redb/redb.Core/Query/Aggregation/AggregateSelectorParser.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/Query/Aggregation/AggregateSelectorParser.cs ---- using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; namespace redb.Core.Query.Aggregation; /// /// Reads the aggregate requests of an AggregateAsync selector (x => new { A = Agg.Sum(x.Props.Price), ... }). /// runs what it returns, and the SQL preview of the /// aggregate (ToAggregateSqlStringAsync) builds its statement from the same requests. /// internal static class AggregateSelectorParser { /// One request per call of the anonymous type, aliased by its member name. public static List Parse(LambdaExpression selector) { var result = new List(); if (selector.Body is not NewExpression newExpr) return result; for (var i = 0; i < newExpr.Arguments.Count; i++) { if (newExpr.Arguments[i] is not MethodCallExpression methodCall || methodCall.Method.DeclaringType != typeof(Agg)) continue; var function = methodCall.Method.Name switch { "Sum" => AggregateFunction.Sum, "Average" => AggregateFunction.Average, "Min" => AggregateFunction.Min, "Max" => AggregateFunction.Max, "Count" => AggregateFunction.Count, _ => throw new NotSupportedException($"Unknown aggregation: {methodCall.Method.Name}") }; var fieldPath = "*"; // Count() var isBaseField = false; if (methodCall.Arguments.Count > 0) { fieldPath = ExtractFieldPath(methodCall.Arguments[0]); isBaseField = AggregateRequest.ReadsObjectField(methodCall.Arguments[0]); } result.Add(new AggregateRequest { FieldPath = fieldPath, Function = function, Alias = newExpr.Members?[i].Name ?? $"Item{i}", IsBaseField = isBaseField }); } return result; } /// /// The field path of an aggregated value. Every single aggregate (SumAsync, AverageAsync, MinAsync, MaxAsync, /// GetStatisticsAsync) and every Agg.* call of AggregateAsync read their path here: /// x.Props.Price → "Price" /// x.Props.Customer.Name → "Customer.Name" /// x.Props.Score.Value → "Score" (the Value of a nullable is the nullable) /// x.Props.Items[2].Price → "Items[2].Price" (specific index) /// x.Props.Items.Select(i => i.Price) → "Items[].Price" (all elements) /// x.Props.PhoneBook["home"] → "PhoneBook[home]" (Dictionary key) /// x.Props.Scores["a"].Value → "Scores[a]" /// x.Props.PhoneBook.Values → "PhoneBook[]" (all Dictionary values) /// A path that is not such a chain from the parameter of the selector (a method call, a value of the caller, a /// conditional) is refused with : it used to be cut at the first node the walk /// did not know, and the aggregate read another field (Items[0].Rank as the object's own Rank). /// public static string ExtractFieldPath(Expression expr) { var parts = new List(); Walk(expr, expr, parts); if (parts.Count == 0) throw new NotSupportedException(Parsing.BaseFilterExpressionParser.UnsupportedFieldPathMessage(expr)); return string.Join(".", parts); } private static void Walk(Expression? expr, Expression whole, List parts) { switch (expr) { case UnaryExpression { NodeType: ExpressionType.Convert or ExpressionType.ConvertChecked } convert: Walk(convert.Operand, whole, parts); return; // The start of the chain: the parameter of the selector, or of a Select lambda inside it. case ParameterExpression: return; // x.Props of the object: the Props of a RedbObject add no part. case MemberExpression { Member.Name: "Props", Expression: ParameterExpression parameter } when typeof(redb.Core.Models.Contracts.IRedbObject).IsAssignableFrom(parameter.Type): return; // Score.Value of a Nullable is the value of Score: the accessor adds no part. case MemberExpression { Member.Name: "Value", Expression: { } nullable } when Nullable.GetUnderlyingType(nullable.Type) != null: Walk(nullable, whole, parts); return; // Dictionary.Values: every value of the dictionary. case MemberExpression { Member.Name: "Values", Expression: { } dictionary } when IsDictionaryType(dictionary.Type): Walk(dictionary, whole, parts); AppendToLast(parts, "[]", whole); return; case MemberExpression { Expression: { } owner } member: Walk(owner, whole, parts); parts.Add(member.Member.Name); return; // Items[2] of an array. case BinaryExpression { NodeType: ExpressionType.ArrayIndex } arrayIndex: Walk(arrayIndex.Left, whole, parts); AppendToLast(parts, $"[{KeyOf(arrayIndex.Right, whole)}]", whole); return; // Items[2] of a list, PhoneBook["home"] of a dictionary. case MethodCallExpression { Method.Name: "get_Item", Object: { } indexed } indexer when indexer.Arguments.Count == 1: Walk(indexed, whole, parts); AppendToLast(parts, $"[{KeyOf(indexer.Arguments[0], whole)}]", whole); return; // Items.ElementAt(2). case MethodCallExpression { Method.Name: "ElementAt" } elementAt when elementAt.Method.DeclaringType == typeof(Enumerable): Walk(elementAt.Arguments[0], whole, parts); AppendToLast(parts, $"[{KeyOf(elementAt.Arguments[1], whole)}]", whole); return; // Items.Select(i => i.Price) and Items.Sum(i => i.Price): every element. case MethodCallExpression { Method.Name: "Select" or "Sum" or "Average" or "Min" or "Max" } overElements when overElements.Method.DeclaringType == typeof(Enumerable): Walk(overElements.Arguments[0], whole, parts); AppendToLast(parts, "[]", whole); if (overElements.Arguments.Count > 1 && StripQuote(overElements.Arguments[1]) is LambdaExpression lambda) Walk(lambda.Body, whole, parts); return; default: throw new NotSupportedException(Parsing.BaseFilterExpressionParser.UnsupportedFieldPathMessage(whole)); } } private static Expression StripQuote(Expression e) => e is UnaryExpression { NodeType: ExpressionType.Quote } q ? q.Operand : e; private static void AppendToLast(List parts, string suffix, Expression whole) { if (parts.Count == 0) throw new NotSupportedException(Parsing.BaseFilterExpressionParser.UnsupportedFieldPathMessage(whole)); parts[^1] += suffix; } /// /// An index or a key: a constant, or a value of the caller (a captured variable). A key read from the object /// itself is refused: the path would depend on the row. /// private static string KeyOf(Expression key, Expression whole) { if (ParameterFinder.Contains(key)) throw new NotSupportedException(Parsing.BaseFilterExpressionParser.UnsupportedFieldPathMessage(whole)); var value = key is ConstantExpression constant ? constant.Value : Expression.Lambda>(Expression.Convert(key, typeof(object))).Compile()(); return Convert.ToString(value, System.Globalization.CultureInfo.InvariantCulture) ?? ""; } private sealed class ParameterFinder : ExpressionVisitor { private bool _found; public static bool Contains(Expression e) { var finder = new ParameterFinder(); finder.Visit(e); return finder._found; } protected override Expression VisitParameter(ParameterExpression node) { _found = true; return node; } } /// /// Checks if a type is Dictionary<K,V> or IDictionary<K,V> /// private static bool IsDictionaryType(Type? type) { if (type == null) return false; if (type.IsGenericType) { var genericDef = type.GetGenericTypeDefinition(); if (genericDef == typeof(Dictionary<,>) || genericDef == typeof(IDictionary<,>)) return true; } return type.GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IDictionary<,>)); } } Path: redb/redb.Core/Query/Aggregation/FieldStatistics.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/Query/Aggregation/FieldStatistics.cs ---- namespace redb.Core.Query.Aggregation; /// /// Result of GetStatisticsAsync - all aggregates for field. /// public class FieldStatistics where T : struct { /// Sum of values public decimal Sum { get; set; } /// Average value public decimal Average { get; set; } /// Minimum value public T? Min { get; set; } /// Maximum value public T? Max { get; set; } /// Record count public int Count { get; set; } public override string ToString() { return $"Sum={Sum}, Avg={Average:F2}, Min={Min}, Max={Max}, Count={Count}"; } } Path: redb/redb.Core/Query/Aggregation/Win.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/Query/Aggregation/Win.cs ---- namespace redb.Core.Query.Aggregation; /// /// Static helper for window functions /// Used in Select to create ROW_NUMBER(), RANK(), SUM() OVER(), etc. expressions. /// public static class Win { // ===== RANKING FUNCTIONS ===== /// /// ROW_NUMBER() OVER (...) /// public static long RowNumber() => throw new NotSupportedException("Win.RowNumber must be processed in WindowQueryable"); /// /// RANK() OVER (...) /// public static long Rank() => throw new NotSupportedException("Win.Rank must be processed in WindowQueryable"); /// /// DENSE_RANK() OVER (...) /// public static long DenseRank() => throw new NotSupportedException("Win.DenseRank must be processed in WindowQueryable"); /// /// NTILE(n) OVER (...) /// public static int Ntile(int buckets) => throw new NotSupportedException("Win.Ntile must be processed in WindowQueryable"); // ===== AGGREGATE FUNCTIONS ===== /// /// SUM(field) OVER (...) /// public static decimal Sum(decimal value) => throw new NotSupportedException("Win.Sum must be processed in WindowQueryable"); public static long Sum(long value) => throw new NotSupportedException("Win.Sum must be processed in WindowQueryable"); public static int Sum(int value) => throw new NotSupportedException("Win.Sum must be processed in WindowQueryable"); public static double Sum(double value) => throw new NotSupportedException("Win.Sum must be processed in WindowQueryable"); /// /// AVG(field) OVER (...) /// public static double Avg(decimal value) => throw new NotSupportedException("Win.Avg must be processed in WindowQueryable"); public static double Avg(long value) => throw new NotSupportedException("Win.Avg must be processed in WindowQueryable"); public static double Avg(int value) => throw new NotSupportedException("Win.Avg must be processed in WindowQueryable"); public static double Avg(double value) => throw new NotSupportedException("Win.Avg must be processed in WindowQueryable"); /// /// COUNT(*) OVER (...) /// public static int Count() => throw new NotSupportedException("Win.Count must be processed in WindowQueryable"); /// /// MIN(field) OVER (...) /// public static T Min(T value) => throw new NotSupportedException("Win.Min must be processed in WindowQueryable"); /// /// MAX(field) OVER (...) /// public static T Max(T value) => throw new NotSupportedException("Win.Max must be processed in WindowQueryable"); // ===== OFFSET FUNCTIONS ===== /// /// LAG(field) OVER (...) /// public static T Lag(T value) => throw new NotSupportedException("Win.Lag must be processed in WindowQueryable"); /// /// LEAD(field) OVER (...) /// public static T Lead(T value) => throw new NotSupportedException("Win.Lead must be processed in WindowQueryable"); /// /// FIRST_VALUE(field) OVER (...) /// public static T FirstValue(T value) => throw new NotSupportedException("Win.FirstValue must be processed in WindowQueryable"); /// /// LAST_VALUE(field) OVER (...) /// public static T LastValue(T value) => throw new NotSupportedException("Win.LastValue must be processed in WindowQueryable"); } Path: redb/redb.Core/Query/Base/LazyReferencesQueryScope.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/Query/Base/LazyReferencesQueryScope.cs ---- using System; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using redb.Core.Data; using redb.Core.Models.Configuration; namespace redb.Core.Query.Base; /// /// V4 (LAZY Л2): runs one query execution under a per-query WithLazyReferences override. /// The override rides the same session flag the builders read (): /// armed before the execution, restored to the global option after it. One implementation for the /// flat and the tree providers, so the two cannot drift in how they arm, degrade and restore. /// internal static class LazyReferencesQueryScope { public static async Task RunAsync( IRedbContext context, ISqlDialect sql, RedbServiceConfiguration configuration, ILogger? logger, bool? lazyOverride, Func> execute) { var toggled = false; if (lazyOverride.HasValue && lazyOverride.Value != configuration.EnableLazyReferences) { // A provider without the channel (Pro SQLite has no session mechanism and may run // without the native extension) degrades to the GLOBAL option - loudly, not silently. try { await context.ExecuteScalarAsync(sql.Session_SetLazyRefs(), lazyOverride.Value ? 1 : 0); toggled = true; } catch (Exception ex) { logger?.LogWarning(ex, "WithLazyReferences: the per-query channel is unavailable on this provider; falling back to the global option (recorded L2 boundary)."); } } try { return await execute(); } finally { if (toggled) { // The restore must never replace the execution's own exception: inside an aborted // transaction PostgreSQL refuses every statement (25P02) and would mask the real // fault - and rolls the flag back with the transaction anyway. MSSQL keeps // SESSION_CONTEXT outside transactions, so the restore is attempted and logged. try { await context.ExecuteScalarAsync(sql.Session_SetLazyRefs(), configuration.EnableLazyReferences ? 1 : 0); } catch (Exception ex) { logger?.LogWarning(ex, "WithLazyReferences: could not restore the session flag to the global option after the query."); } } } } } Path: redb/redb.Core/Query/Base/QueryProviderBase.GroupedWindow.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/Query/Base/QueryProviderBase.GroupedWindow.cs ---- using System.Text.Json; using Microsoft.Extensions.Logging; using redb.Core.Query.Aggregation; using redb.Core.Query.Grouping; using redb.Core.Query.QueryExpressions; using redb.Core.Query.Window; namespace redb.Core.Query.Base; /// /// QueryProviderBase: GroupBy + Window Functions /// public abstract partial class QueryProviderBase { /// /// Execute GroupBy with Window Functions. A provider that supports it overrides this; one that does not refuses /// with its own name. /// public virtual Task ExecuteGroupedWindowQueryAsync( long schemeId, IEnumerable groupFields, IEnumerable aggregations, IEnumerable windowFuncs, IEnumerable partitionBy, IEnumerable orderBy, string? filterJson = null, string? havingJson = null, CancellationToken cancellationToken = default) => throw new NotSupportedException($"GroupBy + WithWindow is not supported by {GetType().Name}."); /// /// Execute GroupBy with Window Functions with FilterExpression. /// Free fallback: converts FilterExpression to facet-JSON. /// public virtual Task ExecuteGroupedWindowQueryAsync( long schemeId, IEnumerable groupFields, IEnumerable aggregations, IEnumerable windowFuncs, IEnumerable partitionBy, IEnumerable orderBy, FilterExpression? filter, string? havingJson = null, CancellationToken cancellationToken = default) { var filterJson = filter != null ? _facetBuilder.BuildFacetFilters(filter) : null; return ExecuteGroupedWindowQueryAsync(schemeId, groupFields, aggregations, windowFuncs, partitionBy, orderBy, filterJson, havingJson, cancellationToken); } /// /// SQL preview for GroupBy + Window query. A provider that supports it overrides this; one that does not refuses /// with its own name. /// public virtual Task GetGroupedWindowSqlPreviewAsync( long schemeId, IEnumerable groupFields, IEnumerable aggregations, IEnumerable windowFuncs, IEnumerable partitionBy, IEnumerable orderBy, string? filterJson = null, string? havingJson = null, CancellationToken cancellationToken = default) => throw new NotSupportedException($"GroupBy + WithWindow is not supported by {GetType().Name}."); /// /// SQL preview for GroupBy + Window query with FilterExpression. /// Free fallback: converts FilterExpression to facet-JSON. /// public virtual Task GetGroupedWindowSqlPreviewAsync( long schemeId, IEnumerable groupFields, IEnumerable aggregations, IEnumerable windowFuncs, IEnumerable partitionBy, IEnumerable orderBy, FilterExpression? filter, string? havingJson = null, CancellationToken cancellationToken = default) { var filterJson = filter != null ? _facetBuilder.BuildFacetFilters(filter) : null; return GetGroupedWindowSqlPreviewAsync(schemeId, groupFields, aggregations, windowFuncs, partitionBy, orderBy, filterJson, havingJson, cancellationToken); } /// /// SQL preview of a GroupBy. A provider that supports it overrides this; one that does not refuses with its own name. /// public virtual Task GetGroupBySqlPreviewAsync( long schemeId, IEnumerable groupFields, IEnumerable aggregations, string? filterJson, string? havingJson = null, CancellationToken cancellationToken = default) => throw new NotSupportedException($"GroupBy SQL preview is not supported by {GetType().Name}."); /// /// SQL preview of a GroupBy with FilterExpression. Free fallback: converts FilterExpression to facet-JSON. /// public virtual Task GetGroupBySqlPreviewAsync( long schemeId, IEnumerable groupFields, IEnumerable aggregations, FilterExpression? filter, string? havingJson = null, CancellationToken cancellationToken = default) { var filterJson = filter != null ? _facetBuilder.BuildFacetFilters(filter) : null; return GetGroupBySqlPreviewAsync(schemeId, groupFields, aggregations, filterJson, havingJson, cancellationToken); } } Path: redb/redb.Core/Query/Base/QueryProviderBase.Grouping.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/Query/Base/QueryProviderBase.Grouping.cs ---- using System.Text.Json; using Microsoft.Extensions.Logging; using redb.Core.Query.Aggregation; using redb.Core.Query.Grouping; using redb.Core.Query.QueryExpressions; namespace redb.Core.Query.Base; /// /// QueryProviderBase: GroupBy functionality /// public abstract partial class QueryProviderBase { /// /// GroupBy aggregation with a facet-JSON filter, built by the provider through its v2-pvt module. The base asked /// the legacy aggregate_grouped function, which no shipped dialect has. /// public abstract Task ExecuteGroupedAggregateAsync( long schemeId, IEnumerable groupFields, IEnumerable aggregations, string? filterJson = null, string? havingJson = null, CancellationToken cancellationToken = default); /// /// Performs GroupBy aggregation with FilterExpression (Pro version). /// Free version fallback: converts FilterExpression to facet-JSON and calls the string-based method. /// public virtual async Task ExecuteGroupedAggregateAsync( long schemeId, IEnumerable groupFields, IEnumerable aggregations, FilterExpression? filter, string? havingJson = null, CancellationToken cancellationToken = default) { // Free version fallback: convert FilterExpression to facet-JSON var filterJson = filter != null ? _facetBuilder.BuildFacetFilters(filter) : null; return await ExecuteGroupedAggregateAsync(schemeId, groupFields, aggregations, filterJson, havingJson); } /// /// Grouping over the elements of an array. Every provider that supports GroupByArray overrides it; a provider /// that does not refuses with its own name instead of answering with nothing. /// public virtual Task ExecuteArrayGroupQueryAsync( ArrayGroupQuery query, CancellationToken cancellationToken = default) => throw new NotSupportedException($"GroupByArray is not supported by {GetType().Name}."); /// /// SQL of ; see there. /// public virtual Task GetArrayGroupQuerySqlAsync( ArrayGroupQuery query, CancellationToken cancellationToken = default) => throw new NotSupportedException($"GroupByArray is not supported by {GetType().Name}."); } Path: redb/redb.Core/Query/Base/QueryProviderBase.Window.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/Query/Base/QueryProviderBase.Window.cs ---- using System.Text.Json; using Microsoft.Extensions.Logging; using redb.Core.Query.QueryExpressions; using redb.Core.Query.Window; namespace redb.Core.Query.Base; /// /// QueryProviderBase: Window Functions /// public abstract partial class QueryProviderBase { /// /// A query with window functions and a facet-JSON filter, built by the provider through its v2-pvt module. The /// base asked the legacy query_with_window function, which no shipped dialect has. /// public abstract Task ExecuteWindowQueryAsync( long schemeId, IEnumerable selectFields, IEnumerable windowFuncs, IEnumerable partitionBy, IEnumerable orderBy, string? filterJson = null, string? frameJson = null, int? take = null, int? skip = null, CancellationToken cancellationToken = default); /// /// SQL preview for window query. /// Base implementation returns placeholder (overridden in Pro). /// public virtual Task GetWindowSqlPreviewAsync( long schemeId, IEnumerable selectFields, IEnumerable windowFuncs, IEnumerable partitionBy, IEnumerable orderBy, string? filterJson = null, string? frameJson = null, int? take = null, int? skip = null, CancellationToken cancellationToken = default) { // Base version uses SQL function, no direct SQL preview available return Task.FromResult($"-- Window SQL Preview not available in Open Source version\n-- SchemeId: {schemeId}\n-- Use Pro version for SQL preview"); } /// /// Execute window query with FilterExpression (Pro version). /// Free fallback: converts FilterExpression to facet-JSON. /// public virtual async Task ExecuteWindowQueryAsync( long schemeId, IEnumerable selectFields, IEnumerable windowFuncs, IEnumerable partitionBy, IEnumerable orderBy, FilterExpression? filter, string? frameJson = null, int? take = null, int? skip = null, CancellationToken cancellationToken = default) { var filterJson = filter != null ? _facetBuilder.BuildFacetFilters(filter) : null; return await ExecuteWindowQueryAsync(schemeId, selectFields, windowFuncs, partitionBy, orderBy, filterJson, frameJson, take, skip); } /// /// SQL preview for window query with FilterExpression (Pro version). /// Free: converts FilterExpression to facet-JSON, as the execution does. /// public virtual Task GetWindowSqlPreviewAsync( long schemeId, IEnumerable selectFields, IEnumerable windowFuncs, IEnumerable partitionBy, IEnumerable orderBy, FilterExpression? filter, string? frameJson = null, int? take = null, int? skip = null, CancellationToken cancellationToken = default) { var filterJson = filter != null ? _facetBuilder.BuildFacetFilters(filter) : null; return GetWindowSqlPreviewAsync(schemeId, selectFields, windowFuncs, partitionBy, orderBy, filterJson, frameJson, take, skip, cancellationToken); } } Path: redb/redb.Core/Query/Base/QueryProviderBase.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/Query/Base/QueryProviderBase.cs ---- using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using redb.Core.Data; using redb.Core.Models.Configuration; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using redb.Core.Providers; using redb.Core.Query.Aggregation; using redb.Core.Query.FacetFilters; using redb.Core.Query.Parsing; using redb.Core.Query.QueryExpressions; using redb.Core.Serialization; namespace redb.Core.Query.Base; /// /// Base query provider for executing LINQ queries through the v2-pvt module of the dialect (pvt_build_query_sql). /// Database-specific implementations should inherit and provide ISqlDialect. /// public abstract partial class QueryProviderBase : IRedbQueryProvider, Grouping.IListItemKeySource { // The list provider of the service: the groupings read their list item keys through it (ListItemGroupKeys). IListProvider? Grouping.IListItemKeySource.ListItems { get; set; } protected readonly IRedbContext _context; protected readonly IRedbObjectSerializer _serializer; protected readonly IFilterExpressionParser _filterParser; protected readonly IOrderingExpressionParser _orderingParser; protected readonly IFacetFilterBuilder _facetBuilder; protected readonly ILogger? _logger; protected readonly ILazyPropsLoader? _lazyPropsLoader; protected readonly RedbServiceConfiguration _configuration; protected readonly ISchemeSyncProvider? _schemeSync; protected readonly ISqlDialect _sql; protected QueryProviderBase( IRedbContext context, IRedbObjectSerializer serializer, ISqlDialect dialect, ILazyPropsLoader? lazyPropsLoader = null, RedbServiceConfiguration? configuration = null, ILogger? logger = null, ISchemeSyncProvider? schemeSync = null) { _context = context; _serializer = serializer; _sql = dialect; _lazyPropsLoader = lazyPropsLoader; _configuration = configuration ?? new RedbServiceConfiguration(); _logger = logger; _schemeSync = schemeSync; _filterParser = CreateFilterParser(); _orderingParser = CreateOrderingParser(); _facetBuilder = CreateFacetBuilder(); } /// /// Creates filter expression parser. Override for Pro features. /// protected virtual IFilterExpressionParser CreateFilterParser() => new FilterExpressionParser(); /// /// Creates ordering expression parser. /// protected virtual IOrderingExpressionParser CreateOrderingParser() => new OrderingExpressionParser(); /// /// Creates facet filter builder. /// protected virtual IFacetFilterBuilder CreateFacetBuilder() => new FacetFilterBuilder(_logger); public IRedbQueryable CreateQuery(long schemeId, long? userId = null, bool checkPermissions = false) where TProps : class, new() { var context = new QueryContext(schemeId, userId, checkPermissions); return new RedbQueryable(this, context, _filterParser, _orderingParser, _facetBuilder); } /// /// Hook for Distinct-related feature checks. No-op in OSS — DistinctRedb / /// DistinctBy are evaluated by SQL builders directly and either work or /// surface a concrete error from the dialect. /// protected virtual void CheckProOnlyDistinctFeatures(QueryContext context) where TProps : class, new() { } /// /// Get scheme by ID (for projections) /// public async Task GetSchemeAsync(long schemeId, CancellationToken cancellationToken = default) { if (_schemeSync != null) { return await _schemeSync.GetSchemeByIdAsync(schemeId); } return null; } public async Task ExecuteAsync(Expression expression, Type elementType, CancellationToken cancellationToken = default) { // Extract QueryContext from the expression if (expression is ConstantExpression constantExpr && constantExpr.Value != null) { // Determine operation type by elementType if (elementType == typeof(int)) { return await ExecuteCountAsyncGeneric(constantExpr.Value, cancellationToken); } else if (elementType == typeof(bool)) { return await ExecuteAnyAsyncGeneric(constantExpr.Value, cancellationToken); } else if (elementType.IsGenericType && elementType.GetGenericTypeDefinition() == typeof(List<>)) { return await ExecuteToListAsyncGeneric(constantExpr.Value, cancellationToken); } } throw new NotSupportedException($"Expression type {expression.GetType().Name} with element type {elementType.Name} is not supported"); } private async Task ExecuteCountAsyncGeneric(object contextObj, CancellationToken cancellationToken) { // Use reflection to call the generic method var contextType = contextObj.GetType(); if (contextType.IsGenericType && contextType.GetGenericTypeDefinition() == typeof(QueryContext<>)) { var propsType = contextType.GetGenericArguments()[0]; // Look for the method in the ACTUAL type (to support inheritance in Pro) var method = GetType().GetMethod(nameof(ExecuteCountAsync), System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); var genericMethod = method!.MakeGenericMethod(propsType); var task = (Task)genericMethod.Invoke(this, new object[] { contextObj, cancellationToken })!; return await task; } throw new NotSupportedException($"Unsupported context type: {contextType.Name}"); } private async Task ExecuteAnyAsyncGeneric(object contextObj, CancellationToken cancellationToken) { // Use reflection to call the generic method var contextType = contextObj.GetType(); if (contextType.IsGenericType && contextType.GetGenericTypeDefinition() == typeof(QueryContext<>)) { var propsType = contextType.GetGenericArguments()[0]; // Look for the method in the ACTUAL type (to support inheritance in Pro) var method = GetType().GetMethod(nameof(ExecuteAnyAsync), System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); var genericMethod = method!.MakeGenericMethod(propsType); var task = (Task)genericMethod.Invoke(this, new object[] { contextObj, cancellationToken })!; return await task; } throw new NotSupportedException($"Unsupported context type: {contextType.Name}"); } /// /// Is there at least one object the query returns: the inner statement of the v2-pvt module (no order, no page, /// as a count reads it) under EXISTS, which stops at the first match. It used to count every match and compare /// the count with zero. The queryable answers a paged query by its count and never asks this. /// protected virtual async Task ExecuteAnyAsync(QueryContext context, CancellationToken cancellationToken = default) where TProps : class, new() { RequirePvtPipeline(context, "AnyAsync"); var inner = await BuildPvtInnerSqlAsync(context, forCount: true); var sql = _sql.Query_WrapPvtWithExists(inner) ?? throw new InvalidOperationException("Query_WrapPvtWithExists returned null for a PVT-enabled dialect."); return ExistsResult(await _context.ExecuteScalarAsync(sql, System.Array.Empty(), cancellationToken)); } /// The value of an EXISTS wrapper: a boolean on PostgreSQL, 1 or 0 on SQL Server and SQLite. protected static bool ExistsResult(object? value) => value is not null and not DBNull && Convert.ToBoolean(value, System.Globalization.CultureInfo.InvariantCulture); /// /// The provider compiles over a filter on Props fields. AllAsync then asks /// for the first counterexample (AnyAsync of the set filtered by NotTrue of the predicate) instead of counting the /// set twice. A provider that does not compile it keeps the two counts. /// protected internal virtual bool CompilesNotTrue => false; /// /// AllAsync of over every object of the scheme (the query has no filter of its own), /// answered by the provider in one statement, or null when it has no such form for this predicate; AllAsync then /// goes on as without it. The predicate reads Props fields only. /// protected internal virtual Task TryAllWithoutFilterAsync(QueryContext context, FilterExpression predicate, CancellationToken cancellationToken) where TProps : class, new() => Task.FromResult(null); /// /// An ordering by Props fields keeps the objects without a value for the key and places them as LINQ does (null /// first ascending), ThenBy included. A projection then sends an OrderBy or ThenBy written after Select to the /// source, so a later Take/Skip stays in SQL; otherwise it sorts the projected rows in memory. /// protected internal virtual bool SortsByPropsLikeLinq => false; private async Task ExecuteToListAsyncGeneric(object contextObj, CancellationToken cancellationToken) { // Use reflection to call the generic method var contextType = contextObj.GetType(); if (contextType.IsGenericType && contextType.GetGenericTypeDefinition() == typeof(QueryContext<>)) { var propsType = contextType.GetGenericArguments()[0]; // Look for the method in the ACTUAL type (to support inheritance in Pro) var method = GetType().GetMethod(nameof(ExecuteToListAsync), System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); var genericMethod = method!.MakeGenericMethod(propsType); var lazyOverride = (bool?)contextType.GetProperty("LazyReferences")?.GetValue(contextObj); return await LazyReferencesQueryScope.RunAsync(_context, _sql, _configuration, _logger, lazyOverride, () => (Task)genericMethod.Invoke(this, new object[] { contextObj, propsType, cancellationToken })!); } throw new NotSupportedException($"Unsupported context type: {contextType.Name}"); } /// /// Executes COUNT query. Override in Pro for PVT-based count with computed expressions. /// protected virtual async Task ExecuteCountAsync(QueryContext context, CancellationToken cancellationToken = default) where TProps : class, new() { // The inner SQL comes from pvt_build_query_sql and is counted on the client side. RequirePvtPipeline(context, "A count"); _logger?.LogDebug("PVT Count Query: SchemeId={SchemeId}", context.SchemeId); return await ExecuteCountAsyncPvt(context, cancellationToken); } /// /// A list read and a count run through the v2-pvt module of the dialect. The legacy search functions they fell back /// to (search_objects_with_facets_base and the projection functions) are gone from every shipped dialect. /// private void RequirePvtPipeline(QueryContext context, string what) where TProps : class, new() { if (!CanUsePvtPipeline(context)) throw new NotSupportedException( $"{what} reads through the v2-pvt module, and the dialect {_sql.GetType().Name} has none " + "(Query_BuildPvtSqlFunction returns null)."); } protected virtual async Task ExecuteToListAsync(QueryContext context, Type propsType, CancellationToken cancellationToken = default) where TProps : class, new() { // Pro-only features check CheckProOnlyDistinctFeatures(context); var hasFieldPathsEarly = context.ProjectedFieldPaths != null && context.ProjectedFieldPaths.Count > 0; // v2-pvt native projection path: when there are projected field paths // AND the dialect ships pvt_build_projection_sql. The outer SELECT // yields the requested scalar columns, wrapped into a JSON-row shape // that flows through the standard materializer. if (hasFieldPathsEarly && CanUsePvtProjection(context)) { _logger?.LogDebug("PVT Projection ToList Query: SchemeId={SchemeId}, Paths={Paths}", context.SchemeId, string.Join(",", context.ProjectedFieldPaths!)); return await ExecuteToListAsyncPvtProjection(context, cancellationToken); } // The full-object read. A projection the module cannot build natively reads whole objects here, and the // compiled selector trims them on the client side. RequirePvtPipeline(context, "A list read"); _logger?.LogDebug("PVT ToList Query: SchemeId={SchemeId}", context.SchemeId); return await ExecuteToListAsyncPvt(context, propsType, cancellationToken); } private async Task>> MaterializeResultsFromJson(System.Text.Json.JsonElement[] objects, QueryContext context, CancellationToken cancellationToken = default) where TProps : class, new() { _logger?.LogDebug("MATERIALIZATION: Received {Count} JSON objects for deserialization", objects?.Length ?? 0); // ⏱MEASURING MATERIALIZATION TIME var materializationTimer = System.Diagnostics.Stopwatch.StartNew(); var materializedResults = new List>(); var successCount = 0; var errorCount = 0; if (objects == null || objects.Length == 0) { _logger?.LogDebug("MATERIALIZATION: JSON array is empty or null"); return materializedResults; } foreach (var objElement in objects) { try { // Objects are already in JSON format from get_object_json var objectJson = objElement.GetRawText(); // Filter by access rights if necessary if (context.CheckPermissions && context.UserId.HasValue) { // Extract object ID for rights check if (objElement.TryGetProperty("id", out var idElement)) { var objectId = idElement.GetInt64(); var hasPermission = await CheckUserPermission(objectId, context.UserId.Value, cancellationToken); if (!hasPermission) { continue; // Skip object without access rights } } } // Deserialize object JSON data var redbObject = _serializer.Deserialize(objectJson); materializedResults.Add(redbObject); successCount++; } catch (Exception ex) { // Fail fast on deserialization error - indicates schema/data mismatch var innerMsg = ex.InnerException?.Message ?? ""; var jsonPreview = objElement.GetRawText(); if (jsonPreview.Length > 500) jsonPreview = jsonPreview[..500] + "..."; throw new InvalidOperationException( $"Deserialization failed: {ex.Message} | Inner: {innerMsg} | JSON: {jsonPreview}", ex); } } materializationTimer.Stop(); _logger?.LogDebug("MATERIALIZATION COMPLETED: Success={Success}, Errors={Errors}, Total objects={Total}", successCount, errorCount, materializedResults.Count); _logger?.LogDebug("Materialization JSON → C# objects completed in {ElapsedMs} ms", materializationTimer.ElapsedMilliseconds); // PROJECTION: If SkipPropsLoading = true — skip Props loading completely if (context.SkipPropsLoading) { return materializedResults; } // OPTIMIZATION: Two-phase loading strategy // Phase 1: the objects without their Props (already done above) // Phase 2: Load Props via LoadPropsForManyAsync (with cache check) // if (materializedResults.Count > 0 && _lazyPropsLoader != null) { // BULK load Props via LoadPropsForManyAsync (two-phase loading) // This method checks cache first, then loads only missing objects via get_object_json batch var projectedIds = context.ProjectedStructureIds; var propsLoadTimer = System.Diagnostics.Stopwatch.StartNew(); if (projectedIds != null && projectedIds.Count > 0) { await _lazyPropsLoader.LoadPropsForManyAsync(materializedResults, projectedIds, context.PropsDepth); } else { await _lazyPropsLoader.LoadPropsForManyAsync(materializedResults, context.PropsDepth); } propsLoadTimer.Stop(); _logger?.LogDebug("Props loaded via batch (with cache check) in {ElapsedMs} ms", propsLoadTimer.ElapsedMilliseconds); } // DISTINCT is performed by the SQL statement // No need to filter in memory! return materializedResults; } private async Task CheckUserPermission(long objectId, long userId, CancellationToken cancellationToken) { var sql = _sql.Query_CheckPermissionSql(); var result = await _context.QueryFirstOrDefaultAsync(sql, new object[] { objectId, userId }, cancellationToken); return result?.HasPermission ?? false; } /// /// Forms JSON for the order_by parameter based on sortings from the context /// FIXED: Uses _facetBuilder.BuildOrderBy to support 0$: prefix for base fields /// private string? BuildOrderByJson(QueryContext context) where TProps : class, new() { if (!context.Orderings.Any()) return null; // Using _facetBuilder.BuildOrderBy which correctly handles IsBaseField return _facetBuilder.BuildOrderBy(context.Orderings); } // ============================================================ // === v2-pvt PIPELINE === // Two-step search: ask the DB to BUILD the inner _id-list SQL via // pvt_build_query_sql(), then wrap on the client side. A dialect without // the module (Query_BuildPvtSqlFunction() == null) cannot list or count. // ============================================================ /// /// Returns true when the active dialect exposes the v2-pvt module. /// Projection is applied client-side (see RedbProjectedQueryable.ToListAsync), /// so the PVT pipeline serves projection queries by returning full objects via /// get_object_json — the compiled selector then extracts the requested fields. /// protected virtual bool CanUsePvtPipeline(QueryContext context) where TProps : class, new() { return _sql.Query_BuildPvtSqlFunction() is not null; } /// /// Phase 1: ask the database to build the inner _id-list SQL string. /// When is true the call passes p_limit=NULL, p_offset=0 and no order (used for the /// COUNT/EXISTS wrappers): a count needs no order, and the SQL Server module keeps an order without paging with /// OFFSET 0 ROWS, which would sort the rows only to count them. /// protected async Task BuildPvtInnerSqlAsync( QueryContext context, bool forCount, CancellationToken cancellationToken = default) where TProps : class, new() { var facetFilters = _facetBuilder.BuildFacetFilters(context.Filter); var orderByJson = BuildOrderByJson(context); var parameters = _facetBuilder.BuildQueryParameters(context.Limit, context.Offset); var limit = forCount ? (int?)null : parameters.Limit; var offset = forCount ? 0 : (parameters.Offset ?? 0); // DistinctBy → p_distinct_on jsonb array (PVT engine handles SELECT DISTINCT ON parity) var distinctOnJson = BuildPvtDistinctOnJson(context); var invocation = _sql.Query_BuildPvtSqlInvocation( schemeId : context.SchemeId, limit : limit, offset : offset, maxDepth : context.MaxRecursionDepth ?? 10, distinct : context.IsDistinct, sourceMode : "flat", treeIds : null, hasDistinctOn: distinctOnJson != null); if (invocation is null) throw new InvalidOperationException( "v2-pvt is enabled by dialect but Query_BuildPvtSqlInvocation returned null."); object filterParam = string.IsNullOrEmpty(facetFilters) || facetFilters == "{}" ? (object)DBNull.Value : facetFilters; object orderParam = forCount || string.IsNullOrEmpty(orderByJson) || orderByJson == "null" || orderByJson == "[]" ? (object)DBNull.Value : orderByJson; string? inner; if (distinctOnJson != null) inner = await _context.ExecuteScalarAsync(invocation, new object[] { filterParam, orderParam, distinctOnJson }, cancellationToken); else inner = await _context.ExecuteScalarAsync(invocation, new object[] { filterParam, orderParam }, cancellationToken); if (string.IsNullOrWhiteSpace(inner)) throw new InvalidOperationException( "pvt_build_query_sql returned an empty SQL string for scheme " + context.SchemeId + "."); return inner; } /// Base fields of a DistinctRedb key, by the names the PVT module maps (01_pvt_field_path). private static readonly string[] DistinctRedbFields = ["Name", "ValueLong", "ValueString", "ValueGuid", "ValueBool", "ParentId", "SchemeId", "Note", "Key"]; /// /// The p_distinct_on argument of pvt_build_query_sql for DistinctBy / DistinctByRedb, or null /// when the query has no distinct key. Shared by the flat query and the tree query of the Free providers. /// internal static string? BuildPvtDistinctOnJson(QueryContext context) where TProps : class, new() { // DistinctRedb: one object per value of the object's own columns except the id, the columns the Pro providers // partition by. The flag was set and never read here, so DistinctRedb() returned every object. if (context.IsDistinctRedb && context.DistinctByField == null) return "[" + string.Join(",", DistinctRedbFields.Select(f => "{\"field\":\"0$:" + f + "\"}")) + "]"; if (context.DistinctByField == null) return null; var name = context.DistinctByField.Property.Name; return context.DistinctByIsBaseField ? "[{\"field\":\"0$:" + name + "\"}]" : "[{\"field\":\"" + name + "\"}]"; } /// v2-pvt Count path: COUNT(*) wrapper over the inner _id-list SQL. protected virtual async Task ExecuteCountAsyncPvt(QueryContext context, CancellationToken cancellationToken = default) where TProps : class, new() { var inner = await BuildPvtInnerSqlAsync(context, forCount: true); var wrapped = _sql.Query_WrapPvtWithCount(inner) ?? throw new InvalidOperationException("Query_WrapPvtWithCount returned null for a PVT-enabled dialect."); var count = await _context.ExecuteScalarAsync(wrapped, System.Array.Empty(), cancellationToken); return checked((int)count); } /// v2-pvt SQL preview path: returns the inner _id-list SQL as-is. protected virtual Task GetSqlPreviewAsyncPvt(QueryContext context, CancellationToken cancellationToken = default) where TProps : class, new() => BuildPvtInnerSqlAsync(context, forCount: false); /// /// v2-pvt ToList path: the inner SQL picks the ids, the wrapper reads their _objects rows in that /// order, and the lazy loader reads the Props once, from the Props cache where it holds them. The JSON of an /// object is built once per read, by the loader; the wrapper used to build it too, and the loader built it again. /// protected virtual async Task ExecuteToListAsyncPvt(QueryContext context, Type propsType, CancellationToken cancellationToken = default) where TProps : class, new() { var loader = _lazyPropsLoader ?? throw new InvalidOperationException("The v2-pvt list read needs the lazy Props loader of the provider."); var inner = await BuildPvtInnerSqlAsync(context, forCount: false); var wrapped = _sql.Query_WrapPvtWithObjectRows(inner) ?? throw new InvalidOperationException("Query_WrapPvtWithObjectRows returned null for a PVT-enabled dialect."); var sqlTimer = System.Diagnostics.Stopwatch.StartNew(); var rows = await _context.QueryAsync(wrapped, System.Array.Empty(), cancellationToken); sqlTimer.Stop(); _logger?.LogDebug("PVT SQL (object rows) executed in {ElapsedMs} ms", sqlTimer.ElapsedMilliseconds); var objects = new List>(rows.Count); foreach (var row in rows) { if (context.CheckPermissions && context.UserId.HasValue && !await CheckUserPermission(row.Id, context.UserId.Value, cancellationToken)) continue; objects.Add(row.ToRedbObject()); } if (objects.Count == 0) return objects; // The rows carry no Props, so they are loaded whatever SkipPropsLoading says: that flag keeps the partial // Props of a projection statement, and this statement reads none. var propsLoadTimer = System.Diagnostics.Stopwatch.StartNew(); await loader.LoadPropsForManyAsync(objects, context.ProjectedStructureIds, context.PropsDepth, cancellationToken); propsLoadTimer.Stop(); _logger?.LogDebug("Props loaded via batch (with cache check) in {ElapsedMs} ms", propsLoadTimer.ElapsedMilliseconds); return objects; } /// /// Returns true when the active dialect exposes native PVT projection /// (pvt_build_projection_sql) AND the context has only safe constructs. /// Currently we exclude DistinctByField (uses p_distinct_on path that /// needs separate wiring) and ProjectedStructureIds (legacy by-ids path). /// protected virtual bool CanUsePvtProjection(QueryContext context) where TProps : class, new() { if (_sql.Query_BuildPvtProjectionSqlFunction() is null) return false; if (context.ProjectedFieldPaths is null || context.ProjectedFieldPaths.Count == 0) return false; if (context.DistinctByField != null) return false; if (context.ProjectedStructureIds != null && context.ProjectedStructureIds.Count > 0) return false; return true; } /// /// v2-pvt native projection path. Builds a projection JSON from /// context.ProjectedFieldPaths, asks pvt_build_projection_sql for the /// inner SELECT yielding the requested scalar columns, wraps it into a /// JSON-row shape compatible with the standard materializer, and runs /// it through ConvertFlatPropertiesToHierarchy + MaterializeResultsFromJson. /// The compiled selector (RedbProjectedQueryable) then trims the resulting /// RedbObject<TProps> instances client-side. /// protected virtual async Task ExecuteToListAsyncPvtProjection(QueryContext context, CancellationToken cancellationToken = default) where TProps : class, new() { var facetFilters = _facetBuilder.BuildFacetFilters(context.Filter); var orderByJson = BuildOrderByJson(context); var parameters = _facetBuilder.BuildQueryParameters(context.Limit, context.Offset); // Build projection JSON: one {"field":""} entry per ProjectedFieldPath. // The default alias inside pvt_build_projection equals the field text, so the // resulting inner-SQL columns are named exactly "FirstName", "Address.City", etc. // When IsDistinct is false we add an extra "_id" entry so we can attach the // object id to each materialized RedbObject. Under DISTINCT we drop // "_id" to avoid making every row trivially unique. var includeId = !context.IsDistinct; var projectionJson = BuildPvtProjectionJson(context.ProjectedFieldPaths!, includeId); var invocation = _sql.Query_BuildPvtProjectionSqlInvocation( schemeId : context.SchemeId, limit : parameters.Limit, offset : parameters.Offset ?? 0, maxDepth : context.MaxRecursionDepth ?? 10, distinct : context.IsDistinct, sourceMode : "flat", treeIds : null, hasDistinctOn: false); if (invocation is null) throw new InvalidOperationException( "Query_BuildPvtProjectionSqlInvocation returned null for a projection-PVT-enabled dialect."); object filterParam = string.IsNullOrEmpty(facetFilters) || facetFilters == "{}" ? (object)DBNull.Value : facetFilters; object orderParam = string.IsNullOrEmpty(orderByJson) || orderByJson == "null" || orderByJson == "[]" ? (object)DBNull.Value : orderByJson; var inner = await _context.ExecuteScalarAsync(invocation, new object[] { projectionJson, filterParam, orderParam }, cancellationToken); if (string.IsNullOrWhiteSpace(inner)) throw new InvalidOperationException( "pvt_build_projection_sql returned an empty SQL string for scheme " + context.SchemeId + "."); var wrapped = _sql.Query_WrapPvtProjectionRowsAsJson(inner, includeId) ?? throw new InvalidOperationException("Query_WrapPvtProjectionRowsAsJson returned null for a projection-PVT-enabled dialect."); var sqlTimer = System.Diagnostics.Stopwatch.StartNew(); var rows = await _context.QueryAsync(wrapped, System.Array.Empty(), cancellationToken); sqlTimer.Stop(); _logger?.LogDebug("PVT projection SQL executed in {ElapsedMs} ms ({RowCount} rows)", sqlTimer.ElapsedMilliseconds, rows?.Count ?? 0); if (rows is null || rows.Count == 0) return new List>(); var objects = new System.Text.Json.JsonElement[rows.Count]; for (var i = 0; i < rows.Count; i++) { var json = rows[i].Value; if (string.IsNullOrWhiteSpace(json)) continue; objects[i] = System.Text.Json.JsonDocument.Parse(json).RootElement.Clone(); } // Convert dotted-key properties ("Address.City") into nested objects so // the typed Props deserializer can map them. Then go through the standard // materializer with SkipPropsLoading=true (we already have the Props subset). var hierarchical = ConvertFlatPropertiesToHierarchy(objects); var prevSkip = context.SkipPropsLoading; context.SkipPropsLoading = true; try { return await MaterializeResultsFromJson(hierarchical, context, cancellationToken); } finally { context.SkipPropsLoading = prevSkip; } } /// /// Serializes the projected field paths into the JSON shape expected by /// pvt_build_projection_sql: [{"field":"FirstName"},{"field":"Address.City"}, ...]. /// Adds a trailing {"field":"_id"} entry when is true. /// private static string BuildPvtProjectionJson(List fieldPaths, bool includeId) { var sb = new System.Text.StringBuilder(); sb.Append('['); for (var i = 0; i < fieldPaths.Count; i++) { if (i > 0) sb.Append(','); sb.Append("{\"field\":"); sb.Append(System.Text.Json.JsonSerializer.Serialize(fieldPaths[i])); sb.Append('}'); } if (includeId) { if (fieldPaths.Count > 0) sb.Append(','); sb.Append("{\"field\":\"_id\"}"); } sb.Append(']'); return sb.ToString(); } /// /// Trivial DTO for one-column string result-sets (e.g. get_object_json output). /// private sealed class StringValue { public string Value { get; set; } = string.Empty; } /// /// PROJECTION: Converts flat paths ("Address.City") to hierarchical JSON /// private System.Text.Json.JsonElement[] ConvertFlatPropertiesToHierarchy(System.Text.Json.JsonElement[] objects) { var result = new List(); foreach (var obj in objects) { try { var dict = new Dictionary(); // Copy all properties except properties foreach (var prop in obj.EnumerateObject()) { if (prop.Name == "properties") { // Convert flat properties to hierarchy var hierarchicalProps = ConvertFlatToHierarchy(prop.Value); dict["properties"] = hierarchicalProps; } else { dict[prop.Name] = JsonElementToObject(prop.Value); } } // Serialize back to JsonElement (without Unicode escaping) var jsonOptions = new System.Text.Json.JsonSerializerOptions { Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping }; var json = System.Text.Json.JsonSerializer.Serialize(dict, jsonOptions); var newElement = System.Text.Json.JsonDocument.Parse(json).RootElement.Clone(); result.Add(newElement); } catch (Exception ex) { _logger?.LogWarning(ex, "Error converting flat properties to hierarchy"); result.Add(obj); // Return original on error } } return result.ToArray(); } /// /// Converts flat paths to a hierarchical dictionary /// "Address.City": "Moscow" → {"Address": {"City": "Moscow"}} /// private Dictionary ConvertFlatToHierarchy(System.Text.Json.JsonElement flatProperties) { var result = new Dictionary(); // STEP 1: Collect all paths that are "classes" (have nested fields) // If there is "Address1.Details.Floor", then "Address1" and "Address1.Details" are classes var classPathPrefixes = new HashSet(); foreach (var prop in flatProperties.EnumerateObject()) { var path = prop.Name; var dotIndex = path.LastIndexOf('.'); while (dotIndex > 0) { var prefix = path.Substring(0, dotIndex); classPathPrefixes.Add(prefix); dotIndex = prefix.LastIndexOf('.'); } } // STEP 2: Sort - first nested paths (with dots), then simple ones var props = flatProperties.EnumerateObject() .OrderByDescending(p => p.Name.Contains('.') || p.Name.Contains('[')) .ThenBy(p => p.Name) .ToList(); foreach (var prop in props) { var path = prop.Name; // Skip class GUIDs at ANY nesting level // If the path is in classPathPrefixes — it's a class GUID, skip it if (classPathPrefixes.Contains(path)) { continue; // "Address1", "Address1.Details" are class GUIDs } var value = JsonElementToObject(prop.Value); var segments = ParsePathSegments(path); SetNestedValue(result, segments, value); } return result; } /// /// Parses path into segments taking arrays into account /// "Address.City" → ["Address", "City"] /// "Items[0].Price" → ["Items", "[0]", "Price"] /// private List ParsePathSegments(string path) { var segments = new List(); var current = new System.Text.StringBuilder(); for (int i = 0; i < path.Length; i++) { char c = path[i]; if (c == '.') { if (current.Length > 0) { segments.Add(current.ToString()); current.Clear(); } } else if (c == '[') { if (current.Length > 0) { segments.Add(current.ToString()); current.Clear(); } // Look for closing bracket int closeIndex = path.IndexOf(']', i); if (closeIndex > i) { segments.Add(path.Substring(i, closeIndex - i + 1)); // "[0]" i = closeIndex; } } else { current.Append(c); } } if (current.Length > 0) { segments.Add(current.ToString()); } return segments; } /// /// Sets value by nested path /// private void SetNestedValue(Dictionary root, List segments, object? value) { if (segments.Count == 0) return; var current = root; for (int i = 0; i < segments.Count - 1; i++) { var segment = segments[i]; var nextSegment = segments[i + 1]; // Check if next segment is an array index? bool nextIsArrayIndex = nextSegment.StartsWith("[") && nextSegment.EndsWith("]"); if (segment.StartsWith("[") && segment.EndsWith("]")) { // Current segment is an array index, skip (processed at previous step) continue; } if (!current.ContainsKey(segment)) { // If next segment is an array index, create a list if (nextIsArrayIndex) { current[segment] = new List(); } else { current[segment] = new Dictionary(); } } var next = current[segment]; if (nextIsArrayIndex) { // Extract index/key: "[0]" → "0", "[home]" → "home" var indexStr = nextSegment.Substring(1, nextSegment.Length - 2); if (int.TryParse(indexStr, out int index)) { // ARRAY: numeric index if (next is not List list) { list = new List(); current[segment] = list; } // Expand list if necessary while (list.Count <= index) { list.Add(new Dictionary()); } // Next element after index if (i + 2 < segments.Count) { if (list[index] is Dictionary itemDict) { current = itemDict; } else { var newDict = new Dictionary(); list[index] = newDict; current = newDict; } } else { // Last segment - just a value in the array list[index] = value; return; } } else { // DICTIONARY: string key (e.g. "home") if (next is not Dictionary dict) { dict = new Dictionary(); current[segment] = dict; } // Next element after key if (i + 2 < segments.Count) { if (!dict.ContainsKey(indexStr)) { dict[indexStr] = new Dictionary(); } if (dict[indexStr] is Dictionary keyDict) { current = keyDict; } else { var newDict = new Dictionary(); dict[indexStr] = newDict; current = newDict; } } else { // Last segment - just a value in the dictionary dict[indexStr] = value; return; } } i++; // Skip index segment } else if (next is Dictionary dict) { current = dict; } } // Set final value var lastSegment = segments[segments.Count - 1]; if (!lastSegment.StartsWith("[")) { current[lastSegment] = value; } } /// /// Converts JsonElement to object /// private object? JsonElementToObject(System.Text.Json.JsonElement element) { return element.ValueKind switch { System.Text.Json.JsonValueKind.Null => null, System.Text.Json.JsonValueKind.True => true, System.Text.Json.JsonValueKind.False => false, System.Text.Json.JsonValueKind.Number => element.TryGetInt64(out var l) ? l : element.GetDouble(), System.Text.Json.JsonValueKind.String => element.GetString(), System.Text.Json.JsonValueKind.Array => element.EnumerateArray().Select(JsonElementToObject).ToList(), System.Text.Json.JsonValueKind.Object => element.EnumerateObject() .ToDictionary(p => p.Name, p => JsonElementToObject(p.Value)), _ => element.GetRawText() }; } /// /// Returns the SQL query that will be executed (for debugging) /// public virtual async Task GetSqlPreviewAsync(QueryContext context, CancellationToken cancellationToken = default) where TProps : class, new() { // v2-pvt path: return the inner _id-list SQL produced by pvt_build_query_sql. // The caller can run it directly or wrap with COUNT/EXISTS/get_object_json on the client side. if (CanUsePvtPipeline(context)) { _logger?.LogDebug("PVT SQL Preview: SchemeId={SchemeId}", context.SchemeId); return await GetSqlPreviewAsyncPvt(context, cancellationToken); } var facetFilters = _facetBuilder.BuildFacetFilters(context.Filter); var parameters = _facetBuilder.BuildQueryParameters(context.Limit, context.Offset); var orderByJson = BuildOrderByJson(context); // The preview function of the dialect (one since the Props-level lazy switch was removed, V4) var functionName = _sql.Query_SqlPreviewFunction(); _logger?.LogDebug("Getting SQL Preview: Function={FunctionName}, SchemeId={SchemeId}, Distinct={Distinct}", functionName, context.SchemeId, context.IsDistinct); var sqlQuery = string.Format(_sql.Query_SqlPreviewTemplate(), functionName); var result = await _context.QueryFirstOrDefaultAsync(sqlQuery, new object[] { context.SchemeId, facetFilters, parameters.Limit ?? int.MaxValue, parameters.Offset ?? 0, orderByJson ?? "null", context.MaxRecursionDepth ?? 10, context.IsDistinct }, cancellationToken); // DISTINCT ON (_hash) in preview return result?.sql_preview ?? "-- SQL preview not available"; } /// /// Returns the JSON filter that will be sent to SQL function (for diagnostics) /// public virtual Task GetFilterJsonAsync(QueryContext context, CancellationToken cancellationToken = default) where TProps : class, new() { var facetFilters = _facetBuilder.BuildFacetFilters(context.Filter); return Task.FromResult(facetFilters); } /// /// SQL preview of an AggregateAsync selector (ToAggregateSqlStringAsync): the statement the provider runs for it. /// Every provider builds it from , the requests the execution reads. /// public abstract Task GetAggregateSqlPreviewAsync( QueryContext context, System.Linq.Expressions.Expression, TResult>> selector, CancellationToken cancellationToken = default) where TProps : class, new(); /// /// The aggregate requests of an AggregateAsync selector, read as the execution reads them /// (): a preview built from them shows the statement that runs. /// protected static List ParseAggregateRequests(System.Linq.Expressions.LambdaExpression selector) => AggregateSelectorParser.Parse(selector); /// /// Access rights check result /// private class PermissionCheckResult { public bool HasPermission { get; set; } } // ===== AGGREGATIONS ===== /// /// One aggregate over a redb field: the batch aggregate with one request, as MSSQL Free runs it. It asked the legacy /// aggregate_field function, which no shipped dialect has, and threw on PostgreSQL and SQLite Free. /// public virtual async Task ExecuteAggregateAsync( long schemeId, string fieldPath, AggregateFunction function, string? filterJson = null, CancellationToken cancellationToken = default) { var request = new AggregateRequest { FieldPath = fieldPath ?? string.Empty, Function = function, Alias = "value" }; var batch = await ExecuteAggregateBatchAsync(schemeId, new[] { request }, filterJson, cancellationToken); return batch.Values.TryGetValue("value", out var raw) && raw is not null ? Convert.ToDecimal(raw, System.Globalization.CultureInfo.InvariantCulture) : null; } /// /// Batch aggregation with a facet-JSON filter: one statement for all requests, built by the provider. /// public abstract Task ExecuteAggregateBatchAsync( long schemeId, IEnumerable requests, string? filterJson = null, CancellationToken cancellationToken = default); /// /// Execute single-field aggregation with FilterExpression (Pro version). /// Free fallback: converts FilterExpression to facet-JSON. /// public virtual async Task ExecuteAggregateAsync( long schemeId, string fieldPath, AggregateFunction function, QueryExpressions.FilterExpression? filter, CancellationToken cancellationToken = default) { var filterJson = filter != null ? _facetBuilder.BuildFacetFilters(filter) : null; return await ExecuteAggregateAsync(schemeId, fieldPath, function, filterJson); } /// /// Execute batch aggregation with FilterExpression (Pro version). /// Free fallback: converts FilterExpression to facet-JSON. /// public virtual async Task ExecuteAggregateBatchAsync( long schemeId, IEnumerable requests, QueryExpressions.FilterExpression? filter, CancellationToken cancellationToken = default) { var filterJson = filter != null ? _facetBuilder.BuildFacetFilters(filter) : null; return await ExecuteAggregateBatchAsync(schemeId, requests, filterJson); } // ===== DELETE ===== /// /// Delete objects by FilterExpression. Pro builds its own DELETE; Free reads the ids through the v2-pvt module, as /// a list read does, and deletes them by ids, counting every one it deleted. Free used to ask the removed /// search_objects_simple function for the ids, and a query delete threw NotSupportedException. /// public virtual async Task ExecuteDeleteAsync(long schemeId, QueryExpressions.FilterExpression? filter, CancellationToken cancellationToken = default) { if (_sql.Query_BuildPvtSqlFunction() is null) throw new NotSupportedException( $"A query delete reads the ids through the v2-pvt module, and the dialect {_sql.GetType().Name} has none " + "(Query_BuildPvtSqlFunction returns null)."); var facetFilters = filter != null ? _facetBuilder.BuildFacetFilters(filter) : null; // The objects of the scheme the filter selects: no page, no order, as a count reads them. var invocation = _sql.Query_BuildPvtSqlInvocation( schemeId: schemeId, limit: null, offset: 0, maxDepth: 10, distinct: false, sourceMode: "flat", treeIds: null, hasDistinctOn: false) ?? throw new InvalidOperationException("v2-pvt is enabled by dialect but Query_BuildPvtSqlInvocation returned null."); object filterParam = string.IsNullOrEmpty(facetFilters) || facetFilters == "{}" ? DBNull.Value : facetFilters; var inner = await _context.ExecuteScalarAsync(invocation, new object[] { filterParam, DBNull.Value }, cancellationToken); if (string.IsNullOrWhiteSpace(inner)) throw new InvalidOperationException("pvt_build_query_sql returned an empty SQL string for scheme " + schemeId + "."); var idsSql = _sql.Query_WrapPvtWithIds(inner) ?? throw new InvalidOperationException("Query_WrapPvtWithIds returned null for a PVT-enabled dialect."); var ids = await _context.QueryScalarListAsync(idsSql, System.Array.Empty(), cancellationToken); if (ids.Count == 0) return 0; var deletedCount = await redb.Core.Providers.Base.ObjectDeleteByIds.RunAsync(_context, _sql, ids.ToArray(), cancellationToken); _logger?.LogDebug("DELETE: Deleted {Count} objects by filter", deletedCount); return deletedCount; } } Path: redb/redb.Core/Query/Base/TreeQueryProviderBase.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/Query/Base/TreeQueryProviderBase.cs ---- using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text.Encodings.Web; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using redb.Core.Data; using redb.Core.Models.Configuration; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using redb.Core.Providers; using redb.Core.Query.Aggregation; using redb.Core.Query.FacetFilters; using redb.Core.Query.Parsing; #pragma warning disable CS0618 // Type or member is obsolete (internal calls into legacy ExecuteTreeToListAsync remain until full migration) using redb.Core.Query.QueryExpressions; using redb.Core.Serialization; using redb.Core.Utils; using redb.Core.Caching; namespace redb.Core.Query.Base; /// /// Base tree query provider for executing hierarchical LINQ queries via search_tree_objects_with_facets. /// Database-specific implementations should inherit and provide ISqlDialect. /// public abstract class TreeQueryProviderBase : ITreeQueryProvider, Grouping.IListItemKeySource { // The list provider of the service: the groupings read their list item keys through it (ListItemGroupKeys). IListProvider? Grouping.IListItemKeySource.ListItems { get; set; } protected readonly IRedbContext _context; protected readonly IRedbObjectSerializer _serializer; protected readonly IFilterExpressionParser _filterParser; protected readonly IOrderingExpressionParser _orderingParser; protected readonly IFacetFilterBuilder _facetBuilder; protected readonly ILogger? _logger; protected readonly ILazyPropsLoader? _lazyPropsLoader; protected readonly RedbServiceConfiguration _configuration; protected readonly ISqlDialect _sql; protected readonly ISchemeSyncProvider? _schemeSync; /// /// Metadata cache for this provider (domain-isolated). /// public GlobalMetadataCache Cache { get; } protected TreeQueryProviderBase( IRedbContext context, IRedbObjectSerializer serializer, ISqlDialect dialect, string? cacheDomain = null, ILazyPropsLoader? lazyPropsLoader = null, RedbServiceConfiguration? configuration = null, ILogger? logger = null, ISchemeSyncProvider? schemeSync = null) { _context = context; _serializer = serializer; _sql = dialect; _lazyPropsLoader = lazyPropsLoader; _configuration = configuration ?? new RedbServiceConfiguration(); _logger = logger; _schemeSync = schemeSync; Cache = new GlobalMetadataCache(cacheDomain ?? _configuration.GetEffectiveCacheDomain()); _filterParser = CreateFilterParser(); _orderingParser = CreateOrderingParser(); _facetBuilder = CreateFacetBuilder(); } /// /// The scheme id of a CLR type, found as Query<T>() finds it: the metadata cache, then the database through the /// scheme provider (a process that does not sync a scheme another one owns, a Tsak worker, meets it there on first /// use). Null when neither has it. The tree filters (WhereHasAncestor / WhereHasDescendant) read their target here; /// they read the cache alone, and failed for a scheme that existed in the database. /// internal long? ResolveSchemeIdByType(Type type) { var cached = Cache.GetSchemeIdByClrType(type); if (cached is > 0) return cached; if (_schemeSync == null) return null; // Task.Run as QueryableProviderBase.GetSchemeSync: no SynchronizationContext deadlock in Blazor or ASP.NET. var scheme = Task.Run(() => _schemeSync.GetSchemeByTypeAsync(type)).GetAwaiter().GetResult(); return scheme?.Id; } /// /// Creates filter expression parser. Override for Pro features. /// protected virtual IFilterExpressionParser CreateFilterParser() => new FilterExpressionParser(); /// /// Creates ordering expression parser. /// protected virtual IOrderingExpressionParser CreateOrderingParser() => new OrderingExpressionParser(); /// /// Creates facet filter builder. /// protected virtual IFacetFilterBuilder CreateFacetBuilder() => new FacetFilterBuilder(_logger); /// /// Creates query provider for delegation. Override in derived classes. /// protected abstract IRedbQueryProvider CreateQueryProvider(); /// /// Creates tree queryable instance. Override in derived classes. /// protected abstract IRedbQueryable CreateTreeQueryable(TreeQueryContext context) where TProps : class, new(); /// /// Check for Pro-only Distinct features (DistinctBy, DistinctByRedb, DistinctRedb). /// Throws NotSupportedException in Free version. /// /// /// The p_distinct_on argument of pvt_build_query_sql for a tree query - the same JSON the flat /// query passes. The Free tree providers used to pass none, and DistinctBy / DistinctByRedb on a tree returned /// every node. /// protected static string? BuildPvtDistinctOnJson(QueryContext context) where TProps : class, new() => QueryProviderBase.BuildPvtDistinctOnJson(context); protected virtual void CheckProOnlyDistinctFeatures(QueryContext context) where TProps : class, new() { // No-op: DistinctRedb / DistinctBy are evaluated downstream by the SQL builder. } // ===== IRedbQueryProvider IMPLEMENTATION (BASE FUNCTIONALITY) ===== public IRedbQueryable CreateQuery(long schemeId, long? userId = null, bool checkPermissions = false) where TProps : class, new() { // For regular queries create standard RedbQueryable // It reads through the v2-pvt module of the flat query provider var baseProvider = CreateQueryProvider(); return baseProvider.CreateQuery(schemeId, userId, checkPermissions); } // ===== AGGREGATIONS IMPLEMENTATION (delegate to QueryProviderBase) ===== // virtual for override in Pro version public virtual async Task ExecuteAggregateAsync(long schemeId, string fieldPath, AggregateFunction function, string? filterJson = null, CancellationToken cancellationToken = default) { var baseProvider = CreateQueryProvider(); return await baseProvider.ExecuteAggregateAsync(schemeId, fieldPath, function, filterJson); } public virtual async Task ExecuteAggregateAsync(long schemeId, string fieldPath, AggregateFunction function, QueryExpressions.FilterExpression? filter, CancellationToken cancellationToken = default) { var baseProvider = CreateQueryProvider(); return await baseProvider.ExecuteAggregateAsync(schemeId, fieldPath, function, filter); } public virtual async Task ExecuteAggregateBatchAsync(long schemeId, IEnumerable requests, string? filterJson = null, CancellationToken cancellationToken = default) { var baseProvider = CreateQueryProvider(); return await baseProvider.ExecuteAggregateBatchAsync(schemeId, requests, filterJson); } public virtual async Task ExecuteAggregateBatchAsync(long schemeId, IEnumerable requests, QueryExpressions.FilterExpression? filter, CancellationToken cancellationToken = default) { var baseProvider = CreateQueryProvider(); return await baseProvider.ExecuteAggregateBatchAsync(schemeId, requests, filter); } /// /// Get scheme by ID (for projections) - delegate to base provider /// public virtual async Task GetSchemeAsync(long schemeId, CancellationToken cancellationToken = default) { var baseProvider = CreateQueryProvider(); return await baseProvider.GetSchemeAsync(schemeId); } // ===== GROUPBY (delegate to QueryProviderBase) ===== // virtual for override in Pro version public virtual async Task ExecuteGroupedAggregateAsync( long schemeId, IEnumerable groupFields, IEnumerable aggregations, string? filterJson = null, string? havingJson = null, CancellationToken cancellationToken = default) { var baseProvider = CreateQueryProvider(); return await baseProvider.ExecuteGroupedAggregateAsync(schemeId, groupFields, aggregations, filterJson, havingJson); } /// /// Execute GroupBy aggregation with FilterExpression (Pro version). /// Delegates to QueryProvider. /// public virtual async Task ExecuteGroupedAggregateAsync( long schemeId, IEnumerable groupFields, IEnumerable aggregations, QueryExpressions.FilterExpression? filter, string? havingJson = null, CancellationToken cancellationToken = default) { var baseProvider = CreateQueryProvider(); return await baseProvider.ExecuteGroupedAggregateAsync(schemeId, groupFields, aggregations, filter, havingJson); } /// /// Array grouping without a tree: the flat provider answers it. /// public virtual Task ExecuteArrayGroupQueryAsync( redb.Core.Query.Grouping.ArrayGroupQuery query, CancellationToken cancellationToken = default) => CreateQueryProvider().ExecuteArrayGroupQueryAsync(query, cancellationToken); /// /// SQL of . /// public virtual Task GetArrayGroupQuerySqlAsync( redb.Core.Query.Grouping.ArrayGroupQuery query, CancellationToken cancellationToken = default) => CreateQueryProvider().GetArrayGroupQuerySqlAsync(query, cancellationToken); // ===== WINDOW FUNCTIONS (delegate to QueryProviderBase) ===== // virtual for override in Pro version public virtual async Task ExecuteWindowQueryAsync( long schemeId, IEnumerable selectFields, IEnumerable windowFuncs, IEnumerable partitionBy, IEnumerable orderBy, string? filterJson = null, string? frameJson = null, int? take = null, int? skip = null, CancellationToken cancellationToken = default) { var baseProvider = CreateQueryProvider(); return await baseProvider.ExecuteWindowQueryAsync(schemeId, selectFields, windowFuncs, partitionBy, orderBy, filterJson, frameJson, take, skip); } public virtual async Task ExecuteWindowQueryAsync( long schemeId, IEnumerable selectFields, IEnumerable windowFuncs, IEnumerable partitionBy, IEnumerable orderBy, QueryExpressions.FilterExpression? filter, string? frameJson = null, int? take = null, int? skip = null, CancellationToken cancellationToken = default) { var baseProvider = CreateQueryProvider(); return await baseProvider.ExecuteWindowQueryAsync(schemeId, selectFields, windowFuncs, partitionBy, orderBy, filter, frameJson, take, skip); } public virtual async Task GetWindowSqlPreviewAsync( long schemeId, IEnumerable selectFields, IEnumerable windowFuncs, IEnumerable partitionBy, IEnumerable orderBy, string? filterJson = null, string? frameJson = null, int? take = null, int? skip = null, CancellationToken cancellationToken = default) { var baseProvider = CreateQueryProvider(); return await baseProvider.GetWindowSqlPreviewAsync(schemeId, selectFields, windowFuncs, partitionBy, orderBy, filterJson, frameJson, take, skip); } // ===== GROUPED WINDOW (delegated to base provider) ===== public virtual Task ExecuteGroupedWindowQueryAsync( long schemeId, IEnumerable groupFields, IEnumerable aggregations, IEnumerable windowFuncs, IEnumerable partitionBy, IEnumerable orderBy, string? filterJson = null, string? havingJson = null, CancellationToken cancellationToken = default) => CreateQueryProvider().ExecuteGroupedWindowQueryAsync( schemeId, groupFields, aggregations, windowFuncs, partitionBy, orderBy, filterJson, havingJson, cancellationToken); public virtual Task ExecuteGroupedWindowQueryAsync( long schemeId, IEnumerable groupFields, IEnumerable aggregations, IEnumerable windowFuncs, IEnumerable partitionBy, IEnumerable orderBy, QueryExpressions.FilterExpression? filter, string? havingJson = null, CancellationToken cancellationToken = default) => CreateQueryProvider().ExecuteGroupedWindowQueryAsync( schemeId, groupFields, aggregations, windowFuncs, partitionBy, orderBy, filter, havingJson, cancellationToken); public virtual Task GetGroupedWindowSqlPreviewAsync( long schemeId, IEnumerable groupFields, IEnumerable aggregations, IEnumerable windowFuncs, IEnumerable partitionBy, IEnumerable orderBy, string? filterJson = null, string? havingJson = null, CancellationToken cancellationToken = default) => CreateQueryProvider().GetGroupedWindowSqlPreviewAsync( schemeId, groupFields, aggregations, windowFuncs, partitionBy, orderBy, filterJson, havingJson, cancellationToken); public virtual Task GetGroupedWindowSqlPreviewAsync( long schemeId, IEnumerable groupFields, IEnumerable aggregations, IEnumerable windowFuncs, IEnumerable partitionBy, IEnumerable orderBy, QueryExpressions.FilterExpression? filter, string? havingJson = null, CancellationToken cancellationToken = default) => CreateQueryProvider().GetGroupedWindowSqlPreviewAsync( schemeId, groupFields, aggregations, windowFuncs, partitionBy, orderBy, filter, havingJson, cancellationToken); public virtual Task GetGroupBySqlPreviewAsync( long schemeId, IEnumerable groupFields, IEnumerable aggregations, string? filterJson, string? havingJson = null, CancellationToken cancellationToken = default) => CreateQueryProvider().GetGroupBySqlPreviewAsync(schemeId, groupFields, aggregations, filterJson, havingJson, cancellationToken); public virtual Task GetGroupBySqlPreviewAsync( long schemeId, IEnumerable groupFields, IEnumerable aggregations, QueryExpressions.FilterExpression? filter, string? havingJson = null, CancellationToken cancellationToken = default) => CreateQueryProvider().GetGroupBySqlPreviewAsync(schemeId, groupFields, aggregations, filter, havingJson, cancellationToken); // ===== ITreeQueryProvider IMPLEMENTATION (TREE FUNCTIONALITY) ===== public IRedbQueryable CreateTreeQuery( long schemeId, long? userId = null, bool checkPermissions = false, long? rootObjectId = null, int? maxDepth = null ) where TProps : class, new() { var context = new TreeQueryContext(schemeId, userId, checkPermissions, rootObjectId, maxDepth); return CreateTreeQueryable(context); } // ===== QUERY EXECUTION ===== public async Task ExecuteAsync(Expression expression, Type elementType, CancellationToken cancellationToken = default) { // Extract context from expression if (expression is ConstantExpression constantExpr && constantExpr.Value != null) { // Determine operation type by elementType if (elementType == typeof(int)) { return await ExecuteCountAsyncGeneric(constantExpr.Value, cancellationToken); } else if (elementType == typeof(bool)) { return await ExecuteAnyAsyncGeneric(constantExpr.Value, cancellationToken); } else if (elementType.IsGenericType) { var genericType = elementType.GetGenericTypeDefinition(); if (genericType == typeof(List<>)) { // Determine result type (RedbObject or TreeRedbObject) var itemType = elementType.GetGenericArguments()[0]; if (itemType.IsGenericType && itemType.GetGenericTypeDefinition() == typeof(TreeRedbObject<>)) { return await ExecuteTreeToListAsyncGeneric(constantExpr.Value, cancellationToken); } else { return await ExecuteToListAsyncGeneric(constantExpr.Value, cancellationToken); } } } } throw new NotSupportedException($"Tree query expression type {expression.GetType().Name} with element type {elementType.Name} is not supported"); } // ===== COUNT QUERY EXECUTION ===== private async Task ExecuteCountAsyncGeneric(object contextObj, CancellationToken cancellationToken) { // Use reflection to call typed method // this.GetType() - support override in Pro version var contextType = contextObj.GetType(); if (contextType.IsGenericType && contextType.GetGenericTypeDefinition() == typeof(TreeQueryContext<>)) { // Tree query var propsType = contextType.GetGenericArguments()[0]; var method = this.GetType().GetMethod(nameof(ExecuteTreeCountAsync), System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); var genericMethod = method!.MakeGenericMethod(propsType); var task = (Task)genericMethod.Invoke(this, new object[] { contextObj, cancellationToken })!; return await task; } else if (contextType.IsGenericType && contextType.GetGenericTypeDefinition() == typeof(QueryContext<>)) { // Regular query - delegate to base provider var baseProvider = CreateQueryProvider(); return await (Task)typeof(QueryProviderBase) .GetMethod("ExecuteCountAsyncGeneric", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)! .Invoke(baseProvider, new object[] { contextObj, cancellationToken })!; } throw new NotSupportedException($"Unsupported context type: {contextType.Name}"); } // ===== ANY QUERY EXECUTION ===== private async Task ExecuteAnyAsyncGeneric(object contextObj, CancellationToken cancellationToken) { var contextType = contextObj.GetType(); if (contextType.IsGenericType && contextType.GetGenericTypeDefinition() == typeof(TreeQueryContext<>)) { // this.GetType(): the Pro provider overrides the method var propsType = contextType.GetGenericArguments()[0]; var method = this.GetType().GetMethod(nameof(ExecuteTreeAnyAsync), System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); var genericMethod = method!.MakeGenericMethod(propsType); return await (Task)genericMethod.Invoke(this, new object[] { contextObj, cancellationToken })!; } throw new NotSupportedException($"Unsupported context type for Any: {contextType.Name}"); } /// /// Is there at least one node the query returns (no Take or Skip: the queryable answers a page by its count). /// The default is the count compared with zero; a provider that can stop at the first node overrides it. /// protected virtual async Task ExecuteTreeAnyAsync(TreeQueryContext context, CancellationToken cancellationToken = default) where TProps : class, new() { #pragma warning disable CS0618 // the count is the default answer until a provider overrides this return await ExecuteTreeCountAsync(context, cancellationToken) > 0; #pragma warning restore CS0618 } /// /// The query cut to its first node, for : Take 1, and neither the /// ordering nor the distinct, which change which nodes come back but not whether any does. /// protected static TreeQueryContext FirstNodeProbe(TreeQueryContext context) where TProps : class, new() { var probe = context.Clone(); probe.Orderings = []; probe.IsDistinct = false; probe.IsDistinctRedb = false; probe.DistinctByField = null; probe.DistinctByIsBaseField = false; probe.Limit = 1; probe.Offset = null; return probe; } // ===== TOLIST QUERY EXECUTION ===== private async Task ExecuteToListAsyncGeneric(object contextObj, CancellationToken cancellationToken) { var contextType = contextObj.GetType(); if (contextType.IsGenericType && contextType.GetGenericTypeDefinition() == typeof(QueryContext<>)) { // Regular query - delegate to base provider var baseProvider = CreateQueryProvider(); return await (Task)typeof(QueryProviderBase) .GetMethod("ExecuteToListAsyncGeneric", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)! .Invoke(baseProvider, new object[] { contextObj, cancellationToken })!; } else if (contextType.IsGenericType && contextType.GetGenericTypeDefinition() == typeof(TreeQueryContext<>)) { // Tree query - use our method // this.GetType() - support override in Pro version var propsType = contextType.GetGenericArguments()[0]; var method = this.GetType().GetMethod(nameof(ExecuteTreeToListAsync), System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); var genericMethod = method!.MakeGenericMethod(propsType); var lazyOverride = (bool?)contextType.GetProperty("LazyReferences")?.GetValue(contextObj); return await LazyReferencesQueryScope.RunAsync(_context, _sql, _configuration, _logger, lazyOverride, () => (Task)genericMethod.Invoke(this, new object[] { contextObj, cancellationToken })!); } throw new NotSupportedException($"Unsupported context type for ToList: {contextType.Name}"); } private async Task ExecuteTreeToListAsyncGeneric(object contextObj, CancellationToken cancellationToken) { var contextType = contextObj.GetType(); if (contextType.IsGenericType && contextType.GetGenericTypeDefinition() == typeof(TreeQueryContext<>)) { // Tree query // this.GetType() - support override in Pro version var propsType = contextType.GetGenericArguments()[0]; var method = this.GetType().GetMethod(nameof(ExecuteTreeToListAsync), System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); var genericMethod = method!.MakeGenericMethod(propsType); var lazyOverride = (bool?)contextType.GetProperty("LazyReferences")?.GetValue(contextObj); return await LazyReferencesQueryScope.RunAsync(_context, _sql, _configuration, _logger, lazyOverride, () => (Task)genericMethod.Invoke(this, new object[] { contextObj, cancellationToken })!); } throw new NotSupportedException($"Unsupported context type for TreeToList: {contextType.Name}"); } // ===== TREE EXECUTION METHODS ===== /// /// COUNT of a tree query. Every provider builds it through its v2-pvt module; the base read the legacy /// search_tree_objects_with_facets functions, which no shipped dialect has. /// protected abstract Task ExecuteTreeCountAsync(TreeQueryContext context, CancellationToken cancellationToken = default) where TProps : class, new(); /// /// ToList of a tree query. Every provider builds it through its v2-pvt module; the base read the legacy /// search_tree_objects_with_facets functions, which no shipped dialect has. /// protected abstract Task ExecuteTreeToListAsync(TreeQueryContext context, CancellationToken cancellationToken = default) where TProps : class, new(); /// The value of an EXISTS wrapper: a boolean on PostgreSQL, 1 or 0 on SQL Server and SQLite. protected static bool ExistsResult(object? value) => value is not null and not DBNull && Convert.ToBoolean(value, System.Globalization.CultureInfo.InvariantCulture); /// /// A WhereHasAncestor / WhereHasDescendant the provider could not turn into object ids: one without a target scheme. /// WhereHasAncestor<T>() and WhereHasDescendant<T>() always set it, or fail naming the type, so only a /// TreeFilter built by hand gets here. It used to fall to the legacy search functions, which no dialect has. /// protected static InvalidOperationException UnresolvedTreeFilter() => new( "A WhereHasAncestor or WhereHasDescendant filter without a target scheme reached the tree query provider. " + "Build it with WhereHasAncestor() or WhereHasDescendant(), which find the scheme of T."); // ===== FILTER BUILDING ===== /// /// Determines if WhereHasAncestor can be optimized through logic inversion /// protected TreeFilter? GetOptimizableHasAncestorFilter(TreeQueryContext context) where TProps : class, new() { // Find first WhereHasAncestor filter (optimize one by one) // TargetSchemeId can be 0 if type is not registered in AutomaticTypeRegistry var filter = context.TreeFilters?.FirstOrDefault(f => f.Operator == TreeFilterOperator.HasAncestor); // Check that TargetSchemeId exists and is not equal to 0 if (filter != null && (!filter.TargetSchemeId.HasValue || filter.TargetSchemeId.Value == 0)) { _logger?.LogWarning("WhereHasAncestor filter found, but TargetSchemeId not set (type not registered in AutomaticTypeRegistry). Optimization skipped."); return null; } return filter; } /// /// WhereHasAncestor with maxDepth 1 as the children of the matching ancestors: the query's own parents, read by the /// tree query in one statement (o._id_parent among them). The general form reads the descendants down to the depth /// limit and hands their ids back to the query as one array parameter; at maxDepth 1 those are exactly the /// children, read by one statement and sent back to the server by the next. Null when the query has a root, /// parents, a depth limit (counted from the real root of an unrooted query) or another tree filter of its own, /// which the parents would replace. The caller returns before this when no ancestor matched: an empty list of /// parents never reaches the query. /// protected static TreeQueryContext? AsChildrenOfAncestors( TreeQueryContext context, TreeFilter hasAncestor, IReadOnlyCollection ancestorIds) where TProps : class, new() { if (hasAncestor.MaxDepth != 1 || context.RootObjectId.HasValue || context.ParentIds is { Length: > 0 } || context.MaxDepth.HasValue || context.TreeFilters.Count != 1) return null; var rewritten = context.CloneWithMaxDepth(1); rewritten.TreeFilters = new List(); rewritten.ParentIds = ancestorIds.ToArray(); return rewritten; } /// /// WhereHasAncestor without maxDepth as the descendants of the matching ancestors at any depth: the query walks down /// from them as its parents, in the statement that reads the page, instead of a statement that lists the descendants /// and a query that takes their ids back as parameters. The same answer, since no depth limit counts from the returned /// object. Null under the same conditions as , and when the filter has a /// maxDepth. /// protected static TreeQueryContext? AsDescendantsOfAncestors( TreeQueryContext context, TreeFilter hasAncestor, IReadOnlyCollection ancestorIds) where TProps : class, new() { if (hasAncestor.MaxDepth.HasValue || context.RootObjectId.HasValue || context.ParentIds is { Length: > 0 } || context.MaxDepth.HasValue || context.TreeFilters.Count != 1) return null; var rewritten = context.Clone(); rewritten.TreeFilters = new List(); rewritten.ParentIds = ancestorIds.ToArray(); return rewritten; } /// /// WhereHasAncestor with a maxDepth above 1 as the descendants of the matching ancestors down to that depth: the query /// walks down from them as its parents with its own depth limit set to maxDepth, in the statement that reads the page, /// instead of a statement that lists the descendants and a query that takes their ids back. The same answer only where /// the walk from several parents visits each node once, at its smallest depth: an object lies at most maxDepth levels /// below a matching ancestor exactly when the nearest one is that close, and a node under two nested matching /// ancestors comes once. The caller confirms its walk does that. Null under the same conditions as /// , and when maxDepth is not above 1. /// protected static TreeQueryContext? AsDescendantsWithinDepthOfAncestors( TreeQueryContext context, TreeFilter hasAncestor, IReadOnlyCollection ancestorIds) where TProps : class, new() { if (hasAncestor.MaxDepth is not > 1 || context.RootObjectId.HasValue || context.ParentIds is { Length: > 0 } || context.MaxDepth.HasValue || context.TreeFilters.Count != 1) return null; var rewritten = context.CloneWithMaxDepth(hasAncestor.MaxDepth.Value); rewritten.TreeFilters = new List(); rewritten.ParentIds = ancestorIds.ToArray(); return rewritten; } /// /// Determines if WhereHasDescendant can be optimized through logic inversion /// protected TreeFilter? GetOptimizableHasDescendantFilter(TreeQueryContext context) where TProps : class, new() { return context.TreeFilters?.FirstOrDefault(f => f.Operator == TreeFilterOperator.HasDescendant && f.TargetSchemeId.HasValue); } /// /// Build JSON for sorting (similar to base provider) /// FIXED: Uses _facetBuilder.BuildOrderBy to support 0$: prefix for base fields /// private JsonDocument? BuildOrderByFilter(TreeQueryContext context) where TProps : class, new() { if (context.Orderings == null || !context.Orderings.Any()) return null; // Use _facetBuilder.BuildOrderBy which correctly handles IsBaseField var jsonString = _facetBuilder.BuildOrderBy(context.Orderings); return JsonDocument.Parse(jsonString); } // ConvertFilterToFacets() REMOVED! REPLACED WITH PostgresFacetFilterBuilder! // Now Tree uses THE SAME POWERFUL SYSTEM as regular LINQ - ALL 25+ operators! /// /// Deserialize JSON result to list of TreeRedbObject /// protected List> DeserializeTreeObjects(string? objectsJson) where TProps : class, new() { if (string.IsNullOrEmpty(objectsJson) || objectsJson == "null") return new List>(); try { // Handle both array format and object format {"objects":[...]} JsonElement[]? jsonArray; var trimmed = objectsJson.TrimStart(); if (trimmed.StartsWith("{")) { // MSSQL returns full object: {"objects":[...],"total_count":N,...} var doc = JsonDocument.Parse(objectsJson); if (doc.RootElement.TryGetProperty("objects", out var objectsElement)) { jsonArray = JsonSerializer.Deserialize(objectsElement.GetRawText()); } else { return new List>(); } } else { // PostgreSQL returns array directly: [{...},{...}] jsonArray = JsonSerializer.Deserialize(objectsJson); } var result = new List>(); if (jsonArray == null) return result; foreach (var jsonElement in jsonArray) { try { // Deserialize as regular RedbObject var redbObj = _serializer.Deserialize(jsonElement.GetRawText()); if (redbObj == null) continue; // Convert to TreeRedbObject var treeObj = ConvertToTreeObject(redbObj); // NOTE: Props are batch-loaded by ExecuteTreeToListAsync; boundary stubs get their // loader from LazyReferenceInstaller after that (V4). result.Add(treeObj); } catch (Exception ex) { _logger?.LogWarning(ex, "Error deserializing tree object from JSON"); // Continue processing other objects } } return result; } catch (Exception ex) { _logger?.LogError(ex, "Error deserializing JSON array of tree objects"); return new List>(); } } /// /// Convert RedbObject to TreeRedbObject /// FIXED: Props copied from source (fixed bug with empty Props) /// protected TreeRedbObject ConvertToTreeObject(RedbObject source) where TProps : class, new() { var treeObj = new TreeRedbObject { id = source.id, parent_id = source.parent_id, scheme_id = source.scheme_id, owner_id = source.owner_id, who_change_id = source.who_change_id, date_create = source.date_create, date_modify = source.date_modify, date_begin = source.date_begin, date_complete = source.date_complete, key = source.key, value_long = source.value_long, value_string = source.value_string, value_guid = source.value_guid, value_bool = source.value_bool, value_double = source.value_double, value_numeric = source.value_numeric, value_datetime = source.value_datetime, value_bytes = source.value_bytes, value_unique = source.value_unique, name = source.name, note = source.note, hash = source.hash }; // CRITICAL FIX: Copy Props directly // Use GetPropsDirectly() to NOT trigger lazy load in source // Props setter is safe - it just sets the value var sourceProps = source.GetPropsDirectly(); if (sourceProps != null) { treeObj.Props = sourceProps; // Setter will set _propsLoaded=true } else if (source._propsLoaded) { // Props was loaded but it's null - set flag treeObj._propsLoaded = true; } return treeObj; } // ===== METHODS FOR BUILDING HIERARCHICAL RELATIONSHIPS ===== /// /// Get IDs of all objects and their parents up to root through recursive CTE /// public async Task> GetIdsWithAncestorsAsync(List filteredIds, CancellationToken cancellationToken = default) where TProps : class, new() { if (filteredIds == null || !filteredIds.Any()) return new List(); try { return await _context.QueryScalarListAsync(_sql.Tree_SelectIdsWithAncestors(), new object[] { filteredIds.ToArray(), redb.Core.Providers.Base.TreeProviderBase.MaxAncestorDepth }, cancellationToken); } catch (Exception ex) { _logger?.LogError(ex, "Error getting IDs with parents"); throw; } } /// /// Load full objects by ID list via get_object_json function /// public async Task>> LoadObjectsByIdsAsync(List objectIds, int? propsDepth = null, CancellationToken cancellationToken = default) where TProps : class, new() { if (objectIds == null || !objectIds.Any()) return new List>(); // Pro path: materialize entirely in C# (PVT) — NEVER call the server-side // get_object_json function. Triggered when a Pro lazy loader is injected. if (_lazyPropsLoader != null) { var rows = await _context.QueryAsync( _sql.ObjectStorage_SelectObjectsByIds(), new object[] { objectIds.ToArray() }, cancellationToken); return await MaterializeTreeObjectsFromRowsAsync(rows, propsDepth); } try { // Use dialect-specific SQL for loading objects by IDs var idsString = string.Join(",", objectIds); var effectiveDepth = propsDepth ?? _configuration.DefaultMaxTreeDepth; var sql = _sql.Query_LoadObjectsByIdsSql(idsString, effectiveDepth); var objectsJsonList = await _context.ExecuteJsonListAsync(sql, System.Array.Empty(), cancellationToken); var result = new List>(); foreach (var objectJson in objectsJsonList) { try { var redbObj = _serializer.Deserialize(objectJson); if (redbObj != null) { var treeObj = ConvertToTreeObject(redbObj); result.Add(treeObj); } } catch (Exception ex) { _logger?.LogWarning(ex, "Error deserializing object from get_object_json"); } } return result; } catch (Exception ex) { _logger?.LogError(ex, "Error loading objects by ID"); throw; } } /// /// Load full polymorphic objects by ID list via get_object_json function. /// Used for polymorphic trees where objects can be of different types. /// Each object is deserialized to its real type based on scheme_id. /// public async Task> LoadObjectsByIdsAsync(List objectIds, int? propsDepth = null, CancellationToken cancellationToken = default) { if (objectIds == null || !objectIds.Any()) return new List(); // Pro path: materialize entirely in C# (PVT) — NEVER call the server-side // get_object_json function. Triggered when a Pro lazy loader is injected. if (_lazyPropsLoader != null) { var rows = await _context.QueryAsync( _sql.ObjectStorage_SelectObjectsByIds(), new object[] { objectIds.ToArray() }, cancellationToken); var proResult = new List(); foreach (var schemeGroup in rows.GroupBy(r => r.IdScheme)) { var propsType = Cache.GetClrType(schemeGroup.Key) ?? throw new InvalidOperationException( $"Type not found for scheme_id={schemeGroup.Key}. Register type in AutomaticTypeRegistry."); var method = typeof(TreeQueryProviderBase).GetMethod( nameof(MaterializeTreeObjectsFromRowsAsync), System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); var genericMethod = method!.MakeGenericMethod(propsType); var task = (Task)genericMethod.Invoke(this, new object[] { schemeGroup.ToList(), propsDepth! })!; await task.ConfigureAwait(false); var typed = (System.Collections.IEnumerable)task.GetType().GetProperty("Result")!.GetValue(task)!; foreach (var o in typed) { if (o is ITreeRedbObject treeObj) proResult.Add(treeObj); } } return proResult; } try { // Use dialect-specific SQL for loading objects by IDs var idsString = string.Join(",", objectIds); var effectiveDepth = propsDepth ?? _configuration.DefaultMaxTreeDepth; var sql = _sql.Query_LoadObjectsByIdsSql(idsString, effectiveDepth); var objectsJsonList = await _context.ExecuteJsonListAsync(sql, System.Array.Empty(), cancellationToken); var result = new List(); foreach (var objectJson in objectsJsonList) { // 1. Extract scheme_id from JSON for polymorphic deserialization using var jsonDoc = JsonDocument.Parse(objectJson); var schemeId = jsonDoc.RootElement.GetProperty("scheme_id").GetInt64(); // 2. Get real C# type via AutomaticTypeRegistry var propsType = Cache.GetClrType(schemeId) ?? throw new InvalidOperationException( $"Type not found for scheme_id={schemeId}. Register type in AutomaticTypeRegistry."); // 3. Polymorphic deserialization: first RedbObject, then TreeRedbObject var redbObj = _serializer.DeserializeRedbDynamic(objectJson, propsType); if (redbObj != null) { // Convert to TreeRedbObject via reflection (call ConvertToTreeObject) var method = typeof(TreeQueryProviderBase).GetMethod(nameof(ConvertToTreeObject), System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); if (method != null) { var genericMethod = method.MakeGenericMethod(propsType); var convertResult = genericMethod.Invoke(this, new[] { redbObj }); if (convertResult is ITreeRedbObject treeObj) { result.Add(treeObj); } } } } return result; } catch (Exception ex) { _logger?.LogError(ex, "Error loading polymorphic objects by ID"); throw; } } /// /// Pro materialization: builds TreeRedbObject<TProps> from base _objects rows and /// loads Props via the injected lazy loader (ProLazyPropsLoader → PVT, in C#). /// Used by the Pro branch of LoadObjectsByIdsAsync to avoid get_object_json. /// private async Task>> MaterializeTreeObjectsFromRowsAsync( List rows, int? propsDepth) where TProps : class, new() { var result = rows.Select(MapRowToTreeObject).ToList(); if (_lazyPropsLoader != null && result.Count > 0) { var baseObjects = result.Cast>().ToList(); await _lazyPropsLoader.LoadPropsForManyAsync(baseObjects, propsDepth); } return result; } /// /// Maps a base _objects row to a TreeRedbObject shell (Props loaded separately). /// protected static TreeRedbObject MapRowToTreeObject(RedbObjectRow row) where TProps : class, new() { return new TreeRedbObject { id = row.Id, name = row.Name, scheme_id = row.IdScheme, parent_id = row.IdParent, owner_id = row.IdOwner, who_change_id = row.IdWhoChange, date_create = row.DateCreate, date_modify = row.DateModify, date_begin = row.DateBegin, date_complete = row.DateComplete, key = row.Key, value_long = row.ValueLong, value_string = row.ValueString, value_guid = row.ValueGuid, value_bool = row.ValueBool, value_double = row.ValueDouble, value_numeric = row.ValueNumeric, value_datetime = row.ValueDatetime, value_bytes = row.ValueBytes, value_unique = row.ValueUnique, note = row.Note, hash = row.Hash }; } /// /// Returns SQL query for tree search that will be executed (for debugging) /// public virtual async Task GetSqlPreviewAsync(TreeQueryContext context, CancellationToken cancellationToken = default) where TProps : class, new() { var facetFilters = _facetBuilder.BuildFacetFilters(context.Filter); var parameters = _facetBuilder.BuildQueryParameters(context.Limit, context.Offset); var orderByDoc = BuildOrderByFilter(context); var orderByJson = orderByDoc?.RootElement.GetRawText(); // OPTIMIZATION: ALWAYS use _base preview function var functionName = _sql.Query_TreeSqlPreviewBaseFunction(); _logger?.LogDebug("Getting Tree SQL Preview: Function={FunctionName}, SchemeId={SchemeId}, RootObjectId={RootObjectId}, MaxDepth={MaxDepth}", functionName, context.SchemeId, context.RootObjectId, context.MaxDepth); // Build parent_ids array for the SQL function var parentIds = context.ParentIds ?? (context.RootObjectId.HasValue ? new[] { context.RootObjectId.Value } : Array.Empty()); var sqlQuery = _sql.Query_TreeSqlPreviewTemplate(functionName); var result = await _context.QueryFirstOrDefaultAsync( sqlQuery, new object[] { context.SchemeId, parentIds, facetFilters, parameters.Limit ?? int.MaxValue, parameters.Offset ?? 0, orderByJson ?? "null", context.MaxDepth ?? 100, context.MaxRecursionDepth ?? 10 }, cancellationToken); return result?.sql_preview ?? "-- Tree SQL preview not available"; } // ===== DELETE ===== /// /// Get SQL preview for standard QueryContext (for IRedbQueryProvider compatibility) /// public Task GetSqlPreviewAsync(QueryContext context, CancellationToken cancellationToken = default) where TProps : class, new() { // For Tree provider convert to TreeQueryContext if (context is TreeQueryContext treeContext) { return GetSqlPreviewAsync(treeContext); } // Create TreeQueryContext from regular QueryContext var newTreeContext = new TreeQueryContext( context.SchemeId, context.UserId, context.CheckPermissions, null, // rootObjectId context.MaxDepth) { Filter = context.Filter, Orderings = context.Orderings.ToList(), Limit = context.Limit, Offset = context.Offset, LazyReferences = context.LazyReferences, }; return GetSqlPreviewAsync(newTreeContext); } /// /// Returns the JSON filter that will be sent to SQL function (for diagnostics) /// public Task GetFilterJsonAsync(QueryContext context, CancellationToken cancellationToken = default) where TProps : class, new() { var facetFilters = _facetBuilder.BuildFacetFilters(context.Filter); return Task.FromResult(facetFilters); } /// /// Delete objects by FilterExpression. Delegates to base QueryProvider. /// Cascade delete in DB handles children automatically. /// public async Task ExecuteDeleteAsync(long schemeId, QueryExpressions.FilterExpression? filter, CancellationToken cancellationToken = default) { var baseProvider = CreateQueryProvider(); return await baseProvider.ExecuteDeleteAsync(schemeId, filter); } /// /// Delete objects by ID array (cascade with children). /// public async Task ExecuteTreeDeleteAsync(long[] objectIds, CancellationToken cancellationToken = default) { if (objectIds.Length == 0) return 0; // Use dialect's cascade delete (handles children automatically) // MSSQL context auto-converts long[] to comma-separated string var deletedCount = await redb.Core.Providers.Base.ObjectDeleteByIds.RunAsync(_context, _sql, objectIds, cancellationToken); _logger?.LogDebug("TreeDelete: Deleted {Count} objects (cascade)", deletedCount); return deletedCount; } /// /// Execute GROUP BY with tree context (CTE for tree traversal). /// Base implementation: gets tree object IDs first, then delegates to base GroupBy with filter. /// Override in Pro version for optimized CTE-based implementation. /// public virtual async Task ExecuteTreeGroupedAggregateAsync( TreeQueryContext context, IEnumerable groupFields, IEnumerable aggregations, string? havingJson = null, CancellationToken cancellationToken = default) where TProps : class, new() { // Base implementation: get tree object IDs first, then filter grouping var treeObjectIds = await GetTreeObjectIdsAsync(context, cancellationToken); if (treeObjectIds.Count == 0) return System.Text.Json.JsonDocument.Parse("[]"); // Build filter JSON with object IDs var filterJson = BuildObjectIdsFilterJson(treeObjectIds); // Delegate to base grouped aggregate with ID filter (PVT path honors having) var baseProvider = CreateQueryProvider(); return await baseProvider.ExecuteGroupedAggregateAsync( context.SchemeId, groupFields, aggregations, filterJson, havingJson); } /// /// Array grouping over the objects of a subtree. Base implementation: the ids of the subtree (roots, depth and /// Where of the context) become the object condition of the flat array grouping. Pro overrides it with a tree CTE. /// public virtual async Task ExecuteTreeArrayGroupQueryAsync( TreeQueryContext context, Grouping.ArrayGroupQuery query, CancellationToken cancellationToken = default) where TProps : class, new() { var treeObjectIds = await GetTreeObjectIdsForArrayGroupAsync(context, query, cancellationToken); if (treeObjectIds.Count == 0) return System.Text.Json.JsonDocument.Parse("[]"); // no object in the subtree, so no element and no group return await CreateQueryProvider().ExecuteArrayGroupQueryAsync( WithObjectIds(query, treeObjectIds), cancellationToken); } /// /// SQL of : the flat array grouping over the ids of the subtree. /// public virtual async Task GetTreeArrayGroupQuerySqlAsync( TreeQueryContext context, Grouping.ArrayGroupQuery query, CancellationToken cancellationToken = default) where TProps : class, new() { var treeObjectIds = await GetTreeObjectIdsForArrayGroupAsync(context, query, cancellationToken); if (treeObjectIds.Count == 0) return "-- the subtree has no objects: the grouping runs no SQL and returns no groups"; return await CreateQueryProvider().GetArrayGroupQuerySqlAsync( WithObjectIds(query, treeObjectIds), cancellationToken); } private async Task> GetTreeObjectIdsForArrayGroupAsync( TreeQueryContext context, Grouping.ArrayGroupQuery query, CancellationToken cancellationToken) where TProps : class, new() { if (query.Filter != null || !string.IsNullOrEmpty(query.FilterJson)) throw new ArgumentException( "A tree array grouping takes its object condition from the tree context; the request must not carry one.", nameof(query)); query.EnsureValid(); return await GetTreeObjectIdsAsync(context, cancellationToken); } private Grouping.ArrayGroupQuery WithObjectIds(Grouping.ArrayGroupQuery query, List objectIds) => new() { SchemeId = query.SchemeId, ArrayPath = query.ArrayPath, GroupFields = query.GroupFields, Aggregations = query.Aggregations, FilterJson = BuildObjectIdsFilterJson(objectIds), HavingJson = query.HavingJson, Window = query.Window }; /// /// Gets object IDs matching tree query context. /// private async Task> GetTreeObjectIdsAsync(TreeQueryContext context, CancellationToken cancellationToken) where TProps : class, new() { // Use existing tree query infrastructure to get matching IDs var treeQueryable = new TreeQueryableBase( this, context.Clone(), _filterParser, _orderingParser, _facetBuilder); var objects = await treeQueryable.ToListAsync(cancellationToken); return objects.Select(o => o.Id).ToList(); } /// /// Builds filter JSON with object ID constraint. /// Uses 0$: prefix for base fields - required for PostgreSQL. /// private string BuildObjectIdsFilterJson(List objectIds) { // Format: {"0$:id":{"$in":[1,2,3]}} - base fields require 0$: prefix! var idsJson = System.Text.Json.JsonSerializer.Serialize(objectIds); return $"{{\"0$:id\":{{\"$in\":{idsJson}}}}}"; } /// /// Execute Window Functions with tree context. /// Base implementation: get tree object IDs first, then execute window functions with ID filter. /// Override in Pro version for optimized CTE-based implementation. /// public virtual async Task ExecuteTreeWindowQueryAsync( TreeQueryContext context, IEnumerable selectFields, IEnumerable windowFuncs, IEnumerable partitionBy, IEnumerable orderBy, string? frameJson = null, CancellationToken cancellationToken = default) where TProps : class, new() { // Base implementation: get tree object IDs first, then filter window query var treeObjectIds = await GetTreeObjectIdsAsync(context, cancellationToken); if (treeObjectIds.Count == 0) { return System.Text.Json.JsonDocument.Parse("[]"); } // Build filter JSON with object IDs var filterJson = BuildObjectIdsFilterJson(treeObjectIds); // Delegate to base window query with ID filter var baseProvider = CreateQueryProvider(); return await baseProvider.ExecuteWindowQueryAsync( context.SchemeId, selectFields, windowFuncs, partitionBy, orderBy, filterJson, frameJson, context.Limit, context.Offset); } /// /// Get SQL preview for tree window query. /// Base implementation: returns placeholder, override in Pro for actual SQL. /// public virtual async Task GetTreeWindowSqlPreviewAsync( TreeQueryContext context, IEnumerable selectFields, IEnumerable windowFuncs, IEnumerable partitionBy, IEnumerable orderBy, string? frameJson = null, CancellationToken cancellationToken = default) where TProps : class, new() { // Mirror the runtime path: fetch tree object IDs, then delegate to // the non-tree window preview with a `0$:id $in [...]` filter. var treeObjectIds = await GetTreeObjectIdsAsync(context, cancellationToken); if (treeObjectIds.Count == 0) { return $"-- Tree Window: subtree is empty (no objects matched RootObjectId={context.RootObjectId})\n-- SchemeId: {context.SchemeId}"; } var filterJson = BuildObjectIdsFilterJson(treeObjectIds); var baseProvider = CreateQueryProvider(); var preview = await baseProvider.GetWindowSqlPreviewAsync( context.SchemeId, selectFields, windowFuncs, partitionBy, orderBy, filterJson, frameJson, context.Limit, context.Offset); return $"-- Tree Window: subtree resolved to {treeObjectIds.Count} object(s) (RootObjectId={context.RootObjectId})\n" + preview; } /// /// Get SQL preview for tree GROUP BY query. /// Base implementation: fetches tree object IDs and delegates to the /// non-tree GroupBy preview with an `0$:id $in [...]` filter. /// public virtual async Task GetTreeGroupBySqlPreviewAsync( TreeQueryContext context, IEnumerable groupFields, IEnumerable aggregations, string? havingJson = null, CancellationToken cancellationToken = default) where TProps : class, new() { var treeObjectIds = await GetTreeObjectIdsAsync(context, cancellationToken); if (treeObjectIds.Count == 0) { return $"-- Tree GroupBy: subtree is empty (no objects matched RootObjectId={context.RootObjectId})\n-- SchemeId: {context.SchemeId}"; } var filterJson = BuildObjectIdsFilterJson(treeObjectIds); var baseProvider = CreateQueryProvider(); var preview = await baseProvider.GetGroupBySqlPreviewAsync( context.SchemeId, groupFields, aggregations, filterJson, havingJson, cancellationToken); return $"-- Tree GroupBy: subtree resolved to {treeObjectIds.Count} object(s) (RootObjectId={context.RootObjectId})\n" + preview; } // ===== TREE GROUPED WINDOW ===== /// /// Execute GroupBy + Window with tree context. /// Base implementation: gets tree object IDs first, then delegates to base GroupBy + Window with filter. /// Override in Pro version for optimized CTE-based implementation. /// public virtual async Task ExecuteTreeGroupedWindowQueryAsync( TreeQueryContext context, IEnumerable groupFields, IEnumerable aggregations, IEnumerable windowFuncs, IEnumerable partitionBy, IEnumerable orderBy, string? havingJson = null, CancellationToken cancellationToken = default) where TProps : class, new() { // Base implementation: get tree object IDs first, then filter grouping + window var treeObjectIds = await GetTreeObjectIdsAsync(context, cancellationToken); if (treeObjectIds.Count == 0) return System.Text.Json.JsonDocument.Parse("[]"); // Build filter JSON with object IDs var filterJson = BuildObjectIdsFilterJson(treeObjectIds); // Delegate to base grouped window query with ID filter var baseProvider = CreateQueryProvider(); return await baseProvider.ExecuteGroupedWindowQueryAsync( context.SchemeId, groupFields, aggregations, windowFuncs, partitionBy, orderBy, filterJson, havingJson, cancellationToken); } /// /// Get SQL preview for tree GroupBy + Window. /// Base implementation: returns placeholder. /// public virtual async Task GetTreeGroupedWindowSqlPreviewAsync( TreeQueryContext context, IEnumerable groupFields, IEnumerable aggregations, IEnumerable windowFuncs, IEnumerable partitionBy, IEnumerable orderBy, string? havingJson = null, CancellationToken cancellationToken = default) where TProps : class, new() { var treeObjectIds = await GetTreeObjectIdsAsync(context, cancellationToken); if (treeObjectIds.Count == 0) { return $"-- Tree GroupBy + Window: subtree is empty (no objects matched RootObjectId={context.RootObjectId})\n-- SchemeId: {context.SchemeId}"; } var filterJson = BuildObjectIdsFilterJson(treeObjectIds); var baseProvider = CreateQueryProvider(); var preview = await baseProvider.GetGroupedWindowSqlPreviewAsync( context.SchemeId, groupFields, aggregations, windowFuncs, partitionBy, orderBy, filterJson, havingJson, cancellationToken); return $"-- Tree GroupBy + Window: subtree resolved to {treeObjectIds.Count} object(s) (RootObjectId={context.RootObjectId})\n" + preview; } } // ===== HELPER CLASSES ===== /// /// Tree query context - extends QueryContext with tree parameters support /// public class TreeQueryContext : QueryContext where TProps : class, new() { public long? RootObjectId { get; set; } // Limit search to subtree public List TreeFilters { get; set; } // Tree filters // FIX: MaxDepth now inherited from base QueryContext public TreeQueryContext(long schemeId, long? userId, bool checkPermissions, long? rootObjectId, int? maxDepth) : base(schemeId, userId, checkPermissions, null, maxDepth) // Pass maxDepth to base constructor { RootObjectId = rootObjectId; TreeFilters = new List(); } /// /// Create a copy of tree context /// public new TreeQueryContext Clone() => CloneWithMaxDepth(MaxDepth); /// /// A copy with another depth limit. MaxDepth is init-only, so this is the one place that copies every setting /// (TQB-10: WithMaxDepth used to copy by hand and dropped the props depth, lazy references, projection, distinct). /// internal TreeQueryContext CloneWithMaxDepth(int? maxDepth) { // FIX: MaxDepth now passed via base constructor var clone = new TreeQueryContext(SchemeId, UserId, CheckPermissions, RootObjectId, maxDepth) { ParentIds = ParentIds, // SYNC: copy batch array Filter = Filter, Orderings = new List(Orderings), Limit = Limit, Offset = Offset, IsDistinct = IsDistinct, IsDistinctRedb = IsDistinctRedb, DistinctByField = DistinctByField, DistinctByIsBaseField = DistinctByIsBaseField, MaxRecursionDepth = MaxRecursionDepth, IsEmpty = IsEmpty, // FIX: copy IsEmpty flag for TreeQueryContext LazyReferences = LazyReferences, ProjectedStructureIds = ProjectedStructureIds, ProjectedFieldPaths = ProjectedFieldPaths, SkipPropsLoading = SkipPropsLoading, ProjectionReadsNoProps = ProjectionReadsNoProps, PropsDepth = PropsDepth }; // Copy tree filters clone.TreeFilters = new List(TreeFilters); return clone; } } /// /// Tree filter - representation of hierarchical operator /// public class TreeFilter { public TreeFilterOperator Operator { get; set; } public object? Value { get; set; } public int? MaxDepth { get; set; } public long? TargetSchemeId { get; set; } // For polymorphic queries (WhereHasAncestor<TTarget>) public Dictionary? FilterConditions { get; set; } // For Open Source: JSON for SQL functions public FilterExpression? OriginalFilter { get; set; } // For Pro: original FilterExpression public TreeFilter(TreeFilterOperator op, object? value = null) { Operator = op; Value = value; FilterConditions = new Dictionary(); } } /// /// Tree operator types (correspond to SQL operators from search_tree_objects_with_facets) /// public enum TreeFilterOperator { HasAncestor, // $hasAncestor - find objects with ancestor matching condition HasDescendant, // $hasDescendant - find objects with descendant matching condition Level, // $level - filter by level in tree IsRoot, // $isRoot - only root objects IsLeaf, // $isLeaf - only leaves ChildrenOf, // $childrenOf - direct children of object DescendantsOf // $descendantsOf - all descendants of object } Path: redb/redb.Core/Query/Base/TreeQueryableBase.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/Query/Base/TreeQueryableBase.cs ---- using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using redb.Core.Models.Entities; using redb.Core.Models.Contracts; using redb.Core.Query.QueryExpressions; using redb.Core.Query.FacetFilters; using redb.Core.Caching; namespace redb.Core.Query.Base; /// /// Base tree queryable for hierarchical LINQ queries. /// Extends RedbQueryable with tree operation support. /// public class TreeQueryableBase : RedbQueryable where TProps : class, new() { protected readonly ITreeQueryProvider _treeProvider; internal ITreeQueryProvider TreeProvider => _treeProvider; protected readonly TreeQueryContext _treeContext; private readonly IFacetFilterBuilder _facetBuilder; public TreeQueryableBase( ITreeQueryProvider provider, TreeQueryContext context, IFilterExpressionParser filterParser, IOrderingExpressionParser orderingParser, IFacetFilterBuilder? facetBuilder = null) : base(provider, context, filterParser, orderingParser) { _treeProvider = provider; _treeContext = context; _facetBuilder = facetBuilder ?? new FacetFilterBuilder(); } /// /// Creates a new instance with the specified context. Override in derived classes. /// protected virtual TreeQueryableBase CreateInstance(TreeQueryContext context) { return new TreeQueryableBase(_treeProvider, context, _filterParser, _orderingParser, _facetBuilder); } // ===== TREE BASE METHODS OVERRIDE ===== public override IRedbQueryable Where(Expression> predicate) { var newContext = _treeContext.Clone(); var filterExpression = _filterParser.ParseFilter(predicate); // FIX: Check for empty filter (Where(x => false)) if (IsEmptyFilter(filterExpression)) { newContext.IsEmpty = true; } // If there's already a filter, combine with AND if (newContext.Filter != null) { newContext.Filter = new LogicalExpression( LogicalOperator.And, new[] { newContext.Filter, filterExpression } ); } else { newContext.Filter = filterExpression; } // FIX: Return PostgresTreeQueryable, not base RedbQueryable return CreateInstance(newContext); } public override IRedbQueryable WhereRedb(Expression> predicate) { if (predicate == null) throw new ArgumentNullException(nameof(predicate)); var newContext = _treeContext.Clone(); var filterExpression = _filterParser.ParseRedbFilter(predicate); // Check for empty filter if (IsEmptyFilter(filterExpression)) { newContext.IsEmpty = true; } // If there's already a filter, combine with AND if (newContext.Filter != null) { newContext.Filter = new LogicalExpression( LogicalOperator.And, new[] { newContext.Filter, filterExpression } ); } else { newContext.Filter = filterExpression; } return CreateInstance(newContext); } // ===== OVERRIDE SORTING METHODS TO PRESERVE TREE CONTEXT ===== /// /// FIX ISSUE #4: Override OrderBy to preserve Tree context /// Base OrderBy returns RedbQueryable and loses Tree context! /// RETURNS: IOrderedTreeQueryable (inherits from IOrderedRedbQueryable + preserves Tree methods) /// public override IOrderedRedbQueryable OrderBy(Expression> keySelector) { var newContext = _treeContext.Clone(); newContext.Orderings.Clear(); // OrderBy replaces previous sorting var ordering = _orderingParser.ParseOrdering(keySelector, SortDirection.Ascending); newContext.Orderings.Add(ordering); // CORRECT: PostgresTreeQueryable implements IOrderedTreeQueryable : IOrderedRedbQueryable // Return as IOrderedRedbQueryable, but actually it's PostgresTreeQueryable! return CreateInstance(newContext); } /// /// FIX ISSUE #4: Override OrderByDescending for Tree context /// public override IOrderedRedbQueryable OrderByDescending(Expression> keySelector) { var newContext = _treeContext.Clone(); newContext.Orderings.Clear(); // OrderByDescending replaces previous sorting var ordering = _orderingParser.ParseOrdering(keySelector, SortDirection.Descending); newContext.Orderings.Add(ordering); // FIX: Return PostgresTreeQueryable, preserving Tree context! return CreateInstance(newContext); } /// /// FIX ISSUE #4: Override ThenBy for Tree context /// public override IOrderedRedbQueryable ThenBy(Expression> keySelector) { var newContext = _treeContext.Clone(); var ordering = _orderingParser.ParseOrdering(keySelector, SortDirection.Ascending); newContext.Orderings.Add(ordering); // ThenBy adds to existing sorting // FIX: Return PostgresTreeQueryable, preserving Tree context! return CreateInstance(newContext); } /// /// FIX ISSUE #4: Override ThenByDescending for Tree context /// public override IOrderedRedbQueryable ThenByDescending(Expression> keySelector) { var newContext = _treeContext.Clone(); var ordering = _orderingParser.ParseOrdering(keySelector, SortDirection.Descending); newContext.Orderings.Add(ordering); // ThenByDescending adds to existing sorting // FIX: Return PostgresTreeQueryable, preserving Tree context! return CreateInstance(newContext); } // ═══════════════════════════════════════════════════════════════════════════ // SORTING BY BASE RedbObject FIELDS FOR TREE CONTEXT // ═══════════════════════════════════════════════════════════════════════════ public override IOrderedRedbQueryable OrderByRedb(Expression> keySelector) { var newContext = _treeContext.Clone(); newContext.Orderings.Clear(); var ordering = _orderingParser.ParseRedbOrdering(keySelector, SortDirection.Ascending); newContext.Orderings.Add(ordering); return CreateInstance(newContext); } public override IOrderedRedbQueryable OrderByDescendingRedb(Expression> keySelector) { var newContext = _treeContext.Clone(); newContext.Orderings.Clear(); var ordering = _orderingParser.ParseRedbOrdering(keySelector, SortDirection.Descending); newContext.Orderings.Add(ordering); return CreateInstance(newContext); } public override IOrderedRedbQueryable ThenByRedb(Expression> keySelector) { var newContext = _treeContext.Clone(); var ordering = _orderingParser.ParseRedbOrdering(keySelector, SortDirection.Ascending); newContext.Orderings.Add(ordering); return CreateInstance(newContext); } public override IOrderedRedbQueryable ThenByDescendingRedb(Expression> keySelector) { var newContext = _treeContext.Clone(); var ordering = _orderingParser.ParseRedbOrdering(keySelector, SortDirection.Descending); newContext.Orderings.Add(ordering); return CreateInstance(newContext); } /// V4 (LAZY Л2): preserve the tree context (the base method would drop it). public override IRedbQueryable WithLazyReferences(bool enabled = true) { var newContext = _treeContext.Clone(); newContext.LazyReferences = enabled; return CreateInstance(newContext); } // ===== TREE FILTERS ===== /// /// The scheme of the target type of WhereHasAncestor / WhereHasDescendant, found as Query<T>() finds it: the /// metadata cache, then the database. A type the database has no scheme for fails here, as Query<T>() fails for /// it: Pro dropped the filter and returned every node, Free ran into a removed legacy path. /// private long RequireTargetSchemeId(string filterName) { var schemeId = _treeProvider is TreeQueryProviderBase provider ? provider.ResolveSchemeIdByType(typeof(TTarget)) : _treeProvider.Cache.GetSchemeIdByClrType(typeof(TTarget)); if (schemeId is null or 0) throw new InvalidOperationException( $"{filterName}<{typeof(TTarget).Name}>: scheme for type '{typeof(TTarget).Name}' not found. " + "Ensure the type is a [RedbScheme] class and InitializeAsync() was called at startup."); return schemeId.Value; } /// /// Filter by ancestors with polymorphic query support /// public override IRedbQueryable WhereHasAncestor( Expression> ancestorCondition, int? maxDepth = null) { if (ancestorCondition == null) throw new ArgumentNullException(nameof(ancestorCondition)); if (maxDepth.HasValue && maxDepth.Value < 1) throw new ArgumentException("maxDepth must be >= 1", nameof(maxDepth)); var newContext = _treeContext.Clone(); var targetSchemeId = RequireTargetSchemeId(nameof(WhereHasAncestor)); // Parse ancestor condition and add tree filter var filterExpression = _filterParser.ParseFilter(ancestorCondition); var ancestorFilter = new TreeFilter(TreeFilterOperator.HasAncestor) { FilterConditions = ConvertFilterToJson(filterExpression), OriginalFilter = filterExpression, // Pro: for ProSqlBuilder MaxDepth = maxDepth, TargetSchemeId = targetSchemeId }; newContext.TreeFilters.Add(ancestorFilter); return CreateInstance(newContext); } /// /// Filter by descendants with polymorphic query support /// public override IRedbQueryable WhereHasDescendant( Expression> descendantCondition, int? maxDepth = null) { if (descendantCondition == null) throw new ArgumentNullException(nameof(descendantCondition)); if (maxDepth.HasValue && maxDepth.Value < 1) throw new ArgumentException("maxDepth must be >= 1", nameof(maxDepth)); var newContext = _treeContext.Clone(); var targetSchemeId = RequireTargetSchemeId(nameof(WhereHasDescendant)); // Parse descendant condition and add tree filter var filterExpression = _filterParser.ParseFilter(descendantCondition); var descendantFilter = new TreeFilter(TreeFilterOperator.HasDescendant) { FilterConditions = ConvertFilterToJson(filterExpression), OriginalFilter = filterExpression, // Pro: for ProSqlBuilder MaxDepth = maxDepth, TargetSchemeId = targetSchemeId }; newContext.TreeFilters.Add(descendantFilter); return CreateInstance(newContext); } public override IRedbQueryable WhereLevel(int level) { var newContext = _treeContext.Clone(); var levelFilter = new TreeFilter(TreeFilterOperator.Level, level); newContext.TreeFilters.Add(levelFilter); return CreateInstance(newContext); } public override IRedbQueryable WhereLevel(Expression> levelCondition) { if (levelCondition == null) throw new ArgumentNullException(nameof(levelCondition)); var newContext = _treeContext.Clone(); var levelFilter = new TreeFilter(TreeFilterOperator.Level); // Analyze level condition (e.g.: level => level > 2) levelFilter.FilterConditions = ParseLevelCondition(levelCondition); newContext.TreeFilters.Add(levelFilter); return CreateInstance(newContext); } public override IRedbQueryable WhereRoots() { var newContext = _treeContext.Clone(); var rootFilter = new TreeFilter(TreeFilterOperator.IsRoot); newContext.TreeFilters.Add(rootFilter); return CreateInstance(newContext); } public override IRedbQueryable WhereLeaves() { var newContext = _treeContext.Clone(); var leafFilter = new TreeFilter(TreeFilterOperator.IsLeaf); newContext.TreeFilters.Add(leafFilter); return CreateInstance(newContext); } public override IRedbQueryable WhereChildrenOf(long parentId) { var newContext = _treeContext.Clone(); var childrenFilter = new TreeFilter(TreeFilterOperator.ChildrenOf, parentId); newContext.TreeFilters.Add(childrenFilter); return CreateInstance(newContext); } public override IRedbQueryable WhereChildrenOf(IRedbObject parentObject) { if (parentObject == null) throw new ArgumentNullException(nameof(parentObject)); return WhereChildrenOf(parentObject.Id); } public override IRedbQueryable WhereDescendantsOf(long ancestorId, int? maxDepth = null) { var newContext = _treeContext.Clone(); var descendantsFilter = new TreeFilter(TreeFilterOperator.DescendantsOf, ancestorId) { MaxDepth = maxDepth }; newContext.TreeFilters.Add(descendantsFilter); return CreateInstance(newContext); } public override IRedbQueryable WhereDescendantsOf(IRedbObject ancestorObject, int? maxDepth = null) { if (ancestorObject == null) throw new ArgumentNullException(nameof(ancestorObject)); return WhereDescendantsOf(ancestorObject.Id, maxDepth); } // ===== MATERIALIZATION METHODS ===== /// /// Execute query and get list of objects (base RedbObject) /// TreeRedbObject inherits from RedbObject, so direct casting works /// public override async Task>> ToListAsync(CancellationToken cancellationToken = default) { // Get TreeRedbObject and cast to RedbObject (they are compatible) var treeObjects = await ToFlatListAsync(cancellationToken: cancellationToken); return treeObjects.Cast>().ToList(); } internal override RedbQueryable CloneForProjection() => CreateInstance(_treeContext.Clone()); /// /// Override ToListWithProjectionAsync for correct type conversion. /// Tree provider returns List<TreeRedbObject>, need Cast to List<RedbObject>. /// protected internal override async Task>> ToListWithProjectionAsync( HashSet? projectedStructureIds, bool skipPropsLoading = false, CancellationToken cancellationToken = default) { // Set structure_ids in context for provider if (projectedStructureIds != null && projectedStructureIds.Count > 0) { _treeContext.ProjectedStructureIds = projectedStructureIds; } _treeContext.ProjectionReadsNoProps = projectedStructureIds is { Count: 0 }; if (skipPropsLoading) { // FIX: Same logic as RedbQueryable.ToListWithProjectionAsync. // Skip Props re-loading and disable lazy loader — projection SQL already // returned partial Props in the JSON, deserialized via Props setter. _treeContext.SkipPropsLoading = true; } // Get TreeRedbObject and cast to RedbObject via Cast var treeObjects = await ToFlatListAsync(cancellationToken: cancellationToken); return treeObjects.Cast>().ToList(); } public override async Task?> FirstOrDefaultAsync(CancellationToken cancellationToken = default) { // Limit to 1 record var limitedQuery = Take(1); var results = await limitedQuery.ToListAsync(cancellationToken: cancellationToken); return results.FirstOrDefault(); } public override IRedbQueryable Take(int count) { if (count < 0) throw new ArgumentException("Take count must be non-negative", nameof(count)); var newContext = _treeContext.Clone(); newContext.Limit = count; // FIX: Return PostgresTreeQueryable, preserving Tree context! return CreateInstance(newContext); } public override IRedbQueryable Skip(int count) { if (count < 0) throw new ArgumentException("Skip count must be non-negative", nameof(count)); var newContext = _treeContext.Clone(); newContext.Offset = count; // FIX: Return PostgresTreeQueryable, preserving Tree context! return CreateInstance(newContext); } public override IRedbQueryable WhereIn(Expression> selector, IEnumerable values) { if (selector == null) throw new ArgumentNullException(nameof(selector)); if (values == null) throw new ArgumentNullException(nameof(values)); var valuesList = values.ToList(); if (!valuesList.Any()) { // If list is empty, return query that finds nothing return Where(_ => false); } // Create expression: x => values.Contains(selector(x)) var parameter = selector.Parameters[0]; var selectorBody = selector.Body; // Create constant with list of values var valuesConstant = Expression.Constant(valuesList); // Create Contains call var containsMethod = typeof(List).GetMethod("Contains", new[] { typeof(TValue) }); var containsCall = Expression.Call(valuesConstant, containsMethod!, selectorBody); // Create lambda expression var lambda = Expression.Lambda>(containsCall, parameter); return Where(lambda); } public override IRedbQueryable WhereInRedb(Expression> selector, IEnumerable values) { if (selector == null) throw new ArgumentNullException(nameof(selector)); if (values == null) throw new ArgumentNullException(nameof(values)); var valuesList = values.ToList(); if (!valuesList.Any()) { // Empty list = finds nothing return WhereRedb(_ => false); } // Create expression: x => values.Contains(selector(x)) var parameter = selector.Parameters[0]; var selectorBody = selector.Body; // Create constant with list of values var valuesConstant = Expression.Constant(valuesList); // Create Contains call var containsMethod = typeof(List).GetMethod("Contains", new[] { typeof(TValue) }); var containsCall = Expression.Call(valuesConstant, containsMethod!, selectorBody); // Create lambda expression for IRedbObject var lambda = Expression.Lambda>(containsCall, parameter); return WhereRedb(lambda); } public override IRedbQueryable Distinct() { var newContext = _treeContext.Clone(); newContext.IsDistinct = true; // FIX: Return PostgresTreeQueryable, preserving Tree context! return CreateInstance(newContext); } public override IRedbQueryable DistinctRedb() { var newContext = _treeContext.Clone(); newContext.IsDistinctRedb = true; return CreateInstance(newContext); } public override IRedbQueryable DistinctBy(Expression> keySelector) { if (keySelector == null) throw new ArgumentNullException(nameof(keySelector)); var newContext = _treeContext.Clone(); var ordering = _orderingParser.ParseOrdering(keySelector, SortDirection.Ascending); newContext.DistinctByField = ordering; newContext.DistinctByIsBaseField = false; // The ordering by the key goes first, once, in the direction the query gave it. newContext.PutDistinctKeyFirst(ordering); return CreateInstance(newContext); } public override IRedbQueryable DistinctByRedb(Expression> keySelector) { if (keySelector == null) throw new ArgumentNullException(nameof(keySelector)); var newContext = _treeContext.Clone(); var ordering = _orderingParser.ParseRedbOrdering(keySelector, SortDirection.Ascending); newContext.DistinctByField = ordering; newContext.DistinctByIsBaseField = true; // The ordering by the key goes first, once, in the direction the query gave it. newContext.PutDistinctKeyFirst(ordering); return CreateInstance(newContext); } public override IRedbQueryable WithMaxRecursionDepth(int depth) { if (depth < 1) throw new ArgumentException("Max recursion depth must be positive", nameof(depth)); var newContext = _treeContext.Clone(); newContext.MaxRecursionDepth = depth; // FIX: Return PostgresTreeQueryable, preserving Tree context! return CreateInstance(newContext); } /// Same contract as the flat query: the rows ToListAsync returns, Take and Skip included. public override async Task CountAsync(CancellationToken cancellationToken = default) { if (!IsPaged(_treeContext)) return await CountWholeTreeSetAsync(cancellationToken); var unpaged = _treeContext.Clone(); unpaged.Limit = null; unpaged.Offset = null; var total = await CreateInstance(unpaged).CountWholeTreeSetAsync(cancellationToken); return PagedCount(total, _treeContext.Offset, _treeContext.Limit); } private async Task CountWholeTreeSetAsync(CancellationToken cancellationToken) { var result = await _treeProvider.ExecuteAsync(BuildCountExpression(), typeof(int), cancellationToken: cancellationToken); return (int)result; } public override async Task AnyAsync(CancellationToken cancellationToken = default) { // A paged query has rows only if the page has: Take(0) has none, Skip(n) only past the n-th. if (IsPaged(_treeContext)) return await CountAsync(cancellationToken: cancellationToken) > 0; // Asked of the provider as its own operation, as in the flat query: one that can stop at the first node does // not count the whole subtree. var result = await _treeProvider.ExecuteAsync(BuildCountExpression(), typeof(bool), cancellationToken: cancellationToken); return (bool)result; } public override async Task AnyAsync(Expression> predicate, CancellationToken cancellationToken = default) { // Create new query with additional filter var filteredQuery = Where(predicate); return await filteredQuery.AnyAsync(cancellationToken: cancellationToken); } public override async Task AllAsync(Expression> predicate, CancellationToken cancellationToken = default) { if (predicate == null) throw new ArgumentNullException(nameof(predicate)); // All() == true if all records satisfy condition. Counts of the whole set, as in the flat query. var totalCount = await CountWholeTreeSetAsync(cancellationToken); if (totalCount == 0) return true; // All elements of empty set satisfy any condition var matching = Where(predicate); var matchingCount = matching is TreeQueryableBase tree ? await tree.CountWholeTreeSetAsync(cancellationToken) : await matching.CountAsync(cancellationToken: cancellationToken); return totalCount == matchingCount; } // ===== TREE-SPECIFIC METHODS ===== /// /// Execute query and return filtered objects with populated Parent/Children chains /// Loads objects + all parents to root and establishes links /// Children contain only objects from the loaded chain /// public override async Task>> ToTreeListAsync(CancellationToken cancellationToken = default) { // 1. Get filtered objects (with Props via lazy loading) var filteredObjects = await ToFlatListAsync(cancellationToken: cancellationToken); if (!filteredObjects.Any()) return new List>(); var filteredIds = filteredObjects.Select(o => o.id).ToList(); // 2. Get IDs of all parents to root var allIds = await _treeProvider.GetIdsWithAncestorsAsync(filteredIds, cancellationToken); // 3. FIX: Calculate IDs of ONLY parents (that aren't already loaded) var parentIds = allIds.Except(filteredIds).ToList(); List allObjectsUntyped; if (parentIds.Any()) { // 4. Load ONLY parents (don't reload children!) var parents = await _treeProvider.LoadObjectsByIdsAsync(parentIds, _treeContext.PropsDepth, cancellationToken: cancellationToken); // 5. Combine parents with already loaded children allObjectsUntyped = parents .Concat(filteredObjects.Cast()) .ToList(); } else { // No parents (all objects are root) - use only filteredObjects allObjectsUntyped = filteredObjects.Cast().ToList(); } // 6. Establish Parent/Children relationships BuildRelationshipsUntyped(allObjectsUntyped); // 7. Return only filtered objects (filter by TProps type). A set: Contains on the list was a scan per object, // quadratic over a large subtree. var filteredIdSet = filteredIds.ToHashSet(); var matchingByIdAndType = allObjectsUntyped .Where(o => filteredIdSet.Contains(o.Id) && o is TreeRedbObject) .Cast>() .ToList(); return matchingByIdAndType; } /// /// Execute query and get list of tree root nodes /// Loads objects + all parents to root, establishes links and returns roots /// Children contain only objects from the loaded chain /// public override async Task> ToRootListAsync(CancellationToken cancellationToken = default) { // 1. Get filtered objects (with Props via lazy loading) var filteredObjects = await ToFlatListAsync(cancellationToken: cancellationToken); if (!filteredObjects.Any()) return new List(); var filteredIds = filteredObjects.Select(o => o.id).ToList(); // 2. Get IDs of all parents to root var allIds = await _treeProvider.GetIdsWithAncestorsAsync(filteredIds, cancellationToken); // 3. FIX: Calculate IDs of ONLY parents (that aren't already loaded) var parentIds = allIds.Except(filteredIds).ToList(); List allObjects; if (parentIds.Any()) { // 4. Load ONLY parents var parents = await _treeProvider.LoadObjectsByIdsAsync(parentIds, _treeContext.PropsDepth, cancellationToken: cancellationToken); // 5. Combine parents with already loaded children allObjects = parents .Concat(filteredObjects.Cast()) .ToList(); } else { // No parents - use only filteredObjects allObjects = filteredObjects.Cast().ToList(); } // 6. Establish Parent/Children relationships BuildRelationshipsUntyped(allObjects); // 7. Return roots (ParentId == null) return allObjects.Where(o => o.ParentId == null).ToList(); } /// /// Execute query and get flat list of tree objects /// public override async Task>> ToFlatListAsync(CancellationToken cancellationToken = default) { // Execute query through provider var expression = BuildTreeExpression(); var result = await _treeProvider.ExecuteAsync(expression, typeof(List>), cancellationToken: cancellationToken); var list = (List>)result; return list; } /// /// NEW METHOD: Determines if filter is empty (Where(x => false)) /// private bool IsEmptyFilter(FilterExpression filter) { // Check for constant false filter (created for Where(x => false)) if (filter is ComparisonExpression comparison && comparison.Property.Name == "__constant" && comparison.Property.Type == typeof(bool) && comparison.Operator == ComparisonOperator.Equal && comparison.Value is bool boolValue && boolValue == false) { return true; } return false; } // ===== LINQ METHODS ARE INHERITED FROM BASE CLASS ===== // REMOVED all duplicated Where/OrderBy/Take/Skip/Distinct methods! // Using logic from RedbQueryable - WITHOUT DUPLICATION! /// /// Configure maximum search depth in tree /// public override IRedbQueryable WithMaxDepth(int depth) { if (depth < 1) throw new ArgumentException("Max depth must be positive", nameof(depth)); return CreateInstance(_treeContext.CloneWithMaxDepth(depth)); } /// /// Configure maximum depth for loading nested RedbObject in Props /// public override IRedbQueryable WithPropsDepth(int depth) { if (depth < 1) throw new ArgumentException("Props depth must be positive", nameof(depth)); var newContext = _treeContext.Clone(); newContext.PropsDepth = depth; return CreateInstance(newContext); } public IRedbProjectedQueryable Select(Expression, TResult>> selector) { return new TreeProjectedQueryable(this, selector); } // ===== HELPER METHODS ===== /// /// Build expression for tree query /// protected virtual Expression BuildTreeExpression() { return Expression.Constant(_treeContext); } /// /// Converts FilterExpression to JSON dictionary. /// Uses FacetFilterBuilder for full operator support. /// private Dictionary ConvertFilterToJson(FilterExpression filter) { // Uses FacetFilterBuilder for full operator support var facetFiltersJson = _facetBuilder.BuildFacetFilters(filter); if (facetFiltersJson == "{}") return new Dictionary(); // Parse JSON back to Dictionary var result = System.Text.Json.JsonSerializer.Deserialize>(facetFiltersJson); return result ?? new Dictionary(); } /// /// Parse level condition (e.g.: level => level > 2) /// private Dictionary ParseLevelCondition(Expression> levelCondition) { // Simplified parsing - analyze lambda body if (levelCondition.Body is BinaryExpression binary) { switch (binary.NodeType) { case ExpressionType.GreaterThan: if (binary.Right is ConstantExpression gtConstant) return new Dictionary { ["$gt"] = gtConstant.Value! }; break; case ExpressionType.LessThan: if (binary.Right is ConstantExpression ltConstant) return new Dictionary { ["$lt"] = ltConstant.Value! }; break; case ExpressionType.GreaterThanOrEqual: if (binary.Right is ConstantExpression gteConstant) return new Dictionary { ["$gte"] = gteConstant.Value! }; break; case ExpressionType.LessThanOrEqual: if (binary.Right is ConstantExpression lteConstant) return new Dictionary { ["$lte"] = lteConstant.Value! }; break; case ExpressionType.Equal: if (binary.Right is ConstantExpression eqConstant) return new Dictionary { ["$eq"] = eqConstant.Value! }; break; } } // Fallback - return equality 0 (root level) return new Dictionary { ["$eq"] = 0 }; } /// /// Establish Parent/Children relationships between loaded objects /// Does not filter objects - only establishes bidirectional links /// private void BuildRelationships(List> objects) { if (!objects.Any()) return; // Create dictionary for fast lookup by ID var objectDict = objects.ToDictionary(obj => obj.id, obj => obj); // Establish relationships for all objects foreach (var obj in objects) { // Clear Children in case of repeated call obj.Children.Clear(); obj.Parent = null; // If parent exists and is in list - establish relationship if (obj.parent_id.HasValue && objectDict.TryGetValue(obj.parent_id.Value, out var parent)) { obj.Parent = parent; parent.Children.Add(obj); } } } /// /// Build Parent/Children relationships for untyped objects /// Used for polymorphic trees in ToRootListAsync /// private void BuildRelationshipsUntyped(List objects) { if (!objects.Any()) return; // Create dictionary for fast lookup by ID var objectDict = objects.ToDictionary(obj => obj.Id, obj => obj); // Establish relationships for all objects foreach (var obj in objects) { // Clear Children in case of repeated call obj.Children.Clear(); obj.Parent = null; // If parent exists and is in list - establish relationship if (obj.ParentId.HasValue && objectDict.TryGetValue(obj.ParentId.Value, out var parent)) { obj.Parent = parent; parent.Children.Add(obj); } } } /// /// Delete objects without loading data /// Executes DELETE with filters from query /// public override async Task DeleteAsync(CancellationToken cancellationToken = default) { // 1. Get list of objects by filter var objects = await ToListAsync(cancellationToken: cancellationToken); if (objects.Count == 0) return 0; // 2. Extract object IDs var objectIds = objects.Select(o => o.Id).ToArray(); // 3. Delete through provider return await _treeProvider.ExecuteTreeDeleteAsync(objectIds, cancellationToken: cancellationToken); } /// /// Override GroupBy to respect tree context (rootObjectId, maxDepth, ParentIds). /// Returns TreeGroupedQueryable that uses tree-aware execution. /// public override Grouping.IRedbGroupedQueryable GroupBy( Expression> keySelector) { // Return tree-aware grouped queryable that has access to TreeQueryContext return new Grouping.TreeGroupedQueryable( _treeProvider, _treeContext, keySelector, BuildFilterJson()); } /// /// Override GroupByRedb to respect tree context. /// public override Grouping.IRedbGroupedQueryable GroupByRedb( Expression> keySelector) { return new Grouping.TreeGroupedQueryable( _treeProvider, _treeContext, keySelector, BuildFilterJson(), isBaseFieldGrouping: true); } /// /// Override GroupByArray to respect tree context: only the elements of the objects of the subtree are grouped. /// public override Grouping.IRedbGroupedQueryable GroupByArray( Expression>> arraySelector, Expression> keySelector) { return new Grouping.RedbArrayGroupedQueryable( new Grouping.TreeArrayGroupRunner(_treeProvider, _treeContext.Clone()), _treeContext.SchemeId, filter: null, arraySelector, keySelector); } /// /// Override WithWindow to use tree-aware execution. /// Returns TreeWindowedQueryable that uses tree-aware execution with CTE. /// public override Window.IRedbWindowedQueryable WithWindow( Action> windowConfig) { var filterJson = BuildFilterJson(); var windowSpec = new Window.WindowSpec(); windowConfig(windowSpec); return new Window.TreeWindowedQueryable( _treeProvider, _treeContext, filterJson, windowSpec); } // ===== AGGREGATIONS ===== // // SumAsync, AverageAsync, MinAsync, MaxAsync, GetStatisticsAsync, AggregateAsync and their // *RedbAsync counterparts all end in the three calls below. Left to the flat provider they // aggregated the whole scheme: the root, the depth limit and the tree filters of this query // never reached it. A tree aggregate is a tree GROUP BY with no group fields, so all three go // through the same call GroupBy already uses, and return its single row. /// protected override async Task ExecuteGroupedAggregateCoreAsync( IEnumerable groupFields, IEnumerable aggregations, CancellationToken cancellationToken) => await _treeProvider.ExecuteTreeGroupedAggregateAsync( _treeContext, groupFields, aggregations, havingJson: null, cancellationToken: cancellationToken); /// protected override async Task ExecuteAggregateBatchCoreAsync( IEnumerable requests, CancellationToken cancellationToken) { var requestList = requests.ToList(); var result = new Aggregation.AggregateResult(); using var json = await _treeProvider.ExecuteTreeGroupedAggregateAsync( _treeContext, Array.Empty(), requestList, havingJson: null, cancellationToken: cancellationToken); var row = json != null && json.RootElement.GetArrayLength() > 0 ? json.RootElement[0] : (System.Text.Json.JsonElement?)null; foreach (var request in requestList) { object? value = null; if (row.HasValue && row.Value.TryGetProperty(request.Alias, out var element)) { value = element.ValueKind switch { System.Text.Json.JsonValueKind.Number => element.GetDecimal(), System.Text.Json.JsonValueKind.String => element.GetString(), System.Text.Json.JsonValueKind.True => true, System.Text.Json.JsonValueKind.False => false, _ => null }; } result.Values[request.Alias] = value; } return result; } /// protected override async Task ExecuteAggregateCoreAsync( string fieldPath, Aggregation.AggregateFunction function, CancellationToken cancellationToken) { const string alias = "result"; var batch = await ExecuteAggregateBatchCoreAsync( [new Aggregation.AggregateRequest { FieldPath = fieldPath, Function = function, Alias = alias }], cancellationToken); return batch.Values.TryGetValue(alias, out var value) && value != null ? redb.Core.Utils.RedbDecimal.From(value) : null; } } Path: redb/redb.Core/Query/CollationNameValidator.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/Query/CollationNameValidator.cs ---- using System; using System.Text.RegularExpressions; namespace redb.Core.Query { /// /// Single source of truth for what may appear as a collation name in generated SQL. /// /// /// This matters more than a normal setting. COLLATE takes an identifier, not a /// value, so the name cannot be sent as a bound parameter: it is concatenated into the SQL text /// the provider builds. An unchecked name is therefore a direct injection point, reachable from /// application configuration. /// /// /// /// Two independent defences, because either one alone is a single point of failure: /// this validator rejects anything outside a conservative shape at the moment the value is /// assigned, long before any SQL exists; and the emitters additionally quote the name /// ( in C#, quote_ident() in the in-database functions). A name that /// somehow passed the first would still be inert after the second. /// /// /// /// The accepted shape is deliberately narrower than what PostgreSQL allows. Real collation names /// are things like und-x-icu, ru-x-icu, en_US.utf8, C; none of them /// need quotes, spaces or punctuation beyond the four characters below. Widening this later is /// safe, narrowing it is not. /// /// public static class CollationNameValidator { /// Longest name accepted. PostgreSQL identifiers truncate at 63 bytes. public const int MaxLength = 63; // Letters, digits, and the four separators that occur in real collation names. // Notably absent: the double quote, which is what Quote() would have to escape. private static readonly Regex AllowedShape = new(@"^[A-Za-z0-9][A-Za-z0-9_.\-]*$", RegexOptions.Compiled | RegexOptions.CultureInvariant); /// /// Throws unless is a plausible /// collation name. Called when the setting is assigned, so a bad value fails at startup with /// a message naming the setting, rather than as a driver-level syntax error on the first /// search query. /// public static void Validate(string name) { if (string.IsNullOrWhiteSpace(name)) throw new ArgumentException("Collation name must not be empty.", nameof(name)); if (name.Length > MaxLength) throw new ArgumentException( $"Collation name '{name}' is {name.Length} characters; the maximum is {MaxLength}.", nameof(name)); if (!AllowedShape.IsMatch(name)) throw new ArgumentException( $"Collation name '{name}' is not a valid identifier. Allowed: letters, digits, " + "'_', '.' and '-', starting with a letter or digit. Examples: und-x-icu, ru-x-icu, en_US.utf8.", nameof(name)); } /// True when would pass . public static bool IsValid(string? name) => !string.IsNullOrWhiteSpace(name) && name!.Length <= MaxLength && AllowedShape.IsMatch(name); /// /// Renders the name as a quoted SQL identifier. The double quote is doubled even though /// already rejects it: the escaping must be correct on its own, not /// because something upstream promised it would never be needed. /// public static string Quote(string name) => "\"" + name.Replace("\"", "\"\"") + "\""; } } Path: redb/redb.Core/Query/Expressions/FieldNameExtractor.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/Query/Expressions/FieldNameExtractor.cs ---- using System.Linq.Expressions; using redb.Core.Utils; namespace redb.Core.Query.Expressions; /// /// Extracts field names from LINQ Expression tree. /// Used for determining which fields to include in PVT. /// Supports: simple fields, nested fields, Dictionary indexers, ContainsKey. /// public class FieldNameExtractor : ExpressionVisitor { /// /// Collected field names. /// public HashSet FieldNames { get; } = new(); /// /// Extracts field names from expression. /// /// Props type /// Expression to extract from /// Set of field names public static HashSet Extract(Expression> expression) { var extractor = new FieldNameExtractor(); extractor.Visit(expression.Body); return extractor.FieldNames; } /// /// Visits member access (e.g., p.Name, p.Address.City). /// protected override Expression VisitMember(MemberExpression node) { // Check if this is a Props property access if (node.Expression?.NodeType == ExpressionType.Parameter) { FieldNames.Add(node.Member.Name); } // Nested property access (p.Address.City) else if (node.Expression is MemberExpression parent && IsPropsAccess(parent)) { var path = BuildPropertyPath(node); if (!string.IsNullOrEmpty(path)) FieldNames.Add(path); } return base.VisitMember(node); } /// /// Visits method calls (Dictionary indexer, ContainsKey, string methods). /// protected override Expression VisitMethodCall(MethodCallExpression node) { // Handle Dictionary indexer: dict["key"] if (node.Method.Name == "get_Item" && node.Object is MemberExpression member) { var keyArg = node.Arguments.FirstOrDefault(); var keyValue = ExtractConstantValue(keyArg); if (keyValue != null) { // Serialize complex keys (Tuples) using RedbKeySerializer var keyType = keyArg?.Type ?? typeof(string); var keyString = RedbKeySerializer.SerializeObject(keyValue, keyType); // Check for nested property after indexer: AddressBook["home"].City var parentExpr = node; // This will be handled in BuildPropertyPath FieldNames.Add($"{member.Member.Name}[{keyString}]"); } } // Handle ContainsKey else if (node.Method.Name == "ContainsKey" && node.Object is MemberExpression dictMember) { var keyArg = node.Arguments.FirstOrDefault(); var keyValue = ExtractConstantValue(keyArg); if (keyValue != null) { var keyType = keyArg?.Type ?? typeof(string); var keyString = RedbKeySerializer.SerializeObject(keyValue, keyType); FieldNames.Add($"{dictMember.Member.Name}[{keyString}]"); } } // Handle string methods (Contains, StartsWith, EndsWith) else if (node.Method.DeclaringType == typeof(string) && node.Object is MemberExpression strMember) { if (IsPropsAccess(strMember)) { FieldNames.Add(strMember.Member.Name); } } return base.VisitMethodCall(node); } /// /// Checks if member expression is a Props property access. /// private static bool IsPropsAccess(MemberExpression member) { return member.Expression?.NodeType == ExpressionType.Parameter || (member.Expression is MemberExpression parent && IsPropsAccess(parent)); } /// /// Builds property path from nested member expression. /// private static string BuildPropertyPath(MemberExpression member) { var parts = new List(); Expression? current = member; while (current is MemberExpression m) { // Skip .Value/.HasValue on Nullable if ((m.Member.Name == "Value" || m.Member.Name == "HasValue") && m.Member.DeclaringType is { IsGenericType: true } dt && dt.GetGenericTypeDefinition() == typeof(Nullable<>)) { current = m.Expression; continue; } parts.Insert(0, m.Member.Name); current = m.Expression; } return string.Join(".", parts); } /// /// Extracts constant value from expression (handles closures). /// private static object? ExtractConstantValue(Expression? expression) { if (expression == null) return null; switch (expression) { case ConstantExpression constant: return constant.Value; case MemberExpression member when member.Expression is ConstantExpression closure: // Handle closure: value(Closure).field var field = member.Member; return field switch { System.Reflection.FieldInfo f => f.GetValue(closure.Value), System.Reflection.PropertyInfo p => p.GetValue(closure.Value), _ => null }; default: // Try to compile and evaluate try { var lambda = Expression.Lambda(expression); var compiled = lambda.Compile(); return compiled.DynamicInvoke(); } catch { return null; } } } } Path: redb/redb.Core/Query/FacetFilterBuilder.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/Query/FacetFilterBuilder.cs ---- using System; using System.Collections.Generic; using System.Linq; using System.Text.Json; using Microsoft.Extensions.Logging; using redb.Core.Models.Contracts; using redb.Core.Query.FacetFilters; using redb.Core.Query.QueryExpressions; namespace redb.Core.Query; /// /// Builds JSON filters for search_objects_with_facets function. /// Supports 25+ operators, nullable fields, Class fields, arrays. /// public class FacetFilterBuilder : IFacetFilterBuilder { private readonly JsonSerializerOptions _jsonOptions; private readonly ILogger? _logger; public FacetFilterBuilder(ILogger? logger = null) { _logger = logger; _jsonOptions = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase, WriteIndented = false, Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping }; } public string BuildFacetFilters(FilterExpression? filter) { if (filter == null) { _logger?.LogDebug("LINQ Filter: No filter provided, returning empty filter: {{}}"); return "{}"; } var filterObject = BuildFilterObject(filter); var filterJson = JsonSerializer.Serialize(filterObject, _jsonOptions); _logger?.LogDebug("LINQ Filter Generated: {FilterJson}", filterJson); return filterJson; } public virtual string BuildOrderBy(IReadOnlyList orderings) { if (!orderings.Any()) { _logger?.LogDebug("LINQ OrderBy: No ordering provided, returning empty array: []"); return "[]"; } // Extended format: [{"field": "Name", "direction": "ASC"}] // Works with both PostgreSQL and MSSQL (MSSQL requires this format) var orderArray = orderings.Select(o => new { field = BuildFieldPath(o.Property), direction = o.Direction == SortDirection.Ascending ? "ASC" : "DESC" }).ToArray(); var orderJson = JsonSerializer.Serialize(orderArray, _jsonOptions); _logger?.LogDebug("LINQ OrderBy Generated: {OrderJson}", orderJson); return orderJson; } public QueryParameters BuildQueryParameters(int? limit = null, int? offset = null) { return new QueryParameters(limit, offset); } private object BuildFilterObject(FilterExpression filter) { return filter switch { ComparisonExpression comparison => BuildComparisonFilter(comparison), LogicalExpression logical => BuildLogicalFilter(logical), NullCheckExpression nullCheck => BuildNullCheckFilter(nullCheck), InExpression inExpr => BuildInFilter(inExpr), ArrayElementAnyExpression elementAny => throw new NotSupportedException( $"Any() with a condition over the array of classes '{elementAny.Collection.Name}' is not supported by the free " + "providers (redb Pro supports it). Any() over a list-item array, Contains over an array of values and Any() " + "without a condition are."), _ => throw new NotSupportedException($"Filter expression type {filter.GetType().Name} is not supported") }; } private object BuildComparisonFilter(ComparisonExpression comparison) { // Where(x => true / false), alone or inside AND / OR / NOT: a comparison of two constants, which every module // compiles as any other $expr. No field is read. if (comparison.Property.Name == "__constant") { return new Dictionary { ["$expr"] = BuildConstantBoolNode(comparison) }; } // Computed-expression comparison: arithmetic/function on either side. // Emits PVT `$expr` boolean predicate node. if (comparison.LeftExpression != null || comparison.RightExpression != null || comparison.Property.Name == "__computed") { // Special case: `arr.Length OP const` (compiled as ArrayLength UnaryExpression // and surfaced as FunctionCallExpression(Length, PropertyValue(arr)) by the // parser) cannot use the generic $expr/$length form because that expands to // text LENGTH(...) only. Route through the `.$length` modifier so the PVT // engine picks the array-aware array_length() form. if (TryBuildArrayLengthCountFilter(comparison, out var arrFilter)) { return arrFilter!; } return BuildComputedExprFilter(comparison); } var fieldName = BuildFieldPath(comparison.Property); // Handling property functions: Length, Count, ToLower, ToUpper, Trim, Year, ... if (comparison.Property.Function.HasValue) { return BuildFunctionComparisonFilter(comparison, fieldName); } // FIX: Convert value to correct type based on field schema! var originalValue = comparison.Value; // NEW: Handle direct ListItem comparison (fallback check) // Main handling happens in parser, but add protection at builder level if (originalValue is IRedbListItem listItem) { originalValue = listItem.Id; // Bare ListItem field path (e.g. "Status") defaults to .Value // (string) on the SQL side. Direct comparison against a // RedbListItem instance always means "match by id", so route // through the .Id (bigint) accessor. if (!fieldName.Contains('.', StringComparison.Ordinal) && IsRedbListItemType(comparison.Property.Type)) { fieldName += ".Id"; } } // CRITICAL LOGGING: check what type comes in // _logger?.LogInformation($"BEFORE ConvertValueToFieldType:"); // _logger?.LogInformation($" Property.Type: {comparison.Property.Type.Name}"); // _logger?.LogInformation($" Is DateTime?: {comparison.Property.Type == typeof(DateTime)}"); // _logger?.LogInformation($" Is Nullable?: {comparison.Property.Type == typeof(DateTime?)}"); // _logger?.LogInformation($" Underlying type: {Nullable.GetUnderlyingType(comparison.Property.Type)?.Name ?? "not nullable"}"); var value = ConvertValueToFieldType(originalValue, comparison.Property.Type); // DETAILED TYPE CONVERSION LOGGING // _logger?.LogInformation($"TYPE CONVERSION: Field '{comparison.Property.Name}' (Type: {comparison.Property.Type.Name})"); // _logger?.LogInformation($" Original value: {originalValue} ({originalValue?.GetType().Name ?? "null"})"); // _logger?.LogInformation($" Converted value: {value} ({value?.GetType().Name ?? "null"})"); // DETAILED LOGGING FOR DateTime/DateTimeOffset // if (value is DateTime dtValue) // { // _logger?.LogInformation($" ⏰ DateTime.Kind: {dtValue.Kind}, Value: {dtValue:yyyy-MM-dd HH:mm:ss}"); // } // else if (value is DateTimeOffset dtoValue) // { // _logger?.LogInformation($" ⏰ DateTimeOffset: {dtoValue:yyyy-MM-dd HH:mm:ss zzz}, UTC: {dtoValue.UtcDateTime:yyyy-MM-dd HH:mm:ss}"); // } // _logger?.LogInformation($" Operator: {comparison.Operator}"); // SPECIAL LOGGING FOR EQUALITY if (comparison.Operator == ComparisonOperator.Equal) { // FIX JSON SERIALIZATION: For Double types forcibly create decimal number var finalValue = value; if (comparison.Property.Type == typeof(double) || comparison.Property.Type == typeof(double?)) { if (value is double doubleVal && doubleVal == Math.Floor(doubleVal)) { // Convert 2000.0 to "2000.0" so SQL understands it's Double finalValue = doubleVal.ToString("F1", System.Globalization.CultureInfo.InvariantCulture); // 2000 → "2000.0" _logger?.LogDebug($"FIXED: Forcibly create double string: {finalValue}"); } } var result = new Dictionary { [fieldName] = new Dictionary { ["$eq"] = finalValue } }; // LOG FINAL JSON FILTER // _logger?.LogInformation($" Generated filter: {{{fieldName}: {{\"$eq\": {finalValue}}}}}"); return result; } return comparison.Operator switch { ComparisonOperator.NotEqual => new Dictionary { [fieldName] = new Dictionary { ["$ne"] = value } }, ComparisonOperator.GreaterThan => new Dictionary { [fieldName] = new Dictionary { ["$gt"] = value } }, ComparisonOperator.GreaterThanOrEqual => new Dictionary { [fieldName] = new Dictionary { ["$gte"] = value } }, ComparisonOperator.LessThan => new Dictionary { [fieldName] = new Dictionary { ["$lt"] = value } }, ComparisonOperator.LessThanOrEqual => new Dictionary { [fieldName] = new Dictionary { ["$lte"] = value } }, ComparisonOperator.Contains => BuildContainsFilter(fieldName, value, false), ComparisonOperator.ContainsIgnoreCase => BuildContainsFilter(fieldName, value, true), ComparisonOperator.StartsWith => new Dictionary { [fieldName] = new Dictionary { ["$startsWith"] = value } }, ComparisonOperator.StartsWithIgnoreCase => new Dictionary { [fieldName] = new Dictionary { ["$startsWithIgnoreCase"] = value } }, ComparisonOperator.EndsWith => new Dictionary { [fieldName] = new Dictionary { ["$endsWith"] = value } }, ComparisonOperator.EndsWithIgnoreCase => new Dictionary { [fieldName] = new Dictionary { ["$endsWithIgnoreCase"] = value } }, // NULL SEMANTICS ComparisonOperator.Exists => new Dictionary { [fieldName] = new Dictionary { ["$exists"] = value } }, // BASIC ARRAY OPERATORS ComparisonOperator.ArrayContains => BuildArrayFilter(fieldName, "$arrayContains", value), ComparisonOperator.ArrayAny => BuildArrayFilter(fieldName, "$arrayAny", true), ComparisonOperator.ArrayEmpty => BuildArrayFilter(fieldName, "$arrayEmpty", true), ComparisonOperator.ArrayCount => BuildArrayFilter(fieldName, "$arrayCount", value), ComparisonOperator.ArrayCountGt => BuildArrayFilter(fieldName, "$arrayCountGt", value), ComparisonOperator.ArrayCountGte => BuildArrayFilter(fieldName, "$arrayCountGte", value), ComparisonOperator.ArrayCountLt => BuildArrayFilter(fieldName, "$arrayCountLt", value), ComparisonOperator.ArrayCountLte => BuildArrayFilter(fieldName, "$arrayCountLte", value), // POSITIONAL ARRAY OPERATORS ComparisonOperator.ArrayAt => BuildArrayFilter(fieldName, "$arrayAt", value), ComparisonOperator.ArrayFirst => BuildArrayFilter(fieldName, "$arrayFirst", value), ComparisonOperator.ArrayLast => BuildArrayFilter(fieldName, "$arrayLast", value), // SEARCH ARRAY OPERATORS ComparisonOperator.ArrayStartsWith => BuildArrayFilter(fieldName, "$arrayStartsWith", value), ComparisonOperator.ArrayEndsWith => BuildArrayFilter(fieldName, "$arrayEndsWith", value), ComparisonOperator.ArrayMatches => BuildArrayFilter(fieldName, "$arrayMatches", value), // AGGREGATION ARRAY OPERATORS ComparisonOperator.ArraySum => BuildArrayFilter(fieldName, "$arraySum", value), ComparisonOperator.ArrayAvg => BuildArrayFilter(fieldName, "$arrayAvg", value), ComparisonOperator.ArrayMin => BuildArrayFilter(fieldName, "$arrayMin", value), ComparisonOperator.ArrayMax => BuildArrayFilter(fieldName, "$arrayMax", value), _ => throw new NotSupportedException($"Comparison operator {comparison.Operator} is not supported") }; } private object BuildLogicalFilter(LogicalExpression logical) { return logical.Operator switch { LogicalOperator.And => BuildAndFilter(logical.Operands), LogicalOperator.Or => new Dictionary { ["$or"] = logical.Operands.Select(BuildFilterObject).ToArray() }, LogicalOperator.Not when HasEmptyIn(logical.Operands[0]) => BuildFilterObject(Negate(logical.Operands[0])), LogicalOperator.Not => new Dictionary { ["$not"] = BuildFilterObject(logical.Operands.First()) }, _ => throw new NotSupportedException($"Logical operator {logical.Operator} is not supported") }; } // Contains over an empty list is false where the field has a value and unknown where it has none, as SQL reads // (col <> col) on Pro. The modules spell $in [] as an IN over an empty set, false on every object, so NOT around it // returned the objects without a value too. A negation over such a membership is pushed down instead (De Morgan // holds in three-valued logic), and the negated empty membership becomes "the field has a value". private static bool HasEmptyIn(FilterExpression expression) => expression switch { InExpression inExpr => inExpr.Values.Count == 0, LogicalExpression logical => logical.Operands.Any(HasEmptyIn), _ => false }; private static FilterExpression Negate(FilterExpression expression) => expression switch { InExpression { Values.Count: 0 } inExpr => new NullCheckExpression(inExpr.Property, IsNull: false), LogicalExpression { Operator: LogicalOperator.Not } negated => negated.Operands[0], LogicalExpression { Operator: LogicalOperator.And } all when HasEmptyIn(all) => new LogicalExpression(LogicalOperator.Or, all.Operands.Select(Negate).ToList()), LogicalExpression { Operator: LogicalOperator.Or } any when HasEmptyIn(any) => new LogicalExpression(LogicalOperator.And, any.Operands.Select(Negate).ToList()), _ => new LogicalExpression(LogicalOperator.Not, [expression]) }; private object BuildAndFilter(IReadOnlyList operands) { // For AND we can merge conditions into one object if they don't conflict // Otherwise use $and var result = new Dictionary(); foreach (var operand in operands) { var filterObj = BuildFilterObject(operand); if (filterObj is Dictionary dict) { foreach (var kvp in dict) { if (result.ContainsKey(kvp.Key)) { // Key conflict - use $and return new Dictionary { ["$and"] = operands.Select(BuildFilterObject).ToArray() }; } result[kvp.Key] = kvp.Value; } } else { // Complex object - use $and return new Dictionary { ["$and"] = operands.Select(BuildFilterObject).ToArray() }; } } return result; } /// /// Builds filter for property functions like Length, ToLower, Year via PVT $expr form: /// {"$expr": {"$gt": [{"$length": {"$field": "Name"}}, {"$const": 3}]}}. /// private object BuildFunctionComparisonFilter(ComparisonExpression comparison, string fieldName) { var function = comparison.Property.Function!.Value; var opKey = MapComparisonOperatorToExprKey(comparison.Operator); // Length/Count on arrays/collections is polymorphic in SQL and cannot use the // generic $expr/$length form (which expands to text LENGTH(...) only). // Route through the legacy `.$length` / `.$count` modifier so the PVT SQL // layer picks the array-aware array_length() form based on registered field metadata. if ((function == QueryExpressions.PropertyFunction.Length || function == QueryExpressions.PropertyFunction.Count) && IsArrayOrCollectionType(comparison.Property.FunctionSourceType)) { var modifier = function == QueryExpressions.PropertyFunction.Length ? ".$length" : ".$count"; return new Dictionary { [fieldName + modifier] = new Dictionary { [opKey] = comparison.Value } }; } var funcKey = MapPropertyFunctionToExprKey(function); // Inner scalar node: {"$": {"$field": ""}} var inner = new Dictionary { [funcKey] = new Dictionary { ["$field"] = fieldName } }; var rhs = new Dictionary { ["$const"] = comparison.Value }; return new Dictionary { ["$expr"] = new Dictionary { [opKey] = new object?[] { inner, rhs } } }; } private static bool IsArrayOrCollectionType(Type? t) { if (t == null) return false; if (t == typeof(string)) return false; if (t.IsArray) return true; if (typeof(System.Collections.IEnumerable).IsAssignableFrom(t)) return true; return false; } /// /// Detects `arr.Length/.Count OP const` (array side) and rewrites the comparison /// as the legacy `.$length` / `.$count` modifier filter, which the PVT SQL builder /// translates to array_length() for array-typed fields. /// Returns false for non-matching shapes (string.Length, both sides expressions, etc.) /// so caller falls back to . /// private bool TryBuildArrayLengthCountFilter(ComparisonExpression comparison, out object? filter) { filter = null; FunctionCallExpression? fc = null; object? constValue = null; ComparisonOperator op = comparison.Operator; bool funcOnLeft = false; if (comparison.LeftExpression is FunctionCallExpression lfc && comparison.RightExpression is ConstantValueExpression rcv) { fc = lfc; constValue = rcv.Value; funcOnLeft = true; } else if (comparison.RightExpression is FunctionCallExpression rfc && comparison.LeftExpression is ConstantValueExpression lcv) { fc = rfc; constValue = lcv.Value; } else { return false; } if (fc.Function != QueryExpressions.PropertyFunction.Length && fc.Function != QueryExpressions.PropertyFunction.Count) { return false; } if (fc.Argument is not PropertyValueExpression pv) return false; if (!IsArrayOrCollectionType(pv.Property.Type)) return false; // Mirror operator if function was on the right side: `5 < arr.Length` becomes `arr.Length > 5` if (!funcOnLeft) { op = op switch { ComparisonOperator.GreaterThan => ComparisonOperator.LessThan, ComparisonOperator.GreaterThanOrEqual => ComparisonOperator.LessThanOrEqual, ComparisonOperator.LessThan => ComparisonOperator.GreaterThan, ComparisonOperator.LessThanOrEqual => ComparisonOperator.GreaterThanOrEqual, _ => op }; } var fieldName = BuildFieldPath(pv.Property); // Both arr.Length and coll.Count on an array/collection field map to the PVT // `.$count` modifier, which expands to COUNT(*) over the rows representing the // array. The `.$length` modifier is reserved for STRING length and expands to // LENGTH(_String), which is the wrong operation for arrays. var modifier = ".$count"; var opKey = MapComparisonOperatorToExprKey(op); filter = new Dictionary { [fieldName + modifier] = new Dictionary { [opKey] = constValue } }; return true; } /// /// The $expr node of a constant condition: 1 = 1 for true, 1 = 0 for false. /// private static Dictionary BuildConstantBoolNode(ComparisonExpression constant) { var holds = constant.Value is true == (constant.Operator == ComparisonOperator.Equal); return new Dictionary { ["$eq"] = new object?[] { new Dictionary { ["$const"] = 1 }, new Dictionary { ["$const"] = holds ? 1 : 0 } } }; } /// /// Builds PVT $expr predicate for computed comparisons whose operands are /// arithmetic / function expressions (LeftExpression/RightExpression). /// private object BuildComputedExprFilter(ComparisonExpression comparison) { var opKey = MapComparisonOperatorToExprKey(comparison.Operator); object? lhs = comparison.LeftExpression != null ? BuildScalarExprNode(comparison.LeftExpression) : new Dictionary { ["$field"] = BuildFieldPath(comparison.Property) }; object? rhs = comparison.RightExpression != null ? BuildScalarExprNode(comparison.RightExpression) : new Dictionary { ["$const"] = comparison.Value }; return new Dictionary { ["$expr"] = new Dictionary { [opKey] = new object?[] { lhs, rhs } } }; } private object BuildScalarExprNode(ValueExpression expr) { switch (expr) { case PropertyValueExpression pv: return new Dictionary { ["$field"] = BuildFieldPath(pv.Property) }; case ConstantValueExpression cv: { var value = cv.Value; if (value is IRedbListItem li) value = li.Id; return new Dictionary { ["$const"] = value }; } case ArithmeticExpression ax: { // String '+' in C# is concatenation. PVT $add maps to SQL '+' // (numeric); for text operands we must emit $concat (SQL '||'). var key = ax.Operator switch { ArithmeticOperator.Add when IsStringValueExpression(ax.Left) || IsStringValueExpression(ax.Right) => "$concat", ArithmeticOperator.Add => "$add", ArithmeticOperator.Subtract => "$sub", ArithmeticOperator.Multiply => "$mul", ArithmeticOperator.Divide => "$div", ArithmeticOperator.Modulo => "$mod", _ => throw new NotSupportedException($"ArithmeticOperator.{ax.Operator} is not supported.") }; return new Dictionary { [key] = new object?[] { BuildScalarExprNode(ax.Left), BuildScalarExprNode(ax.Right) } }; } case FunctionCallExpression fc: { var key = MapPropertyFunctionToExprKey(fc.Function); return new Dictionary { [key] = BuildScalarExprNode(fc.Argument) }; } case MultiArgFunctionCallExpression mfc: { // DateTime.AddX(n) -> {"$dateadd": ["", , ]} (unit is a plain JSON // string literal, NOT wrapped in $const — see pvt_build_scalar_expr in 17_pvt_expr.sql). var unit = MapAddFunctionToUnit(mfc.Function); if (unit != null) { if (mfc.Arguments.Count != 2) throw new InvalidOperationException($"DateTime.{mfc.Function} expects [date, n] (2 args)."); return new Dictionary { ["$dateadd"] = new object?[] { unit, BuildScalarExprNode(mfc.Arguments[0]), BuildScalarExprNode(mfc.Arguments[1]) } }; } // Regex.Replace(input, pattern, replacement) -> {"$regexreplace": [input, pat, repl, "g"]} // Inject 'g' flag as 4th arg ($const text literal) so PVT REGEXP_REPLACE replaces // all matches like .NET Regex.Replace (PG default is first-match only). if (mfc.Function == QueryExpressions.PropertyFunction.RegexReplace) { if (mfc.Arguments.Count != 3) throw new InvalidOperationException("Regex.Replace expects [input, pattern, replacement] (3 args)."); return new Dictionary { ["$regexreplace"] = new object?[] { BuildScalarExprNode(mfc.Arguments[0]), BuildScalarExprNode(mfc.Arguments[1]), BuildScalarExprNode(mfc.Arguments[2]), new Dictionary { ["$const"] = "g" } } }; } // Multi-arg string functions (Substring/Replace/IndexOf/PadLeft/PadRight) // map to {"$substring": [a, b[, c]]}, {"$replace": [a, b, c]}, etc. // The parser already applied C#->SQL index translation (Substring start+1, IndexOf - 1). var key = MapPropertyFunctionToExprKey(mfc.Function); var args = new object?[mfc.Arguments.Count]; for (int i = 0; i < mfc.Arguments.Count; i++) args[i] = BuildScalarExprNode(mfc.Arguments[i]); return new Dictionary { [key] = args }; } case CustomFunctionExpression cfe: { var args = new object?[cfe.Arguments.Count]; for (int i = 0; i < cfe.Arguments.Count; i++) args[i] = BuildScalarExprNode(cfe.Arguments[i]); return new Dictionary { ["$" + cfe.FunctionName.ToLowerInvariant()] = args }; } case CoalesceExpression ce: { // ?? operator (n-ary) → {"$coalesce": [a, b, ...]}, handled by // pvt_build_scalar_expr (17_pvt_expr.sql) which emits COALESCE(a, b, ...). var args = new object?[ce.Arguments.Count]; for (int i = 0; i < ce.Arguments.Count; i++) args[i] = BuildScalarExprNode(ce.Arguments[i]); return new Dictionary { ["$coalesce"] = args }; } case ConditionalValueExpression cv: { // C# ternary cond ? a : b → {"$if": [, , ]}, // handled by pvt_build_scalar_expr ($if branch) in 17_pvt_expr.sql. return new Dictionary { ["$if"] = new object?[] { BuildBoolExprNode(cv.Test), BuildScalarExprNode(cv.IfTrue), BuildScalarExprNode(cv.IfFalse) } }; } default: throw new NotSupportedException($"ValueExpression {expr.GetType().Name} is not supported in $expr."); } } /// /// Builds the inner-predicate JSON shape expected by pvt_build_bool_expr /// (see 17_pvt_expr.sql): comparisons render as /// {"$eq":[lhs,rhs]}, logical operators as {"$and"/"$or":[..]} / /// {"$not":node}, null-checks as {"$null":[field]} / /// {"$notnull":[field]}. Used as the cond slot of $if. /// private object BuildBoolExprNode(FilterExpression filter) { switch (filter) { case ComparisonExpression cmp: { if (cmp.Property.Name == "__constant") return BuildConstantBoolNode(cmp); var opKey = MapComparisonOperatorToExprKey(cmp.Operator); var lhs = cmp.LeftExpression != null ? BuildScalarExprNode(cmp.LeftExpression) : new Dictionary { ["$field"] = BuildFieldPath(cmp.Property) }; var rhs = cmp.RightExpression != null ? BuildScalarExprNode(cmp.RightExpression) : new Dictionary { ["$const"] = cmp.Value }; return new Dictionary { [opKey] = new object?[] { lhs, rhs } }; } case LogicalExpression logical: { if (logical.Operator == LogicalOperator.Not) { return new Dictionary { ["$not"] = BuildBoolExprNode(logical.Operands[0]) }; } var key = logical.Operator == LogicalOperator.And ? "$and" : "$or"; var parts = new object?[logical.Operands.Count]; for (int i = 0; i < logical.Operands.Count; i++) parts[i] = BuildBoolExprNode(logical.Operands[i]); return new Dictionary { [key] = parts }; } case NullCheckExpression nc: { var fieldNode = new Dictionary { ["$field"] = BuildFieldPath(nc.Property) }; return new Dictionary { [nc.IsNull ? "$null" : "$notnull"] = new object?[] { fieldNode } }; } default: throw new NotSupportedException( $"FilterExpression {filter.GetType().Name} is not supported inside a ternary $if condition."); } } /// /// Best-effort check whether a resolves to a string at runtime. /// Used to decide between SQL '+' (numeric $add) and '||' ($concat) for arithmetic Add. /// private static bool IsStringValueExpression(ValueExpression expr) { return expr switch { PropertyValueExpression pve => pve.Property.Type == typeof(string), ConstantValueExpression cve => cve.Type == typeof(string) || cve.Value is string, ArithmeticExpression ae when ae.Operator == ArithmeticOperator.Add => IsStringValueExpression(ae.Left) || IsStringValueExpression(ae.Right), FunctionCallExpression fce => fce.Function is QueryExpressions.PropertyFunction.ToLower or QueryExpressions.PropertyFunction.ToUpper or QueryExpressions.PropertyFunction.Trim or QueryExpressions.PropertyFunction.TrimStart or QueryExpressions.PropertyFunction.TrimEnd || IsStringValueExpression(fce.Argument), MultiArgFunctionCallExpression mfce => mfce.Function is QueryExpressions.PropertyFunction.Substring or QueryExpressions.PropertyFunction.Replace or QueryExpressions.PropertyFunction.PadLeft or QueryExpressions.PropertyFunction.PadRight or QueryExpressions.PropertyFunction.RegexReplace, _ => false }; } private static string MapPropertyFunctionToExprKey(QueryExpressions.PropertyFunction function) => function switch { QueryExpressions.PropertyFunction.Length => "$length", QueryExpressions.PropertyFunction.Count => "$count", QueryExpressions.PropertyFunction.ToLower => "$lower", QueryExpressions.PropertyFunction.ToUpper => "$upper", QueryExpressions.PropertyFunction.Trim => "$trim", QueryExpressions.PropertyFunction.TrimStart => "$trimstart", QueryExpressions.PropertyFunction.TrimEnd => "$trimend", QueryExpressions.PropertyFunction.Substring => "$substring", QueryExpressions.PropertyFunction.Replace => "$replace", QueryExpressions.PropertyFunction.IndexOf => "$indexof", QueryExpressions.PropertyFunction.PadLeft => "$padleft", QueryExpressions.PropertyFunction.PadRight => "$padright", QueryExpressions.PropertyFunction.Abs => "$abs", QueryExpressions.PropertyFunction.Round => "$round", QueryExpressions.PropertyFunction.Floor => "$floor", QueryExpressions.PropertyFunction.Ceiling => "$ceil", QueryExpressions.PropertyFunction.Sqrt => "$sqrt", QueryExpressions.PropertyFunction.Sign => "$sign", QueryExpressions.PropertyFunction.Exp => "$exp", QueryExpressions.PropertyFunction.Log => "$ln", // 1-arg Math.Log = natural log QueryExpressions.PropertyFunction.LogBase => "$log", // 2-arg: [base, value] QueryExpressions.PropertyFunction.Pow => "$power", QueryExpressions.PropertyFunction.Year => "$year", QueryExpressions.PropertyFunction.Month => "$month", QueryExpressions.PropertyFunction.Day => "$day", QueryExpressions.PropertyFunction.Hour => "$hour", QueryExpressions.PropertyFunction.Minute => "$minute", QueryExpressions.PropertyFunction.Second => "$second", QueryExpressions.PropertyFunction.DayOfWeek => "$dayofweek", QueryExpressions.PropertyFunction.DayOfYear => "$dayofyear", QueryExpressions.PropertyFunction.RegexReplace => "$regexreplace", _ => throw new NotSupportedException($"PropertyFunction.{function} has no $expr mapping.") }; /// /// Maps a AddX function to the /// PVT $dateadd unit literal (lowercase). Returns null if the /// function is not a DateTime add. Used in the MultiArgFunctionCallExpression /// branch to emit {"$dateadd": ["unit", date, n]} facet shape. /// private static string? MapAddFunctionToUnit(QueryExpressions.PropertyFunction function) => function switch { QueryExpressions.PropertyFunction.AddYears => "year", QueryExpressions.PropertyFunction.AddMonths => "month", QueryExpressions.PropertyFunction.AddDays => "day", QueryExpressions.PropertyFunction.AddHours => "hour", QueryExpressions.PropertyFunction.AddMinutes => "minute", QueryExpressions.PropertyFunction.AddSeconds => "second", _ => null }; private static string MapComparisonOperatorToExprKey(ComparisonOperator op) => op switch { ComparisonOperator.Equal => "$eq", ComparisonOperator.NotEqual => "$ne", ComparisonOperator.GreaterThan => "$gt", ComparisonOperator.GreaterThanOrEqual => "$gte", ComparisonOperator.LessThan => "$lt", ComparisonOperator.LessThanOrEqual => "$lte", ComparisonOperator.Contains => "$contains", ComparisonOperator.ContainsIgnoreCase => "$containsignorecase", ComparisonOperator.StartsWith => "$startswith", ComparisonOperator.StartsWithIgnoreCase => "$startswithignorecase", ComparisonOperator.EndsWith => "$endswith", ComparisonOperator.EndsWithIgnoreCase => "$endswithignorecase", ComparisonOperator.RegexMatch => "$regex", ComparisonOperator.RegexMatchIgnoreCase => "$iregex", _ => throw new NotSupportedException($"Operator {op} is not supported in $expr predicate.") }; private object BuildNullCheckFilter(NullCheckExpression nullCheck) { var fieldName = BuildFieldPath(nullCheck.Property); // Target logic for base fields and EAV fields: // - Base fields (_objects): column always exists, check only value -> null directly // - EAV fields (Props): record may not exist -> $exists for "field exists" semantics if (nullCheck.Property.IsBaseField) { // Base fields: simple null / $ne null if (nullCheck.IsNull) { return new Dictionary { [fieldName] = null // Serialized as field: null }; } else { return new Dictionary { [fieldName] = new Dictionary { ["$ne"] = null } }; } } else { // EAV fields: $exists for record existence semantics if (nullCheck.IsNull) { return new Dictionary { [fieldName] = new Dictionary { ["$exists"] = false } }; } else { return new Dictionary { [fieldName] = new Dictionary { ["$ne"] = null } }; } } } private object BuildInFilter(InExpression inExpr) { var fieldName = BuildFieldPath(inExpr.Property); // Each value spelled as a single comparison value of the field is ($eq goes through the same conversion): a list // of dates, times or texts reached the module in another spelling than the field stores. var values = inExpr.Values.Select(v => ConvertValueToFieldType(v, inExpr.Property.Type)).ToArray(); return new Dictionary { [fieldName] = new Dictionary { ["$in"] = values } }; } // ===== NEW METHODS FOR NEW PARADIGM ===== /// /// Build field path with Class fields support (Contact.Name, Contacts[].Email) /// BUG FIX: For RedbObject base fields use "0$:" prefix /// to distinguish them from Props fields with same names (e.g. name vs Name) /// Prefix "0$:" is impossible as identifier in any programming language /// private string BuildFieldPath(redb.Core.Query.QueryExpressions.PropertyInfo property) { var fieldPath = property.Name; // RedbObject BASE FIELDS: add "0$:" prefix for explicit identification // SQL function _build_single_facet_condition recognizes this prefix if (property.IsBaseField) { // Prefix "0$:" + field name (e.g.: "0$:name", "0$:parent_id", "0$:Id") return "0$:" + fieldPath; } // DETERMINE FIELD TYPE FOR CLASS FIELDS if (IsClassField(property)) { // Class field: Contact.Name, Address.City return fieldPath; // Field already contains full path from parser } if (IsClassArrayField(property)) { // Class array: Contacts[].Email, Addresses[].Street return fieldPath; // Field already contains full path from parser } if (IsCollectionType(property.Type)) { // Regular array: Tags[], Scores[], Categories[] if (!fieldPath.EndsWith("[]")) { return fieldPath + "[]"; } } // Regular field: Name, Age, Status return fieldPath; } /// /// Normalize RedbObject base field names to SQL names /// C# names (snake_case/PascalCase) → _objects SQL columns with _ prefix /// IMPORTANT: Normalize only UNIQUE base fields that are NOT in Props! /// Fields like "name", "Name" are NOT normalized - they may be Props fields. /// SQL function _normalize_base_field_name() will handle them itself. /// private static string? NormalizeBaseFieldName(string fieldName) { return fieldName switch { // ID fields - UNIQUE, definitely base "id" or "Id" => "_id", "parent_id" or "ParentId" or "id_parent" => "_id_parent", "scheme_id" or "SchemeId" or "id_scheme" => "_id_scheme", "owner_id" or "OwnerId" => "_id_owner", "who_change_id" or "WhoChangeId" => "_id_who_change", // Value fields - UNIQUE, definitely base "value_long" or "ValueLong" => "_value_long", "value_string" or "ValueString" => "_value_string", "value_guid" or "ValueGuid" => "_value_guid", "value_bool" or "ValueBool" => "_value_bool", "value_double" or "ValueDouble" => "_value_double", "value_numeric" or "ValueNumeric" => "_value_numeric", "value_datetime" or "ValueDatetime" => "_value_datetime", "value_bytes" or "ValueBytes" => "_value_bytes", "value_unique" or "ValueUnique" => "_value_unique", // DateTime fields - UNIQUE, definitely base "date_create" or "DateCreate" => "_date_create", "date_modify" or "DateModify" => "_date_modify", "date_begin" or "DateBegin" => "_date_begin", "date_complete" or "DateComplete" => "_date_complete", // Other UNIQUE base fields "key" or "Key" => "_key", "note" or "Note" => "_note", "hash" or "Hash" => "_hash", // NOT normalized: name, Name - they often exist in Props! // SQL function _normalize_base_field_name() will process them if they're base fields _ => null }; } /// /// CLIENT SEMANTICS: Build Contains filter with case-insensitive search support /// Supports: r.Article.Contains(filter, StringComparison.OrdinalIgnoreCase) /// private object BuildContainsFilter(string fieldName, object? value, bool ignoreCase) { if (ignoreCase) { // CASE-INSENSITIVE SEARCH return new Dictionary { [fieldName] = new Dictionary { ["$containsIgnoreCase"] = value } }; } else { // REGULAR CASE-SENSITIVE SEARCH return new Dictionary { [fieldName] = new Dictionary { ["$contains"] = value } }; } } /// /// Build filters for arrays with nullable support /// private object BuildArrayFilter(string fieldName, string operatorName, object? value, bool isNullable = false) { // FIX DOUBLE BRACKETS - DON'T add "[]" if path already contains "[]" // Example: "Roles[].Value" already contains [] and doesn't need addition var arrayFieldName = fieldName.Contains("[]") ? fieldName : fieldName + "[]"; if (isNullable && value == null) { // Nullable array - search for array absence return new Dictionary { [arrayFieldName] = new Dictionary { ["$exists"] = false } }; } return new Dictionary { [arrayFieldName] = new Dictionary { [operatorName] = value } }; } /// /// CLIENT SEMANTICS: Build filters for nullable fields /// Supports: r.Auction != null && r.Auction.Costs > 100 /// private object BuildNullableFieldFilter(string fieldName, object? value, ComparisonOperator op) { if (value == null) { // Nullable field with null value switch (op) { case ComparisonOperator.Equal: // field == null → field is absent return new Dictionary { [fieldName] = new Dictionary { ["$exists"] = false } }; case ComparisonOperator.NotEqual: // field != null → field exists with any value return new Dictionary { [fieldName] = new Dictionary { ["$exists"] = true } }; default: throw new NotSupportedException($"Operator {op} is not supported for nullable field with null value"); } } // Nullable field with real value - regular logic var operatorName = op switch { ComparisonOperator.Equal => "=", ComparisonOperator.NotEqual => "$ne", ComparisonOperator.GreaterThan => "$gt", ComparisonOperator.GreaterThanOrEqual => "$gte", ComparisonOperator.LessThan => "$lt", ComparisonOperator.LessThanOrEqual => "$lte", ComparisonOperator.Contains => "$contains", ComparisonOperator.StartsWith => "$startsWith", ComparisonOperator.EndsWith => "$endsWith", _ => throw new NotSupportedException($"Operator {op} is not supported for nullable field") }; if (operatorName == "=") { return new Dictionary { [fieldName] = value }; } return new Dictionary { [fieldName] = new Dictionary { [operatorName] = value } }; } /// /// Check for nullable field type /// private bool IsNullableType(Type type) { return type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>); } /// /// Returns true when the type is (or a /// nullable / collection wrapper around it). /// private static bool IsRedbListItemType(Type type) { var t = Nullable.GetUnderlyingType(type) ?? type; if (typeof(IRedbListItem).IsAssignableFrom(t)) return true; if (t.IsGenericType) { var arg = t.GetGenericArguments().FirstOrDefault(); if (arg != null) return IsRedbListItemType(arg); } if (t.IsArray) { var elem = t.GetElementType(); if (elem != null) return IsRedbListItemType(elem); } return false; } /// /// Check for array/collection /// private bool IsCollectionType(Type type) { if (type == typeof(string)) return false; // string is not collection for our purposes return type.IsArray || (type.IsGenericType && ( type.GetGenericTypeDefinition() == typeof(List<>) || type.GetGenericTypeDefinition() == typeof(IList<>) || type.GetGenericTypeDefinition() == typeof(ICollection<>) || type.GetGenericTypeDefinition() == typeof(IEnumerable<>) )); } /// /// Check for Class field (Contact.Name, Address.City) /// private bool IsClassField(redb.Core.Query.QueryExpressions.PropertyInfo property) { // Class field is determined by presence of dot in name and absence of [] return property.Name.Contains('.') && !property.Name.Contains("[]"); } /// /// Check for Class array (Contacts[].Email, Addresses[].Street) /// private bool IsClassArrayField(redb.Core.Query.QueryExpressions.PropertyInfo property) { // Class array is determined by presence of both dot and [] in name return property.Name.Contains('.') && property.Name.Contains("[]"); } /// /// Check for business class (not primitive and not collection) /// private bool IsBusinessClass(Type type) { // Business class: not primitive, not string, not collection, not nullable primitive if (type.IsPrimitive || type == typeof(string) || type == typeof(decimal) || type == typeof(DateTime) || type == typeof(DateTimeOffset) || type == typeof(DateOnly) || type == typeof(TimeOnly) || type == typeof(TimeSpan) || type == typeof(Guid)) return false; if (IsNullableType(type)) { var underlyingType = Nullable.GetUnderlyingType(type)!; return IsBusinessClass(underlyingType); } if (IsCollectionType(type)) return false; // This is business class (Address, Contact, etc.) return type.IsClass; } /// /// FIX FOR PROBLEM #4: Convert value to correct field type /// Solves problem when Price (double) is searched as integer value /// private object? ConvertValueToFieldType(object? value, Type fieldType) { if (value == null) return null; // Remove Nullable wrapper if present var targetType = Nullable.GetUnderlyingType(fieldType) ?? fieldType; // CRITICAL FIX: Process DateTime/DateTimeOffset BEFORE type checking! // Problem: DateTime without explicit Kind serializes WITHOUT timezone ('2025-11-16T00:00:00') // PostgreSQL interprets this as SERVER LOCAL time (not client!) // Solution: ALWAYS convert to UTC for explicit zone indication ('2025-11-16T00:00:00Z') if (value is DateTime dt && targetType == typeof(DateTime)) { // Use centralized converter: DateTime → UTC // Unspecified is treated as UTC (NOT as Local!) return Core.Utils.DateTimeConverter.NormalizeForStorage(dt); } // TimeOnly and TimeSpan are stored as their Ticks in _Long, BEFORE the "types already match" shortcut below, // which would hand them to the JSON writer as text. if (value is TimeOnly timeOnlyValue && targetType == typeof(TimeOnly)) return timeOnlyValue.Ticks; if (value is TimeSpan timeSpanValue && targetType == typeof(TimeSpan)) return timeSpanValue.Ticks; // DateOnly is stored in _DateTimeOffset at midnight (db_type "DateTime"), so the filter has // to compare against the same zone-less reading the writer produced. if (value is DateOnly dateOnlyValue && targetType == typeof(DateOnly)) return Core.Utils.DateTimeConverter.NormalizeForStorage( dateOnlyValue.ToDateTime(TimeOnly.MinValue)); // If types already match (NOT DateTime!) - return as is if (value.GetType() == targetType) return value; try { // NUMERIC TYPES - main cause of the problem! if (targetType == typeof(double)) { return Convert.ToDouble(value); // 2000 → 2000.0 } else if (targetType == typeof(float)) { return Convert.ToSingle(value); } else if (targetType == typeof(decimal)) { return redb.Core.Utils.RedbDecimal.From(value); } else if (targetType == typeof(long)) { return Convert.ToInt64(value); } else if (targetType == typeof(int)) { return Convert.ToInt32(value); } else if (targetType == typeof(short)) { return Convert.ToInt16(value); } else if (targetType == typeof(byte)) { return Convert.ToByte(value); } // BOOLEAN TYPES else if (targetType == typeof(bool)) { return Convert.ToBoolean(value); } // DATE-TIME (DateTime processed EARLIER at method start!) else if (targetType == typeof(DateTimeOffset)) { // CORRECT DateTimeOffset HANDLING: // DateTimeOffset already contains offset (timezone), therefore: // 1. If value is already DateTimeOffset - use it // 2. If DateTime - create DateTimeOffset explicitly // 3. If string - parse // 4. Convert to UTC for uniformity (PostgreSQL timestamptz stores in UTC) DateTimeOffset dtofs; if (value is DateTimeOffset existingOffset) { // Already DateTimeOffset - use directly dtofs = existingOffset; _logger?.LogDebug($" DateTimeOffset from existing: {dtofs:yyyy-MM-dd HH:mm:ss zzz}"); } else if (value is DateTime dtValue) { _logger?.LogDebug($" DateTimeOffset from DateTime: {dtValue:yyyy-MM-dd HH:mm:ss} (Kind: {dtValue.Kind})"); // DateTime → DateTimeOffset // Consider Kind for correct conversion if (dtValue.Kind == DateTimeKind.Utc) { dtofs = new DateTimeOffset(dtValue, TimeSpan.Zero); } else if (dtValue.Kind == DateTimeKind.Local) { dtofs = new DateTimeOffset(dtValue); } else // Unspecified { // For Unspecified consider UTC dtofs = new DateTimeOffset(dtValue, TimeSpan.Zero); } } else if (value is string strValue) { // Parse string dtofs = DateTimeOffset.Parse(strValue); _logger?.LogDebug($" DateTimeOffset from string: {dtofs:yyyy-MM-dd HH:mm:ss zzz}"); } else { // Fallback - try to convert dtofs = new DateTimeOffset(Convert.ToDateTime(value)); _logger?.LogDebug($" DateTimeOffset from fallback: {dtofs:yyyy-MM-dd HH:mm:ss zzz}"); } // Convert to UTC for uniformity with PostgreSQL timestamptz // PostgreSQL stores timestamptz in UTC and compares in UTC var result = dtofs.ToUniversalTime(); _logger?.LogDebug($"DateTimeOffset → UTC: {result:yyyy-MM-dd HH:mm:ss zzz}"); return result; } // GUID else if (targetType == typeof(Guid)) { if (value is string guidStr) return Guid.Parse(guidStr); return (Guid)value; } // STRINGS else if (targetType == typeof(string)) { return value.ToString(); } // For other types return as is return value; } catch (Exception ex) { _logger?.LogWarning($"Failed to convert value {value} ({value.GetType().Name}) to type {targetType.Name}: {ex.Message}"); return value; // Fallback - return original value } } } Path: redb/redb.Core/Query/FacetFilters/IFacetFilterBuilder.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/Query/FacetFilters/IFacetFilterBuilder.cs ---- using System.Collections.Generic; using redb.Core.Query.QueryExpressions; namespace redb.Core.Query.FacetFilters; /// /// JSON filter builder for search_objects_with_facets. /// public interface IFacetFilterBuilder { /// /// Build JSON for facet_filters from FilterExpression. /// string BuildFacetFilters(FilterExpression? filter); /// /// Build JSON for order from OrderingExpression. /// string BuildOrderBy(IReadOnlyList orderings); /// /// Build query parameters (limit, offset). /// QueryParameters BuildQueryParameters(int? limit = null, int? offset = null); } /// /// Query parameters. /// public record QueryParameters( int? Limit = null, int? Offset = null ); Path: redb/redb.Core/Query/FieldPathRefusal.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/Query/FieldPathRefusal.cs ---- using System; using System.Text.RegularExpressions; namespace redb.Core.Query; /// /// The one refusal of a field path a query cannot read: a filter, a sort, an aggregate, a group key or a window key /// whose path is not a chain of fields of the queried object, or that a provider cannot read. It is thrown before any /// statement runs, as , so the query never answers with another field's value. /// public static class FieldPathRefusal { /// The message of the refusal for the path (an expression or a field path). public static string Message(string path) => $"A query cannot read '{path}': the path must be a chain of fields of the queried object. " + "A filter, a sort and a window key take no method call inside the path (First(), ElementAt(...)); a sort and a " + "window key take no array or list element by index and no dictionary entry either. A filter of redb Pro reads " + "an element of an array or a list field of the object by a non-negative index, itself or one field of it " + "(Tags[0], Items[0].Name); the filters of redb.Postgres, redb.MSSql and redb.SQLite read none. The aggregates of " + "redb.Postgres, redb.MSSql and redb.SQLite read no field of an element of an array of classes by index " + "(Items[0].Price); redb Pro does. In a filter use Contains(...) for an array of simple values, Any(...) for an " + "array of list items, or a dictionary with its key; a value of your own goes on the other side of the comparison."; private static readonly Regex FieldOfElementByIndex = new(@"\[\d+\]\.", RegexOptions.Compiled | RegexOptions.CultureInvariant); /// /// For the providers whose aggregates are compiled by the SQL module in the database: refuses a field of an element /// of an array of classes by index (Items[0].Rank). The module reads no row for it and the aggregate came back as 0 /// or null. A field of a dictionary entry (ByKey[k].Rank) and an element of an array of simple values (Tags[0]) are /// read. An entry of a dictionary with an integer key whose value is a class (ById[5].Rank) cannot be told apart /// from an element by the path, and is refused as well. /// public static void EnsureModuleAggregateCanRead(string? fieldPath) { if (fieldPath != null && FieldOfElementByIndex.IsMatch(fieldPath)) throw new NotSupportedException(Message(fieldPath)); } } Path: redb/redb.Core/Query/Filtering/ArrayFilterExtractor.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/Query/Filtering/ArrayFilterExtractor.cs ---- using redb.Core.Query.Models; using redb.Core.Query.QueryExpressions; namespace redb.Core.Query.Filtering; /// /// [OBSOLETE] This class is no longer used in Pro version. /// Arrays are now included in PVT and filtered with ANY()/array_length(). /// Kept for backward compatibility with non-Pro implementations. /// /// Extracts ArrayFilterNode tree from FilterExpression. /// Preserves logical structure (AND/OR/NOT). /// Returns "remainder" FilterExpression without ArrayContains for PVT. /// [Obsolete("Arrays are now included in PVT in Pro version. Use ProSqlBuilder for array filtering.")] public class ArrayFilterExtractor { /// /// Extraction result containing both PVT filter and Array filter. /// /// Filter without ArrayContains for PVT WHERE clause /// ArrayContains tree for EXISTS subqueries /// Names of array fields found public record ExtractionResult( FilterExpression? PvtFilter, ArrayFilterNode? ArrayFilter, HashSet ArrayFieldNames ); private readonly IReadOnlyDictionary _fields; /// /// Creates extractor with field metadata for array detection. /// public ArrayFilterExtractor(IReadOnlyDictionary fields) { _fields = fields; } /// /// Extracts ArrayContains into separate tree, returns remainder for PVT. /// public ExtractionResult Extract(FilterExpression? filter) { if (filter == null) return new ExtractionResult(null, null, new HashSet()); var arrayFieldNames = new HashSet(); var (pvtFilter, arrayFilter) = ExtractRecursive(filter, arrayFieldNames); return new ExtractionResult(pvtFilter, arrayFilter, arrayFieldNames); } /// /// Recursive extraction. /// private (FilterExpression? pvt, ArrayFilterNode? array) ExtractRecursive( FilterExpression filter, HashSet arrayFieldNames) { switch (filter) { case ComparisonExpression comparison: return ExtractComparison(comparison, arrayFieldNames); case LogicalExpression logical: return ExtractLogical(logical, arrayFieldNames); case NullCheckExpression nullCheck: // NullCheck doesn't contain ArrayContains return (nullCheck, null); case InExpression inExpr: // InExpression doesn't contain ArrayContains return (inExpr, null); default: return (filter, null); } } /// /// Extracts from ComparisonExpression. /// private (FilterExpression? pvt, ArrayFilterNode? array) ExtractComparison( ComparisonExpression comparison, HashSet arrayFieldNames) { if (!IsArrayOperator(comparison.Operator)) { // Not ArrayContains - goes to PVT return (comparison, null); } // This is ArrayContains - convert to ArrayLeaf var fieldName = comparison.Property.Name; arrayFieldNames.Add(fieldName); if (!_fields.TryGetValue(fieldName, out var fieldInfo)) { // Field not found - return as-is (will error later) return (comparison, null); } var leafOp = MapToArrayLeafOperator(comparison.Operator); var leaf = new ArrayLeaf( fieldName, fieldInfo.StructureId, fieldInfo.DbColumn, leafOp, comparison.Value, fieldInfo.ListItemProp // Pass ListItemProp for ListItem arrays ); return (null, leaf); } /// /// Extracts from LogicalExpression. /// private (FilterExpression? pvt, ArrayFilterNode? array) ExtractLogical( LogicalExpression logical, HashSet arrayFieldNames) { var pvtOperands = new List(); var arrayOperands = new List(); foreach (var operand in logical.Operands) { var (pvt, array) = ExtractRecursive(operand, arrayFieldNames); if (pvt != null) pvtOperands.Add(pvt); if (array != null) arrayOperands.Add(array); } // Build results FilterExpression? pvtResult = null; ArrayFilterNode? arrayResult = null; // PVT part if (pvtOperands.Count > 0) { if (pvtOperands.Count == 1) { // For NOT need to wrap even single operand pvtResult = logical.Operator == LogicalOperator.Not ? new LogicalExpression(LogicalOperator.Not, pvtOperands) : pvtOperands[0]; } else { pvtResult = new LogicalExpression(logical.Operator, pvtOperands); } } // Array part if (arrayOperands.Count > 0) { arrayResult = arrayOperands.Count == 1 ? arrayOperands[0] : logical.Operator switch { LogicalOperator.And => new ArrayAnd(arrayOperands), LogicalOperator.Or => new ArrayOr(arrayOperands), LogicalOperator.Not when arrayOperands.Count == 1 => new ArrayNot(arrayOperands[0]), _ => new ArrayAnd(arrayOperands) // fallback }; } // Special handling for NOT if (logical.Operator == LogicalOperator.Not && arrayResult != null && pvtResult == null) { // Entire NOT was on ArrayContains arrayResult = new ArrayNot(arrayResult); } return (pvtResult, arrayResult); } /// /// Checks if operator is array-related. /// private static bool IsArrayOperator(ComparisonOperator op) { return op is ComparisonOperator.ArrayContains or ComparisonOperator.ArrayAny or ComparisonOperator.ArrayEmpty or ComparisonOperator.ArrayCount or ComparisonOperator.ArrayCountGt or ComparisonOperator.ArrayCountGte or ComparisonOperator.ArrayCountLt or ComparisonOperator.ArrayCountLte; } /// /// Maps ComparisonOperator to ArrayLeafOperator. /// private static ArrayLeafOperator MapToArrayLeafOperator(ComparisonOperator op) { return op switch { ComparisonOperator.ArrayContains => ArrayLeafOperator.Contains, ComparisonOperator.ArrayAny => ArrayLeafOperator.Any, ComparisonOperator.ArrayEmpty => ArrayLeafOperator.Empty, ComparisonOperator.ArrayCount => ArrayLeafOperator.CountEqual, ComparisonOperator.ArrayCountGt => ArrayLeafOperator.CountGreater, ComparisonOperator.ArrayCountGte => ArrayLeafOperator.CountGreaterOrEqual, ComparisonOperator.ArrayCountLt => ArrayLeafOperator.CountLess, ComparisonOperator.ArrayCountLte => ArrayLeafOperator.CountLessOrEqual, _ => throw new NotSupportedException($"Unknown array operator: {op}") }; } } Path: redb/redb.Core/Query/Filtering/ArrayFilterNode.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/Query/Filtering/ArrayFilterNode.cs ---- using redb.Core.Query.Models; namespace redb.Core.Query.Filtering; /// /// Tree structure for ArrayContains filter operations. /// Preserves logical structure (AND/OR/NOT) for correct SQL generation. /// public abstract record ArrayFilterNode; /// /// Leaf node - a specific operation on an array field. /// /// Name of the array field (e.g., "Scores", "Tags") /// ID of the structure in _structures table /// Column name in _values table (_Long, _String, etc.) /// Type of array operation /// Value to compare against (for Contains, Count operations) /// For ListItem arrays: which property (Value, Alias, Id) public record ArrayLeaf( string FieldName, long StructureId, string DbColumn, ArrayLeafOperator Operator, object? Value, ListItemProperty? ListItemProp = null ) : ArrayFilterNode; /// /// AND node - all child conditions must be true. /// public record ArrayAnd(IReadOnlyList Children) : ArrayFilterNode; /// /// OR node - at least one child condition must be true. /// public record ArrayOr(IReadOnlyList Children) : ArrayFilterNode; /// /// NOT node - negation of inner condition. /// public record ArrayNot(ArrayFilterNode Inner) : ArrayFilterNode; /// /// Operators for array leaf nodes. /// public enum ArrayLeafOperator { /// array.Contains(value) → EXISTS ... AND _column = value Contains, /// array.Any() → EXISTS ... (array is not empty) Any, /// !array.Any() or array.Length == 0 → NOT EXISTS Empty, /// array.Count == N CountEqual, /// array.Count > N CountGreater, /// array.Count >= N CountGreaterOrEqual, /// array.Count < N CountLess, /// array.Count <= N CountLessOrEqual } Path: redb/redb.Core/Query/Filtering/FilterFieldExtractor.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/Query/Filtering/FilterFieldExtractor.cs ---- using redb.Core.Query.QueryExpressions; namespace redb.Core.Query.Filtering; /// /// Extracts field information from FilterExpression tree. /// Returns field names and whether they are base fields. /// Handles Dictionary field normalization. /// public class FilterFieldExtractor { /// /// Extract field names with IsBaseField flag from FilterExpression. /// Handles Dictionary fields: PhoneBook.ContainsKey("home") → PhoneBook[home] /// Removes Dictionary base fields when keyed versions exist (for PVT). /// /// Filter expression to extract from /// Dictionary: field name → is base field public Dictionary ExtractFieldInfos(FilterExpression? filter) { var infos = new Dictionary(); var nullCheckFields = new HashSet(); if (filter != null) ExtractRecursive(filter, infos, nullCheckFields); // Remove Dictionary base fields from NullCheck // If we have "PhoneBook[home]" from ContainsKey, remove "PhoneBook" from NullCheck // because Dictionary base field doesn't exist in PVT (only keyed fields do) foreach (var nullField in nullCheckFields) { var isDictionary = infos.Keys.Any(k => k.StartsWith($"{nullField}[")); if (isDictionary) infos.Remove(nullField); } return infos; } /// /// Extract only Props field names (not base fields) from FilterExpression. /// public HashSet ExtractPropsFieldNames(FilterExpression? filter) { var infos = ExtractFieldInfos(filter); return infos.Where(kv => !kv.Value).Select(kv => kv.Key).ToHashSet(); } /// /// Extract only base field names from FilterExpression. /// public HashSet ExtractBaseFieldNames(FilterExpression? filter) { var infos = ExtractFieldInfos(filter); return infos.Where(kv => kv.Value).Select(kv => kv.Key).ToHashSet(); } private void ExtractRecursive(FilterExpression filter, Dictionary infos, HashSet nullCheckFields) { switch (filter) { case ComparisonExpression comparison: // Ignore special names and Pro ValueExpression if (comparison.Property.Name != "__constant" && comparison.Property.Name != "__computed") { var fieldName = NormalizeDictionaryFieldName(comparison.Property.Name, comparison.Value); infos.TryAdd(fieldName, comparison.Property.IsBaseField); } // Pro: Extract fields from ValueExpression if (comparison.LeftExpression != null) ExtractFromValueExpression(comparison.LeftExpression, infos); if (comparison.RightExpression != null) ExtractFromValueExpression(comparison.RightExpression, infos); break; case LogicalExpression logical: foreach (var operand in logical.Operands) ExtractRecursive(operand, infos, nullCheckFields); break; case NullCheckExpression nullCheck: infos.TryAdd(nullCheck.Property.Name, nullCheck.Property.IsBaseField); // Track NullCheck fields to potentially remove Dictionary base fields later if (!nullCheck.Property.IsBaseField) nullCheckFields.Add(nullCheck.Property.Name); break; case InExpression inExpr: infos.TryAdd(inExpr.Property.Name, inExpr.Property.IsBaseField); break; case ArrayElementAnyExpression elementAny: // The fields of the element (Rows[].Kind) are resolved with the others; they are not pivot columns. ExtractRecursive(elementAny.Element, infos, nullCheckFields); break; } } /// /// Extracts fields from Pro ValueExpression (arithmetic/functions). /// private void ExtractFromValueExpression(ValueExpression expr, Dictionary infos) { switch (expr) { case PropertyValueExpression propExpr: infos.TryAdd(propExpr.Property.Name, propExpr.Property.IsBaseField); break; case ArithmeticExpression arith: ExtractFromValueExpression(arith.Left, infos); ExtractFromValueExpression(arith.Right, infos); break; case FunctionCallExpression func: ExtractFromValueExpression(func.Argument, infos); break; case MultiArgFunctionCallExpression mfunc: foreach (var arg in mfunc.Arguments) ExtractFromValueExpression(arg, infos); break; case CustomFunctionExpression custom: foreach (var arg in custom.Arguments) ExtractFromValueExpression(arg, infos); break; case CoalesceExpression coalesce: foreach (var arg in coalesce.Arguments) ExtractFromValueExpression(arg, infos); break; case ConditionalValueExpression cond: ExtractRecursive(cond.Test, infos, new HashSet()); ExtractFromValueExpression(cond.IfTrue, infos); ExtractFromValueExpression(cond.IfFalse, infos); break; // ConstantValueExpression doesn't contribute fields } } /// /// Normalizes Dictionary field names: /// - "PhoneBook.ContainsKey" with value "home" → "PhoneBook[home]" /// - "PhoneBook[home]" → unchanged /// private static string NormalizeDictionaryFieldName(string fieldName, object? value) { // Handle ContainsKey: "PhoneBook.ContainsKey" with value "home" → "PhoneBook[home]" if (fieldName.EndsWith(".ContainsKey") && value is string keyValue) { var baseName = fieldName[..^".ContainsKey".Length]; return $"{baseName}[{keyValue}]"; } return fieldName; } } Path: redb/redb.Core/Query/Grouping/ArrayGroupMaterializer.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/Query/Grouping/ArrayGroupMaterializer.cs ---- using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text.Json; using redb.Core.Query.Aggregation; using redb.Core.Query.Utils; using redb.Core.Query.Window; namespace redb.Core.Query.Grouping; /// /// Builds the results of a grouping from the JSON rows a provider returns. Strict: an answer that is not an array, /// or a row without a column the selector reads, is an error and never an empty list or a default value. /// internal static class ArrayGroupMaterializer { /// The root array of the answer, or an naming the provider. public static JsonElement RequireArray(JsonDocument? json, string provider, string api) { if (json == null) throw new InvalidOperationException($"{api}: {provider} returned no answer for the grouping."); if (json.RootElement.ValueKind != JsonValueKind.Array) throw new InvalidOperationException( $"{api}: {provider} returned {json.RootElement.ValueKind} instead of an array of group rows."); return json.RootElement; } /// /// One result per row. A member that reads g.Key takes the key's alias, an Agg.* or Win.* member takes its own /// name, a member that does not use the group is computed once. /// public static List Materialize( JsonDocument? json, LambdaExpression selector, IReadOnlyList groupFields, string provider, string api) { var root = RequireArray(json, provider, api); var members = GroupSelectorMembers.Extract(selector, api); var groupParam = selector.Parameters[0]; var plan = new (bool Client, object? ClientValue, string[] Columns, Type Type, Type? CompositeKey)[members.Count]; for (int i = 0; i < members.Count; i++) { var (name, type, raw) = members[i]; var expr = GroupSelectorMembers.StripConvert(raw); var serverCall = expr is MethodCallExpression mc && (mc.Method.DeclaringType == typeof(Agg) || mc.Method.DeclaringType == typeof(Win)); if (!serverCall && !GroupSelectorMembers.ReferencesParameter(expr, groupParam)) { plan[i] = (true, Expression.Lambda(raw).Compile().DynamicInvoke(), Array.Empty(), type, null); continue; } if (GroupSelectorMembers.IsKeyAccess(expr, groupParam)) { var keyMember = (MemberExpression)expr; if (keyMember.Member.Name == "Key" && keyMember.Expression == groupParam) { // g.Key: one key reads its column; a composite key is rebuilt from all of them. plan[i] = groupFields.Count == 1 ? (false, null, new[] { groupFields[0].Alias }, type, null) : (false, null, groupFields.Select(g => g.Alias).ToArray(), type, type); continue; } // g.Key.X of a composite key (g.Key.X.Id reads the same column), or g.Key.Id of a single list item key. var underKey = keyMember; while (underKey.Expression is MemberExpression parent && !(parent.Member.Name == "Key" && parent.Expression == groupParam)) underKey = parent; var column = groupFields.Count > 1 ? groupFields.FirstOrDefault(g => g.Alias == underKey.Member.Name)?.Alias : groupFields[0].Alias; if (column == null) throw new NotSupportedException($"{api}: member '{name}' reads '{raw}', which is not a key of the grouping."); plan[i] = (false, null, new[] { column }, type, null); continue; } plan[i] = (false, null, new[] { name }, type, null); } var results = new List(); foreach (var row in root.EnumerateArray()) { if (row.ValueKind != JsonValueKind.Object) throw new InvalidOperationException($"{api}: {provider} returned a group row that is {row.ValueKind}, not an object."); var values = new object?[members.Count]; for (int i = 0; i < members.Count; i++) { var p = plan[i]; if (p.Client) { values[i] = p.ClientValue; continue; } if (p.CompositeKey != null) { var ctor = p.CompositeKey.GetConstructors().Single(); var parameters = ctor.GetParameters(); var args = new object?[parameters.Length]; for (int k = 0; k < parameters.Length; k++) args[k] = JsonValueConverter.Convert(Column(row, p.Columns[k], provider, api), parameters[k].ParameterType); values[i] = ctor.Invoke(args); continue; } values[i] = JsonValueConverter.Convert(Column(row, p.Columns[0], provider, api), p.Type); } results.Add(GroupSelectorMembers.Construct(selector, values)); } return results; } private static JsonElement Column(JsonElement row, string name, string provider, string api) { if (row.TryGetProperty(name, out var exact)) return exact; // Providers fold the case of aliases differently. foreach (var p in row.EnumerateObject()) if (string.Equals(p.Name, name, StringComparison.OrdinalIgnoreCase)) return p.Value; throw new InvalidOperationException( $"{api}: {provider} returned a group row without the column '{name}' " + $"(columns: {string.Join(", ", row.EnumerateObject().Select(o => o.Name))})."); } } Path: redb/redb.Core/Query/Grouping/ArrayGroupModuleJson.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/Query/Grouping/ArrayGroupModuleJson.cs ---- using System; using System.Collections.Generic; using System.Linq; using System.Text.Json; using redb.Core.Query.Aggregation; namespace redb.Core.Query.Grouping; /// /// The JSON arguments of the free providers' pvt_build_array_groupby_sql (PostgreSQL and SQL Server modules, /// SQLite extension): keys [{field, alias}] and aggregates [{field, func, alias, filter?}], where /// field may be and filter is the condition of a conditional /// count in the HAVING language. One writer for the three providers. /// public static class ArrayGroupModuleJson { public static string GroupBy(IEnumerable groupFields) => JsonSerializer.Serialize(groupFields.Select(g => new Dictionary { ["field"] = g.FieldPath, ["alias"] = g.Alias })); public static string? Aggregations(IReadOnlyList aggregations) { if (aggregations.Count == 0) return null; return JsonSerializer.Serialize(aggregations.Select(a => { var entry = new Dictionary { ["field"] = string.IsNullOrEmpty(a.FieldPath) ? "*" : a.FieldPath, ["func"] = a.Function switch { AggregateFunction.Average => "AVG", AggregateFunction.Sum => "SUM", AggregateFunction.Min => "MIN", AggregateFunction.Max => "MAX", AggregateFunction.Count => "COUNT", _ => throw new NotSupportedException($"Aggregation function {a.Function} is not supported for GroupByArray.") }, ["alias"] = a.Alias ?? a.Function.ToString() }; if (a.ConditionJson != null) entry["filter"] = JsonDocument.Parse(a.ConditionJson).RootElement.Clone(); return entry; })); } /// A JSON argument or DBNull for an empty one. public static object Param(string? json) => string.IsNullOrEmpty(json) || json == "{}" || json == "null" ? DBNull.Value : json; } Path: redb/redb.Core/Query/Grouping/ArrayGroupQuery.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/Query/Grouping/ArrayGroupQuery.cs ---- using System; using System.Collections.Generic; using redb.Core.Query.Aggregation; using redb.Core.Query.QueryExpressions; using redb.Core.Query.Window; namespace redb.Core.Query.Grouping; /// /// A grouping over the elements of an array, as every provider receives it: what to group, how to aggregate, which /// objects take part and, for WithWindow, the window over the groups. One request serves execution and SQL /// preview, so the previewed SQL is the SQL that runs. /// public sealed class ArrayGroupQuery { /// Scheme of the objects that own the array. public required long SchemeId { get; init; } /// /// Path to the array whose elements are grouped, through classes and arrays, joined with dots: /// Contacts, Contacts.Metadata, HomeAddress.Building.Amenities. Keys and aggregates read the /// elements of the last array in the path. /// public required string ArrayPath { get; init; } /// /// Group keys: paths of element fields (Type, Address.City) or /// for the element of an array of simple values. Never empty. /// public required IReadOnlyList GroupFields { get; init; } /// Aggregates over the elements of each group, with their aliases. public required IReadOnlyList Aggregations { get; init; } /// Condition on the owning objects (the query's Where), or null. public FilterExpression? Filter { get; init; } /// /// Condition on the owning objects in the facet JSON of the free provider, or null. Used by the free tree path /// to pass the objects of a subtree; the Pro provider refuses a non-empty value. /// public string? FilterJson { get; init; } /// HAVING in the JSON of HavingPredicateParser, or null. public string? HavingJson { get; init; } /// Window over the groups (WithWindow), or null. public ArrayGroupWindow? Window { get; init; } /// /// Refuses a request no generator can answer: no array path, no key, a key or aggregate without a path or alias, /// a window without functions. Every provider calls it first, so none of them answers such a request with nothing. /// public void EnsureValid() { if (string.IsNullOrWhiteSpace(ArrayPath)) throw new ArgumentException("An array grouping needs the path of the array.", nameof(ArrayPath)); if (GroupFields.Count == 0) throw new ArgumentException("An array grouping needs at least one key.", nameof(GroupFields)); foreach (var g in GroupFields) { if (string.IsNullOrWhiteSpace(g.FieldPath)) throw new ArgumentException("A key of an array grouping has no field path.", nameof(GroupFields)); if (string.IsNullOrWhiteSpace(g.Alias)) throw new ArgumentException($"The key '{g.FieldPath}' of an array grouping has no alias.", nameof(GroupFields)); } foreach (var a in Aggregations) { if (string.IsNullOrWhiteSpace(a.FieldPath)) throw new ArgumentException($"The aggregate '{a.Alias}' of an array grouping has no field path.", nameof(Aggregations)); if (string.IsNullOrWhiteSpace(a.Alias)) throw new ArgumentException($"The aggregate {a.Function}({a.FieldPath}) of an array grouping has no alias.", nameof(Aggregations)); if (a.ConditionJson != null && a.Function != AggregateFunction.Count) throw new ArgumentException($"Only a count takes a condition; {a.Function}({a.FieldPath}) has one.", nameof(Aggregations)); } if (Window != null && Window.Functions.Count == 0) throw new ArgumentException("A window over an array grouping needs at least one window function.", nameof(Window)); } } /// /// Window functions over the rows of an array grouping, in the form the grouped window of GroupBy uses. /// public sealed class ArrayGroupWindow { /// Window functions with their aliases. Never empty. public required IReadOnlyList Functions { get; init; } /// PARTITION BY: group aliases or aggregate references. public required IReadOnlyList PartitionBy { get; init; } /// ORDER BY: group aliases or aggregate references. public required IReadOnlyList OrderBy { get; init; } } Path: redb/redb.Core/Query/Grouping/GroupAggregateParser.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/Query/Grouping/GroupAggregateParser.cs ---- using System; using System.Collections.Generic; using System.Linq.Expressions; using redb.Core.Query.Aggregation; namespace redb.Core.Query.Grouping; /// /// What the parameter of an aggregate or condition lambda stands for in a grouping. /// internal enum GroupItemKind { /// An object's Props (GroupBy, tree GroupBy, grouped window). Props, /// An element of an array of classes (GroupByArray over Contacts). ArrayClassElement, /// An element of an array of simple values (GroupByArray over Skills): the element itself is a value. ArrayValueElement } /// /// One strict reading of Agg.* calls for every grouping (GroupBy, tree GroupBy, grouped window, GroupByArray). /// A call it cannot translate is refused with ; nothing becomes "*" or a /// path the caller did not write. /// internal static class GroupAggregateParser { /// Whether the expression is a call of a method of . public static bool IsAggCall(Expression expression) => GroupSelectorMembers.StripConvert(expression) is MethodCallExpression mc && mc.Method.DeclaringType == typeof(Agg); /// /// Reads one Agg.* call over the group parameter into an aggregate request. /// /// The call, already known to be a method of . /// Parameter of the group in the selector or HAVING lambda. /// Alias of the result column. /// What the lambda parameter of the call stands for. /// Name of the API for messages, e.g. "GroupByArray.SelectAsync". public static AggregateRequest Parse( MethodCallExpression call, ParameterExpression groupParam, string alias, GroupItemKind kind, string ownerApi) { var name = call.Method.Name; var function = name switch { "Sum" => AggregateFunction.Sum, "Average" => AggregateFunction.Average, "Min" => AggregateFunction.Min, "Max" => AggregateFunction.Max, "Count" => AggregateFunction.Count, _ => throw new NotSupportedException($"{ownerApi}: Agg.{name} is not an aggregate of a group.") }; if (call.Arguments.Count == 0 || GroupSelectorMembers.StripConvert(call.Arguments[0]) != groupParam) throw new NotSupportedException( $"{ownerApi}: Agg.{name} takes the group as its first argument (Agg.{name}(g, ...)); got '{call}'."); if (function == AggregateFunction.Count) { if (call.Arguments.Count == 1) return new AggregateRequest { FieldPath = "*", Function = function, Alias = alias }; var predicate = UnwrapLambda(call.Arguments[1]) ?? throw new NotSupportedException($"{ownerApi}: the condition of Agg.Count must be a lambda; got '{call.Arguments[1]}'."); return new AggregateRequest { FieldPath = "*", Function = function, Alias = alias, ConditionJson = ItemPredicateParser.ToJson(predicate, kind, ownerApi) }; } if (call.Arguments.Count < 2) throw new NotSupportedException($"{ownerApi}: Agg.{name} needs a selector over the group: Agg.{name}(g, x => x.Field)."); var selector = UnwrapLambda(call.Arguments[1]) ?? throw new NotSupportedException($"{ownerApi}: the selector of Agg.{name} must be a lambda; got '{call.Arguments[1]}'."); return new AggregateRequest { FieldPath = FieldPath(selector, kind, ownerApi, $"the selector of Agg.{name}"), Function = function, Alias = alias }; } /// /// The stored field a lambda names: a chain of members from its parameter (x => x.Address.City), or the /// parameter itself for an element of an array of simple values (). /// Anything else is a computation and is refused. /// public static string FieldPath(LambdaExpression lambda, GroupItemKind kind, string ownerApi, string what) => FieldPath(lambda.Body, lambda.Parameters[0], kind, ownerApi, what); /// /// The stored field an expression over names; see . /// public static string FieldPath(Expression body, ParameterExpression parameter, GroupItemKind kind, string ownerApi, string what) { var expr = GroupSelectorMembers.StripConvert(body); if (expr == parameter) { if (kind == GroupItemKind.ArrayValueElement) return GroupFieldRequest.ElementPath; throw new NotSupportedException(kind == GroupItemKind.ArrayClassElement ? $"{ownerApi}: {what} names the whole element of an array of classes; name a field of the element (x => x.Field)." : $"{ownerApi}: {what} names the whole object; name a field (x => x.Field)."); } if (expr is MemberExpression member && GroupSelectorMembers.IsFieldChain(member) && TryMemberPath(member, parameter, out var path)) return path; throw new NotSupportedException( $"{ownerApi}: {what} must name a stored field ({Example(kind)}); '{body}' is a computation, which is not translated to SQL."); } /// /// Path of a member chain that starts at , joined with dots. A Props member and /// the Value of a are not part of the stored path. /// public static bool TryMemberPath(MemberExpression member, ParameterExpression parameter, out string path) { var parts = new List(); Expression? current = member; while (current is MemberExpression m) { var declaring = m.Member.DeclaringType; var isNullableValue = m.Member.Name == "Value" && declaring is { IsGenericType: true } && declaring.GetGenericTypeDefinition() == typeof(Nullable<>); if (!isNullableValue && m.Member.Name != "Props") parts.Insert(0, m.Member.Name); current = m.Expression is null ? null : GroupSelectorMembers.StripConvert(m.Expression); } path = string.Join(".", parts); return current == parameter && parts.Count > 0; } private static string Example(GroupItemKind kind) => kind switch { GroupItemKind.ArrayValueElement => "x => x for the element itself", GroupItemKind.ArrayClassElement => "x => x.Field or x => x.Inner.Field of the element", _ => "x => x.Field or x => x.Inner.Field" }; private static LambdaExpression? UnwrapLambda(Expression expression) { if (expression is UnaryExpression quote && quote.NodeType == ExpressionType.Quote) expression = quote.Operand; return expression as LambdaExpression; } } Path: redb/redb.Core/Query/Grouping/GroupFieldRequest.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/Query/Grouping/GroupFieldRequest.cs ---- namespace redb.Core.Query.Grouping; /// /// Request for grouping field for SQL function aggregate_grouped /// public class GroupFieldRequest { /// /// Path that names the element itself in an array grouping: the key of GroupByArray(e => e.Skills, s => s), /// the argument of Agg.Sum(g, h => h). Valid only for an array of simple values; a C# member name cannot /// start with '$', so no field can be mistaken for it. /// public const string ElementPath = "$element"; public string FieldPath { get; set; } = string.Empty; public string Alias { get; set; } = string.Empty; /// /// true = base field from _objects (scheme_id, parent_id, etc.) /// false = Props field from _values (Props.Category, etc.) /// public bool IsBaseField { get; set; } = false; } Path: redb/redb.Core/Query/Grouping/GroupKeyFields.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/Query/Grouping/GroupKeyFields.cs ---- using System; using System.Collections.Generic; using System.Linq.Expressions; namespace redb.Core.Query.Grouping; /// /// The keys of a GroupBy over objects (flat, tree, grouped window): a stored field (x => x.Department, /// x => x.Address.City, x => x.Status.Id) or an anonymous type of such fields. A computed key is /// refused, never read as a path it is not. /// internal static class GroupKeyFields { public static List Parse(Expression keySelector, bool isBaseFieldGrouping, string ownerApi) { var lambda = keySelector as LambdaExpression ?? throw new NotSupportedException($"{ownerApi}: the key of the grouping must be a lambda; got '{keySelector}'."); var parameter = lambda.Parameters[0]; var body = GroupSelectorMembers.StripConvert(lambda.Body); var result = new List(); if (body is NewExpression newExpr) { for (int i = 0; i < newExpr.Arguments.Count; i++) { var alias = newExpr.Members?[i].Name ?? $"Key{i}"; result.Add(new GroupFieldRequest { FieldPath = GroupAggregateParser.FieldPath(newExpr.Arguments[i], parameter, GroupItemKind.Props, ownerApi, $"key member '{alias}'"), Alias = alias, IsBaseField = isBaseFieldGrouping }); } return result; } if (body is MemberExpression member) { result.Add(new GroupFieldRequest { FieldPath = GroupAggregateParser.FieldPath(member, parameter, GroupItemKind.Props, ownerApi, "the key"), Alias = member.Member.Name, IsBaseField = isBaseFieldGrouping }); return result; } // G-3: a computed key used to give an empty GROUP BY without a word. throw new NotSupportedException( $"{ownerApi} supports a field (x => x.Category) or an anonymous type of fields (x => new {{ x.A, x.B }}); " + $"a computed key is not supported: '{lambda.Body}'."); } } Path: redb/redb.Core/Query/Grouping/GroupSelectorMembers.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/Query/Grouping/GroupSelectorMembers.cs ---- using System; using System.Collections.Generic; using System.Linq.Expressions; namespace redb.Core.Query.Grouping; /// /// Общий разбор селектора SelectAsync для всех группировщиков (G-1, решение владельца /// 2026-09-04: DTO/MemberInit поддерживается ВЕЗДЕ, а не только в обычном GroupBy). /// Селектор - анонимный тип (NewExpression) или DTO с инициализатором членов /// (MemberInitExpression, parameterless конструктор); всё прочее - громкий отказ /// (fail-closed, ревью 2026-09-03). Классификацию членов (Key/Agg/Win/клиентское значение) /// делает каждый группировщик сам - здесь только форма. /// internal static class GroupSelectorMembers { internal readonly record struct Member(string Name, Type Type, Expression Expr); public static List Extract(LambdaExpression selector, string ownerApi) { var members = new List(); switch (selector.Body) { case NewExpression newExpr: for (int i = 0; i < newExpr.Arguments.Count; i++) { var name = newExpr.Members?[i].Name ?? $"Item{i}"; var type = (newExpr.Members?[i] as System.Reflection.PropertyInfo)?.PropertyType ?? newExpr.Arguments[i].Type; members.Add(new Member(name, type, newExpr.Arguments[i])); } break; case MemberInitExpression initExpr: if (initExpr.NewExpression.Arguments.Count > 0) throw new NotSupportedException( $"{ownerApi}: DTO с параметрами конструктора не поддерживается - " + "нужен parameterless конструктор и инициализатор членов."); foreach (var binding in initExpr.Bindings) { if (binding is not MemberAssignment assignment) throw new NotSupportedException( $"{ownerApi}: биндинг '{binding.Member.Name}' ({binding.BindingType}) не поддерживается - " + "только простые присваивания членов DTO."); var type = (assignment.Member as System.Reflection.PropertyInfo)?.PropertyType ?? assignment.Expression.Type; members.Add(new Member(assignment.Member.Name, type, assignment.Expression)); } break; default: throw new NotSupportedException( $"{ownerApi} поддерживает анонимный тип (g => new {{ ... }}) или DTO с инициализатором " + $"членов (g => new Dto {{ ... }}); получено: {selector.Body.NodeType}."); } return members; } public static Expression StripConvert(Expression expr) { while (expr is UnaryExpression u && (u.NodeType == ExpressionType.Convert || u.NodeType == ExpressionType.ConvertChecked)) expr = u.Operand; return expr; } /// /// A member chain that names a stored field: it ends at a parameter, and no member in it belongs to a system type /// (Value.Length, Date.Year are computations, not fields). Nullable<T> members are left /// as they were read before. /// public static bool IsFieldChain(MemberExpression member) { Expression? current = member; while (current is MemberExpression m) { var declaring = m.Member.DeclaringType; var isNullable = declaring is { IsGenericType: true } && declaring.GetGenericTypeDefinition() == typeof(Nullable<>); var ns = declaring?.Namespace; if (!isNullable && (ns == "System" || (ns != null && ns.StartsWith("System.", StringComparison.Ordinal)))) return false; current = StripConvert(m.Expression!); } return current is ParameterExpression; } /// Цепочка членов от параметра группы через .Key (g.Key / g.Key.X / g.Key.X.Id). public static bool IsKeyAccess(Expression expr, ParameterExpression groupParam) { var sawKey = false; var current = expr; while (current is MemberExpression m) { if (m.Member.Name == "Key") sawKey = true; current = m.Expression; } return sawKey && ReferenceEquals(current, groupParam); } public static bool ReferencesParameter(Expression expr, ParameterExpression parameter) { var finder = new ParameterFinder(parameter); finder.Visit(expr); return finder.Found; } private sealed class ParameterFinder : ExpressionVisitor { private readonly ParameterExpression _target; public bool Found { get; private set; } public ParameterFinder(ParameterExpression target) => _target = target; protected override Expression VisitParameter(ParameterExpression node) { if (node == _target) Found = true; return base.VisitParameter(node); } } /// Сборка результата: анонимный тип - через его конструктор; DTO - Activator + /// присваивания членов (null для non-nullable value-типа оставляет default). public static TResult Construct(LambdaExpression selector, object?[] values) { if (selector.Body is NewExpression newExpr && newExpr.Constructor != null) return (TResult)newExpr.Constructor.Invoke(values); var initExpr = (MemberInitExpression)selector.Body; var instance = Activator.CreateInstance(typeof(TResult))!; for (int i = 0; i < initExpr.Bindings.Count; i++) { var assignment = (MemberAssignment)initExpr.Bindings[i]; var value = values[i]; switch (assignment.Member) { case System.Reflection.PropertyInfo pi: if (value == null && pi.PropertyType.IsValueType && Nullable.GetUnderlyingType(pi.PropertyType) == null) break; pi.SetValue(instance, value); break; case System.Reflection.FieldInfo fi: if (value == null && fi.FieldType.IsValueType && Nullable.GetUnderlyingType(fi.FieldType) == null) break; fi.SetValue(instance, value); break; } } return (TResult)instance; } } Path: redb/redb.Core/Query/Grouping/GroupedWindowNames.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/Query/Grouping/GroupedWindowNames.cs ---- using System; using System.Collections.Generic; using System.Linq; using redb.Core.Query.Aggregation; namespace redb.Core.Query.Grouping; /// /// How a grouped window (GroupBy(...).WithWindow(...)) names what it sorts and partitions by, /// and what a provider has to make of those names. Shared by every provider: the names are written /// by and its tree twin, in three shapes: /// "Agg_Sum_Salary" - the aggregate Sum over Salary; /// "Agg_Count_..." - Count(*), whatever follows: Agg.Count(g) has no field to name; /// a member name - a part of a composite key, or "Key" for a key of a single field. /// IRedbGrouping spells the average "Avg", the Agg class spells it "Average"; both arrive here. /// public static class GroupedWindowNames { /// /// Aggregates the window refers to that the selector does not compute. Each comes back as a /// request under a private alias: the provider computes it inside the grouping and leaves it /// out of the result, so sorting by an aggregate does not oblige the caller to select it. /// public static List HiddenAggregates( IEnumerable windowFieldPaths, IReadOnlyList aggregations) { var hidden = new List(); foreach (var path in windowFieldPaths.Where(p => p != null && p.StartsWith("Agg_", StringComparison.Ordinal)).Distinct()) { if (!TryParseAggregateName(path!, out var function, out var field)) continue; var isCount = function == AggregateFunction.Count; if (!isCount && string.IsNullOrEmpty(field)) continue; bool Same(AggregateRequest a) => Matches(a, function, field); if (aggregations.Any(Same) || hidden.Any(Same)) continue; hidden.Add(new AggregateRequest { Function = function, FieldPath = isCount ? "" : field!, Alias = $"__window_{hidden.Count}" }); } return hidden; } /// /// The column of the grouped result a window name refers to: the alias of the matching /// aggregate, or the alias of the group key. Null when the name matches nothing; the caller /// decides whether that is an error. /// public static string? TryResolveColumn( string? fieldPath, IReadOnlyList aggregations, IReadOnlyList groupFields) { var path = fieldPath ?? string.Empty; if (path.StartsWith("Agg_", StringComparison.Ordinal)) { if (!TryParseAggregateName(path, out var function, out var field)) return null; var aggregate = aggregations.FirstOrDefault(a => Matches(a, function, field)); return aggregate == null ? null : aggregate.Alias ?? aggregate.Function.ToString(); } if (path == "Key" && groupFields.Count == 1) return Alias(groupFields[0]); var group = groupFields.FirstOrDefault(g => g.Alias == path || g.FieldPath == path); if (group != null) return Alias(group); return aggregations.FirstOrDefault(a => a.Alias == path)?.Alias; } /// /// for a provider that refuses what matches nothing instead of /// sending the database a column that does not exist. /// public static string ResolveColumn( string? fieldPath, IReadOnlyList aggregations, IReadOnlyList groupFields) => TryResolveColumn(fieldPath, aggregations, groupFields) ?? throw new NotSupportedException( $"The window refers to '{fieldPath}', which is neither a key of the grouping nor an aggregate it computes."); private static string Alias(GroupFieldRequest group) => string.IsNullOrEmpty(group.Alias) ? group.FieldPath : group.Alias; private static bool Matches(AggregateRequest aggregate, AggregateFunction function, string? field) => aggregate.Function == function && (function == AggregateFunction.Count ? aggregate.ConditionJson == null && (string.IsNullOrEmpty(aggregate.FieldPath) || aggregate.FieldPath == "*" || aggregate.FieldPath == field) : aggregate.FieldPath == field); private static bool TryParseAggregateName(string path, out AggregateFunction function, out string? field) { var parts = path.Split('_', 3); var name = parts.Length > 1 ? parts[1] : ""; field = parts.Length > 2 ? parts[2] : null; if (name.Equals("Avg", StringComparison.OrdinalIgnoreCase)) name = "Average"; return Enum.TryParse(name, ignoreCase: true, out function) && Enum.IsDefined(function); } } Path: redb/redb.Core/Query/Grouping/GroupedWindowSelect.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/Query/Grouping/GroupedWindowSelect.cs ---- using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using redb.Core.Query.Aggregation; using redb.Core.Query.Window; namespace redb.Core.Query.Grouping; /// /// The window over the rows of a grouping, as the free providers write it around the grouping SQL their module /// builds: SELECT g.<columns>, <func> OVER (...) AS <alias> FROM (<grouping>) g. One builder /// for GroupBy and GroupByArray on every free provider; a reference that names no key and no aggregate is refused. /// public static class GroupedWindowSelect { /// /// The aggregates the grouping must compute: those of the selector, then those the window partitions, orders or /// reads by without the selector asking for them, under private aliases. /// public static List WithHiddenAggregates( IReadOnlyList shown, IEnumerable functions, IEnumerable partitionBy, IEnumerable orderBy) { var all = shown.ToList(); all.AddRange(GroupedWindowNames.HiddenAggregates( partitionBy.Select(p => p.FieldPath) .Concat(orderBy.Select(o => o.FieldPath)) .Concat(functions.Select(f => f.FieldPath)), shown)); return all; } /// The grouping, computing every aggregate of . /// Keys of the grouping. /// Every aggregate the grouping computes, hidden ones included. /// The aggregates of the selector; hidden ones are left out of the result. /// Window functions with their aliases. /// PARTITION BY references. /// ORDER BY references. /// Identifier quoting of the dialect. /// True for a dialect whose window functions require ORDER BY (SQL Server): without /// an order of its own the window is ordered by the first key. public static string Build( string innerSql, IReadOnlyList groupFields, IReadOnlyList aggregations, IReadOnlyList shownAggregates, IReadOnlyList functions, IReadOnlyList partitionBy, IReadOnlyList orderBy, Func quote, bool rankingNeedsOrder) { if (functions.Count == 0) throw new ArgumentException("A window over groups needs at least one window function.", nameof(functions)); string Column(string? reference) => "g." + quote(GroupedWindowNames.ResolveColumn(reference, aggregations, groupFields)); var over = new List(); if (partitionBy.Count > 0) over.Add("PARTITION BY " + string.Join(", ", partitionBy.Select(p => Column(p.FieldPath)))); if (orderBy.Count > 0) over.Add("ORDER BY " + string.Join(", ", orderBy.Select(o => Column(o.FieldPath) + (o.Descending ? " DESC" : " ASC")))); else if (rankingNeedsOrder) over.Add("ORDER BY g." + quote(groupFields[0].Alias) + " ASC"); var overClause = string.Join(" ", over); var columns = groupFields.Select(g => g.Alias) .Concat(shownAggregates.Select(a => a.Alias ?? a.Function.ToString())) .Select(c => "g." + quote(c)); var sb = new StringBuilder("SELECT "); sb.Append(string.Join(", ", columns)); foreach (var f in functions) { var alias = string.IsNullOrEmpty(f.Alias) ? (f.Func ?? string.Empty).ToLowerInvariant() : f.Alias; sb.Append(", ").Append(FunctionCall(f, Column)).Append(" OVER (").Append(overClause).Append(") AS ").Append(quote(alias)); } sb.Append(" FROM (").Append(innerSql).Append(") g"); return sb.ToString(); } private static string FunctionCall(WindowFuncRequest f, Func column) { var hasArg = !string.IsNullOrEmpty(f.FieldPath); return (f.Func ?? string.Empty).ToUpperInvariant() switch { "ROWNUMBER" or "ROW_NUMBER" => "ROW_NUMBER()", "RANK" => "RANK()", "DENSERANK" or "DENSE_RANK" => "DENSE_RANK()", "PERCENTRANK" or "PERCENT_RANK" => "PERCENT_RANK()", "CUMEDIST" or "CUME_DIST" => "CUME_DIST()", "NTILE" => "NTILE(" + (f.Buckets ?? 4).ToString(CultureInfo.InvariantCulture) + ")", "SUM" when hasArg => "SUM(" + column(f.FieldPath) + ")", "AVG" when hasArg => "AVG(" + column(f.FieldPath) + ")", "MIN" when hasArg => "MIN(" + column(f.FieldPath) + ")", "MAX" when hasArg => "MAX(" + column(f.FieldPath) + ")", "COUNT" when hasArg => "COUNT(" + column(f.FieldPath) + ")", "COUNT" => "COUNT(*)", "LAG" when hasArg => "LAG(" + column(f.FieldPath) + ")", "LEAD" when hasArg => "LEAD(" + column(f.FieldPath) + ")", "FIRSTVALUE" or "FIRST_VALUE" when hasArg => "FIRST_VALUE(" + column(f.FieldPath) + ")", "LASTVALUE" or "LAST_VALUE" when hasArg => "LAST_VALUE(" + column(f.FieldPath) + ")", _ => WindowFunctionName.ZeroArgCall(f.Func) }; } } Path: redb/redb.Core/Query/Grouping/GroupedWindowSpec.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/Query/Grouping/GroupedWindowSpec.cs ---- using System; using System.Collections.Generic; using System.Linq.Expressions; using redb.Core.Models.Contracts; namespace redb.Core.Query.Grouping; /// /// Window specification for grouped queries. /// public class GroupedWindowSpec : IGroupedWindowSpec { internal List PartitionByExpressions { get; } = []; internal List<(LambdaExpression Expression, bool Descending)> OrderByExpressions { get; } = []; public IGroupedWindowSpec PartitionBy( Expression> keySelector) { PartitionByExpressions.Add(keySelector); return this; } public IGroupedWindowSpec OrderBy( Expression, TField>> orderSelector) { OrderByExpressions.Add((orderSelector, false)); return this; } public IGroupedWindowSpec OrderByDesc( Expression, TField>> orderSelector) { OrderByExpressions.Add((orderSelector, true)); return this; } } Path: redb/redb.Core/Query/Grouping/GroupedWindowedQueryable.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/Query/Grouping/GroupedWindowedQueryable.cs ---- using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using redb.Core.Query.Aggregation; using redb.Core.Query.QueryExpressions; using redb.Core.Query.Window; namespace redb.Core.Query.Grouping; /// /// Where the groups of a grouped window come from: a GroupBy over objects or a GroupByArray over elements. /// internal interface IGroupedWindowSource { /// Name of the provider for messages. string ProviderName { get; } /// What the lambdas inside Agg.* read. GroupItemKind Kind { get; } /// Keys of the grouping, aliased as the selector names g.Key. List GroupFields(LambdaExpression selector); Task ExecuteAsync(LambdaExpression selector, List aggregations, ArrayGroupWindow window, CancellationToken cancellationToken); Task GetSqlAsync(LambdaExpression selector, List aggregations, ArrayGroupWindow window, CancellationToken cancellationToken); /// The list provider the list item keys are read through (ListItemGroupKeys). redb.Core.Providers.IListProvider? ListItems { get; } } /// /// Queryable for applying window functions to grouped data. /// Wraps grouped query and adds window function support. /// public class GroupedWindowedQueryable : IGroupedWindowedQueryable { private const string OwnerApi = "WithWindow.SelectAsync"; private readonly IGroupedWindowSource _source; private readonly GroupedWindowSpec _windowSpec; /// True when the key comes from GroupByRedb: its members are fields of the object, not of Props. public bool IsBaseFieldGrouping { get; init; } /// /// Constructor with filterJson (legacy compatibility). /// public GroupedWindowedQueryable( IRedbQueryProvider provider, long schemeId, Expression keySelector, GroupedWindowSpec windowSpec, string? filterJson = null) : this(provider, schemeId, keySelector, windowSpec, filterJson, null, null) { } /// /// Constructor with FilterExpression (Pro version). /// public GroupedWindowedQueryable( IRedbQueryProvider provider, long schemeId, Expression keySelector, GroupedWindowSpec windowSpec, FilterExpression? filter) : this(provider, schemeId, keySelector, windowSpec, null, filter, null) { } /// /// Constructor for a GroupBy with HAVING: the window runs over the groups that pass it. /// public GroupedWindowedQueryable( IRedbQueryProvider provider, long schemeId, Expression keySelector, GroupedWindowSpec windowSpec, string? filterJson, FilterExpression? filter, string? havingJson) { _windowSpec = windowSpec; _source = new FlatGroupWindowSource(this, provider, schemeId, keySelector, filterJson, filter, havingJson); } internal GroupedWindowedQueryable(IGroupedWindowSource source, GroupedWindowSpec windowSpec) { _source = source; _windowSpec = windowSpec; } public async Task> SelectAsync( Expression, TResult>> selector, CancellationToken cancellationToken = default) { var (aggregations, window) = Parse(selector); var json = await _source.ExecuteAsync(selector, aggregations, window, cancellationToken); var rows = ArrayGroupMaterializer.Materialize(json, selector, _source.GroupFields(selector), _source.ProviderName, OwnerApi); await ListItemGroupKeys.FillAsync(rows, _source.ListItems, OwnerApi, cancellationToken); return rows; } public Task ToSqlStringAsync( Expression, TResult>> selector, CancellationToken cancellationToken = default) { var (aggregations, window) = Parse(selector); return _source.GetSqlAsync(selector, aggregations, window, cancellationToken); } private (List Aggregations, ArrayGroupWindow Window) Parse(LambdaExpression selector) { var aggregations = new List(); var functions = new List(); var param = selector.Parameters[0]; foreach (var (name, _, rawExpr) in GroupSelectorMembers.Extract(selector, OwnerApi)) { var expr = GroupSelectorMembers.StripConvert(rawExpr); if (GroupSelectorMembers.IsKeyAccess(expr, param)) continue; if (expr is MethodCallExpression win && win.Method.DeclaringType == typeof(Win)) { functions.Add(WindowFunction(win, param, name)); continue; } if (GroupAggregateParser.IsAggCall(expr)) { aggregations.Add(GroupAggregateParser.Parse((MethodCallExpression)expr, param, name, _source.Kind, OwnerApi)); continue; } if (!GroupSelectorMembers.ReferencesParameter(expr, param)) continue; // a client value, computed once at materialization throw new NotSupportedException( $"{OwnerApi}: member '{name}' uses the group but is neither g.Key, nor Agg.*, nor Win.* ('{rawExpr}')."); } if (functions.Count == 0) throw new NotSupportedException($"{OwnerApi}: the selector of a window over groups needs at least one Win.* function."); return (aggregations, new ArrayGroupWindow { Functions = functions, PartitionBy = ParsePartitionBy(), OrderBy = ParseOrderBy() }); } /// /// A Win.* call of the selector. Ntile takes its bucket count; Sum, Avg, Min, Max, Count, Lag, Lead, /// FirstValue and LastValue take a key or an Agg.* over the group; the ranking functions take nothing. /// private WindowFuncRequest WindowFunction(MethodCallExpression win, ParameterExpression groupParam, string alias) { var request = new WindowFuncRequest { Func = win.Method.Name, Alias = alias }; if (win.Arguments.Count == 0) return request; if (win.Method.Name == "Ntile") { if (GroupSelectorMembers.ReferencesParameter(win.Arguments[0], groupParam)) throw new NotSupportedException($"{OwnerApi}: Win.Ntile takes a constant number of buckets; got '{win.Arguments[0]}'."); request.Buckets = Expression.Lambda>(win.Arguments[0]).Compile()(); return request; } request.FieldPath = OverReference(win.Arguments[0], groupParam, $"the argument of Win.{win.Method.Name}"); return request; } private List ParsePartitionBy() { var result = new List(); foreach (var expr in _windowSpec.PartitionByExpressions) { var body = GroupSelectorMembers.StripConvert(expr.Body); // PartitionBy(k => k.Department): a member of a composite key, by its name. if (body is MemberExpression memberExpr && memberExpr.Expression == expr.Parameters[0]) { result.Add(new WindowFieldRequest { FieldPath = memberExpr.Member.Name, Alias = memberExpr.Member.Name }); continue; } // PartitionBy(k => k): the single key. if (body == expr.Parameters[0]) { result.Add(new WindowFieldRequest { FieldPath = "Key", Alias = "Key" }); continue; } throw new NotSupportedException($"WithWindow: PartitionBy takes the key or a member of it (k => k.Field); got '{expr}'."); } return result; } private List ParseOrderBy() { var result = new List(); foreach (var (expr, desc) in _windowSpec.OrderByExpressions) result.Add(new WindowOrderRequest { FieldPath = OverReference(expr.Body, expr.Parameters[0], "OrderBy of the window"), Descending = desc }); return result; } /// /// A reference inside OVER or a window function: g.Key (single key), g.Key.Member (composite key) or /// Agg.*(g, ...) in the "Agg_Func_Field" form providers resolve with . /// private string OverReference(Expression body, ParameterExpression groupParam, string what) { var expr = GroupSelectorMembers.StripConvert(body); if (GroupAggregateParser.IsAggCall(expr)) { var request = GroupAggregateParser.Parse((MethodCallExpression)expr, groupParam, "over", _source.Kind, OwnerApi); if (request.ConditionJson != null) throw new NotSupportedException( $"WithWindow: {what} refers to a conditional count; select it in SelectAsync and sort the result instead."); return request.Function == AggregateFunction.Count ? "Agg_Count_Count" : $"Agg_{request.Function}_{request.FieldPath}"; } if (expr is MemberExpression m && GroupSelectorMembers.IsKeyAccess(m, groupParam)) return m.Member.Name == "Key" ? "Key" : m.Member.Name; throw new NotSupportedException($"WithWindow: {what} must be g.Key, a member of g.Key or an Agg.* call; got '{body}'."); } /// /// A GroupBy over objects as the source of the window. /// private sealed class FlatGroupWindowSource : IGroupedWindowSource { private readonly GroupedWindowedQueryable _owner; private readonly IRedbQueryProvider _provider; private readonly long _schemeId; private readonly Expression _keySelector; private readonly string? _filterJson; private readonly FilterExpression? _filter; private readonly string? _havingJson; public FlatGroupWindowSource(GroupedWindowedQueryable owner, IRedbQueryProvider provider, long schemeId, Expression keySelector, string? filterJson, FilterExpression? filter, string? havingJson) { _owner = owner; _provider = provider; _schemeId = schemeId; _keySelector = keySelector; _filterJson = filterJson; _filter = filter; _havingJson = havingJson; } public string ProviderName => _provider.GetType().Name; public redb.Core.Providers.IListProvider? ListItems => (_provider as IListItemKeySource)?.ListItems; public GroupItemKind Kind => GroupItemKind.Props; public List GroupFields(LambdaExpression selector) => GroupKeyFields.Parse(_keySelector, _owner.IsBaseFieldGrouping, "WithWindow"); public async Task ExecuteAsync(LambdaExpression selector, List aggregations, ArrayGroupWindow window, CancellationToken cancellationToken) { var groupFields = GroupFields(selector); var json = _filter != null ? await _provider.ExecuteGroupedWindowQueryAsync(_schemeId, groupFields, aggregations, window.Functions, window.PartitionBy, window.OrderBy, _filter, _havingJson, cancellationToken) : await _provider.ExecuteGroupedWindowQueryAsync(_schemeId, groupFields, aggregations, window.Functions, window.PartitionBy, window.OrderBy, _filterJson, _havingJson, cancellationToken); return json ?? throw new InvalidOperationException($"{OwnerApi}: {ProviderName} returned no answer for the grouped window."); } public Task GetSqlAsync(LambdaExpression selector, List aggregations, ArrayGroupWindow window, CancellationToken cancellationToken) { var groupFields = GroupFields(selector); return _filter != null ? _provider.GetGroupedWindowSqlPreviewAsync(_schemeId, groupFields, aggregations, window.Functions, window.PartitionBy, window.OrderBy, _filter, _havingJson, cancellationToken) : _provider.GetGroupedWindowSqlPreviewAsync(_schemeId, groupFields, aggregations, window.Functions, window.PartitionBy, window.OrderBy, _filterJson, _havingJson, cancellationToken); } } } Path: redb/redb.Core/Query/Grouping/HavingPredicateParser.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/Query/Grouping/HavingPredicateParser.cs ---- using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Linq.Expressions; using System.Text.Json; using redb.Core.Query.Aggregation; namespace redb.Core.Query.Grouping; /// /// Translates HAVING predicates of the form /// Expression<Func<IRedbGrouping<TKey, TProps>, bool>> into the /// JSON shape understood by pvt_build_groupby_sql (and by the Pro /// SQL builder, which compiles the same shape to native HAVING SQL). /// /// Supported predicates: /// Agg.Count(g) — {"$count":"*"} /// Agg.Count(g, x => condition) — {"$count":"*","filter":<condition>} /// Agg.Sum/Average/Min/Max(g, x => x.Field) — {"$sum":{"$field":"Field"}} /// binary comparisons (>, <, >=, <=, ==, !=) and && / || /// /// Captured constants and outer-scope values are evaluated via /// .Compile() and emitted as /// {"$const":value} nodes. /// internal static class HavingPredicateParser { private const string OwnerApi = "Having"; /// /// Compile predicate body to PVT JSON string. /// Returns null when predicate is null. /// public static string? ToJson( Expression, bool>>? predicate) => ToJson(predicate, GroupItemKind.Props); /// /// Compile predicate body to PVT JSON string; says what the lambdas inside Agg.* read. /// public static string? ToJson( Expression, bool>>? predicate, GroupItemKind kind) { if (predicate is null) return null; var node = TranslateBoolean(predicate.Body, predicate.Parameters[0], kind); return JsonSerializer.Serialize(node); } private static object TranslateBoolean(Expression expr, ParameterExpression groupParam, GroupItemKind kind) { // Unwrap Convert(... , bool) while (expr is UnaryExpression u && (u.NodeType == ExpressionType.Convert || u.NodeType == ExpressionType.ConvertChecked)) expr = u.Operand; switch (expr.NodeType) { case ExpressionType.AndAlso: case ExpressionType.And: { var be = (BinaryExpression)expr; return new Dictionary { ["$and"] = new[] { TranslateBoolean(be.Left, groupParam, kind), TranslateBoolean(be.Right, groupParam, kind) } }; } case ExpressionType.OrElse: case ExpressionType.Or: { var be = (BinaryExpression)expr; return new Dictionary { ["$or"] = new[] { TranslateBoolean(be.Left, groupParam, kind), TranslateBoolean(be.Right, groupParam, kind) } }; } case ExpressionType.Not: { var ue = (UnaryExpression)expr; return new Dictionary { ["$not"] = TranslateBoolean(ue.Operand, groupParam, kind) }; } case ExpressionType.GreaterThan: case ExpressionType.GreaterThanOrEqual: case ExpressionType.LessThan: case ExpressionType.LessThanOrEqual: case ExpressionType.Equal: case ExpressionType.NotEqual: return TranslateComparison((BinaryExpression)expr, groupParam, kind); } throw new NotSupportedException( "Unsupported HAVING expression node: " + expr.NodeType + " (" + expr + ")"); } private static Dictionary TranslateComparison(BinaryExpression be, ParameterExpression groupParam, GroupItemKind kind) { var opKey = be.NodeType switch { ExpressionType.GreaterThan => "$gt", ExpressionType.GreaterThanOrEqual => "$gte", ExpressionType.LessThan => "$lt", ExpressionType.LessThanOrEqual => "$lte", ExpressionType.Equal => "$eq", ExpressionType.NotEqual => "$ne", _ => throw new NotSupportedException("Comparison " + be.NodeType + " is not supported in HAVING.") }; var left = TranslateOperand(be.Left, groupParam, kind); var right = TranslateOperand(be.Right, groupParam, kind); return new Dictionary { [opKey] = new[] { left, right } }; } private static object TranslateOperand(Expression expr, ParameterExpression groupParam, GroupItemKind kind) { // Unwrap Convert (boxing for value types: e.g. (decimal)Agg.Sum(...)) while (expr is UnaryExpression u && (u.NodeType == ExpressionType.Convert || u.NodeType == ExpressionType.ConvertChecked)) expr = u.Operand; if (expr is MethodCallExpression mc && mc.Method.DeclaringType == typeof(Agg)) return TranslateAggregate(mc, groupParam, kind); // Treat anything not referencing the group parameter as a captured constant. if (!GroupSelectorMembers.ReferencesParameter(expr, groupParam)) { var value = EvaluateConstant(expr); if (value is null) // G-5 (ревью 2026-09-03): null превращался в СТРОКУ "null" и сравнение шло с // текстом. NULL-семантики у HAVING-констант нет - отказ громкий. throw new NotSupportedException( "HAVING: сравнение с null-константой не поддерживается - сравните с Count или не-null значением."); return new Dictionary { ["$const"] = value }; } throw new NotSupportedException( "Unsupported HAVING operand: " + expr + ". Only Agg.* aggregates and captured constants are allowed."); } private static object TranslateAggregate(MethodCallExpression mc, ParameterExpression groupParam, GroupItemKind kind) { // One strict reading for SelectAsync and HAVING: the same call means the same SQL in both. var request = GroupAggregateParser.Parse(mc, groupParam, alias: mc.Method.Name, kind, OwnerApi); if (request.Function == AggregateFunction.Count) { var node = new Dictionary { ["$count"] = "*" }; if (request.ConditionJson != null) node["filter"] = JsonDocument.Parse(request.ConditionJson).RootElement.Clone(); return node; } var opKey = request.Function switch { AggregateFunction.Sum => "$sum", AggregateFunction.Average => "$avg", AggregateFunction.Min => "$min", _ => "$max" }; return new Dictionary { [opKey] = new Dictionary { ["$field"] = request.FieldPath } }; } private static object? EvaluateConstant(Expression expr) { if (expr is ConstantExpression ce) return NormalizeConstant(ce.Value); var lambda = Expression.Lambda(Expression.Convert(expr, typeof(object))); var compiled = (Func)lambda.Compile(); return NormalizeConstant(compiled()); } private static object? NormalizeConstant(object? v) { if (v is null) return null; // Keep JSON-friendly primitive types switch (v) { case bool or string or short or int or long or decimal or double or float: return v; case DateTime dt: return dt.ToString("o", CultureInfo.InvariantCulture); case DateTimeOffset dto: return dto.ToString("o", CultureInfo.InvariantCulture); case Guid g: return g.ToString(); default: return v.ToString(); } } } Path: redb/redb.Core/Query/Grouping/IGroupedWindowedQueryable.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/Query/Grouping/IGroupedWindowedQueryable.cs ---- using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using redb.Core.Models.Contracts; namespace redb.Core.Query.Grouping; /// /// Queryable for applying window functions to grouped data. /// Allows ranking, running totals, and other analytics on aggregated results. /// /// Group key type /// Object properties type public interface IGroupedWindowedQueryable { /// /// Execute query and materialize results with window functions applied to groups. /// /// Result type /// Projection expression with group aggregations and window functions /// List of results with window calculations /// Cancels the operation (OCE only; a rollback in flight always completes). Task> SelectAsync( Expression, TResult>> selector, CancellationToken cancellationToken = default); /// /// Get SQL preview for debugging. /// Task ToSqlStringAsync( Expression, TResult>> selector, CancellationToken cancellationToken = default); } /// /// Window specification for grouped queries. /// /// Group key type /// Object properties type public interface IGroupedWindowSpec { /// /// Partition window by group key field (for ranking within partitions). /// IGroupedWindowSpec PartitionBy( Expression> keySelector); /// /// Order rows within window ascending. /// IGroupedWindowSpec OrderBy( Expression, TField>> orderSelector); /// /// Order rows within window descending. /// IGroupedWindowSpec OrderByDesc( Expression, TField>> orderSelector); } Path: redb/redb.Core/Query/Grouping/IRedbGroupedQueryable.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/Query/Grouping/IRedbGroupedQueryable.cs ---- using System.Linq.Expressions; namespace redb.Core.Query.Grouping; /// /// Interface for grouped REDB queries. /// Allows executing aggregations per group via SelectAsync. /// public interface IRedbGroupedQueryable { /// /// Executes projection with aggregations for each group. /// Task> SelectAsync( Expression, TResult>> selector, CancellationToken cancellationToken = default); /// /// Returns group count. /// Task CountAsync(CancellationToken cancellationToken = default); /// /// Returns SQL string that will be executed for this GroupBy query. /// Useful for debugging and diagnostics. /// Task ToSqlStringAsync( Expression, TResult>> selector, CancellationToken cancellationToken = default); /// /// Filter groups by a predicate over aggregates (SQL HAVING). /// The predicate must reference the grouped projection only through /// helpers, e.g.: /// .Having(g => Agg.Count(g) > 5 && Agg.Sum(g, x => x.Salary) > 1000). /// Multiple Having calls compose with logical AND. /// IRedbGroupedQueryable Having( System.Linq.Expressions.Expression, bool>> predicate); /// /// Apply window functions to grouped results. /// Allows ranking, running totals, and other analytics on aggregated data. /// /// Window specification (partition, order) /// Grouped windowed queryable for further projection IGroupedWindowedQueryable WithWindow( Action> windowConfig); } Path: redb/redb.Core/Query/Grouping/IRedbGrouping.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/Query/Grouping/IRedbGrouping.cs ---- namespace redb.Core.Query.Grouping; /// /// Represents group of objects with common key. /// Used in SelectAsync to access Key and aggregations via Agg.* /// public interface IRedbGrouping { /// /// Group key (value by which grouped). /// TKey Key { get; } } Path: redb/redb.Core/Query/Grouping/ItemPredicateParser.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/Query/Grouping/ItemPredicateParser.cs ---- using System; using System.Collections.Generic; using System.Globalization; using System.Linq.Expressions; using System.Text.Json; namespace redb.Core.Query.Grouping; /// /// Translates the condition of a conditional count (Agg.Count(g, c => c.IsVerified && c.Type == "email")) /// into the boolean JSON that HAVING already uses, so every generator reads one language: /// $and/$or/$not, $eq/$ne/$gt/$gte/$lt/$lte, $isnull/$notnull, $field, $const. /// Any other form is refused with in the message. /// internal static class ItemPredicateParser { /// What a condition may contain; part of every refusal. public const string Supported = "a condition of Agg.Count may compare a field with a constant or with another field (==, !=, <, <=, >, >=), " + "combine comparisons with &&, || and !, test a field for null (x.F == null, x.F != null, x.F.HasValue) " + "and use a boolean field alone"; /// JSON of the condition, or a naming the part it cannot translate. public static string ToJson(LambdaExpression predicate, GroupItemKind kind, string ownerApi) => JsonSerializer.Serialize(new Translator(predicate.Parameters[0], kind, ownerApi).Boolean(predicate.Body)); private sealed class Translator { private readonly ParameterExpression _param; private readonly GroupItemKind _kind; private readonly string _ownerApi; public Translator(ParameterExpression param, GroupItemKind kind, string ownerApi) { _param = param; _kind = kind; _ownerApi = ownerApi; } public object Boolean(Expression expr) { expr = GroupSelectorMembers.StripConvert(expr); switch (expr.NodeType) { case ExpressionType.AndAlso: case ExpressionType.And when expr.Type == typeof(bool): return Node("$and", new[] { Boolean(((BinaryExpression)expr).Left), Boolean(((BinaryExpression)expr).Right) }); case ExpressionType.OrElse: case ExpressionType.Or when expr.Type == typeof(bool): return Node("$or", new[] { Boolean(((BinaryExpression)expr).Left), Boolean(((BinaryExpression)expr).Right) }); case ExpressionType.Not: return Node("$not", Boolean(((UnaryExpression)expr).Operand)); case ExpressionType.Equal: case ExpressionType.NotEqual: case ExpressionType.GreaterThan: case ExpressionType.GreaterThanOrEqual: case ExpressionType.LessThan: case ExpressionType.LessThanOrEqual: return Comparison((BinaryExpression)expr); } // x.F.HasValue if (expr is MemberExpression { Member.Name: "HasValue" } hasValue && hasValue.Expression is { } inner && Nullable.GetUnderlyingType(inner.Type) != null && IsField(inner)) return Node("$notnull", Field(inner)); // A boolean field alone: x.IsVerified, or the element of a bool[] (x => x). if ((expr.Type == typeof(bool) || expr.Type == typeof(bool?)) && IsField(expr)) return Node("$eq", new object[] { Field(expr), Const(true) }); throw Refuse(expr); } private object Comparison(BinaryExpression be) { var op = be.NodeType switch { ExpressionType.Equal => "$eq", ExpressionType.NotEqual => "$ne", ExpressionType.GreaterThan => "$gt", ExpressionType.GreaterThanOrEqual => "$gte", ExpressionType.LessThan => "$lt", _ => "$lte" }; var leftIsField = IsField(be.Left); var rightIsField = IsField(be.Right); if (!leftIsField && !rightIsField) throw Refuse(be); var fieldSide = leftIsField ? be.Left : be.Right; var otherSide = leftIsField ? be.Right : be.Left; if (!ReferencesParameter(otherSide) && Evaluate(otherSide) is null) { return op switch { "$eq" => Node("$isnull", Field(fieldSide)), "$ne" => Node("$notnull", Field(fieldSide)), _ => throw new NotSupportedException( $"{_ownerApi}: '{be}' orders a field against null; {Supported}.") }; } var left = Operand(be.Left, be.Right); var right = Operand(be.Right, be.Left); return Node(op, new[] { left, right }); } private object Operand(Expression side, Expression otherSide) { if (IsField(side)) return Field(side); if (ReferencesParameter(side)) throw Refuse(side); var value = Evaluate(side); // C# compares an enum through its number: Convert(x.Kind, Int32) == 2. Stored enums are their names. var enumType = EnumTypeOf(otherSide); if (enumType != null && value != null && !(value is string)) value = Enum.ToObject(enumType, value).ToString(); return Const(Normalize(value!)); } private bool IsField(Expression expr) { expr = GroupSelectorMembers.StripConvert(expr); if (expr == _param) return _kind == GroupItemKind.ArrayValueElement; return expr is MemberExpression m && GroupSelectorMembers.IsFieldChain(m) && GroupAggregateParser.TryMemberPath(m, _param, out _); } private object Field(Expression expr) => Node("$field", GroupAggregateParser.FieldPath(expr, _param, _kind, _ownerApi, "a field in the condition of Agg.Count")); private static Type? EnumTypeOf(Expression expr) { var stripped = GroupSelectorMembers.StripConvert(expr); var t = Nullable.GetUnderlyingType(stripped.Type) ?? stripped.Type; return t.IsEnum ? t : null; } private bool ReferencesParameter(Expression expr) => GroupSelectorMembers.ReferencesParameter(expr, _param); private static object? Evaluate(Expression expr) { if (expr is ConstantExpression ce) return ce.Value; return Expression.Lambda>(Expression.Convert(expr, typeof(object))).Compile()(); } private static object Normalize(object value) => value switch { bool or string or short or int or long or decimal or double or float or byte => value, char c => c.ToString(), DateTime dt => dt.ToString("o", CultureInfo.InvariantCulture), DateTimeOffset dto => dto.ToString("o", CultureInfo.InvariantCulture), Guid g => g.ToString(), Enum e => e.ToString(), _ => throw new NotSupportedException( $"A constant of type {value.GetType().Name} cannot be used in the condition of Agg.Count; {Supported}.") }; private static Dictionary Const(object value) => Node("$const", value); private static Dictionary Node(string key, object value) => new() { [key] = value }; private NotSupportedException Refuse(Expression expr) => new($"{_ownerApi}: '{expr}' cannot be translated; {Supported}."); } } Path: redb/redb.Core/Query/Grouping/ListItemGroupKeys.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/Query/Grouping/ListItemGroupKeys.cs ---- using System.Reflection; using System.Runtime.CompilerServices; using redb.Core.Models.Entities; using redb.Core.Providers; namespace redb.Core.Query.Grouping; /// /// A query provider that hands the list provider of its service to the groupings it runs. Set by /// on every query it creates. /// internal interface IListItemKeySource { IListProvider? ListItems { get; set; } } /// /// The key of a grouping by a list item (GroupBy(p => p.Status)) is the item a loaded object carries: Id, /// IdList, Value, Alias, IdObject. Every engine groups by the item id and returns only that id, which becomes a stub /// item; after materializing, the stubs of a result are made the items of their ids, read in one batch through the /// list provider. The SQL and its preview stay the same on every engine; the extra read happens only when a result /// carries a list item. An id that names no item any more leaves its stub with the id alone. /// internal static class ListItemGroupKeys { private const int MaxDepth = 3; public static async Task FillAsync(List rows, IListProvider? lists, string api, CancellationToken cancellationToken) { if (rows.Count == 0 || !MayCarryListItem(typeof(TResult), 0)) return; var stubs = new List(); foreach (var row in rows) Collect(row, stubs, 0); if (stubs.Count == 0) return; if (lists == null) throw new InvalidOperationException( $"{api}: the key of this grouping is a list item, and the query has no list provider to read the items with."); var items = (await lists.GetListItemsByIdsAsync(stubs.Select(s => s.Id), cancellationToken)).ToDictionary(i => i.Id); foreach (var stub in stubs) if (items.TryGetValue(stub.Id, out var item)) stub.TakeFrom(item); } private static bool MayCarryListItem(Type type, int depth) { if (type == typeof(RedbListItem)) return true; if (depth >= MaxDepth || !IsComposite(type)) return false; return type.GetProperties(BindingFlags.Public | BindingFlags.Instance) .Any(p => p.GetIndexParameters().Length == 0 && MayCarryListItem(p.PropertyType, depth + 1)); } private static void Collect(object? value, List stubs, int depth) { switch (value) { case null: return; case RedbListItem item: if (item.Id != 0) stubs.Add(item); return; } var type = value.GetType(); if (depth >= MaxDepth || !IsComposite(type)) return; foreach (var p in type.GetProperties(BindingFlags.Public | BindingFlags.Instance)) if (p.GetIndexParameters().Length == 0 && MayCarryListItem(p.PropertyType, depth + 1)) Collect(p.GetValue(value), stubs, depth + 1); } // A result row or a composite key: an anonymous type, a record or class the selector builds. Strings, values, // collections and the model types of redb are not walked. private static bool IsComposite(Type type) => type.IsClass && type != typeof(string) && !typeof(System.Collections.IEnumerable).IsAssignableFrom(type) && (type.IsDefined(typeof(CompilerGeneratedAttribute), false) || type.Namespace?.StartsWith("redb.Core") != true); } Path: redb/redb.Core/Query/Grouping/RedbArrayGroupedQueryable.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/Query/Grouping/RedbArrayGroupedQueryable.cs ---- using System.Linq.Expressions; using System.Text.Json; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using redb.Core.Query.Aggregation; using redb.Core.Query.Base; using redb.Core.Query.QueryExpressions; using redb.Core.Query.Utils; using redb.Core.Query.Window; namespace redb.Core.Query.Grouping; /// /// Runs an on a provider: the flat one, or the tree one with its subtree. /// internal interface IArrayGroupRunner { /// Name of the provider for messages. string ProviderName { get; } Task ExecuteAsync(ArrayGroupQuery query, CancellationToken cancellationToken); Task GetSqlAsync(ArrayGroupQuery query, CancellationToken cancellationToken); /// The list provider the list item keys are read through (ListItemGroupKeys). redb.Core.Providers.IListProvider? ListItems { get; } } internal sealed class FlatArrayGroupRunner : IArrayGroupRunner { private readonly IRedbQueryProvider _provider; public FlatArrayGroupRunner(IRedbQueryProvider provider) => _provider = provider; public string ProviderName => _provider.GetType().Name; public redb.Core.Providers.IListProvider? ListItems => (_provider as IListItemKeySource)?.ListItems; public Task ExecuteAsync(ArrayGroupQuery query, CancellationToken cancellationToken) => _provider.ExecuteArrayGroupQueryAsync(query, cancellationToken); public Task GetSqlAsync(ArrayGroupQuery query, CancellationToken cancellationToken) => _provider.GetArrayGroupQuerySqlAsync(query, cancellationToken); } internal sealed class TreeArrayGroupRunner : IArrayGroupRunner where TProps : class, new() { private readonly ITreeQueryProvider _provider; private readonly TreeQueryContext _context; public TreeArrayGroupRunner(ITreeQueryProvider provider, TreeQueryContext context) { _provider = provider; _context = context; } public string ProviderName => _provider.GetType().Name; public redb.Core.Providers.IListProvider? ListItems => (_provider as IListItemKeySource)?.ListItems; public Task ExecuteAsync(ArrayGroupQuery query, CancellationToken cancellationToken) => _provider.ExecuteTreeArrayGroupQueryAsync(_context, query, cancellationToken); public Task GetSqlAsync(ArrayGroupQuery query, CancellationToken cancellationToken) => _provider.GetTreeArrayGroupQuerySqlAsync(_context, query, cancellationToken); } /// /// Grouping by the elements of an array: GroupByArray(e => e.Contacts, c => c.Type), an inner array /// (e => e.Contacts.SelectMany(c => c.Metadata)), an array of simple values (e => e.Skills, s => s). /// Every form it cannot translate is refused with . /// public class RedbArrayGroupedQueryable : IRedbGroupedQueryable where TProps : class, new() { private const string OwnerApi = "GroupByArray"; private readonly IArrayGroupRunner _runner; private readonly long _schemeId; private readonly FilterExpression? _filter; private readonly LambdaExpression _arraySelector; private readonly LambdaExpression _keySelector; private readonly List _havingPredicates = new(); private readonly GroupItemKind _kind; /// /// Flat grouping; is not used, the condition comes from . /// public RedbArrayGroupedQueryable( IRedbQueryProvider provider, long schemeId, string? filterJson, FilterExpression? filter, Expression>> arraySelector, Expression> keySelector) : this(new FlatArrayGroupRunner(provider), schemeId, filter, arraySelector, keySelector) { } internal RedbArrayGroupedQueryable( IArrayGroupRunner runner, long schemeId, FilterExpression? filter, LambdaExpression arraySelector, LambdaExpression keySelector) { _runner = runner; _schemeId = schemeId; _filter = filter; _arraySelector = arraySelector; _keySelector = keySelector; _kind = ResolveItemKind(); // Parse now: a form that cannot be translated is refused where it is written, not at execution. _ = ParseArrayPath(_arraySelector); _ = ParseGroupFields(alias: null); } public async Task> SelectAsync( Expression, TResult>> selector, CancellationToken cancellationToken = default) { var query = BuildQuery(selector, window: null); var json = await _runner.ExecuteAsync(query, cancellationToken); var rows = ArrayGroupMaterializer.Materialize(json, selector, query.GroupFields, _runner.ProviderName, OwnerApi); await ListItemGroupKeys.FillAsync(rows, _runner.ListItems, OwnerApi, cancellationToken); return rows; } public async Task CountAsync(CancellationToken cancellationToken = default) { var query = new ArrayGroupQuery { SchemeId = _schemeId, ArrayPath = ParseArrayPath(_arraySelector), GroupFields = ParseGroupFields(alias: null), Aggregations = new[] { new AggregateRequest { FieldPath = "*", Function = AggregateFunction.Count, Alias = "cnt" } }, Filter = _filter, HavingJson = BuildHavingJson() }; using var json = await _runner.ExecuteAsync(query, cancellationToken); return ArrayGroupMaterializer.RequireArray(json, _runner.ProviderName, OwnerApi).GetArrayLength(); } public Task ToSqlStringAsync( Expression, TResult>> selector, CancellationToken cancellationToken = default) => _runner.GetSqlAsync(BuildQuery(selector, window: null), cancellationToken); public IGroupedWindowedQueryable WithWindow(Action> windowConfig) { var windowSpec = new GroupedWindowSpec(); windowConfig(windowSpec); return new GroupedWindowedQueryable(new ArrayWindowSource(this), windowSpec); } /// public IRedbGroupedQueryable Having(Expression, bool>> predicate) { if (predicate is null) throw new ArgumentNullException(nameof(predicate)); // G-4: a copying builder - a branch does not leak into its sibling. var copy = new RedbArrayGroupedQueryable(_runner, _schemeId, _filter, _arraySelector, _keySelector); copy._havingPredicates.AddRange(_havingPredicates); copy._havingPredicates.Add(predicate); return copy; } // ---------------------------------------------------------------------------------------------------------------- private ArrayGroupQuery BuildQuery(LambdaExpression selector, ArrayGroupWindow? window) => new() { SchemeId = _schemeId, ArrayPath = ParseArrayPath(_arraySelector), GroupFields = ParseGroupFields(KeyAliasFromSelector(selector)), Aggregations = ParseAggregations(selector), Filter = _filter, HavingJson = BuildHavingJson(), Window = window }; private string? BuildHavingJson() { if (_havingPredicates.Count == 0) return null; var param = Expression.Parameter(typeof(IRedbGrouping), "g"); Expression? body = null; foreach (var p in _havingPredicates) { var next = new ParameterReplacer(p.Parameters[0], param).Visit(p.Body)!; body = body == null ? next : Expression.AndAlso(body, next); } var combined = Expression.Lambda, bool>>(body!, param); return HavingPredicateParser.ToJson(combined, _kind); } private sealed class ParameterReplacer : ExpressionVisitor { private readonly ParameterExpression _from; private readonly ParameterExpression _to; public ParameterReplacer(ParameterExpression from, ParameterExpression to) { _from = from; _to = to; } protected override Expression VisitParameter(ParameterExpression node) => node == _from ? _to : base.VisitParameter(node); } /// /// What an element of the array is. A class other than string is an element with fields; a list item and an /// object reference are refused by name; every other type is a simple value read from the element row. /// private static GroupItemKind ResolveItemKind() { var t = Nullable.GetUnderlyingType(typeof(TItem)) ?? typeof(TItem); if (t == typeof(string)) return GroupItemKind.ArrayValueElement; if (typeof(IRedbListItem).IsAssignableFrom(t)) throw new NotSupportedException( $"{OwnerApi} over an array of {t.Name} is not supported: group the objects by the list item instead " + "(GroupBy(e => e.Field)), or keep the item id in a long field."); if (typeof(IRedbObject).IsAssignableFrom(t)) throw new NotSupportedException( $"{OwnerApi} over an array of object references ({t.Name}) is not supported: group the referenced objects " + "by their own fields."); if (t == typeof(byte[])) throw new NotSupportedException($"{OwnerApi} over an array of byte[] is not supported."); if (t.IsClass || t.IsInterface) return GroupItemKind.ArrayClassElement; return GroupItemKind.ArrayValueElement; } /// /// The array path: a chain of fields (e => e.Contacts, e => e.HomeAddress.Building.Amenities) and /// SelectMany over an inner array (e => e.Contacts.SelectMany(c => c.Metadata)), joined with dots. /// private static string ParseArrayPath(LambdaExpression selector) => PathOf(selector.Body, selector.Parameters[0], selector); private static string PathOf(Expression expression, ParameterExpression parameter, LambdaExpression whole) { var e = GroupSelectorMembers.StripConvert(expression); if (e is MethodCallExpression mc && mc.Method.Name == "SelectMany" && mc.Method.DeclaringType == typeof(Enumerable)) { if (mc.Arguments.Count != 2) throw new NotSupportedException( $"{OwnerApi}: SelectMany with a result selector is not supported in the array path ('{mc}'). Group the " + "inner array alone (e => e.Contacts.SelectMany(c => c.Metadata)); keys and aggregates read its elements."); var inner = mc.Arguments[1] is UnaryExpression { NodeType: ExpressionType.Quote } q ? q.Operand : mc.Arguments[1]; if (inner is not LambdaExpression lambda || lambda.Parameters.Count != 1) throw new NotSupportedException( $"{OwnerApi}: SelectMany in the array path takes a lambda over the element (c => c.Inner); got '{mc.Arguments[1]}'."); return PathOf(mc.Arguments[0], parameter, whole) + "." + FieldChainPath(lambda.Body, lambda.Parameters[0], whole); } if (e is MemberExpression) return FieldChainPath(e, parameter, whole); throw new NotSupportedException( $"{OwnerApi}: the array path supports a chain of fields (e => e.Contacts, e => e.HomeAddress.Building.Amenities) " + $"and SelectMany over an inner array (e => e.Contacts.SelectMany(c => c.Metadata)); got '{whole}'."); } private static string FieldChainPath(Expression expression, ParameterExpression parameter, LambdaExpression whole) { var e = GroupSelectorMembers.StripConvert(expression); if (e is MemberExpression member && GroupSelectorMembers.IsFieldChain(member) && GroupAggregateParser.TryMemberPath(member, parameter, out var path)) { for (Expression? cur = member; cur is MemberExpression m; cur = m.Expression is null ? null : GroupSelectorMembers.StripConvert(m.Expression)) { if (IsDictionary(m.Type)) throw new NotSupportedException( $"{OwnerApi}: a dictionary in the array path is not supported ('{m}' in '{whole}')."); } return path; } throw new NotSupportedException( $"{OwnerApi}: '{expression}' in the array path '{whole}' is not a chain of stored fields."); } private static bool IsDictionary(Type type) => type.GetInterfaces().Concat(new[] { type }).Any(i => i.IsGenericType && (i.GetGenericTypeDefinition() == typeof(IDictionary<,>) || i.GetGenericTypeDefinition() == typeof(IReadOnlyDictionary<,>))); /// /// Keys: a field of the element (c => c.Type, c => c.Address.City), the element itself for an array /// of simple values (s => s), or an anonymous type of those. A key is a stored value, never a class. /// private List ParseGroupFields(string? alias) { var parameter = _keySelector.Parameters[0]; var body = GroupSelectorMembers.StripConvert(_keySelector.Body); var fields = new List(); if (body is NewExpression newExpr && newExpr.Members != null && body.Type.Name.Contains("AnonymousType")) { for (int i = 0; i < newExpr.Arguments.Count; i++) { var memberName = newExpr.Members[i].Name; fields.Add(new GroupFieldRequest { FieldPath = KeyPath(newExpr.Arguments[i], parameter, $"key member '{memberName}'"), Alias = memberName }); } return fields; } fields.Add(new GroupFieldRequest { FieldPath = KeyPath(body, parameter, "the key"), Alias = alias ?? DefaultKeyAlias(body) }); return fields; } private static string DefaultKeyAlias(Expression body) => body is MemberExpression m ? m.Member.Name : "Key"; private string KeyPath(Expression expression, ParameterExpression parameter, string what) { var e = GroupSelectorMembers.StripConvert(expression); var type = Nullable.GetUnderlyingType(e.Type) ?? e.Type; if (type != typeof(string) && (type.IsClass || type.IsInterface) && !typeof(IRedbListItem).IsAssignableFrom(type)) throw new NotSupportedException( $"{OwnerApi}: {what} ('{expression}') is a class; a key is a stored value: name a field of it."); return GroupAggregateParser.FieldPath(expression, parameter, _kind, OwnerApi, what); } /// The name the selector gives to g.Key (single key), used as the key's alias in SQL. private static string? KeyAliasFromSelector(LambdaExpression selector) { var groupParam = selector.Parameters[0]; foreach (var (name, _, expr) in GroupSelectorMembers.Extract(selector, OwnerApi + ".SelectAsync")) { if (GroupSelectorMembers.StripConvert(expr) is MemberExpression { Member.Name: "Key" } m && m.Expression == groupParam) return name; } return null; } private List ParseAggregations(LambdaExpression selector) { var aggregations = new List(); var groupParam = selector.Parameters[0]; foreach (var (name, _, rawExpr) in GroupSelectorMembers.Extract(selector, OwnerApi + ".SelectAsync")) { var expr = GroupSelectorMembers.StripConvert(rawExpr); if (GroupSelectorMembers.IsKeyAccess(expr, groupParam)) continue; if (GroupAggregateParser.IsAggCall(expr)) { aggregations.Add(GroupAggregateParser.Parse((MethodCallExpression)expr, groupParam, name, _kind, OwnerApi + ".SelectAsync")); continue; } if (expr is MethodCallExpression wc && wc.Method.DeclaringType == typeof(Win)) continue; // a window function: the window over the groups reads it if (!GroupSelectorMembers.ReferencesParameter(expr, groupParam)) continue; // a client value, computed once at materialization throw new NotSupportedException( $"{OwnerApi}.SelectAsync: member '{name}' uses the group but is neither g.Key nor a direct Agg.* call ('{rawExpr}')."); } return aggregations; } /// /// The array grouping as the source of a window over its groups. /// private sealed class ArrayWindowSource : IGroupedWindowSource { private readonly RedbArrayGroupedQueryable _owner; public ArrayWindowSource(RedbArrayGroupedQueryable owner) => _owner = owner; public string ProviderName => _owner._runner.ProviderName; public redb.Core.Providers.IListProvider? ListItems => _owner._runner.ListItems; public GroupItemKind Kind => _owner._kind; public List GroupFields(LambdaExpression selector) => _owner.ParseGroupFields(KeyAliasFromSelector(selector)); public Task ExecuteAsync(LambdaExpression selector, List aggregations, ArrayGroupWindow window, CancellationToken cancellationToken) => _owner._runner.ExecuteAsync(Query(selector, aggregations, window), cancellationToken); public Task GetSqlAsync(LambdaExpression selector, List aggregations, ArrayGroupWindow window, CancellationToken cancellationToken) => _owner._runner.GetSqlAsync(Query(selector, aggregations, window), cancellationToken); private ArrayGroupQuery Query(LambdaExpression selector, List aggregations, ArrayGroupWindow window) => new() { SchemeId = _owner._schemeId, ArrayPath = ParseArrayPath(_owner._arraySelector), GroupFields = GroupFields(selector), Aggregations = aggregations, Filter = _owner._filter, HavingJson = _owner.BuildHavingJson(), Window = window }; } } Path: redb/redb.Core/Query/Grouping/RedbGroupedQueryable.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/Query/Grouping/RedbGroupedQueryable.cs ---- using System.Linq.Expressions; using System.Text.Json; using redb.Core.Query.Aggregation; using redb.Core.Query.QueryExpressions; namespace redb.Core.Query.Grouping; /// /// Implementation of REDB grouped queries /// public class RedbGroupedQueryable : IRedbGroupedQueryable where TProps : class, new() { private const string OwnerApi = "GroupBy"; private readonly IRedbQueryProvider _provider; private readonly long _schemeId; private readonly string? _filterJson; private readonly FilterExpression? _filter; private readonly Expression _keySelector; private readonly bool _isBaseFieldGrouping; private readonly List _havingPredicates = new(); /// /// Constructor with filterJson (Free version compatibility). /// public RedbGroupedQueryable( IRedbQueryProvider provider, long schemeId, string? filterJson, Expression keySelector, bool isBaseFieldGrouping = false) { _provider = provider; _schemeId = schemeId; _filterJson = filterJson; _filter = null; _keySelector = keySelector; _isBaseFieldGrouping = isBaseFieldGrouping; } /// /// Constructor with FilterExpression (Pro version - direct access to filter). /// public RedbGroupedQueryable( IRedbQueryProvider provider, long schemeId, FilterExpression? filter, Expression keySelector, bool isBaseFieldGrouping = false) { _provider = provider; _schemeId = schemeId; _filterJson = null; _filter = filter; _keySelector = keySelector; _isBaseFieldGrouping = isBaseFieldGrouping; } public async Task> SelectAsync( Expression, TResult>> selector, CancellationToken cancellationToken = default) { var groupFields = GroupKeyFields.Parse(_keySelector, _isBaseFieldGrouping, OwnerApi); var aggregations = ParseAggregations(selector); var json = await ExecuteAsync(groupFields, aggregations, cancellationToken); var rows = ArrayGroupMaterializer.Materialize(json, selector, groupFields, _provider.GetType().Name, OwnerApi + ".SelectAsync"); await ListItemGroupKeys.FillAsync(rows, (_provider as IListItemKeySource)?.ListItems, OwnerApi + ".SelectAsync", cancellationToken); return rows; } public async Task CountAsync(CancellationToken cancellationToken = default) { var groupFields = GroupKeyFields.Parse(_keySelector, _isBaseFieldGrouping, OwnerApi); var aggregations = new List { new() { FieldPath = "*", Function = AggregateFunction.Count, Alias = "cnt" } }; using var json = await ExecuteAsync(groupFields, aggregations, cancellationToken); return ArrayGroupMaterializer.RequireArray(json, _provider.GetType().Name, OwnerApi + ".CountAsync").GetArrayLength(); } /// /// Returns SQL string that will be executed for this GroupBy query. /// public Task ToSqlStringAsync( Expression, TResult>> selector, CancellationToken cancellationToken = default) { var groupFields = GroupKeyFields.Parse(_keySelector, _isBaseFieldGrouping, OwnerApi); var aggregations = ParseAggregations(selector); var havingJson = BuildHavingJson(); return _filter != null ? _provider.GetGroupBySqlPreviewAsync(_schemeId, groupFields, aggregations, _filter, havingJson, cancellationToken) : _provider.GetGroupBySqlPreviewAsync(_schemeId, groupFields, aggregations, _filterJson, havingJson, cancellationToken); } /// /// Apply window functions to grouped results: the window runs over the groups that pass Having. /// public IGroupedWindowedQueryable WithWindow( Action> windowConfig) { var windowSpec = new GroupedWindowSpec(); windowConfig(windowSpec); return new GroupedWindowedQueryable( _provider, _schemeId, _keySelector, windowSpec, _filterJson, _filter, BuildHavingJson()) { IsBaseFieldGrouping = _isBaseFieldGrouping }; } /// public IRedbGroupedQueryable Having( Expression, bool>> predicate) { if (predicate is null) throw new ArgumentNullException(nameof(predicate)); // G-4 (ревью 2026-09-03): строитель копирующий, как весь остальной LINQ-API. Раньше // Having мутировал this - ветвление (var a = g.Having(x); var b = g.Having(y);) // заражало сестринскую ветку обоими предикатами. var copy = _filter != null ? new RedbGroupedQueryable(_provider, _schemeId, _filter, _keySelector, _isBaseFieldGrouping) : new RedbGroupedQueryable(_provider, _schemeId, _filterJson, _keySelector, _isBaseFieldGrouping); copy._havingPredicates.AddRange(_havingPredicates); copy._havingPredicates.Add(predicate); return copy; } private Task ExecuteAsync(List groupFields, List aggregations, CancellationToken cancellationToken) { var havingJson = BuildHavingJson(); return _filter != null ? _provider.ExecuteGroupedAggregateAsync(_schemeId, groupFields, aggregations, _filter, havingJson, cancellationToken: cancellationToken) : _provider.ExecuteGroupedAggregateAsync(_schemeId, groupFields, aggregations, _filterJson, havingJson, cancellationToken: cancellationToken); } private string? BuildHavingJson() { if (_havingPredicates.Count == 0) return null; // Compose multiple Having(...) calls with AndAlso into one predicate var param = Expression.Parameter(typeof(IRedbGrouping), "g"); Expression? body = null; foreach (var p in _havingPredicates) { var next = new ParameterReplacer(p.Parameters[0], param).Visit(p.Body)!; body = body == null ? next : Expression.AndAlso(body, next); } return HavingPredicateParser.ToJson(Expression.Lambda, bool>>(body!, param)); } private sealed class ParameterReplacer : ExpressionVisitor { private readonly ParameterExpression _from; private readonly ParameterExpression _to; public ParameterReplacer(ParameterExpression from, ParameterExpression to) { _from = from; _to = to; } protected override Expression VisitParameter(ParameterExpression node) => node == _from ? _to : base.VisitParameter(node); } /// /// Aggregations of SelectAsync. Fail-closed (G-2): a member that uses the group but is neither g.Key nor a direct /// Agg.* call is refused; a member that does not use the group is a client value. /// private static List ParseAggregations(LambdaExpression selector) { var result = new List(); var groupParam = selector.Parameters[0]; foreach (var (name, _, rawExpr) in GroupSelectorMembers.Extract(selector, OwnerApi + ".SelectAsync")) { var expr = GroupSelectorMembers.StripConvert(rawExpr); if (GroupSelectorMembers.IsKeyAccess(expr, groupParam)) continue; if (GroupAggregateParser.IsAggCall(expr)) { result.Add(GroupAggregateParser.Parse((MethodCallExpression)expr, groupParam, name, GroupItemKind.Props, OwnerApi + ".SelectAsync")); continue; } if (!GroupSelectorMembers.ReferencesParameter(expr, groupParam)) continue; throw new NotSupportedException( $"{OwnerApi}.SelectAsync: member '{name}' uses the group but is neither g.Key nor a direct Agg.* call; " + "computations around aggregates are not translated to SQL, compute them from the result."); } return result; } } Path: redb/redb.Core/Query/Grouping/TreeGroupedQueryable.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/Query/Grouping/TreeGroupedQueryable.cs ---- using System.Linq.Expressions; using System.Text.Json; using redb.Core.Query.Aggregation; using redb.Core.Query.Base; namespace redb.Core.Query.Grouping; /// /// Tree-aware grouped queryable that preserves TreeQueryContext for proper CTE generation. /// Uses ITreeQueryProvider.ExecuteTreeGroupedAggregateAsync for tree traversal. /// public class TreeGroupedQueryable : IRedbGroupedQueryable where TProps : class, new() { private const string OwnerApi = "Tree GroupBy"; private readonly ITreeQueryProvider _treeProvider; private readonly TreeQueryContext _treeContext; private readonly Expression _keySelector; private readonly string? _baseFilterJson; private readonly bool _isBaseFieldGrouping; private readonly List _havingPredicates = new(); public TreeGroupedQueryable( ITreeQueryProvider treeProvider, TreeQueryContext treeContext, Expression keySelector, string? baseFilterJson = null, bool isBaseFieldGrouping = false) { _treeProvider = treeProvider; _treeContext = treeContext.Clone(); // Clone to preserve state _keySelector = keySelector; _baseFilterJson = baseFilterJson; _isBaseFieldGrouping = isBaseFieldGrouping; } public async Task> SelectAsync( Expression, TResult>> selector, CancellationToken cancellationToken = default) { var groupFields = GroupKeyFields.Parse(_keySelector, _isBaseFieldGrouping, OwnerApi); var aggregations = ParseAggregations(selector); var json = await _treeProvider.ExecuteTreeGroupedAggregateAsync( _treeContext, groupFields, aggregations, BuildHavingJson(), cancellationToken: cancellationToken); var rows = ArrayGroupMaterializer.Materialize(json, selector, groupFields, _treeProvider.GetType().Name, OwnerApi + ".SelectAsync"); await ListItemGroupKeys.FillAsync(rows, (_treeProvider as IListItemKeySource)?.ListItems, OwnerApi + ".SelectAsync", cancellationToken); return rows; } public async Task CountAsync(CancellationToken cancellationToken = default) { var groupFields = GroupKeyFields.Parse(_keySelector, _isBaseFieldGrouping, OwnerApi); var aggregations = new[] { new AggregateRequest { FieldPath = "*", Function = AggregateFunction.Count, Alias = "cnt" } }; using var json = await _treeProvider.ExecuteTreeGroupedAggregateAsync( _treeContext, groupFields, aggregations, BuildHavingJson(), cancellationToken: cancellationToken); return ArrayGroupMaterializer.RequireArray(json, _treeProvider.GetType().Name, OwnerApi + ".CountAsync").GetArrayLength(); } public Task ToSqlStringAsync( Expression, TResult>> selector, CancellationToken cancellationToken = default) => _treeProvider.GetTreeGroupBySqlPreviewAsync( _treeContext, GroupKeyFields.Parse(_keySelector, _isBaseFieldGrouping, OwnerApi), ParseAggregations(selector), BuildHavingJson(), cancellationToken: cancellationToken); /// /// Apply window functions to grouped results (tree-aware): the window runs over the groups that pass Having. /// public IGroupedWindowedQueryable WithWindow( Action> windowConfig) { var windowSpec = new GroupedWindowSpec(); windowConfig(windowSpec); return new GroupedWindowedQueryable(new TreeGroupWindowSource(this, BuildHavingJson()), windowSpec); } /// public IRedbGroupedQueryable Having( Expression, bool>> predicate) { if (predicate is null) throw new ArgumentNullException(nameof(predicate)); // TGR-1 (review 2026-09-24): a copy, as the flat grouping does since G-4. Changing this builder let a // second query branched from the same grouping inherit the first one's condition. var copy = new TreeGroupedQueryable( _treeProvider, _treeContext, _keySelector, _baseFilterJson, _isBaseFieldGrouping); copy._havingPredicates.AddRange(_havingPredicates); copy._havingPredicates.Add(predicate); return copy; } private string? BuildHavingJson() { if (_havingPredicates.Count == 0) return null; var param = Expression.Parameter(typeof(IRedbGrouping), "g"); Expression? body = null; foreach (var p in _havingPredicates) { var next = new ParameterReplacer(p.Parameters[0], param).Visit(p.Body)!; body = body == null ? next : Expression.AndAlso(body, next); } return HavingPredicateParser.ToJson(Expression.Lambda, bool>>(body!, param)); } private sealed class ParameterReplacer : ExpressionVisitor { private readonly ParameterExpression _from; private readonly ParameterExpression _to; public ParameterReplacer(ParameterExpression from, ParameterExpression to) { _from = from; _to = to; } protected override Expression VisitParameter(ParameterExpression node) => node == _from ? _to : base.VisitParameter(node); } private static List ParseAggregations(LambdaExpression selector) { var result = new List(); var groupParam = selector.Parameters[0]; foreach (var (name, _, rawExpr) in GroupSelectorMembers.Extract(selector, OwnerApi + ".SelectAsync")) { var expr = GroupSelectorMembers.StripConvert(rawExpr); if (GroupSelectorMembers.IsKeyAccess(expr, groupParam)) continue; if (GroupAggregateParser.IsAggCall(expr)) { result.Add(GroupAggregateParser.Parse((MethodCallExpression)expr, groupParam, name, GroupItemKind.Props, OwnerApi + ".SelectAsync")); continue; } if (!GroupSelectorMembers.ReferencesParameter(expr, groupParam)) continue; throw new NotSupportedException( $"{OwnerApi}.SelectAsync: member '{name}' uses the group but is neither g.Key nor a direct Agg.* call ('{rawExpr}')."); } return result; } /// /// The tree grouping as the source of a window over its groups. /// private sealed class TreeGroupWindowSource : IGroupedWindowSource { private readonly TreeGroupedQueryable _owner; private readonly string? _havingJson; public TreeGroupWindowSource(TreeGroupedQueryable owner, string? havingJson) { _owner = owner; _havingJson = havingJson; } public string ProviderName => _owner._treeProvider.GetType().Name; public redb.Core.Providers.IListProvider? ListItems => (_owner._treeProvider as IListItemKeySource)?.ListItems; public GroupItemKind Kind => GroupItemKind.Props; public List GroupFields(LambdaExpression selector) => GroupKeyFields.Parse(_owner._keySelector, _owner._isBaseFieldGrouping, "Tree WithWindow"); public async Task ExecuteAsync(LambdaExpression selector, List aggregations, ArrayGroupWindow window, CancellationToken cancellationToken) => await _owner._treeProvider.ExecuteTreeGroupedWindowQueryAsync( _owner._treeContext, GroupFields(selector), aggregations, window.Functions, window.PartitionBy, window.OrderBy, _havingJson, cancellationToken) ?? throw new InvalidOperationException($"Tree WithWindow: {ProviderName} returned no answer for the grouped window."); public Task GetSqlAsync(LambdaExpression selector, List aggregations, ArrayGroupWindow window, CancellationToken cancellationToken) => _owner._treeProvider.GetTreeGroupedWindowSqlPreviewAsync( _owner._treeContext, GroupFields(selector), aggregations, window.Functions, window.PartitionBy, window.OrderBy, _havingJson, cancellationToken); } } Path: redb/redb.Core/Query/IRedbProjectedQueryable.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/Query/IRedbProjectedQueryable.cs ---- using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; namespace redb.Core.Query; /// /// Interface for LINQ query projections in REDB. /// public interface IRedbProjectedQueryable { /// /// Additional filtering of projected results. /// IRedbProjectedQueryable Where(Expression> predicate); /// /// Sort projected results. /// IRedbProjectedQueryable OrderBy(Expression> keySelector); /// /// Sort projected results descending. /// IRedbProjectedQueryable OrderByDescending(Expression> keySelector); /// /// Adds a key to the ordering started by OrderBy or OrderByDescending. /// IRedbProjectedQueryable ThenBy(Expression> keySelector) => throw new NotSupportedException($"{GetType().Name} does not implement ThenBy."); /// /// Adds a descending key to the ordering started by OrderBy or OrderByDescending. /// IRedbProjectedQueryable ThenByDescending(Expression> keySelector) => throw new NotSupportedException($"{GetType().Name} does not implement ThenByDescending."); /// /// Limit number of results. /// IRedbProjectedQueryable Take(int count); /// /// Skip results. /// IRedbProjectedQueryable Skip(int count); /// /// Distinct values. /// IRedbProjectedQueryable Distinct(); /// /// Execute query and get list of results. /// Task> ToListAsync(CancellationToken cancellationToken = default); /// /// Count results. /// Task CountAsync(CancellationToken cancellationToken = default); /// /// Get first result or default value. /// Task FirstOrDefaultAsync(CancellationToken cancellationToken = default); /// /// Get projection info including SQL function and structure_ids /// Task GetProjectionInfoAsync(CancellationToken cancellationToken = default); } /// /// Extension methods for Task<IRedbProjectedQueryable<T>> to avoid double await. /// public static class RedbProjectedQueryableTaskExtensions { public static async Task> Where( this Task> queryTask, Expression> predicate) { var query = await queryTask; return query.Where(predicate); } public static async Task> OrderBy( this Task> queryTask, Expression> keySelector) { var query = await queryTask; return query.OrderBy(keySelector); } public static async Task> OrderByDescending( this Task> queryTask, Expression> keySelector) { var query = await queryTask; return query.OrderByDescending(keySelector); } public static async Task> ThenBy( this Task> queryTask, Expression> keySelector) { var query = await queryTask; return query.ThenBy(keySelector); } public static async Task> ThenByDescending( this Task> queryTask, Expression> keySelector) { var query = await queryTask; return query.ThenByDescending(keySelector); } public static async Task> Take( this Task> queryTask, int count) { var query = await queryTask; return query.Take(count); } public static async Task> Skip( this Task> queryTask, int count) { var query = await queryTask; return query.Skip(count); } public static async Task> Distinct( this Task> queryTask) { var query = await queryTask; return query.Distinct(); } public static async Task> ToListAsync( this Task> queryTask, CancellationToken cancellationToken = default) { var query = await queryTask; return await query.ToListAsync(cancellationToken); } public static async Task CountAsync( this Task> queryTask, CancellationToken cancellationToken = default) { var query = await queryTask; return await query.CountAsync(cancellationToken); } public static async Task FirstOrDefaultAsync( this Task> queryTask, CancellationToken cancellationToken = default) { var query = await queryTask; return await query.FirstOrDefaultAsync(cancellationToken); } } Path: redb/redb.Core/Query/IRedbQueryProvider.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/Query/IRedbQueryProvider.cs ---- using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using redb.Core.Models.Contracts; using redb.Core.Query.Aggregation; using redb.Core.Query.QueryExpressions; namespace redb.Core.Query; /// /// Provider for executing LINQ queries. /// public interface IRedbQueryProvider { /// /// Create new query for specified scheme. /// IRedbQueryable CreateQuery(long schemeId, long? userId = null, bool checkPermissions = false) where TProps : class, new(); /// /// Execute query asynchronously. /// Task ExecuteAsync(Expression expression, Type elementType, CancellationToken cancellationToken = default); /// /// Get scheme by ID (for projections). /// Task GetSchemeAsync(long schemeId, CancellationToken cancellationToken = default); // ===== AGGREGATIONS (EAV) ===== /// /// Execute aggregation on EAV field (SQL strategy for simple fields). /// /// Scheme ID /// Field path (e.g. "Price") /// Aggregation function /// JSON filter (as for search_objects) /// Aggregation result /// Cancels the operation (OCE only; a rollback in flight always completes). Task ExecuteAggregateAsync( long schemeId, string fieldPath, AggregateFunction function, string? filterJson = null, CancellationToken cancellationToken = default); /// /// Execute batch aggregation (multiple fields in one query). /// Task ExecuteAggregateBatchAsync( long schemeId, IEnumerable requests, string? filterJson = null, CancellationToken cancellationToken = default); /// /// Execute single-field aggregation with FilterExpression (Pro version). /// Task ExecuteAggregateAsync( long schemeId, string fieldPath, AggregateFunction function, FilterExpression? filter, CancellationToken cancellationToken = default); /// /// Execute batch aggregation with FilterExpression (Pro version). /// Task ExecuteAggregateBatchAsync( long schemeId, IEnumerable requests, FilterExpression? filter, CancellationToken cancellationToken = default); // ===== GROUPBY AGGREGATIONS ===== /// /// Execute GroupBy aggregation. Uses filterJson for Free version compatibility. /// is a PVT-shape HAVING predicate; pass null when none. /// Task ExecuteGroupedAggregateAsync( long schemeId, IEnumerable groupFields, IEnumerable aggregations, string? filterJson = null, string? havingJson = null, CancellationToken cancellationToken = default); /// /// Execute GroupBy aggregation with FilterExpression (Pro version). /// Provides direct access to filter for proper SQL compilation. /// carries the PVT-shape HAVING predicate when present. /// Task ExecuteGroupedAggregateAsync( long schemeId, IEnumerable groupFields, IEnumerable aggregations, FilterExpression? filter, string? havingJson = null, CancellationToken cancellationToken = default); /// /// The SQL /// runs, for ToSqlStringAsync. /// Task GetGroupBySqlPreviewAsync( long schemeId, IEnumerable groupFields, IEnumerable aggregations, string? filterJson, string? havingJson = null, CancellationToken cancellationToken = default); /// /// The SQL /// runs, for ToSqlStringAsync. /// Task GetGroupBySqlPreviewAsync( long schemeId, IEnumerable groupFields, IEnumerable aggregations, FilterExpression? filter, string? havingJson = null, CancellationToken cancellationToken = default); /// /// Runs a grouping over the elements of an array (GroupByArray, with or without a window over the groups) and /// returns its rows as a JSON array of objects, one property per key and aggregate alias, NULL values included. /// Task ExecuteArrayGroupQueryAsync( Grouping.ArrayGroupQuery query, CancellationToken cancellationToken = default); /// /// The SQL runs for the same request, for ToSqlStringAsync. /// Task GetArrayGroupQuerySqlAsync( Grouping.ArrayGroupQuery query, CancellationToken cancellationToken = default); // ===== WINDOW FUNCTIONS ===== /// /// Execute query with window functions (SQL function query_with_window). /// Task ExecuteWindowQueryAsync( long schemeId, IEnumerable selectFields, IEnumerable windowFuncs, IEnumerable partitionBy, IEnumerable orderBy, string? filterJson = null, string? frameJson = null, int? take = null, int? skip = null, CancellationToken cancellationToken = default); /// /// Execute query with window functions with FilterExpression (Pro version). /// Task ExecuteWindowQueryAsync( long schemeId, IEnumerable selectFields, IEnumerable windowFuncs, IEnumerable partitionBy, IEnumerable orderBy, FilterExpression? filter, string? frameJson = null, int? take = null, int? skip = null, CancellationToken cancellationToken = default); /// /// Get SQL preview for window query (for debugging). /// Task GetWindowSqlPreviewAsync( long schemeId, IEnumerable selectFields, IEnumerable windowFuncs, IEnumerable partitionBy, IEnumerable orderBy, string? filterJson = null, string? frameJson = null, int? take = null, int? skip = null, CancellationToken cancellationToken = default); /// /// Get SQL preview for window query with FilterExpression (Pro version): the SQL that /// /// runs for the same arguments. /// Task GetWindowSqlPreviewAsync( long schemeId, IEnumerable selectFields, IEnumerable windowFuncs, IEnumerable partitionBy, IEnumerable orderBy, QueryExpressions.FilterExpression? filter, string? frameJson = null, int? take = null, int? skip = null, CancellationToken cancellationToken = default) // A default body keeps implementations outside redb compiling; QueryProviderBase overrides it. => throw new NotSupportedException( $"{GetType().Name} has no SQL preview of a window query with a FilterExpression; implement this overload " + "of GetWindowSqlPreviewAsync."); // ===== GROUPED WINDOW (GroupBy + Window Functions) ===== /// /// Execute GroupBy with Window Functions (ranking, running totals on aggregated data). /// Task ExecuteGroupedWindowQueryAsync( long schemeId, IEnumerable groupFields, IEnumerable aggregations, IEnumerable windowFuncs, IEnumerable partitionBy, IEnumerable orderBy, string? filterJson = null, string? havingJson = null, CancellationToken cancellationToken = default); /// /// Execute GroupBy with Window Functions with FilterExpression (Pro version). /// Task ExecuteGroupedWindowQueryAsync( long schemeId, IEnumerable groupFields, IEnumerable aggregations, IEnumerable windowFuncs, IEnumerable partitionBy, IEnumerable orderBy, FilterExpression? filter, string? havingJson = null, CancellationToken cancellationToken = default); /// /// Get SQL preview for GroupBy + Window query. /// Task GetGroupedWindowSqlPreviewAsync( long schemeId, IEnumerable groupFields, IEnumerable aggregations, IEnumerable windowFuncs, IEnumerable partitionBy, IEnumerable orderBy, string? filterJson = null, string? havingJson = null, CancellationToken cancellationToken = default); /// /// Get SQL preview for GroupBy + Window query with FilterExpression (Pro version). /// Task GetGroupedWindowSqlPreviewAsync( long schemeId, IEnumerable groupFields, IEnumerable aggregations, IEnumerable windowFuncs, IEnumerable partitionBy, IEnumerable orderBy, FilterExpression? filter, string? havingJson = null, CancellationToken cancellationToken = default); // ===== DELETE ===== /// /// Delete objects by filter: the objects of the scheme the filter selects, null for every object of the scheme. /// /// Scheme ID /// Filter expression from LINQ /// Number of deleted objects /// Cancels the operation (OCE only; a rollback in flight always completes). Task ExecuteDeleteAsync(long schemeId, FilterExpression? filter, CancellationToken cancellationToken = default); // ===== SQL PREVIEW ===== /// /// Get SQL query for debugging (analogous to ToQueryString in EF Core). /// Pro version returns PVT SQL, Open Source - redb_json_objects. /// Task GetSqlPreviewAsync(QueryContext context, CancellationToken cancellationToken = default) where TProps : class, new(); /// /// Returns the JSON filter that will be sent to SQL function (for diagnostics) /// Task GetFilterJsonAsync(QueryContext context, CancellationToken cancellationToken = default) where TProps : class, new(); }