Bundle: redb / redb.Core (redb.Core.2.txt), 74 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/Query/IRedbQueryable.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/IRedbQueryable.cs ---- using System; using System.Collections.Generic; 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.Aggregation; namespace redb.Core.Query; /// /// Main interface for type-safe LINQ queries to REDB. /// public interface IRedbQueryable where TProps : class, new() { /// /// Filter by Props fields. /// IRedbQueryable Where(Expression> predicate); /// /// Filter by base object fields (Id, Name, ParentId, etc.). /// Allows LINQ queries on IRedbObject fields: Id, ParentId, SchemeId, /// Name, Note, Key, Hash, OwnerId, WhoChangeId, /// DateCreate, DateModify, DateBegin, DateComplete, /// ValueLong, ValueString, ValueGuid, ValueBool, ValueDouble, ValueNumeric, ValueDatetime, ValueBytes. /// Uses IRedbObject for compile-time safety - Props not visible in IntelliSense! /// /// /// .WhereRedb(x => x.Id == 123) /// .WhereRedb(x => x.ValueLong > 100) /// .WhereRedb(x => x.Name.Contains("test")) /// .WhereRedb(x => x.ParentId == null) // root objects /// IRedbQueryable WhereRedb(Expression> predicate); /// /// Sort ascending by Props field. /// IOrderedRedbQueryable OrderBy(Expression> keySelector); /// /// Sort descending by Props field. /// IOrderedRedbQueryable OrderByDescending(Expression> keySelector); /// /// Sort ascending by IRedbObject base fields (id, name, date_create, etc.). /// Uses IRedbObject for compile-time safety - Props not visible in IntelliSense! /// /// /// .OrderByRedb(x => x.DateCreate) /// .OrderByRedb(x => x.Name) /// .OrderByRedb(x => x.Id) /// IOrderedRedbQueryable OrderByRedb(Expression> keySelector); /// /// Sort descending by IRedbObject base fields. /// Uses IRedbObject for compile-time safety - Props not visible in IntelliSense! /// IOrderedRedbQueryable OrderByDescendingRedb(Expression> keySelector); /// /// Limit the number of records. /// IRedbQueryable Take(int count); /// /// Skip records. /// IRedbQueryable Skip(int count); /// /// Execute query and return list of objects. /// Task>> ToListAsync(CancellationToken cancellationToken = default); /// /// Count records without loading data. /// Task CountAsync(CancellationToken cancellationToken = default); /// /// Get first object or null. /// Task?> FirstOrDefaultAsync(CancellationToken cancellationToken = default); /// /// Get first object matching condition, or null. /// Task?> FirstOrDefaultAsync(Expression> predicate, CancellationToken cancellationToken = default); /// /// Check if any records exist. /// Task AnyAsync(CancellationToken cancellationToken = default); /// /// Check if any records match condition. /// Task AnyAsync(Expression> predicate, CancellationToken cancellationToken = default); /// /// Filter by value in list (WHERE field IN (...)). /// IRedbQueryable WhereIn(Expression> selector, IEnumerable values); /// /// Filter by IRedbObject base field in list (WHERE _field IN (...)). /// Uses IRedbObject for compile-time safety - Props not visible! /// /// /// .WhereInRedb(x => x.Id, new[] { 1L, 2L, 3L }) /// .WhereInRedb(x => x.Name, new[] { "Alice", "Bob" }) /// IRedbQueryable WhereInRedb(Expression> selector, IEnumerable values); /// /// Check if ALL records match condition. /// Task AllAsync(Expression> predicate, CancellationToken cancellationToken = default); /// /// Project fields - return only selected properties. /// IRedbProjectedQueryable Select(Expression, TResult>> selector); /// /// Get distinct values (by all object fields). /// IRedbQueryable Distinct(); /// /// DISTINCT by IRedbObject base fields (Name, ValueLong, ParentId, etc.) excluding Id. /// Used for finding duplicates by base fields. /// IRedbQueryable DistinctRedb(); /// /// DISTINCT ON (field) - one object per unique Props field value. /// Automatically adds field to beginning of ORDER BY (PostgreSQL requirement). /// /// /// .DistinctBy(x => x.Category) // one object per Category /// IRedbQueryable DistinctBy(Expression> keySelector); /// /// DISTINCT ON (base_field) - one object per unique IRedbObject base field value. /// Automatically adds field to beginning of ORDER BY (PostgreSQL requirement). /// Uses IRedbObject for compile-time safety - Props not visible! /// /// /// .DistinctByRedb(x => x.Name) // one object per unique Name /// IRedbQueryable DistinctByRedb(Expression> keySelector); /// /// Configure maximum recursion depth for complex queries ($and/$or/$not). /// Default: 10 levels. /// IRedbQueryable WithMaxRecursionDepth(int depth); /// /// V4 (LAZY Л2): per-query override of the lazy-references option. true = references whose /// structures carry the `virtual` marker come back as stubs; false = full objects, whatever /// the global option says. With the Pro packages the override has no effect: the query loads /// references by the global RedbServiceConfiguration.EnableLazyReferences. /// IRedbQueryable WithLazyReferences(bool enabled = true); // ===== TREE FILTERS ===== /// /// Filter by ancestors: find objects that have an ancestor of specified type matching condition. /// The objects of that match are looked for below the start of the query; an object /// the query returns is kept when one of them lies at most levels above it. /// Supports polymorphic trees - can search for ancestors of different type. /// /// Ancestor type to search for (may differ from TProps) /// Condition for ancestor search /// How many levels up from the returned object the matching ancestor may lie (1 = its parent, /// 2 = its parent or grandparent; null = any ancestor), as maxDepth of WhereHasDescendant counts down from the /// object. /// Query with ancestor filter IRedbQueryable WhereHasAncestor( Expression> ancestorCondition, int? maxDepth = null) where TTarget : class; /// /// Filter by descendants: find objects that have a descendant of specified type matching condition. /// Uses SQL operator $hasDescendant. /// Supports polymorphic trees - can search for descendants of different type. /// /// Descendant type to search for (may differ from TProps) /// Condition for descendant search /// Maximum depth to search down the tree (null = to leaves) /// Query with descendant filter IRedbQueryable WhereHasDescendant( Expression> descendantCondition, int? maxDepth = null) where TTarget : class; /// /// Filter by tree level. /// Uses SQL operator $level. /// /// Tree level: 0 = the node the query starts from (the real root for TreeQuery<T>()), 1 = its /// children; counted as the maxDepth of the same query /// Query with level filter IRedbQueryable WhereLevel(int level); /// /// Filter by tree level with comparison operator. /// Uses SQL operators $level: {$gt: N}, {$lt: N}, etc. /// /// Condition for level (e.g.: level => level > 2); levels count from the node the /// query starts from (0; the real root for TreeQuery<T>()) /// Query with level condition filter IRedbQueryable WhereLevel(Expression> levelCondition); /// /// Root elements only (parent_id IS NULL). /// Uses SQL operator $isRoot. /// /// Query for root objects only IRedbQueryable WhereRoots(); /// /// Leaf nodes only (objects without children). /// Uses SQL operator $isLeaf. /// /// Query for leaf objects only IRedbQueryable WhereLeaves(); /// /// Direct children of specified object. /// The filter replaces the start of the query: the children of this object are returned whatever the root and the /// maxDepth of the tree query are. /// /// Parent object ID /// Query for object children IRedbQueryable WhereChildrenOf(long parentId); /// /// Direct children of specified object. /// The filter replaces the start of the query: the children of this object are returned whatever the root and the /// maxDepth of the tree query are. /// /// Parent object /// Query for object children IRedbQueryable WhereChildrenOf(IRedbObject parentObject); /// /// All descendants of specified object (recursive). /// The filter replaces the start of the query: the walk starts at this object, and the maxDepth of the tree query /// counts from it when this filter has none. /// /// Ancestor ID /// Maximum search depth below the object (null = the maxDepth of the tree query, if any) /// Query for all object descendants IRedbQueryable WhereDescendantsOf(long ancestorId, int? maxDepth = null); /// /// All descendants of specified object (recursive). /// The filter replaces the start of the query: the walk starts at this object, and the maxDepth of the tree query /// counts from it when this filter has none. /// /// Ancestor object /// Maximum search depth below the object (null = the maxDepth of the tree query, if any) /// Query for all object descendants IRedbQueryable WhereDescendantsOf(IRedbObject ancestorObject, int? maxDepth = null); /// /// Configure maximum tree search depth. /// Default: 50 levels (descendant search), 1 (children search). /// IRedbQueryable WithMaxDepth(int depth); /// /// Configure maximum depth for loading nested RedbObject in Props. /// Controls recursion when Props contain references to other RedbObjects via _values._Object. /// Default: uses global DefaultMaxTreeDepth from config. /// /// Maximum depth for nested RedbObject loading (1 = only direct references) /// Query with configured Props depth IRedbQueryable WithPropsDepth(int depth); // ===== MATERIALIZATION METHODS ===== /// /// Execute query and return filtered objects with populated Parent/Children chains. /// Loads objects + all their parents to root and establishes relationships. /// Children contain only objects from loaded chain (not all children from DB). /// /// List of filtered TreeRedbObject with populated relationships Task>> ToTreeListAsync(CancellationToken cancellationToken = default); /// /// Execute query and get list of root tree nodes. /// Loads objects + all their parents to root, establishes relationships and returns roots. /// Children contain only objects from loaded chain (not all children from DB). /// Supports polymorphic trees - each object of its own type via ITreeRedbObject. /// /// List of root ITreeRedbObject (polymorphic - each of its own TProps type) Task> ToRootListAsync(CancellationToken cancellationToken = default); /// /// Execute query and get flat list of tree objects. /// Without loading Parent/Children relationships (for performance). /// /// Flat list of TreeRedbObject Task>> ToFlatListAsync(CancellationToken cancellationToken = default); /// /// Delete objects without loading data. /// Executes DELETE with filters from query. /// /// Number of deleted records Task DeleteAsync(CancellationToken cancellationToken = default); // ===== AGGREGATIONS (EAV) ===== /// /// Sum of field values. /// Strategy: SQL for simple fields, C# for complex (Class, arrays). /// /// /// var total = await query.Where(x => x.Status == "Active").SumAsync(x => x.Price); /// Task SumAsync(Expression> selector, CancellationToken cancellationToken = default) where TField : struct; /// /// Average of field values. /// Task AverageAsync(Expression> selector, CancellationToken cancellationToken = default) where TField : struct; /// /// Minimum field value. /// Task MinAsync(Expression> selector, CancellationToken cancellationToken = default) where TField : struct; /// /// Maximum field value. /// Task MaxAsync(Expression> selector, CancellationToken cancellationToken = default) where TField : struct; /// /// Get field statistics (Sum, Avg, Min, Max, Count) in single call. /// All aggregations execute in parallel for maximum performance. /// /// /// var stats = await query.GetStatisticsAsync(x => x.Price); /// stats.Sum, stats.Average, stats.Min, stats.Max, stats.Count /// Task> GetStatisticsAsync(Expression> selector, CancellationToken cancellationToken = default) where TField : struct; /// /// Flexible aggregation - choose what to aggregate via Agg.Sum/Avg/Min/Max/Count. /// /// /// var result = await query /// .Where(x => x.Status == "Active") /// .AggregateAsync(x => new { /// TotalAmount = Agg.Sum(x.Props.Amount), /// AvgPrice = Agg.Avg(x.Props.Price), /// MinStock = Agg.Min(x.Props.Stock), /// OrderCount = Agg.Count() /// }); /// Task AggregateAsync(Expression, TResult>> selector, CancellationToken cancellationToken = default); // ===== AGGREGATIONS FOR BASE FIELDS ===== /// /// Sum of IRedbObject base field values (ValueLong, Key, etc.). /// Uses IRedbObject for compile-time safety - Props not visible! /// /// /// var totalValue = await query.SumRedbAsync(x => x.ValueLong); /// Task SumRedbAsync(Expression> selector, CancellationToken cancellationToken = default) where TField : struct; /// /// Average of IRedbObject base field values. /// Uses IRedbObject for compile-time safety - Props not visible! /// Task AverageRedbAsync(Expression> selector, CancellationToken cancellationToken = default) where TField : struct; /// /// Minimum IRedbObject base field value (ValueLong, Key, DateCreate, etc.). /// Uses IRedbObject for compile-time safety - Props not visible! /// Task MinRedbAsync(Expression> selector, CancellationToken cancellationToken = default) where TField : struct; /// /// Maximum IRedbObject base field value (ValueLong, Key, DateCreate, etc.). /// Uses IRedbObject for compile-time safety - Props not visible! /// Task MaxRedbAsync(Expression> selector, CancellationToken cancellationToken = default) where TField : struct; /// /// Flexible aggregation for IRedbObject base fields ONLY. /// For aggregating both base AND Props fields - use AggregateAsync. /// /// /// var result = await query /// .AggregateRedbAsync(x => new { /// MaxId = Agg.Max(x.Id), /// MinDateCreate = Agg.Min(x.DateCreate), /// AvgValue = Agg.Avg(x.ValueLong), /// Count = Agg.Count() /// }); /// Task AggregateRedbAsync(Expression> selector, CancellationToken cancellationToken = default); // ===== GROUPBY ===== /// /// Group by field with subsequent aggregation. /// /// /// var result = await query /// .GroupBy(x => x.Category) /// .SelectAsync(g => new { /// Category = g.Key, /// Total = Agg.Sum(g, x => x.Stock), /// Count = Agg.Count(g) /// }); /// Grouping.IRedbGroupedQueryable GroupBy(Expression> keySelector); /// /// Group by IRedbObject base fields (id, scheme_id, parent_id, etc.). /// Uses IRedbObject for compile-time safety - Props not visible! /// /// /// var result = await query /// .GroupByRedb(x => x.SchemeId) /// .SelectAsync(g => new { /// SchemeId = g.Key, /// Count = Agg.Count(g) /// }); /// Multiple base fields: /// var result = await query /// .GroupByRedb(x => new { x.SchemeId, x.OwnerId }) /// .SelectAsync(g => new { /// g.Key.SchemeId, /// g.Key.OwnerId, /// Count = Agg.Count(g) /// }); /// Grouping.IRedbGroupedQueryable GroupByRedb(Expression> keySelector); /// /// Group by the elements of an array. The array is a chain of fields (x => x.Items, /// x => x.Address.Building.Amenities) or an inner array reached with SelectMany /// (x => x.Contacts.SelectMany(c => c.Metadata)). The key is a field of the element, an anonymous type /// of fields, or the element itself for an array of simple values (s => s). Any other form throws /// . /// /// /// var result = await query /// .GroupByArray(x => x.Items, item => item.Category) /// .SelectAsync(g => new { /// Category = g.Key, /// TotalPrice = Agg.Sum(g, item => item.Price), /// Expensive = Agg.Count(g, item => item.Price > 100) /// }); /// var skills = await query /// .GroupByArray(x => x.Skills, s => s) /// .SelectAsync(g => new { Skill = g.Key, People = Agg.Count(g) }); /// Grouping.IRedbGroupedQueryable GroupByArray( Expression>> arraySelector, Expression> keySelector); // ===== WINDOW FUNCTIONS ===== /// /// Query with window functions. /// /// /// var result = await query /// .WithWindow(w => w.PartitionBy(x => x.Category).OrderByDesc(x => x.Stock)) /// .SelectAsync(x => new { x.name, Rank = Win.RowNumber() }); /// Window.IRedbWindowedQueryable WithWindow(Action> windowConfig); // ===== SQL PREVIEW ===== /// /// Get SQL representation of query (for debugging). /// Analogous to EF Core ToQueryString(). /// /// SQL query as string with comments string ToSqlString(); /// /// Async version of getting SQL (recommended). /// Task ToSqlStringAsync(CancellationToken cancellationToken = default); /// /// Get JSON filter that will be sent to SQL function (for diagnostics). /// Task ToFilterJsonAsync(CancellationToken cancellationToken = default); } /// /// Interface for ordered queries (after OrderBy). /// Supports cascading sorts: OrderBy().ThenByRedb().ThenBy(). /// public interface IOrderedRedbQueryable : IRedbQueryable where TProps : class, new() { /// /// Additional ascending sort by Props field. /// IOrderedRedbQueryable ThenBy(Expression> keySelector); /// /// Additional descending sort by Props field. /// IOrderedRedbQueryable ThenByDescending(Expression> keySelector); /// /// Additional ascending sort by IRedbObject base fields. /// Uses IRedbObject for compile-time safety - Props not visible in IntelliSense! /// /// /// .OrderBy(p => p.Name).ThenByRedb(x => x.DateCreate) /// IOrderedRedbQueryable ThenByRedb(Expression> keySelector); /// /// Additional descending sort by IRedbObject base fields. /// Uses IRedbObject for compile-time safety - Props not visible in IntelliSense! /// IOrderedRedbQueryable ThenByDescendingRedb(Expression> keySelector); } Path: redb/redb.Core/Query/ISqlDialect.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/ISqlDialect.cs ---- using System.Collections.Generic; namespace redb.Core.Query; /// /// SQL syntax abstraction for different DBMS support. /// /// IMPORTANT: Implementations in different projects MAY DIFFER! /// - PostgreSqlDialect: CASE WHEN (tested - 15 ms on 15K objects) /// - MsSqlDialect: will be later, possibly different implementation /// /// Current focus: PostgreSQL + performance. /// public interface ISqlDialect { /// /// Provider name (PostgreSQL, SqlServer, MySql) /// string ProviderName { get; } /// /// Pagination format: LIMIT/OFFSET for PostgreSQL, TOP/OFFSET for MSSQL /// string FormatPagination(int? limit, int? offset); /// /// Subquery wrapper: (subquery) AS alias /// string WrapSubquery(string subquery, string alias); /// /// PVT column for CASE WHEN approach. /// PostgreSQL: MAX(CASE WHEN _id_structure = X THEN _Long END) AS "Age" /// string FormatPvtColumn(long structureId, string dbColumn, string alias); /// /// Array containment check: = ANY($1) for PostgreSQL, IN for MSSQL /// string FormatArrayContains(string column, string paramName); /// /// Mapping of redb types to SQL types /// string GetDbTypeName(string redbType); /// /// Parameter format: $1 for PostgreSQL, @p1 for MSSQL /// string FormatParameter(int index); /// /// Identifier escaping: "name" for PostgreSQL, [name] for MSSQL /// string QuoteIdentifier(string name); /// /// Case-insensitive LIKE: ILIKE for PostgreSQL, LIKE for MSSQL (CI collation) /// string FormatCaseInsensitiveLike(string column, string parameter); /// /// Wraps a text expression so the database folds its case for ALL scripts, not just ASCII. /// /// /// Every case-insensitive operation goes through here, so the three of them /// (ILIKE/LIKE, LOWER, UPPER) can never drift apart: fixing one and /// forgetting another is exactly how a search finds a row that an equality check then rejects. /// /// /// /// The mechanism differs per provider and that is deliberate, because the providers differ in /// kind and not merely in syntax. PostgreSQL attaches a COLLATE clause to the operand. /// MSSQL needs nothing: its default collation already folds every script. SQLite has no /// collation that could help (its only case-insensitive one, NOCASE, is ASCII-only, and /// LIKE is a function that ignores collations entirely), so its provider fixes the /// problem one level down by overriding the built-in functions on the connection and returns /// the expression untouched here. /// /// /// Returns unchanged when the feature is off, so generated SQL is /// byte-for-byte what it was. /// /// A SQL text expression, already quoted or parenthesised as needed. string FoldCase(string expression); /// /// Format DateTime as SQL literal. PostgreSQL: '...'::timestamptz, MSSQL: '...' (parsed natively) /// string FormatDateTimeLiteral(DateTime dt); /// /// Format DateTimeOffset as SQL literal. PostgreSQL: '...'::timestamptz, MSSQL: '...' (parsed natively) /// string FormatDateTimeOffsetLiteral(DateTimeOffset dto); /// /// Format a bool as SQL literal for the _Boolean column. TRUE/FALSE by default (PostgreSQL); MSSQL (bit) and SQLite /// (INTEGER) write 1/0. /// string FormatBooleanLiteral(bool value) => value ? "TRUE" : "FALSE"; /// /// Format a string as SQL literal for the _String column: single quotes, a quote inside doubled. SQL Server /// prefixes N, or every character outside the database code page is stored as '?'. /// string FormatStringLiteral(string value) => "'" + value.Replace("'", "''") + "'"; /// Format a Guid as SQL literal for the _Guid column: the quoted 'D' form by default. string FormatGuidLiteral(Guid value) => "'" + value.ToString("D") + "'"; /// /// Format bytes as SQL literal for the _ByteArray column: X'..' by default (SQLite); PostgreSQL '\x..'::bytea, /// SQL Server 0x... /// string FormatBinaryLiteral(byte[] value) => "X'" + Convert.ToHexString(value) + "'"; /// /// The longest dictionary key the _array_index column holds, in UTF-16 code units, or null when /// the column has no bound. SQL Server declares it NVARCHAR(430) (index key width); PostgreSQL and SQLite /// use unbounded text. The save checks a serialized key against it before any row is written. /// int? DictionaryKeyMaxLength => null; // ============================================================ // === ROLES SQL === // ============================================================ /// /// SELECT role by ID. Returns: Id, Name, IdConfiguration /// string Roles_SelectById(); /// /// SELECT role by name. Returns: Id, Name, IdConfiguration /// string Roles_SelectByName(); /// /// SELECT all roles ordered by name. Returns: Id, Name, IdConfiguration /// string Roles_SelectAll(); /// /// INSERT new role. Params: $1=id, $2=name /// string Roles_Insert(); /// /// UPDATE role name. Params: $1=newName, $2=roleId /// string Roles_UpdateName(); /// /// DELETE role by ID. Params: $1=roleId /// string Roles_Delete(); /// /// Check if role name exists (excluding role). Params: $1=name, $2=excludeId (optional) /// string Roles_ExistsByName(); /// /// Check if role name exists excluding specific role. Params: $1=name, $2=excludeId /// string Roles_ExistsByNameExcluding(); /// /// SELECT COUNT of all roles /// string Roles_Count(); /// /// UPDATE role configuration. Params: $1=configId, $2=roleId /// string Roles_UpdateConfiguration(); /// /// SELECT role configuration ID. Params: $1=roleId /// string Roles_SelectConfigurationId(); // ============================================================ // === USERS_ROLES SQL === // ============================================================ /// /// INSERT user-role assignment. Params: $1=id, $2=userId, $3=roleId /// string UsersRoles_Insert(); /// /// DELETE user-role assignment. Params: $1=userId, $2=roleId /// string UsersRoles_Delete(); /// /// DELETE all user-role assignments for user. Params: $1=userId /// string UsersRoles_DeleteByUser(); /// /// DELETE all user-role assignments for role. Params: $1=roleId /// string UsersRoles_DeleteByRole(); /// /// Check if user-role assignment exists. Params: $1=userId, $2=roleId /// string UsersRoles_Exists(); /// /// SELECT roles for user. Params: $1=userId. Returns: Id, Name, IdConfiguration /// string UsersRoles_SelectRolesByUser(); /// /// SELECT users for role. Params: $1=roleId. Returns user fields /// string UsersRoles_SelectUsersByRole(); /// /// SELECT COUNT of users for role. Params: $1=roleId /// string UsersRoles_CountByRole(); // ============================================================ // === USERS SQL (for role operations) === // ============================================================ /// /// Check if user exists by ID. Params: $1=userId /// string Users_ExistsById(); /// /// SELECT user by login. Params: $1=login. Returns: Id /// string Users_SelectIdByLogin(); // ============================================================ // === PERMISSIONS SQL === // ============================================================ /// /// SELECT all permission columns FROM _permissions (no WHERE). Used for dynamic queries. /// string Permissions_SelectAllColumns(); /// /// SELECT COUNT(*) FROM _permissions (no WHERE). Used for dynamic count queries. /// string Permissions_CountFrom(); /// /// DELETE permissions by role. Params: $1=roleId /// string Permissions_DeleteByRole(); /// /// Get user permissions for object via SQL function or query. /// CRITICAL: PostgreSQL uses get_user_permissions_for_object() function! /// MSSQL: Must be expanded to CTE/JOIN query. /// Params: $1=objectId, $2=userId /// string Permissions_GetEffectiveForObject(); /// /// The rows of for many objects in one statement, by the same rule /// (the same function or view), with object_id the requested id. An object may have no row, as with the single /// query. Params: $1=objectIds (array), $2=userId /// string Permissions_GetEffectiveForObjects(); /// /// SELECT readable object IDs for user. Params: $1=userId /// string Permissions_SelectReadableObjectIds(); /// /// INSERT new permission. Params: $1=id, $2=userId, $3=roleId, $4=refId, $5=select, $6=insert, $7=update, $8=delete /// string Permissions_Insert(); /// /// UPDATE permission flags. Params: $1=select, $2=insert, $3=update, $4=delete, $5=permissionId /// string Permissions_Update(); /// /// DELETE permission by ID. Params: $1=permissionId /// string Permissions_Delete(); /// /// SELECT permission by ID. Params: $1=permissionId /// string Permissions_SelectById(); /// /// SELECT permissions by user. Params: $1=userId /// string Permissions_SelectByUser(); /// /// SELECT permissions by role. Params: $1=roleId /// string Permissions_SelectByRole(); /// /// SELECT permissions by object. Params: $1=objectId /// string Permissions_SelectByObject(); /// /// SELECT permission by user/role/object. Params: $1=userId, $2=roleId, $3=objectId /// string Permissions_SelectByUserRoleObject(); /// /// DELETE permission by user/role/object. Params: $1=userId, $2=roleId, $3=objectId /// string Permissions_DeleteByUserRoleObject(); /// /// DELETE all permissions by user. Params: $1=userId /// string Permissions_DeleteByUser(); /// /// SELECT COUNT of all permissions /// string Permissions_Count(); /// /// SELECT COUNT of permissions by user. Params: $1=userId /// string Permissions_CountByUser(); /// /// SELECT COUNT of permissions by role. Params: $1=roleId /// string Permissions_CountByRole(); /// /// SELECT user's role IDs. Params: $1=userId /// string Permissions_SelectUserRoleIds(); // ============================================================ // === USERS SQL (full) === // ============================================================ /// /// SELECT all user columns FROM _users (no WHERE). Used for dynamic search queries. /// string Users_SelectAllColumns(); /// /// SELECT COUNT(*) FROM _users (no WHERE). Used for dynamic count queries. /// string Users_CountFrom(); /// /// SELECT all user fields by ID. Params: $1=userId /// string Users_SelectById(); /// /// SELECT all user fields by IDs (batch). Params: $1=userIds (array/csv) /// string Users_SelectByIds(); /// /// SELECT all user fields by login. Params: $1=login /// string Users_SelectByLogin(); /// /// SELECT all user fields by email (case-insensitive, first match, active only). /// Params: $1=email. Used by . /// string Users_SelectByEmail(); /// /// INSERT new user with all fields. /// Params: $1=id, $2=login, $3=password, $4=name, $5=phone, $6=email, $7=enabled, /// $8=dateRegister, $9=dateDismiss, $10=key, $11=codeInt, $12=codeString, /// $13=codeGuid, $14=note, $15=hash /// string Users_Insert(); /// /// UPDATE user fields. /// Params: $1=login, $2=name, $3=phone, $4=email, $5=enabled, $6=dateDismiss, /// $7=key, $8=codeInt, $9=codeString, $10=codeGuid, $11=note, $12=hash, $13=userId /// string Users_Update(); /// /// UPDATE user for soft delete. Params: $1=newLogin, $2=newName, $3=enabled, $4=dateDismiss, $5=userId /// string Users_SoftDelete(); /// /// UPDATE user password. Params: $1=hashedPassword, $2=userId /// string Users_UpdatePassword(); /// /// UPDATE user enabled status. Params: $1=enabled, $2=dateDismiss, $3=userId /// string Users_UpdateStatus(); /// /// Check login exists. Params: $1=login /// string Users_ExistsByLogin(); /// /// Check login exists excluding user. Params: $1=login, $2=excludeUserId /// string Users_ExistsByLoginExcluding(); /// /// Check email exists. Params: $1=email /// string Users_ExistsByEmail(); /// /// SELECT COUNT of all users /// string Users_Count(); /// /// SELECT COUNT of enabled users /// string Users_CountEnabled(); /// /// SELECT user configuration ID. Params: $1=userId /// string Users_SelectConfigurationId(); /// /// UPDATE user configuration. Params: $1=configId, $2=userId /// string Users_UpdateConfiguration(); /// /// SELECT role by name. Params: $1=roleName /// string Roles_SelectIdByName(); /// /// Check role exists by ID. Params: $1=roleId /// string Roles_ExistsById(); // ============================================================ // === SCHEMES SQL === // ============================================================ /// /// SELECT scheme by name. Params: $1=name /// Returns: _id, _name, _alias, _name_space, _structure_hash, _type /// string Schemes_SelectByName(); /// /// SELECT scheme by ID. Params: $1=schemeId /// Returns: _id, _name, _alias, _name_space, _structure_hash, _type /// string Schemes_SelectById(); /// /// SELECT all schemes. /// Returns: _id, _name, _alias, _name_space, _structure_hash, _type /// string Schemes_SelectAll(); /// /// INSERT new scheme. Params: $1=id, $2=name, $3=alias, $4=type /// string Schemes_Insert(); /// /// INSERT a new scheme, doing nothing when the name is already taken. /// Params: $1=id, $2=name, $3=alias, $4=type, $5=nameSpace (nullable). Returns 0 affected rows on conflict. /// /// Exists because several nodes starting simultaneously all miss the lookup and all try to create /// the same scheme. The conflict must be suppressed by the statement itself rather than caught: /// on PostgreSQL a failed INSERT inside a transaction poisons that transaction, so a catch-and-retry /// cannot re-read the winner's row. /// /// string Schemes_InsertIfAbsent(); /// /// UPDATE scheme alias by ID. Params: $1=alias (nullable), $2=schemeId /// string Schemes_UpdateAlias(); /// /// UPDATE scheme namespace by ID (V4, К7 — the ownership mark that gates short-name adoption). /// Params: $1=nameSpace (nullable), $2=schemeId /// string Schemes_UpdateNameSpace(); /// /// UPDATE scheme structure hash. Params: $1=hash, $2=schemeId /// string Schemes_UpdateHash(); /// /// UPDATE the version of the Props class the scheme was synchronised with (_schemes._version), never lower /// than the stored one. Params: $1=version, $2=schemeId /// string Schemes_UpdateVersion(); /// /// Rename a scheme in place: the name and the list of its previous names. Used for every scheme rename of the sync /// (short name or FullName to the explicit name, RedbScheme.RenamedFrom). /// Params: $1=new name, $2=renamed_from (JSON array text), $3=schemeId /// string Schemes_Rename(); /// /// SELECT the schemes that were renamed: _id, _name, _renamed_from where _renamed_from is set. Read only when the /// sync is about to create a scheme, to stop a class older than a rename. No params. /// string Schemes_SelectRenamed(); /// /// SELECT scheme hash by ID. Params: $1=schemeId /// string Schemes_SelectHashById(); /// /// Check scheme exists by name. Params: $1=name /// string Schemes_ExistsByName(); /// /// SELECT Object scheme by name and type. Params: $1=name, $2=type /// string Schemes_SelectObjectByName(); /// /// INSERT Object scheme. Params: $1=id, $2=name, $3=type /// string Schemes_InsertObject(); /// /// INSERT an Object scheme, doing nothing when the name is already taken. /// Params: $1=id, $2=name, $3=type. Returns 0 affected rows on conflict. /// Same race as , on the untyped path. /// string Schemes_InsertObjectIfAbsent(); // ============================================================ // === STRUCTURES SQL === // ============================================================ /// /// SELECT full structures by scheme. Params: $1=schemeId /// Returns all structure fields /// string Structures_SelectByScheme(); /// /// SELECT structures short fields by scheme. Params: $1=schemeId /// Returns: _id, _id_parent, _id_scheme, _id_type, _name, _order /// string Structures_SelectBySchemeShort(); /// /// SELECT structures with cache fields by scheme. Params: $1=schemeId /// Returns fields needed for caching /// string Structures_SelectBySchemeCacheable(); /// /// INSERT new structure. /// Params: $1=id, $2=schemeId, $3=parentId, $4=name, $5=alias, $6=typeId, $7=allowNotNull, $8=collectionType, $9=keyType, $10=order /// string Structures_Insert(); /// /// UPDATE structure type. Params: $1=typeId, $2=structureId /// string Structures_UpdateType(); /// /// UPDATE structure collection type. Params: $1=collectionType, $2=structureId /// string Structures_UpdateCollectionType(); /// /// UPDATE structure key type. Params: $1=keyType, $2=structureId /// string Structures_UpdateKeyType(); /// /// UPDATE structure alias. Params: $1=alias, $2=structureId /// string Structures_UpdateAlias(); /// /// UPDATE structure allow_not_null. Params: $1=allowNotNull, $2=structureId /// string Structures_UpdateAllowNotNull(); /// /// UPDATE the lazy-reference marker (V4, LAZY Л2). Params: $1=lazy, $2=structureId /// string Structures_UpdateLazy(); /// /// Set the session lazy-references flag the JSON builders read (V4, LAZY L2). /// Params: $1 = 1|0 /// string Session_SetLazyRefs(); /// /// DELETE structures by IDs. Params: dynamic IN clause /// string Structures_DeleteByIds(IEnumerable ids); // ============================================================ // === ROOT STRUCTURE KEY (Data.RootStructureKey) === // One root field name once per scheme: a partial unique index over the root rows on engines whose structure key // counts two NULL parents as distinct (PostgreSQL, SQLite). SQL Server counts NULLs as equal, so its structure // key holds for root rows already: there Structures_RootKeyExists returns null and the other members of this // group are not called (they throw NotSupportedException). // ============================================================ /// /// SELECT returning a row when the unique key of root structures exists. No params. null: the engine needs /// no such key (SQL Server), and none of the members below applies. /// string? Structures_RootKeyExists(); /// CREATE the unique key of root structures. No params. string Structures_CreateRootKey(); /// /// SELECT the root structures whose (_id_scheme, _name) occurs more than once, as structure rows /// (_id, _id_parent, _id_scheme, _name), ordered by scheme, name and id. No params. /// string Structures_SelectRootDuplicates(); /// /// Locks a structure and every structure below it against writers until the transaction ends, so that a value /// inserted into it meanwhile waits and then fails on the foreign key instead of being cascaded away by a delete. /// Params: $1 = structure id. null: the engine has one writer at a time and the schema lock is that writer /// (SQLite). /// string? Structures_LockSubtree(); /// /// SELECT 1 when anything points to a structure or a structure below it (a value, an overriding structure and, with /// , a record of _migrations), else 0. Params: $1 = structure id. /// string Structures_SubtreeIsReferenced(bool withMigrations); /// DELETE the metadata cache rows of a structure and every structure below it. Params: $1 = structure id. string Structures_DeleteSubtreeMetadataCache(); /// DELETE a structure; its children go by the cascade of _id_parent. Params: $1 = structure id. string Structures_DeleteById(); /// SELECT the number of metadata cache rows of a scheme as BIGINT. Params: $1 = scheme id. string Schemes_CountMetadataCache(); /// /// UPDATE the unique-key flag, encoder version and element-key scope of a structure. /// Params: $1=unique (bool), $2=unique_version (long, nullable), /// $3=unique_scope (long, nullable; S3), $4=id /// string Structures_UpdateUnique(); /// UPDATE the free-form _tags marker of a structure. Params: $1=tags, $2=id string Structures_UpdateTags(); /// /// Rename a structure in place ([RedbRename]): the name and the list of its previous names. /// Params: $1=new name, $2=renamed_from (JSON array text), $3=id /// string Structures_Rename(); /// UPDATE the free-form _tags marker of a scheme. Params: $1=tags, $2=id string Schemes_UpdateTags(); /// /// SELECT one structure by id (same columns as Structures_SelectByScheme). Params: $1=id /// string Structures_SelectById(); // ============================================================ // === UNIQUE KEYS (_values._unique) SQL === // ============================================================ /// /// SELECT the root scalar rows of a structure — no array parent, no array index — with their /// typed columns, for recomputing keys. Params: $1=structureId. /// Returns RedbValue columns: Id, IdStructure, IdObject, String, Long, Guid, Double, /// DateTimeOffset, Boolean, ByteArray, Numeric, Unique. /// string Values_SelectRootScalarsByStructure(); /// /// SELECT the ELEMENT rows of a collection structure — array index present — with their /// typed columns, reference targets and the owning collection id, for recomputing /// element-scoped keys (S3). Params: $1=structureId. /// Returns RedbValue columns: Id, IdStructure, IdObject, String, Long, Guid, Double, /// DateTimeOffset, Boolean, ByteArray, Numeric, ListItem, Object, ArrayParentId, Unique. /// string Values_SelectElementRowsByStructure(); /// UPDATE one row's key. Params: $1=unique (Guid, nullable), $2=id string Values_UpdateUnique(); /// UPDATE every row of a structure to _unique = NULL. Params: $1=structureId string Values_ClearUniqueByStructure(); /// /// 1 when the structure has any value row, else 0: the sync refuses a change of the collection kind of a structure that /// holds values. Params: $1=structureId (SQL Server: @p0). /// string Values_ExistsByStructure() => "SELECT CASE WHEN EXISTS (SELECT 1 FROM _values WHERE _id_structure = $1) THEN 1 ELSE 0 END"; /// /// SELECT _id_object of the root scalar row holding a key. Params: $1=structureId, $2=unique (Guid). /// At most one row can match: the unique index guarantees it. /// string Values_SelectObjectIdByUnique(); /// /// SELECT 1 if the structure has a root scalar row with a value in /// but no key — the trace of a SQL-side writer. Params: $1=structureId. Column name is one of the /// _values typed columns and is interpolated, never user input. /// string Values_ExistsUnhashedByStructure(string typedColumn); /// /// SELECT every row of a structure (base and array-element rows alike) with RedbValue aliases. /// Params: $1=structureId. Used by the byte[]-storage conversion (V4, work Б1). /// string Values_SelectByStructure(); /// /// UPDATE one row into the scalar byte[] shape: _ByteArray = payload, _Guid and _Long cleared. /// Params: $1=bytes, $2=id. /// string Values_SetByteArrayScalar(); /// /// DELETE the per-byte element rows of a legacy Array-of-Byte structure: rows of the structure /// whose _array_parent_id points at another row OF THE SAME structure (the base row). A base row /// nested in a class points at the class row, another structure, and is left alone. Set-based on /// purpose: a megabyte payload is a million element rows. Params: $1=structureId (used twice). /// string Values_DeleteByteArrayElements(); /// /// SELECT _id of the object holding a unique key in a scheme. Params: $1=schemeId, $2=valueUnique. /// At most one row: the partial unique index over (_id_scheme, _value_unique) guarantees it. /// string ObjectStorage_SelectIdBySchemeValueUnique(); /// /// UPDATE the listed objects to _value_unique = NULL (P7: release before take inside the batch /// transaction, so an in-batch key exchange passes). Ids are inlined like Structures_DeleteByIds. /// string ObjectStorage_ClearValueUniqueByIds(IEnumerable ids); /// /// P7-аналог для ПОЛЕВЫХ ключей (Э2): освободить _values._unique у обновляемых строк перед /// bulk-UPDATE - иначе обмен [RedbUnique]-значений двух объектов в одном батче бьётся об /// частичный уникальный индекс (проверка немедленная; на SQLite bulk идёт построчно и своп /// падал всегда, на PG/MSSQL исход зависел от порядка строк). Та же транзакция - снаружи /// разрыв не виден. CT-1/CT-выяснение 2026-09-04. /// string Values_ClearUniqueByValueIds(IEnumerable ids); // ============================================================ // === TYPES SQL === // ============================================================ /// /// SELECT type by name. Params: $1=name /// Returns: _id, _name /// string Types_SelectByName(); /// /// SELECT all types. Returns: _id, _name, _db_type, _type /// string Types_SelectAll(); // ============================================================ // === SCHEME FUNCTIONS (PostgreSQL-specific, MSSQL: stored procs or queries) === // ============================================================ /// /// Sync metadata cache for scheme. Params: $1=schemeId /// PostgreSQL: SELECT sync_metadata_cache_for_scheme($1) /// MSSQL: EXEC sp_sync_metadata_cache @schemeId /// string Schemes_SyncMetadataCache(); /// /// Migrate structure type. Params: $1=structureId, $2=oldType, $3=newType, $4=dryRun /// PostgreSQL: SELECT * FROM migrate_structure_type($1, $2, $3, $4) /// string Schemes_MigrateStructureType(); /// /// Get structure tree JSON. Params: $1=schemeId /// PostgreSQL: SELECT get_scheme_structure_tree($1) /// string Schemes_GetStructureTree(); // ============================================================ // === TREE SQL === // ============================================================ /// /// SELECT children with JSON by parent and scheme. Params: $1=parentId, $2=schemeId /// Returns: json_data column /// string Tree_SelectChildrenJson(); /// /// SELECT polymorphic children with scheme. Params: $1=parentId /// Returns: ObjectId, SchemeId, JsonData columns /// string Tree_SelectPolymorphicChildren(); /// /// SELECT scheme and JSON for object. Params: $1=objectId /// Returns: SchemeId, JsonData columns /// string Tree_SelectSchemeAndJson(); /// /// SELECT children base fields by parent and scheme (Pro PVT mode). /// Params: $1=parentId, $2=schemeId /// Returns: RedbObjectRow columns /// string Tree_SelectChildrenBySchemeBase(); /// /// SELECT all children base fields by parent (Pro PVT polymorphic mode). /// Params: $1=parentId /// Returns: RedbObjectRow columns /// string Tree_SelectChildrenBase(); /// /// Check if object exists. Params: $1=objectId /// string Tree_ObjectExists(); /// /// UPDATE object parent (move). Params: $1=newParentId, $2=dateModify, $3=whoChangeId, $4=objectId /// string Tree_UpdateParent(); /// /// DELETE values by object IDs. Params: $1=objectIds (array) /// string Tree_DeleteValuesByObjectIds(); /// /// DELETE objects by IDs. Params: $1=objectIds (array). Its rows-affected is the number of the given objects this /// statement deleted, unless gives the count instead. /// string Tree_DeleteObjectsByIds(); /// /// The count of a delete by ids (, ) /// where the rows-affected of the delete is not it. SQLite: the _id_parent cascade removes a child before the /// statement reaches it, and the child is not counted. Run in the delete's transaction, which holds the write lock, /// so no other writer changes the rows between the count and the delete. Params: $1=objectIds (array). Null: the /// rows-affected of the delete is the count. /// string? ObjectStorage_CountObjectsByIds() => null; /// /// The subtree under an object in one statement: every descendant down to a depth, as rows /// (Id, IdParent, IdScheme, Depth; the children of the object have depth 1), ordered by _name, _id as the children /// queries order them, so that the children of each parent come in that order. With a scheme, the walk keeps to /// objects of that scheme (a child of another scheme and what hangs below it are not reached). /// Params: $1=objectId, $2=schemeId or NULL for any scheme, $3=maxDepth. A cycle in _id_parent repeats rows up to /// the depth; the caller detects it. /// string Tree_SelectSubtreeRows(); /// /// An object and its ancestors in one statement, as rows (Id, IdParent, IdScheme, Depth; the object itself has /// depth 0, its parent 1), ordered by depth. Params: $1=objectId, $2=maxDepth. A cycle repeats rows up to the /// depth; the caller detects it. /// string Tree_SelectAncestorRows(); /// /// The ids of the given objects and of all their ancestors, each once, in one statement (ToTreeListAsync, /// ToRootListAsync, LoadWithParentsAsync). Params: $1=object ids (long[]), $2=maxDepth: how far up a chain is read. /// string Tree_SelectIdsWithAncestors(); // ============================================================ // === OBJECT STORAGE SQL === // ============================================================ /// /// SELECT all base fields for object by ID. Params: $1=objectId /// Returns: Id, IdScheme, Hash, Name, IdParent, IdOwner, IdWhoChange, DateCreate, DateModify, DateBegin, DateComplete, Key, ValueLong, ValueString, ValueGuid, ValueBool, ValueDouble, ValueNumeric, ValueDatetime, ValueBytes, Note /// string ObjectStorage_SelectObjectById(); /// /// SELECT only Id and Hash for object. Params: $1=objectId /// string ObjectStorage_SelectIdHash(); /// /// SELECT Id, Hash, IdScheme for cache check. Params: $1=objectId /// string ObjectStorage_SelectIdHashScheme(); /// /// SELECT all base fields for objects by IDs. Params: $1=objectIds (array) /// string ObjectStorage_SelectObjectsByIds(); /// /// DELETE object by ID. Params: $1=objectId /// string ObjectStorage_DeleteById(); /// /// DELETE objects by IDs (bulk). Params: $1=objectIds (array) /// string ObjectStorage_DeleteByIds(); /// /// INSERT new object with all fields. /// Params: $1=id, $2=schemeId, $3=name, $4=note, $5=dateCreate, $6=dateModify, /// $7=ownerId, $8=whoChangeId, $9=parentId, $10=hash, /// $11=valueString, $12=valueLong, $13=valueGuid, $14=valueBool, /// $15=valueDouble, $16=valueNumeric, $17=valueDatetime, $18=valueBytes, /// $19=key, $20=dateBegin, $21=dateComplete /// string ObjectStorage_InsertObject(); /// /// UPDATE object with all fields. /// Params: $1=name, $2=note, $3=dateModify, $4=whoChangeId, $5=hash, /// $6=valueString, $7=valueLong, $8=valueGuid, $9=valueBool, /// $10=valueDouble, $11=valueNumeric, $12=valueDatetime, $13=valueBytes, /// $14=key, $15=dateBegin, $16=dateComplete, $17=objectId /// string ObjectStorage_UpdateObject(); /// /// DELETE all values for object. Params: $1=objectId /// string ObjectStorage_DeleteValuesByObjectId(); /// /// SELECT object as JSON. Params: $1=objectId, $2=depth /// PostgreSQL: SELECT get_object_json($1, $2)::text /// MSSQL: Stored procedure or CTE /// string ObjectStorage_GetObjectJson(); /// /// SELECT objects as JSON (bulk). Params: $1=objectIds (array), $2=depth /// PostgreSQL: SELECT get_object_json(id, $2)::text FROM unnest($1::bigint[]) AS id /// MSSQL: Cursor or table-valued function /// string ObjectStorage_GetObjectsJsonBulk(); /// /// SELECT structure metadata by scheme ID. Params: $1=schemeId /// Returns: Id, IdParent, Name, DbType, CollectionType, KeyType, StoreNull, Lazy, TypeSemantic /// string ObjectStorage_SelectStructuresWithMetadata(); /// /// SELECT type info by ID. Params: $1=typeId /// Returns: Id, Name, DbType, Type1 /// string ObjectStorage_SelectTypeById(); /// /// Check if object exists by ID. Params: $1=objectId /// Returns: _id or NULL /// string ObjectStorage_CheckObjectExists(); /// /// SELECT scheme by ID. Params: $1=schemeId /// Returns: Id, Name /// string ObjectStorage_SelectSchemeById(); /// /// SELECT all values for object IDs (ChangeTracking). Params: $1=objectIds (array) /// Returns: Id, IdStructure, IdObject, String, Long, Guid, Double, DateTimeOffset, Boolean, ByteArray, Numeric, ListItem, Object, ArrayParentId, ArrayIndex /// string ObjectStorage_SelectValuesForObjects(); /// /// SELECT scheme IDs for objects. Params: $1=objectIds (array) /// Returns: ObjectId, SchemeId /// string ObjectStorage_SelectSchemeIdsForObjects(); /// /// SELECT single value by ID. Params: $1=valueId /// Returns: all value fields /// string ObjectStorage_SelectValueById(); /// /// SELECT all types (for cache preload). No params. /// Returns: Id, Name, DbType, Type1 /// string ObjectStorage_SelectAllTypes(); /// /// SELECT existing object IDs from array. Params: $1=objectIds (array) /// Returns: Id only /// string ObjectStorage_SelectExistingIds(); /// /// SELECT id + stored creation date of existing objects, then one row per listed scheme. /// Params: $1=objectIds (array), $2=schemeIds (array). /// Returns: Id, DateCreate, SchemeHash, SchemeId. An object row carries its scheme's structure hash; a scheme row /// has Id 0 and DateCreate NULL, so a save of new objects only still learns the hash of every scheme it writes. /// The save strategies take the existing ids from it and hand the stored creation date back to the saved object: /// an update never rewrites _date_create. /// string ObjectStorage_SelectExistingCreateDates(); /// /// SELECT id + persisted content hash of existing objects. Params: $1=objectIds (array). /// Returns: Id, Hash. F1 (CT hash shortcut): an existing object whose recomputed hash /// equals the persisted one skips the value pipeline under ChangeTracking. /// string ObjectStorage_SelectIdHashPairs(); /// /// SELECT schemes by IDs. Params: $1=schemeIds (array) /// Returns: Id, Name, Alias, NameSpace, StructureHash, Type /// string ObjectStorage_SelectSchemesByIds(); /// /// Lock objects for update (row locking) and RETURN THE LOCKED IDS. Params: $1=objectIds (array) /// Contract (BR-9, 2026-09-02): SELECT _id (not SELECT 1) - the returned rows are the ids that /// exist and are now locked; the caller counts them, a missing id is simply not in the result. /// Rows are taken in ascending _id order so concurrent lockers cannot deadlock on each other. /// PostgreSQL: SELECT _id ... FOR UPDATE. MSSQL: WITH (UPDLOCK, ROWLOCK). SQLite: existence /// check only - writers are serialized database-wide, there is no row lock to take. /// string ObjectStorage_LockObjectsForUpdate(); /// /// SELECT scheme ID for object. Params: $1=objectId /// Returns: _id_scheme (long) /// string ObjectStorage_SelectSchemeIdByObjectId(); // ============================================================ // === LIST SQL === // ============================================================ /// /// SELECT list by ID. Params: $1=listId /// string Lists_SelectById(); /// /// SELECT list by name. Params: $1=name /// string Lists_SelectByName(); /// /// SELECT all lists ordered by name. /// string Lists_SelectAll(); /// /// INSERT new list. Params: $1=id, $2=name, $3=alias /// string Lists_Insert(); /// /// UPDATE list. Params: $1=name, $2=alias, $3=id /// string Lists_Update(); /// /// DELETE list by ID. Params: $1=listId /// string Lists_Delete(); /// /// Check if list is used in structures. Params: $1=listId /// string Lists_IsUsedInStructures(); // ============================================================ // === LIST ITEMS SQL === // ============================================================ /// /// SELECT list item by ID. Params: $1=itemId /// string ListItems_SelectById(); /// /// SELECT list items by their ids. Params: $1=itemIds (long[]) /// string ListItems_SelectByIds(); /// /// SELECT list items by list ID. Params: $1=listId /// string ListItems_SelectByListId(); /// /// SELECT list item by list ID and value. Params: $1=listId, $2=value /// string ListItems_SelectByListIdAndValue(); /// /// INSERT list item. Params: $1=id, $2=idList, $3=value, $4=alias, $5=idObject /// string ListItems_Insert(); /// /// UPDATE list item alias and idObject. Params: $1=alias, $2=idObject, $3=id /// string ListItems_UpdateAliasAndObject(); /// /// UPDATE list item. Params: $1=value, $2=alias, $3=idObject, $4=id /// string ListItems_Update(); /// /// DELETE list item by ID. Params: $1=itemId /// string ListItems_Delete(); /// /// SELECT list items by object reference. Params: $1=objectId /// string ListItems_SelectByObjectId(); // ============================================================ // === MAINTENANCE SQL === // ============================================================ // All provider variability of IMaintenanceProvider lives in these three texts; the base // provider holds the only logic and the only mapping. Index-stats SQL must normalize the // engine's catalogs to EXACTLY these column aliases: Table, Name, IsUnique, SizeBytes, // EstimatedRows, Seeks, Scans, Updates, LastUsed - NULL where the engine cannot say. /// /// Refresh planner statistics. bounds SQLite's ANALYZE /// (PRAGMA analysis_limit; 0 = unbounded); PostgreSQL and MSSQL ignore it. /// string Maintenance_Analyze(int analysisLimit); /// /// Refresh planner statistics of ONE table. The identifier arrives already checked against /// the catalogs by the base provider, and the dialect quotes it itself: an identifier cannot /// be a query parameter, and this one comes from a dashboard. /// string Maintenance_AnalyzeTable(string? schema, string table, int analysisLimit); /// Does the table exist? Params: table name, then schema (null = the engine's default). string Maintenance_SelectTableExists(); /// Index statistics of user tables, normalized to the alias contract above. string Maintenance_SelectIndexStats(); /// /// Table statistics, normalized to the TableStatistics alias contract: Schema, Table, /// EstimatedRows, DataSizeBytes, IndexesSizeBytes, DeadRows, LastAnalyze, LastAutoAnalyze, /// LastVacuum, HasStatistics. /// string Maintenance_SelectTableStats(); /// /// The table-stats forms in decreasing capability, tried in order until one runs. SQLite needs /// three: the optional dbstat module may be missing, and sqlite_stat1 does not /// exist at all until the first ANALYZE - the state every fresh database starts in, where a /// storage page must report "no statistics" rather than fail (redb.Tsak BR-13, 2026-09-21). /// Engines that can always answer return a single text. /// System.Collections.Generic.IReadOnlyList Maintenance_SelectTableStatsForms(); /// /// The window the usage counters cover: aliases CountersSince and IsReplica, both null where /// the engine keeps no counters. /// string Maintenance_SelectStatisticsWindow(); /// /// Fallback form for engines where the full form may be unavailable: SQLite without the dbstat /// virtual table (no sizes), SQL Server without VIEW SERVER STATE (no usage counters). Engines /// with no such failure mode return the same text as , /// and the base provider then never falls back. /// string Maintenance_SelectIndexStatsNoSize(); /// /// The index check (CheckBaseIndexesAsync): every index of the tables of the redb schema, cheaply, one row each with /// the columns Name, Table, IsUnique, KeyColumnsCsv (key columns in index order), /// IncludedColumnsCsv and IsValid (false only for a PostgreSQL index left INVALID). No sizes and no /// counters: it runs at every start. Null where the provider does not check its indexes. /// string? Schema_SelectIndexShapes() => null; /// /// The repair's look before it builds a unique index of _values keyed on the place of a value /// (RepairBaseIndexesAsync): the groups of rows the index would refuse, at most 100, one row each with the columns /// ObjectId, StructureId and Rows. are the key columns of the /// index, its filter in this provider's own text, null for none. Null where the provider /// does not look. /// string? Schema_SelectValueIndexDuplicates(IReadOnlyList keyColumns, string? predicate) => null; // ============================================================ // === VALIDATION SQL === // ============================================================ /// /// SELECT all types for validation. /// string Validation_SelectAllTypes(); /// /// SELECT scheme by name. Params: $1=schemeName /// string Validation_SelectSchemeByName(); /// /// SELECT structures by scheme ID. Params: $1=schemeId /// string Validation_SelectStructuresBySchemeId(); // ============================================================ // === LAZY LOADER SQL === // ============================================================ /// /// Get object base fields (without Props). Params: $1=objectId /// string LazyLoader_SelectObjectBase(); /// /// Get object as JSON via get_object_json. Params: $1=objectId, $2=maxDepth /// string LazyLoader_GetObjectJson(); /// /// Get multiple objects as JSON via get_object_json batch. Params: $1=objectIds array, $2=depth /// (V4: a stub reload passes 1, query pages their PropsDepth, otherwise 10). /// Returns: (Id, JsonData) tuples /// string LazyLoader_GetObjectJsonBatch(); /// /// Get object hash for cache validation. Params: $1=objectId /// string LazyLoader_SelectObjectHash(); /// /// Savepoint trio for a save running inside the CALLER's transaction (bug report п.2, /// 2026-09-02): a unique violation must not leave that transaction aborted (PostgreSQL 25P02), /// so the batch runs under a savepoint and rolls back TO it before the typed exception leaves. /// Release is null where the engine has nothing to release (MSSQL savepoints dissolve on their /// own). MSSQL note: SAVE TRANSACTION does not work in a distributed transaction. /// string Transaction_SavepointBegin(); /// RELEASE of the savepoint above; null when the engine needs none. string? Transaction_SavepointRelease(); /// ROLLBACK TO the savepoint above - the caller's transaction stays alive. string Transaction_SavepointRollback(); // ============================================================ // === QUERY PROVIDER SQL === // ============================================================ /// /// SQL for checking user permission on object. /// string Query_CheckPermissionSql(); /// /// SQL for SQL preview function. /// string Query_SqlPreviewTemplate(); /// /// SQL for getting parent IDs from descendant IDs using recursive CTE. /// PostgreSQL: WITH RECURSIVE ancestors AS (...) /// MSSQL: WITH ancestors AS (...) /// string Query_GetParentIdsFromDescendantsSql(string idsString, int depthLimit); /// /// SQL for the ids of the descendants of the given objects, down to levels below them /// (1 = their children); the objects themselves are not among them. WhereHasAncestor uses it with its maxDepth. /// string Query_GetDescendantIdsFromAncestorsSql(string idsString, int depthLimit); /// /// SQL for loading objects by IDs as JSON. /// PostgreSQL: SELECT get_object_json(id, 10)::text FROM unnest(ARRAY[...]) /// MSSQL: SELECT dbo.get_object_json(_id, 10) FROM _objects WHERE _id IN (...) /// string Query_LoadObjectsByIdsSql(string idsString, int maxDepth); /// /// SQL for tree SQL preview. /// string Query_TreeSqlPreviewTemplate(string functionName); // ============================================================ // === SQL PREVIEW FUNCTION NAMES === // ============================================================ /// /// SQL preview function name for regular search. /// PostgreSQL: "get_search_sql_preview" /// MSSQL: "dbo.get_search_sql_preview" /// string Query_SqlPreviewFunction(); /// /// SQL preview function name for tree base (lazy loading) search. /// PostgreSQL: "get_search_tree_sql_preview_base" /// MSSQL: "dbo.get_search_tree_sql_preview_base" /// string Query_TreeSqlPreviewBaseFunction(); // ============================================================ // === v2-pvt MODULE (free Postgres only, phase 1) === // ------------------------------------------------------------ // Two-step search pipeline: // 1. BUILD: ask the database to generate an _id-list SQL via // pvt_build_query_sql(...) — returned as plain text. // 2. EXECUTE: the client (C#/Python/Go) wraps that text with // a materializer (get_object_json), COUNT(*), EXISTS(...) or // a projection JOIN and executes the wrapped SQL. // // Dialects that don't support v2-pvt MUST return null from all // methods in this block. A null return is the explicit "no PVT" // signal — there is no fallback flag, no try/catch on the hot // path. The dispatch happens once per query call. // ============================================================ /// /// Bare SQL function name returning the inner _id-list SQL string. /// PostgreSQL: "pvt_build_query_sql". Return null when the dialect /// has no v2-pvt module deployed (e.g. MSSql phase 1). /// string? Query_BuildPvtSqlFunction(); /// /// Builds the full SELECT statement that invokes pvt_build_query_sql. /// Scalar arguments are inlined safely (no user-controlled strings); /// only the three jsonb arguments are exposed as binding placeholders: /// $1 = filter (jsonb) /// $2 = order (jsonb) /// $3 = distinct_on (jsonb) — array of {field|$expr} entries; NULL when absent. /// All may be NULL — the caller should pass DBNull when absent. /// Returns null when v2-pvt is not supported. /// string? Query_BuildPvtSqlInvocation( long schemeId, int? limit, int offset, int maxDepth, bool distinct, string sourceMode, long[]? treeIds, bool hasDistinctOn = false); /// /// Wraps the inner _id-list SQL so that it returns the _objects row of every id, in the order of the /// inner list, with the columns of . Props are not read here: the /// query provider loads them once, through the lazy loader and the Props cache. Returns null when v2-pvt is not /// supported. /// string? Query_WrapPvtWithObjectRows(string innerSql); /// /// Wraps the inner _id-list SQL with COUNT(*). /// Returns null when v2-pvt is not supported. /// string? Query_WrapPvtWithCount(string innerSql); /// /// Wraps the inner _id-list SQL with EXISTS(...). /// Returns null when v2-pvt is not supported. /// string? Query_WrapPvtWithExists(string innerSql); /// /// Wraps the inner _id-list SQL so that it returns the ids alone, one column, in no particular order: a query delete /// reads them before it deletes them through . /// Returns null when v2-pvt is not supported. /// string? Query_WrapPvtWithIds(string innerSql); /// /// Bare SQL function name returning the deployed v2-pvt module /// semver string (e.g. "0.1.0"). Used by RedbServiceBase.InitializeAsync /// to enforce major-match + minor-compatibility. Returns null when /// the dialect does not require a v2-pvt deployment check. /// string? Query_PvtModuleVersionFunction(); /// /// Semver string the shipped v2-pvt bundle for this dialect declares. /// Compared against the value returned by /// at startup: an older or /// missing module is replaced by 's embedded /// bundle, a newer one is never replaced (see /// ). Bump this string whenever /// any *.sql file under the dialect's v2-pvt folder changes (together with /// the `pvt_module_version()` literal inside `99_module_version.sql`). /// Returns null for dialects that do not ship a v2-pvt module. /// string? Query_PvtRequiredVersion(); /// /// Bare SQL function name returning what a deployed module still serves: '<oldest package module version>|<redb /// package version that first shipped it>', e.g. '0.7.24|4.8.0'. A package whose module is older than the deployed /// one leaves the module in place and starts when its own version is not below the first part; otherwise it stops /// with . Returns null when the dialect has no such function. /// string? Query_PvtModuleCompatFunction(); // ------------------------------------------------------------ // Native PVT projection orchestrator (pvt_build_projection_sql). // Drives the .Select(...)/Distinct() shape directly in SQL: the // outer SELECT yields the requested scalar columns (one per // projection entry) instead of materializing full objects. // // Dialects that have no v2-pvt projection support MUST throw // NotSupportedException from these methods. The caller dispatches // via Query_BuildPvtProjectionSqlFunction() returning non-null. // ------------------------------------------------------------ /// /// Bare SQL function name returning the projection SELECT string. /// PostgreSQL: "pvt_build_projection_sql". Return null when the /// dialect has no native PVT projection (projection then falls /// back to the standard PVT full-object path or to legacy SQL). /// string? Query_BuildPvtProjectionSqlFunction(); /// /// Builds the full SELECT statement that invokes /// pvt_build_projection_sql. Scalar arguments are inlined safely; /// jsonb arguments are exposed as bound placeholders: /// $1 = projection (jsonb) — non-empty array, required /// $2 = filter (jsonb) — nullable /// $3 = order (jsonb) — nullable /// $4 = distinct_on (jsonb) — nullable; required when hasDistinctOn /// Returns null when native PVT projection is not supported. /// string? Query_BuildPvtProjectionSqlInvocation( long schemeId, int? limit, int offset, int maxDepth, bool distinct, string sourceMode, long[]? treeIds, bool hasDistinctOn = false); /// /// Wraps the projection inner SQL into a result-set of JSON rows /// shaped as {"id": <_id>, "properties": { ...projected columns... }}. /// The inner SQL MUST contain an _id column (the caller adds /// it explicitly to the projection JSON unless DISTINCT collapses it). /// When is false the wrapper synthesizes /// id=0 and treats every inner column as a projected property. /// Returns null when native PVT projection is not supported. /// string? Query_WrapPvtProjectionRowsAsJson(string innerSql, bool includeId); // ===================================================== // SOFT DELETE METHODS // ===================================================== /// /// SQL to mark objects for soft-deletion. /// Creates trash container and moves objects under it. /// Params: $1=objectIds (array/comma-separated), $2=userId, $3=trashParentId (nullable) /// Returns: trash_id, marked_count /// PostgreSQL: SELECT * FROM mark_for_deletion($1, $2, $3) /// MSSQL: EXEC sp_mark_for_deletion @p0, @p1, @p2 (with OUTPUT params) /// string SoftDelete_MarkForDeletion(); /// /// SQL to purge (physically delete) objects from trash container. /// Deletes in batches, removes trash container when empty. /// Params: $1=trashId, $2=batchSize /// Returns: deleted_count, remaining_count /// PostgreSQL: SELECT * FROM purge_trash($1, $2) /// MSSQL: EXEC sp_purge_trash @p0, @p1 (with OUTPUT params) /// string SoftDelete_PurgeTrash(); /// /// SQL that removes a trash container once it holds no objects, for a dialect whose /// cannot do it itself - SQLite, where the result row must be /// the last statement of the batch and there is no variable to keep it in. Null when the purge /// statement removes the container (PostgreSQL, MSSQL). Runs after the last batch. /// Params: $1=trashId /// string? SoftDelete_DeleteCompletedTrashContainer() => null; /// /// SQL query listing the objects of a trash container that live objects (scheme other than -10) /// still reference through a _values._Object row, paired with the referencing objects. /// Used to report a purge that ended 'failed'. /// Params: $1=trashId /// Returns: referenced_id, referencing_id (at most 100 pairs, ordered) /// string SoftDelete_SelectLiveReferrersOfTrash(); /// /// SQL query to get deletion progress for a specific trash container. /// Reads progress from trash object fields: _value_long=total, _key=deleted, _value_string=status. /// Params: $1=trashId /// Returns: trash_id, total, deleted, status, started_at, owner_id /// string SoftDelete_GetDeletionProgress(); /// /// SQL query to get all active deletions for a user. /// Returns trash containers with status='pending' or 'running' owned by user. /// Params: $1=userId /// Returns: trash_id, total, deleted, status, started_at, owner_id /// string SoftDelete_GetUserActiveDeletions(); /// /// SQL query to get orphaned deletion tasks (for recovery at startup). /// Returns 'pending' tasks OR 'running' tasks where _date_modify older than timeout. /// CLUSTER-SAFE: Only returns tasks that are likely abandoned. /// Params: $1=timeoutMinutes (int) /// Returns: trash_id, total, deleted, status, owner_id /// string SoftDelete_GetOrphanedTasks(); /// /// SQL to atomically claim an orphaned task (prevent race condition in cluster). /// Updates status to 'running' and _date_modify to NOW() only if conditions still match. /// CLUSTER-SAFE: Uses atomic UPDATE with condition check. /// Params: $1=trashId, $2=timeoutMinutes /// Returns: claimed (1 = success, 0 = task already taken by another instance) /// string SoftDelete_ClaimOrphanedTask(); // ============================================================ // === METADATA CACHE WARMUP === // ============================================================ /// /// SQL to warmup all metadata caches. /// PostgreSQL: SELECT scheme_id, structures_count, scheme_name FROM warmup_all_metadata_caches() /// MSSQL: EXEC warmup_all_metadata_caches (returns same columns) /// Returns: scheme_id, structures_count, scheme_name /// string Warmup_AllMetadataCaches(); } Path: redb/redb.Core/Query/ITreeQueryProvider.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/ITreeQueryProvider.cs ---- using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using redb.Core.Caching; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; namespace redb.Core.Query; /// /// Extended provider for executing tree LINQ queries. /// Inherits base IRedbQueryProvider functionality and adds hierarchical constraint support. /// public interface ITreeQueryProvider : IRedbQueryProvider { /// /// Metadata cache for this provider (domain-isolated). /// GlobalMetadataCache Cache { get; } /// /// Create tree query with hierarchical constraint support. /// Uses SQL function search_tree_objects_with_facets() instead of search_objects_with_facets(). /// Returns IRedbQueryable with full tree method support. /// /// Object scheme ID /// User ID for permission check (null = current user) /// Check object access permissions /// Limit search to subtree of specified root (null = entire forest) /// Maximum tree search depth (null = unlimited) /// Typed query with tree operation support IRedbQueryable CreateTreeQuery( long schemeId, long? userId = null, bool checkPermissions = false, long? rootObjectId = null, int? maxDepth = null ) where TProps : class, new(); /// /// Get IDs of all objects and their parents to root via recursive CTE. /// Used for building hierarchical relationships in ToTreeListAsync. /// /// IDs of filtered objects /// List of all IDs including parents to root /// Cancels the operation (OCE only; a rollback in flight always completes). Task> GetIdsWithAncestorsAsync(List filteredIds, CancellationToken cancellationToken = default) where TProps : class, new(); /// /// Load full typed objects by ID list via v_objects_json. /// Used for loading homogeneous objects of one type. /// /// Object IDs to load /// Maximum depth for nested RedbObject loading (null = use config default) /// List of TreeRedbObject with full data /// Cancels the operation (OCE only; a rollback in flight always completes). Task>> LoadObjectsByIdsAsync(List objectIds, int? propsDepth = null, CancellationToken cancellationToken = default) where TProps : class, new(); /// /// Load full untyped objects by ID list via v_objects_json. /// Used for loading polymorphic trees (objects of different types). /// Returns ITreeRedbObject for polymorphism support (each object of its own type). /// /// Object IDs to load /// Maximum depth for nested RedbObject loading (null = use config default) /// List of polymorphic ITreeRedbObject (each of its own TProps type) /// Cancels the operation (OCE only; a rollback in flight always completes). Task> LoadObjectsByIdsAsync(List objectIds, int? propsDepth = null, CancellationToken cancellationToken = default); /// /// Delete objects by ID array. /// Used in TreeQueryable.DeleteAsync() to delete objects after filtering. /// /// Object IDs to delete /// Number of deleted objects /// Cancels the operation (OCE only; a rollback in flight always completes). Task ExecuteTreeDeleteAsync(long[] objectIds, CancellationToken cancellationToken = default); /// /// Execute GROUP BY aggregation with tree context (CTE for tree traversal). /// Used by TreeGroupedQueryable to perform tree-aware grouping. /// /// Object properties type /// Tree query context with rootObjectId, maxDepth, filters /// Fields to group by /// Aggregation functions to apply /// HAVING predicate as the JSON HavingPredicateParser writes; null for none. /// JSON document with grouped results /// Cancels the operation (OCE only; a rollback in flight always completes). Task ExecuteTreeGroupedAggregateAsync( Base.TreeQueryContext context, IEnumerable groupFields, IEnumerable aggregations, string? havingJson = null, CancellationToken cancellationToken = default) where TProps : class, new(); /// /// Execute Window Functions query with tree context (CTE for tree traversal). /// Used by TreeWindowedQueryable to perform tree-aware window functions. /// /// Object properties type /// Tree query context with rootObjectId, maxDepth, filters /// Fields to select /// Window functions to apply /// Partition by fields /// Order by fields /// Optional window frame specification /// JSON document with windowed results /// Cancels the operation (OCE only; a rollback in flight always completes). Task ExecuteTreeWindowQueryAsync( Base.TreeQueryContext context, IEnumerable selectFields, IEnumerable windowFuncs, IEnumerable partitionBy, IEnumerable orderBy, string? frameJson = null, CancellationToken cancellationToken = default) where TProps : class, new(); /// /// Get SQL preview for tree window query (for debugging). /// Task GetTreeWindowSqlPreviewAsync( Base.TreeQueryContext context, IEnumerable selectFields, IEnumerable windowFuncs, IEnumerable partitionBy, IEnumerable orderBy, string? frameJson = null, CancellationToken cancellationToken = default) where TProps : class, new(); /// /// Get SQL preview for tree GROUP BY query (for debugging). /// Task GetTreeGroupBySqlPreviewAsync( Base.TreeQueryContext context, IEnumerable groupFields, IEnumerable aggregations, string? havingJson = null, CancellationToken cancellationToken = default) where TProps : class, new(); /// /// Runs a grouping over the elements of an array for the objects of a subtree: the objects the tree context /// selects (its roots, depth and Where) take part, no others. and /// must be null: the context carries the condition. /// Task ExecuteTreeArrayGroupQueryAsync( Base.TreeQueryContext context, Grouping.ArrayGroupQuery query, CancellationToken cancellationToken = default) where TProps : class, new(); /// /// The SQL runs for the same request. /// Task GetTreeArrayGroupQuerySqlAsync( Base.TreeQueryContext context, Grouping.ArrayGroupQuery query, CancellationToken cancellationToken = default) where TProps : class, new(); // ===== TREE GROUPED WINDOW (GroupBy + Window for Trees) ===== /// /// Execute GroupBy + Window Functions with tree context. /// Allows ranking, running totals on aggregated tree data. /// Task ExecuteTreeGroupedWindowQueryAsync( Base.TreeQueryContext context, IEnumerable groupFields, IEnumerable aggregations, IEnumerable windowFuncs, IEnumerable partitionBy, IEnumerable orderBy, string? havingJson = null, CancellationToken cancellationToken = default) where TProps : class, new(); /// /// Get SQL preview for tree GroupBy + Window query. /// Task GetTreeGroupedWindowSqlPreviewAsync( Base.TreeQueryContext context, IEnumerable groupFields, IEnumerable aggregations, IEnumerable windowFuncs, IEnumerable partitionBy, IEnumerable orderBy, string? havingJson = null, CancellationToken cancellationToken = default) where TProps : class, new(); } Path: redb/redb.Core/Query/Mapping/BaseFieldMapper.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/Mapping/BaseFieldMapper.cs ---- namespace redb.Core.Query.Mapping; /// /// Maps C# property names to SQL column names for base RedbObject fields. /// DB-agnostic: same column names across all databases (_objects table). /// public static class BaseFieldMapper { private static readonly HashSet _baseFieldNames = new(StringComparer.OrdinalIgnoreCase) { "Id", "Name", "ParentId", "SchemeId", "DateCreate", "DateModify", "Hash", "ValueLong", "ValueString", "ValueGuid", "ValueBool", "OwnerId", "WhoChangeId", "ValueDouble", "ValueNumeric", "ValueDatetime", "ValueBytes", "ValueUnique", "Note", "Key", "DateBegin", "DateComplete", "_id", "_name", "_id_parent", "_id_scheme", "_date_create", "_date_modify", "_hash", "_value_long", "_value_string", "_value_guid", "_value_bool", "_id_owner", "_id_who_change", "_value_double", "_value_numeric", "_value_datetime", "_value_bytes", "_value_unique", "_note", "_key", "_date_begin", "_date_complete" }; /// /// Checks if the field name is a base RedbObject field (not a Props field). /// public static bool IsBaseField(string name) => _baseFieldNames.Contains(name); /// /// Maps C# property name to SQL column name. /// Returns "_id" as default for unknown fields. /// public static string MapToColumn(string fieldPath) => fieldPath.ToLowerInvariant() switch { "id" or "_id" => "_id", "name" or "_name" => "_name", "parentid" or "_id_parent" or "parent_id" => "_id_parent", "schemeid" or "_id_scheme" or "scheme_id" => "_id_scheme", "datecreate" or "_date_create" or "date_create" => "_date_create", "datemodify" or "_date_modify" or "date_modify" => "_date_modify", "hash" or "_hash" => "_hash", "valuelong" or "_value_long" or "value_long" => "_value_long", "valuestring" or "_value_string" or "value_string" => "_value_string", "valueguid" or "_value_guid" or "value_guid" => "_value_guid", "valuebool" or "_value_bool" or "value_bool" => "_value_bool", "valuedouble" or "_value_double" or "value_double" => "_value_double", "valuenumeric" or "_value_numeric" or "value_numeric" => "_value_numeric", "valuedatetime" or "_value_datetime" or "value_datetime" => "_value_datetime", "valuebytes" or "_value_bytes" or "value_bytes" => "_value_bytes", "valueunique" or "_value_unique" or "value_unique" => "_value_unique", "ownerid" or "_id_owner" or "owner_id" => "_id_owner", "whochangeid" or "_id_who_change" or "who_change_id" => "_id_who_change", "note" or "_note" => "_note", "key" or "_key" => "_key", "datebegin" or "_date_begin" or "date_begin" => "_date_begin", "datecomplete" or "_date_complete" or "date_complete" => "_date_complete", _ => "_id" }; } Path: redb/redb.Core/Query/Mapping/DbTypeMapper.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/Mapping/DbTypeMapper.cs ---- namespace redb.Core.Query.Mapping; /// /// Maps redb DbType names to _values column names. /// DB-agnostic: same column structure across all databases. /// public static class DbTypeMapper { /// /// Maps database type name to corresponding column in _values table. /// /// Type name from _types table (Long, String, Boolean, etc.) /// Column name in _values table (_Long, _String, etc.) public static string MapDbTypeToColumn(string? dbType) => dbType switch { "Long" => "_Long", "String" => "_String", "Boolean" => "_Boolean", "DateTime" => "_DateTimeOffset", "DateTimeOffset" => "_DateTimeOffset", "Double" => "_Double", "Numeric" => "_Numeric", "Guid" => "_Guid", "ByteArray" => "_ByteArray", "ListItem" => "_ListItem", "Object" => "_Object", "Text" => "_Text", _ => "_String" }; /// /// Gets the C# type for a database type. /// public static Type GetClrType(string? dbType) => dbType switch { "Long" => typeof(long), "String" => typeof(string), "Text" => typeof(string), "Boolean" => typeof(bool), "DateTime" => typeof(DateTime), "DateTimeOffset" => typeof(DateTimeOffset), "Double" => typeof(double), "Numeric" => typeof(decimal), "Guid" => typeof(Guid), "ByteArray" => typeof(byte[]), "ListItem" => typeof(long), // Foreign key to _list_items "Object" => typeof(long), // Foreign key to _objects _ => typeof(string) }; } Path: redb/redb.Core/Query/Models/FieldInfo.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/Models/FieldInfo.cs ---- namespace redb.Core.Query.Models; /// /// Metadata about a field in the PVT query. /// Contains structure_id for SQL generation and type information for value extraction. /// /// ID of the structure in _structures table /// Database type name (Long, String, Boolean, etc.) /// Column name in _values table (_Long, _String, etc.) /// Field name as it appears in Props class /// Whether this field is an array type /// For ListItem fields: which property (Id, Value, Alias) /// For Dictionary fields: the key (e.g., "home" for PhoneBook["home"]) /// For nested Dictionary fields: parent structure ID for JOIN via _array_parent_id /// For a field of an element of an array of classes (Rows[].Kind): the /// structure of that array. Such a field is not a pivot column; a condition reads it under the element row. public record FieldInfo( long StructureId, string DbType, string DbColumn, string Name, bool IsArray = false, ListItemProperty? ListItemProp = null, string? DictKey = null, long? ParentStructureId = null, long? ElementOfArrayStructureId = null ); Path: redb/redb.Core/Query/Models/ListItemProperty.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/Models/ListItemProperty.cs ---- namespace redb.Core.Query.Models; /// /// Specifies which property of ListItem is being accessed. /// Used in PVT queries to determine JOIN requirements. /// public enum ListItemProperty { /// Status.Id → _values._ListItem directly (no JOIN) Id, /// Status.Value → JOIN _list_items._value Value, /// Status.Alias → JOIN _list_items._alias (if available) Alias } Path: redb/redb.Core/Query/OrderingExpressionParser.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/OrderingExpressionParser.cs ---- using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using redb.Core.Query.QueryExpressions; namespace redb.Core.Query; /// /// Parses ordering expressions from LINQ to REDB query format. /// Supports simple properties, ternary operators, arithmetic expressions and functions. /// public class OrderingExpressionParser : IOrderingExpressionParser { /// /// Parse ordering expression for Props fields. /// Supports: p.Name, p.Price * 2, p.Name.ToLower(), etc. /// public OrderingExpression ParseOrdering(Expression> keySelector, SortDirection direction) where TProps : class { return ParseOrderingInternal(keySelector.Body, direction, isBaseField: false); } /// /// Parse sorting by base IRedbObject fields (id, name, date_create, etc.) /// Uses IRedbObject for compile-time safety - Props not visible! /// public OrderingExpression ParseRedbOrdering(Expression> keySelector, SortDirection direction) { return ParseOrderingInternal(keySelector.Body, direction, isBaseField: true); } /// /// Parse multiple orderings. /// public IReadOnlyList ParseMultipleOrderings(IEnumerable<(LambdaExpression KeySelector, SortDirection Direction)> orderings) where TProps : class { return orderings .Select(o => ParseOrderingInternal(o.KeySelector.Body, o.Direction, isBaseField: false)) .ToList(); } #region Internal Parsing /// /// Main parsing entry point - tries complex expressions first, falls back to simple property. /// private OrderingExpression ParseOrderingInternal(Expression expression, SortDirection direction, bool isBaseField) { // Try to parse as complex expression (arithmetic, functions) var valueExpr = TryExtractValueExpression(expression, isBaseField); if (valueExpr != null) { // For complex expressions, extract primary property for backward compatibility var primaryProperty = ExtractPrimaryProperty(valueExpr) ?? new QueryExpressions.PropertyInfo("__computed", expression.Type, isBaseField); return new OrderingExpression(primaryProperty, direction, valueExpr); } // Simple property case var property = ExtractProperty(expression, isBaseField); return new OrderingExpression(property, direction); } /// /// Try to extract ValueExpression for complex expressions (arithmetic, functions). /// Returns null for simple property access. /// private ValueExpression? TryExtractValueExpression(Expression expression, bool isBaseField) { return expression switch { // Arithmetic: p.Price + p.Discount, p.Quantity * p.Price BinaryExpression binary when IsArithmeticExpression(binary) => CreateArithmeticExpression(binary, isBaseField), // Method calls: p.Name.ToLower(), p.Name.Trim() MethodCallExpression method when IsStringMethod(method) => CreateFunctionExpression(method, isBaseField), // Unary: -p.Value (negation) UnaryExpression unary when unary.NodeType == ExpressionType.Negate => CreateNegationExpression(unary, isBaseField), _ => null }; } /// /// Check if expression is arithmetic (Add, Subtract, Multiply, Divide, Modulo). /// private static bool IsArithmeticExpression(BinaryExpression binary) => binary.NodeType switch { ExpressionType.Add => true, ExpressionType.Subtract => true, ExpressionType.Multiply => true, ExpressionType.Divide => true, ExpressionType.Modulo => true, _ => false }; /// /// Check if method is supported string/function call. /// private static bool IsStringMethod(MethodCallExpression method) { var name = method.Method.Name; return name is "ToLower" or "ToUpper" or "Trim" or "TrimStart" or "TrimEnd"; } /// /// Create ArithmeticExpression from binary expression. /// private ArithmeticExpression CreateArithmeticExpression(BinaryExpression binary, bool isBaseField) { var left = ExtractValueExpression(binary.Left, isBaseField); var right = ExtractValueExpression(binary.Right, isBaseField); var op = MapArithmeticOperator(binary.NodeType); return new ArithmeticExpression(left, op, right); } /// /// Create FunctionCallExpression from method call. /// private FunctionCallExpression CreateFunctionExpression(MethodCallExpression method, bool isBaseField) { var function = MapStringFunction(method.Method.Name); // Instance method (p.Name.ToLower()) - object is the argument if (method.Object != null) { var argument = ExtractValueExpression(method.Object, isBaseField); return new FunctionCallExpression(function, argument); } // Static method - first argument if (method.Arguments.Count > 0) { var argument = ExtractValueExpression(method.Arguments[0], isBaseField); return new FunctionCallExpression(function, argument); } throw new NotSupportedException($"Method {method.Method.Name} requires at least one argument"); } /// /// Create negation expression (-p.Value). /// private ArithmeticExpression CreateNegationExpression(UnaryExpression unary, bool isBaseField) { var operand = ExtractValueExpression(unary.Operand, isBaseField); var zero = new ConstantValueExpression(0, unary.Type); return new ArithmeticExpression(zero, ArithmeticOperator.Subtract, operand); } /// /// Extract ValueExpression from any expression (recursive). /// private ValueExpression ExtractValueExpression(Expression expression, bool isBaseField) { return expression switch { // Nested arithmetic BinaryExpression binary when IsArithmeticExpression(binary) => CreateArithmeticExpression(binary, isBaseField), // Method call MethodCallExpression method when IsStringMethod(method) => CreateFunctionExpression(method, isBaseField), // Property access MemberExpression member when member.Member is System.Reflection.PropertyInfo => new PropertyValueExpression(ExtractPropertyFromMember(member, isBaseField)), // Constant ConstantExpression constant => new ConstantValueExpression(constant.Value, constant.Type), // Captured variable (closure) MemberExpression member when IsCapturedVariable(member) => new ConstantValueExpression(EvaluateExpression(member), member.Type), // Unary conversion (e.g., int to double) UnaryExpression { NodeType: ExpressionType.Convert } unary => ExtractValueExpression(unary.Operand, isBaseField), _ => throw new NotSupportedException($"Unsupported expression type in OrderBy: {expression.GetType().Name} ({expression.NodeType})") }; } /// /// Extract primary property from ValueExpression (for backward compatibility). /// private static QueryExpressions.PropertyInfo? ExtractPrimaryProperty(ValueExpression expr) => expr switch { PropertyValueExpression pve => pve.Property, ArithmeticExpression ae => ExtractPrimaryProperty(ae.Left) ?? ExtractPrimaryProperty(ae.Right), FunctionCallExpression fce => ExtractPrimaryProperty(fce.Argument), _ => null }; /// /// Map C# operator to ArithmeticOperator. /// private static ArithmeticOperator MapArithmeticOperator(ExpressionType nodeType) => nodeType switch { ExpressionType.Add => ArithmeticOperator.Add, ExpressionType.Subtract => ArithmeticOperator.Subtract, ExpressionType.Multiply => ArithmeticOperator.Multiply, ExpressionType.Divide => ArithmeticOperator.Divide, ExpressionType.Modulo => ArithmeticOperator.Modulo, _ => throw new NotSupportedException($"Unsupported arithmetic operator: {nodeType}") }; /// /// Map string method to PropertyFunction. /// private static PropertyFunction MapStringFunction(string methodName) => methodName switch { "ToLower" => PropertyFunction.ToLower, "ToUpper" => PropertyFunction.ToUpper, "Trim" => PropertyFunction.Trim, "TrimStart" => PropertyFunction.TrimStart, "TrimEnd" => PropertyFunction.TrimEnd, _ => throw new NotSupportedException($"Unsupported string method in OrderBy: {methodName}") }; /// /// Check if member expression is captured variable (closure). /// private static bool IsCapturedVariable(MemberExpression member) { return member.Expression is ConstantExpression || (member.Expression is MemberExpression inner && IsCapturedVariable(inner)); } /// /// Evaluate expression to get constant value. /// private static object? EvaluateExpression(Expression expression) { var lambda = Expression.Lambda(expression); var compiled = lambda.Compile(); return compiled.DynamicInvoke(); } #endregion #region Simple Property Extraction (backward compatibility) /// /// Extract property with ternary operators support for nullable fields. /// private QueryExpressions.PropertyInfo ExtractProperty(Expression expression, bool isBaseField) { return expression switch { // Ternary operator (r.Auction != null ? r.Auction.Baskets : 0) ConditionalExpression conditional => ExtractFromConditional(conditional, isBaseField), // Binary expression for comparison (r.Auction != null) BinaryExpression binary when !IsArithmeticExpression(binary) => ExtractFromBinaryExpression(binary, isBaseField), // Regular property (r.Name) or nested (r.Auction.Baskets) MemberExpression member when member.Member is System.Reflection.PropertyInfo propInfo => ExtractPropertyFromMember(member, isBaseField), _ => throw new ArgumentException( "An ordering or DistinctBy key must be a property (x.Price, x.Address.City, a whole collection " + "such as x.Tags), a ternary over such properties or a comparison of one. A dictionary entry " + "(x.Codes[\"key\"]), a list element or a method call cannot be such a key; got " + $"{expression.NodeType} ({expression.GetType().Name}): {expression}.") }; } /// /// Extract property from binary expression (r.Auction != null, r.Field == value). /// private QueryExpressions.PropertyInfo ExtractFromBinaryExpression(BinaryExpression binary, bool isBaseField) { if (binary.Left is MemberExpression leftMember && leftMember.Member is System.Reflection.PropertyInfo) { return ExtractPropertyFromMember(leftMember, isBaseField); } if (binary.Right is MemberExpression rightMember && rightMember.Member is System.Reflection.PropertyInfo) { return ExtractPropertyFromMember(rightMember, isBaseField); } throw new ArgumentException($"Binary expression must have at least one property access side. Got: {binary.Left.GetType().Name} {binary.NodeType} {binary.Right.GetType().Name}"); } /// /// Extract property from ternary operator (r.Auction != null ? r.Auction.Baskets : 0). /// private QueryExpressions.PropertyInfo ExtractFromConditional(ConditionalExpression conditional, bool isBaseField) { if (conditional.IfTrue is MemberExpression trueMember && trueMember.Member is System.Reflection.PropertyInfo) { return ExtractPropertyFromMember(trueMember, isBaseField); } if (conditional.IfFalse is MemberExpression falseMember && falseMember.Member is System.Reflection.PropertyInfo) { return ExtractPropertyFromMember(falseMember, isBaseField); } throw new ArgumentException("Conditional expression must have at least one property access branch"); } /// /// Extract property from member expression with nested fields support. /// private QueryExpressions.PropertyInfo ExtractPropertyFromMember(MemberExpression member, bool isBaseField) { var fullPath = BuildPropertyPath(member); var propInfo = member.Member as System.Reflection.PropertyInfo; return new QueryExpressions.PropertyInfo(fullPath, propInfo?.PropertyType ?? typeof(object), isBaseField); } /// /// Build full property path for nested fields (Auction.Baskets). /// private static string BuildPropertyPath(MemberExpression memberExpression) { var pathParts = new List(); var current = memberExpression; while (current != null && current.Member is System.Reflection.PropertyInfo) { // .Value/.HasValue on Nullable add no part if (!((current.Member.Name == "Value" || current.Member.Name == "HasValue") && IsNullableAccessor(current))) pathParts.Add(current.Member.Name); if (current.Expression is MemberExpression parentMember) { current = parentMember; } else { // The start of the chain must be the object of the query. A dictionary entry, an element by index or a // method call before it used to be dropped, so OrderBy(p => p.Items[0].Name) sorted by the field Name // of the object itself and OrderBy(p => p.Scores["a"].Value) sent an empty path. var root = current.Expression; while (root is UnaryExpression { NodeType: ExpressionType.Convert or ExpressionType.ConvertChecked or ExpressionType.TypeAs } conversion) root = conversion.Operand; if (root is not ParameterExpression) throw new NotSupportedException(Parsing.BaseFilterExpressionParser.UnsupportedFieldPathMessage(memberExpression)); break; } } pathParts.Reverse(); return string.Join(".", pathParts); } private static bool IsNullableAccessor(MemberExpression member) { var declaringType = member.Member.DeclaringType; return declaringType != null && declaringType.IsGenericType && declaringType.GetGenericTypeDefinition() == typeof(Nullable<>); } #endregion } Path: redb/redb.Core/Query/Parameters/SqlParameterCollectorBase.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/Parameters/SqlParameterCollectorBase.cs ---- using System.Text; using redb.Core.Query; using redb.Core.Utils; namespace redb.Core.Query.Parameters; /// /// Base class for SQL parameter collection. /// Provides value normalization and debug output. /// Uses ISqlDialect for dialect-specific parameter formatting. /// public class SqlParameterCollectorBase { private readonly ISqlDialect _dialect; private readonly List _parameters = new(); private long? _schemeId; /// /// Creates a new parameter collector with the specified SQL dialect. /// public SqlParameterCollectorBase(ISqlDialect dialect) { _dialect = dialect ?? throw new ArgumentNullException(nameof(dialect)); } /// /// Number of parameters added. /// public int Count => _parameters.Count; /// /// Sets SchemeId for debug output. /// public void SetSchemeId(long schemeId) => _schemeId = schemeId; /// /// Adds a parameter and returns the dialect-specific placeholder. /// /// Parameter value (will be normalized) /// Parameter placeholder (e.g., "$1" for PostgreSQL, "@p0" for MSSQL) public string AddParameter(object? value) { var index = _parameters.Count; _parameters.Add(NormalizeValue(value)); return _dialect.FormatParameter(index); } /// /// Adds a parameter with a custom index offset. /// Useful when building complex queries with multiple parameter sets. /// public string AddParameterWithOffset(object? value, int offset) { var index = _parameters.Count + offset; _parameters.Add(NormalizeValue(value)); return _dialect.FormatParameter(index); } /// /// Returns parameters as array for use with FromSqlRaw/SqlQueryRaw. /// public object?[] ToArray() => _parameters.ToArray(); /// /// Generates debug comment with parameter values (EF Core style). /// public string GetDebugComment() { var sb = new StringBuilder(); sb.AppendLine("-- REDB Query Parameters:"); if (_schemeId.HasValue) sb.AppendLine($"-- SchemeId: {_schemeId.Value}"); for (int i = 0; i < _parameters.Count; i++) { var p = _parameters[i]; var type = p?.GetType().Name ?? "null"; var val = FormatForComment(p); sb.AppendLine($"-- {_dialect.FormatParameter(i)}={val} ({type})"); } return sb.ToString(); } /// /// Normalizes value before adding to parameters. /// Handles DateTime → UTC, object[] → typed array conversion. /// protected virtual object? NormalizeValue(object? value) { return value switch { // DateTime always converts to UTC DateTime dt => DateTimeConverter.NormalizeForStorage(dt), // DateTimeOffset converts to UTC DateTime DateTimeOffset dto => dto.UtcDateTime, // object[] converts to typed array for EF Core object[] arr => ConvertToTypedArray(arr), // Other values as-is _ => value }; } /// /// Converts object[] to typed array for EF Core. /// EF Core doesn't support object[] - needs long[], string[], etc. /// private static object ConvertToTypedArray(object[] arr) { if (arr.Length == 0) return Array.Empty(); // Default to long[] for empty array var firstNonNull = arr.FirstOrDefault(x => x != null); if (firstNonNull == null) return Array.Empty(); return firstNonNull switch { long => arr.Select(x => x is long l ? l : Convert.ToInt64(x)).ToArray(), int => arr.Select(x => x is int i ? i : Convert.ToInt32(x)).ToArray(), string => arr.Select(x => x?.ToString() ?? "").ToArray(), Guid => arr.Select(x => x is Guid g ? g : Guid.Parse(x?.ToString() ?? "")).ToArray(), decimal => arr.Select(x => x is decimal d ? d : redb.Core.Utils.RedbDecimal.From(x!)).ToArray(), double => arr.Select(x => x is double d ? d : Convert.ToDouble(x)).ToArray(), bool => arr.Select(x => x is bool b ? b : Convert.ToBoolean(x)).ToArray(), DateTime => arr.Select(x => x is DateTime dt ? DateTimeConverter.NormalizeForStorage(dt) : DateTime.MinValue).ToArray(), // Fallback - try to convert to long (most common case for IDs) _ when IsNumericType(firstNonNull.GetType()) => arr.Select(x => Convert.ToInt64(x)).ToArray(), _ => arr // If can't determine type - leave as is (may fail) }; } private static bool IsNumericType(Type type) => type == typeof(int) || type == typeof(long) || type == typeof(short) || type == typeof(byte) || type == typeof(uint) || type == typeof(ulong) || type == typeof(decimal) || type == typeof(double) || type == typeof(float); /// /// Formats value for debug comment. /// protected virtual string FormatForComment(object? value) { return value switch { null => "NULL", string s => $"'{EscapeForComment(s)}'", bool b => b ? "TRUE" : "FALSE", DateTime dt => $"'{dt:yyyy-MM-ddTHH:mm:ss.ffffffZ}'", DateTimeOffset dto => $"'{dto:yyyy-MM-ddTHH:mm:ss.ffffffzzz}'", decimal d => d.ToString(System.Globalization.CultureInfo.InvariantCulture), double d => d.ToString(System.Globalization.CultureInfo.InvariantCulture), float f => f.ToString(System.Globalization.CultureInfo.InvariantCulture), Guid g => $"'{g}'", long[] arr => $"[{string.Join(",", arr)}]", int[] arr => $"[{string.Join(",", arr)}]", string[] arr => $"[{string.Join(",", arr.Select(s => $"'{s}'"))}]", System.Collections.IEnumerable enumerable => FormatEnumerable(enumerable), _ => value.ToString() ?? "NULL" }; } /// /// Formats IEnumerable for comment. /// private static string FormatEnumerable(System.Collections.IEnumerable enumerable) { var items = new List(); foreach (var item in enumerable) { items.Add(item?.ToString() ?? "NULL"); if (items.Count > 10) { items.Add("..."); break; } } return $"[{string.Join(",", items)}]"; } /// /// Escapes string for comment (truncates long strings). /// private static string EscapeForComment(string s) { var escaped = s.Replace("'", "''"); if (escaped.Length > 50) { escaped = escaped[..47] + "..."; } return escaped; } } Path: redb/redb.Core/Query/Parsing/BaseFilterExpressionParser.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/Parsing/BaseFilterExpressionParser.cs ---- using System.Linq.Expressions; using redb.Core.Models.Contracts; using redb.Core.Query.QueryExpressions; using redb.Core.Utils; namespace redb.Core.Query.Parsing; /// /// Base class for parsing LINQ expressions to FilterExpression. /// Contains all DB-agnostic logic. DB-specific implementations override CheckProOnlyFeatures. /// public abstract class BaseFilterExpressionParser : IFilterExpressionParser { /// /// Context flag: true when parsing WhereRedb (base fields), false for regular Where (Props). /// protected bool _isBaseFieldContext = false; /// /// Parse LINQ predicate to FilterExpression for Props fields. /// public virtual FilterExpression ParseFilter(Expression> predicate) where TProps : class { _isBaseFieldContext = false; CheckProOnlyFeatures(predicate.Body, "Where filter"); return VisitExpression(predicate.Body); } /// /// Hook for backend-specific feature checks. No-op in OSS. /// Implementations may override to raise on unsupported expressions. /// protected virtual void CheckProOnlyFeatures(Expression body, string context) { // No-op: OSS allows all expression shapes; unsupported ones surface // later as concrete errors during SQL generation or execution. } /// /// Check property path nesting depth. /// No artificial limit — PVT engine supports up to 50 levels natively. /// Override in implementations if a backend-specific cap is needed. /// protected virtual void CheckPathDepth(int depth, string fullPath) { // Intentionally no-op: deep nested paths (e.g. Address.Building.Floor) // are fully supported by the SQL builder. } /// /// Parse LINQ predicate for base RedbObject fields (id, name, parent_id, etc.). /// public FilterExpression ParseRedbFilter(Expression> predicate) { _isBaseFieldContext = true; var result = VisitExpression(predicate.Body); _isBaseFieldContext = false; return result; } #region Expression Visitors /// /// Main visitor dispatcher. /// protected virtual FilterExpression VisitExpression(Expression expression) { return expression switch { BinaryExpression binary => VisitBinaryExpression(binary), UnaryExpression unary => VisitUnaryExpression(unary), MethodCallExpression method => VisitMethodCallExpression(method), ConstantExpression constant when constant.Type == typeof(bool) => VisitConstantBooleanExpression(constant), // Support for .Where(p => p.IsActive) without explicit == true MemberExpression member when member.Type == typeof(bool) => VisitBooleanMemberExpression(member, negated: false), _ => throw new NotSupportedException($"Expression type {expression.NodeType} is not supported") }; } /// /// Handles boolean member expressions like p.IsActive or !p.IsActive. /// For Nullable<T>.HasValue, converts to IS [NOT] NULL check. /// Otherwise converts to field = true/false comparison. /// protected virtual FilterExpression VisitBooleanMemberExpression(MemberExpression member, bool negated) { // A value of the caller (a captured variable, a field or property of another object, a static member), not a // field of the object: it is the constant it holds now, as Where(x => true) is. if (!ReadsParameter(member)) { var value = (bool)EvaluateExpression(member)!; return VisitConstantBooleanExpression(Expression.Constant(value != negated)); } // Nullable.HasValue → IS [NOT] NULL if (member.Member.Name == "HasValue" && IsNullableAccessor(member)) { var property = ExtractProperty(member); // HasValue (negated=false) → IS NOT NULL; !HasValue (negated=true) → IS NULL return new NullCheckExpression(property, negated); } var prop = ExtractProperty(member); return new ComparisonExpression(prop, ComparisonOperator.Equal, !negated); } /// /// AND / OR of two parsed operands with a constant operand folded away, so a constant is only ever the whole /// condition: "a AND true" and "a OR false" are a, "a AND false" is false, "a OR true" is true. The rows a /// database returns for the folded condition are the rows of the written one, an unset field included. /// private FilterExpression FoldLogical(LogicalOperator op, FilterExpression left, FilterExpression right) { // The constant that decides the result alone: false for AND, true for OR. var deciding = op == LogicalOperator.Or; if (TryGetConstant(left, out var l)) return l == deciding ? left : right; if (TryGetConstant(right, out var r)) return r == deciding ? right : left; return new LogicalExpression(op, new[] { left, right }); } /// The value of a constant condition (the node of Where(x => true / false)). private static bool TryGetConstant(FilterExpression filter, out bool value) { if (filter is ComparisonExpression { Property.Name: "__constant", Operator: ComparisonOperator.Equal, Value: bool b }) { value = b; return true; } value = false; return false; } /// /// The expression reads the object of the query (the lambda parameter) somewhere inside it. /// private static bool ReadsParameter(Expression expression) { var finder = new ParameterFinder(); finder.Visit(expression); return finder.Found; } private sealed class ParameterFinder : ExpressionVisitor { public bool Found { get; private set; } protected override Expression VisitParameter(ParameterExpression node) { Found = true; return node; } } /// /// A value the caller holds: it reads no field of the object and calls no database function, so it can be evaluated /// in .NET before the query is built. /// private bool IsCallerValue(Expression expression) { if (ReadsParameter(expression)) return false; var finder = new DatabaseFunctionFinder(m => IsCustomFunctionCall(m) || IsProFunctionCall(m)); finder.Visit(expression); return !finder.Found; } private sealed class DatabaseFunctionFinder(Func isDatabaseFunction) : ExpressionVisitor { public bool Found { get; private set; } protected override Expression VisitMethodCall(MethodCallExpression node) { if (isDatabaseFunction(node)) { Found = true; return node; } return base.VisitMethodCall(node); } } /// One side of a computed comparison: a field of the object, or a value of the caller. private ValueExpression Operand(Expression side) => ReadsParameter(side) ? FieldOperand(side) : new ConstantValueExpression(EvaluateExpression(side), side.Type); /// A side that reads the object and is not itself computed must be a field of it (behind a cast). private ValueExpression FieldOperand(Expression side) { var field = side; while (field is UnaryExpression { NodeType: ExpressionType.Convert or ExpressionType.ConvertChecked } conversion) field = conversion.Operand; if (TryExtractValueExpression(field) is { } computed) return computed; if (!IsPropertyAccess(field)) throw new NotSupportedException(UnsupportedFieldPathMessage(side)); return new PropertyValueExpression(ExtractProperty(field)); } /// /// Binary expression visitor (AND, OR, comparisons, arithmetic). /// protected virtual FilterExpression VisitBinaryExpression(BinaryExpression binary) { switch (binary.NodeType) { case ExpressionType.AndAlso: return FoldLogical(LogicalOperator.And, VisitExpression(binary.Left), VisitExpression(binary.Right)); case ExpressionType.OrElse: return FoldLogical(LogicalOperator.Or, VisitExpression(binary.Left), VisitExpression(binary.Right)); case ExpressionType.Equal: return VisitComparisonExpression(binary, ComparisonOperator.Equal); case ExpressionType.NotEqual: return VisitComparisonExpression(binary, ComparisonOperator.NotEqual); case ExpressionType.GreaterThan: return VisitComparisonExpression(binary, ComparisonOperator.GreaterThan); case ExpressionType.GreaterThanOrEqual: return VisitComparisonExpression(binary, ComparisonOperator.GreaterThanOrEqual); case ExpressionType.LessThan: return VisitComparisonExpression(binary, ComparisonOperator.LessThan); case ExpressionType.LessThanOrEqual: return VisitComparisonExpression(binary, ComparisonOperator.LessThanOrEqual); case ExpressionType.Add: case ExpressionType.Subtract: case ExpressionType.Multiply: case ExpressionType.Divide: case ExpressionType.Modulo: return VisitArithmeticComparisonExpression(binary); default: throw new NotSupportedException($"Binary operator {binary.NodeType} is not supported"); } } /// /// Arithmetic expression as top-level is not allowed. /// protected virtual FilterExpression VisitArithmeticComparisonExpression(BinaryExpression binary) { throw new NotSupportedException( $"Arithmetic expression ({binary.NodeType}) must be part of a comparison. " + "Use: Where(p => p.Price * 2 > 100), not: Where(p => p.Price * 2)"); } /// /// Comparison expression visitor. /// protected virtual FilterExpression VisitComparisonExpression(BinaryExpression binary, ComparisonOperator op) { if ((op == ComparisonOperator.Equal || op == ComparisonOperator.NotEqual) && TryEnumComparison(binary, op) is { } byName) return byName; // A side that does not read the queried object is a value of the caller (tag + "-none", a + 1, x ?? "d"): it is // evaluated here, once, whatever its shape. A database function stays an expression even without a field. var leftValueExpr = IsCallerValue(binary.Left) ? null : TryExtractValueExpression(binary.Left); var rightValueExpr = IsCallerValue(binary.Right) ? null : TryExtractValueExpression(binary.Right); if (leftValueExpr != null || rightValueExpr != null) { return CreateExtendedComparison(binary, op, leftValueExpr, rightValueExpr); } // A field against a field (p.A == p.B): both sides are operands of a computed comparison. if (ReadsParameter(binary.Left) && ReadsParameter(binary.Right)) { return CreateExtendedComparison(binary, op, FieldOperand(binary.Left), FieldOperand(binary.Right)); } var (property, value) = ExtractPropertyAndValue(binary); if (value is IRedbListItem listItem) { // 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 (!property.Name.Contains('.')) { property = property with { Name = property.Name + ".Id", Type = typeof(long) }; } return new ComparisonExpression(property, op, listItem.Id); } if (value != null && value.GetType().IsEnum) { value = value.ToString(); } if (value == null) { return new NullCheckExpression(property, op == ComparisonOperator.Equal); } return new ComparisonExpression(property, op, value); } /// /// p.Kind == Shade.Green and !=, nullable or not, with a constant or a caller's value: C# compares an /// enum as its underlying number, so the field arrives wrapped in a conversion and the value as a number. The field is /// taken from under the conversion and the value turned back into the enum, so the filter compares the stored name, /// as for a string field. Null for any other comparison. /// private FilterExpression? TryEnumComparison(BinaryExpression binary, ComparisonOperator op) { var left = UnwrapEnumConversion(binary.Left); var right = UnwrapEnumConversion(binary.Right); if (ReferenceEquals(left, binary.Left) && ReferenceEquals(right, binary.Right)) return null; Expression field, other; if (left != binary.Left && IsPropertyAccess(left) && !ReadsParameter(binary.Right)) (field, other) = (left, binary.Right); else if (right != binary.Right && IsPropertyAccess(right) && !ReadsParameter(binary.Left)) (field, other) = (right, binary.Left); else return null; var enumType = Nullable.GetUnderlyingType(field.Type) ?? field.Type; var property = ExtractProperty(field); var value = EvaluateExpression(other); if (value == null) return new NullCheckExpression(property, op == ComparisonOperator.Equal); var name = (value.GetType().IsEnum ? value : Enum.ToObject(enumType, value)).ToString()!; return new ComparisonExpression(property, op, name); static Expression UnwrapEnumConversion(Expression expression) { while (expression is UnaryExpression { NodeType: ExpressionType.Convert } convert && (Nullable.GetUnderlyingType(convert.Operand.Type) ?? convert.Operand.Type).IsEnum) expression = convert.Operand; return expression; } } /// /// Extended comparison with ValueExpression (arithmetic/functions). /// protected virtual FilterExpression CreateExtendedComparison( BinaryExpression binary, ComparisonOperator op, ValueExpression? leftValueExpr, ValueExpression? rightValueExpr) { // The other side is a field of the object (p.A == p.B + 1) or a value of the caller (p.A + 1 == limit). if (leftValueExpr != null && rightValueExpr == null) rightValueExpr = Operand(binary.Right); else if (rightValueExpr != null && leftValueExpr == null) leftValueExpr = Operand(binary.Left); var dummyProperty = new QueryExpressions.PropertyInfo( "__computed", typeof(object), _isBaseFieldContext); return new ComparisonExpression(dummyProperty, op, null) { LeftExpression = leftValueExpr, RightExpression = rightValueExpr }; } /// /// Try to extract ValueExpression from Expression (arithmetic, functions). /// Returns null for simple property/constant. /// protected virtual ValueExpression? TryExtractValueExpression(Expression expression) { return expression switch { BinaryExpression binary when IsArithmeticExpression(binary) => CreateArithmeticExpression(binary), // x ?? y — Coalesce (binary, right-associative; flattened to n-ary). BinaryExpression binary when binary.NodeType == ExpressionType.Coalesce => CreateCoalesceExpression(binary), // C# ternary: cond ? a : b System.Linq.Expressions.ConditionalExpression cond => CreateConditionalValueExpression(cond), MethodCallExpression method when IsCustomFunctionCall(method) => CreateCustomFunctionExpression(method), MethodCallExpression method when IsProFunctionCall(method) => CreateFunctionCallExpression(method), MemberExpression member when IsDateTimePropertyAccess(member) => CreateDateTimeFunctionExpression(member), MemberExpression member when member.Member.Name == "Length" && member.Expression is MethodCallExpression innerMethod && IsProFunctionCall(innerMethod) => new FunctionCallExpression(PropertyFunction.Length, CreateFunctionCallExpression(innerMethod)), // (any-ValueExpression).Length — e.g. `(s ?? "n/a").Length`. Falls through // for simple property paths (which the legacy emitter handles via // PropertyFunction.Length on the property column directly). MemberExpression member when member.Member.Name == "Length" && member.Expression != null && member.Expression.Type == typeof(string) && member.Expression is not MemberExpression && member.Expression is not MethodCallExpression && TryExtractValueExpression(member.Expression) is { } innerValue => new FunctionCallExpression(PropertyFunction.Length, innerValue), // arr.Length (C# compiles array .Length as ExpressionType.ArrayLength UnaryExpression, // not a regular MemberExpression). ArrayLength is array-only (IL ldlen), so translate // to PropertyFunction.Count: Pro path emits array_length(col,1), PVT path uses .$count. UnaryExpression unaryArr when unaryArr.NodeType == ExpressionType.ArrayLength && unaryArr.Operand is MemberExpression arrMember => new FunctionCallExpression( PropertyFunction.Count, new PropertyValueExpression(ExtractPropertyFromMember(arrMember))), _ => null }; } /// /// Unary expression visitor (NOT). /// protected virtual FilterExpression VisitUnaryExpression(UnaryExpression unary) { switch (unary.NodeType) { case ExpressionType.Not: // Special case for !p.IsActive - convert to field = false if (unary.Operand is MemberExpression member && member.Type == typeof(bool)) { return VisitBooleanMemberExpression(member, negated: true); } var operand = VisitExpression(unary.Operand); if (TryGetConstant(operand, out var constantOperand)) return VisitConstantBooleanExpression(Expression.Constant(!constantOperand)); return new LogicalExpression(LogicalOperator.Not, new[] { operand }); default: throw new NotSupportedException($"Unary operator {unary.NodeType} is not supported"); } } /// /// Method call expression visitor. /// protected virtual FilterExpression VisitMethodCallExpression(MethodCallExpression method) { var methodName = method.Method.Name; var declaringType = method.Method.DeclaringType; if (declaringType == typeof(string)) { return methodName switch { "Contains" => VisitStringMethodWithComparison(method, ComparisonOperator.Contains, ComparisonOperator.ContainsIgnoreCase), "StartsWith" => VisitStringMethodWithComparison(method, ComparisonOperator.StartsWith, ComparisonOperator.StartsWithIgnoreCase), "EndsWith" => VisitStringMethodWithComparison(method, ComparisonOperator.EndsWith, ComparisonOperator.EndsWithIgnoreCase), _ => throw new NotSupportedException($"String method {methodName} is not supported") }; } // Regex.IsMatch(input, pattern[, options]) -> ComparisonExpression with // LeftExpression=input, RightExpression=pattern, RegexMatch / RegexMatchIgnoreCase. if (declaringType == typeof(System.Text.RegularExpressions.Regex) && methodName == "IsMatch") { return VisitRegexIsMatch(method); } if (declaringType == typeof(Enumerable)) { return methodName switch { "Contains" => VisitEnumerableContains(method), "Any" => VisitEnumerableAny(method), _ => throw new NotSupportedException($"Enumerable method {methodName} is not supported") }; } // C# 13 / .NET 9 resolves `array.Contains(x)` to the ReadOnlySpan overload // (System.MemoryExtensions.Contains) instead of Enumerable.Contains — same // 2-arg (source, value) shape, same IN translation. The source arg is a // ReadOnlySpan Convert over the underlying array/list; a ref struct cannot // be compiled by EvaluateExpression, so unwrap the conversion back to the // collection first. if (declaringType == typeof(MemoryExtensions) && methodName == "Contains" && method.Arguments.Count == 2) { // The receiver is a ReadOnlySpan built from the underlying array — // the compiler emits the array→span conversion as a Call (op_Implicit / // AsSpan) or, less commonly, a Convert. A ref struct can't be compiled / // invoked by EvaluateExpression, so peel it back to the source collection. var source = method.Arguments[0] switch { UnaryExpression { NodeType: ExpressionType.Convert } u => u.Operand, MethodCallExpression { Arguments.Count: >= 1 } c => c.Arguments[0], var other => other }; return VisitContainsCore(source, method.Arguments[1]); } if (methodName == "Contains" && method.Object != null) { var objectType = method.Object.Type; if (objectType.IsArray) { return VisitCollectionContains(method); } if (objectType.IsGenericType) { var genericDef = objectType.GetGenericTypeDefinition(); if (genericDef == typeof(List<>) || genericDef == typeof(IList<>) || genericDef == typeof(ICollection<>) || genericDef == typeof(IEnumerable<>) || objectType.GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IEnumerable<>))) { return VisitCollectionContains(method); } } } if (methodName == "ContainsKey" && method.Object != null && IsDictionaryType(method.Object.Type)) { return VisitDictionaryContainsKey(method); } throw new NotSupportedException($"Method {declaringType?.Name}.{methodName} is not supported"); } /// /// Constant boolean expression visitor. /// protected virtual FilterExpression VisitConstantBooleanExpression(ConstantExpression constant) { var value = (bool)constant.Value!; var dummyProperty = new QueryExpressions.PropertyInfo("__constant", typeof(bool), false); return new ComparisonExpression(dummyProperty, ComparisonOperator.Equal, value); } #endregion #region String Methods /// /// String methods with StringComparison support. /// protected virtual FilterExpression VisitStringMethodWithComparison( MethodCallExpression method, ComparisonOperator caseSensitiveOp, ComparisonOperator ignoreCaseOp) { if (method.Object == null) throw new ArgumentException("String method must have an object instance"); var op = caseSensitiveOp; if (method.Arguments.Count == 2) { var stringComparison = EvaluateStringComparison(method.Arguments[1]); op = IsIgnoreCaseComparison(stringComparison) ? ignoreCaseOp : caseSensitiveOp; } else if (method.Arguments.Count != 1) { throw new NotSupportedException($"String method with {method.Arguments.Count} arguments is not supported"); } var value = EvaluateExpression(method.Arguments[0]); // LHS may be a computed value (string concat, ToLower over concat, Substring, etc.). // ExtractProperty only handles property paths and bare string-function chains; // anything richer (e.g. `(a + " " + b).ToLower()`) must go through the computed // $expr / arithmetic ComparisonExpression route. A property path keeps the // simple-field SQL fast path (and its refusals: an element by index inside it is // refused, not computed); any other shape goes the computed way. if (IsPropertyPathShape(method.Object)) { var property = ExtractProperty(method.Object); return new ComparisonExpression(property, op, value); } var leftValueExpr = TryExtractValueExpression(method.Object) ?? throw new NotSupportedException( $"Cannot translate LHS of string method '{method.Method.Name}': {method.Object}"); var dummyProperty = new QueryExpressions.PropertyInfo( "__computed", typeof(bool), _isBaseFieldContext); return new ComparisonExpression(dummyProperty, op, null) { LeftExpression = leftValueExpr, RightExpression = new ConstantValueExpression(value, method.Arguments[0].Type) }; } /// /// Regex.IsMatch(input, pattern[, options]) — builds computed ComparisonExpression /// routed through PVT $expr / PG '~' '~*'. /// protected virtual FilterExpression VisitRegexIsMatch(MethodCallExpression method) { if (method.Arguments.Count < 2) throw new NotSupportedException("Regex.IsMatch requires (input, pattern[, options])."); var inputExpr = ExtractValueExpression(method.Arguments[0]); var patternExpr = ExtractValueExpression(method.Arguments[1]); var op = ComparisonOperator.RegexMatch; if (method.Arguments.Count >= 3) { var optsValue = EvaluateExpression(method.Arguments[2]); if (optsValue is System.Text.RegularExpressions.RegexOptions opts && (opts & System.Text.RegularExpressions.RegexOptions.IgnoreCase) != 0) { op = ComparisonOperator.RegexMatchIgnoreCase; } } var dummyProperty = new QueryExpressions.PropertyInfo( "__computed", typeof(bool), _isBaseFieldContext); return new ComparisonExpression(dummyProperty, op, null) { LeftExpression = inputExpr, RightExpression = patternExpr }; } protected StringComparison EvaluateStringComparison(Expression comparisonExpression) { var value = EvaluateExpression(comparisonExpression); return value is StringComparison comparison ? comparison : StringComparison.Ordinal; } protected bool IsIgnoreCaseComparison(StringComparison comparison) { return comparison is StringComparison.CurrentCultureIgnoreCase or StringComparison.InvariantCultureIgnoreCase or StringComparison.OrdinalIgnoreCase; } #endregion #region Collection Methods /// /// Enumerable.Contains visitor. /// protected virtual FilterExpression VisitEnumerableContains(MethodCallExpression method) { if (method.Arguments.Count != 2) throw new ArgumentException("Contains method must have exactly 2 arguments"); return VisitContainsCore(method.Arguments[0], method.Arguments[1]); } /// /// Core of a 2-arg Contains(source, value) translation — shared by /// (Enumerable.Contains) and the /// MemoryExtensions.Contains span overload that C# 13 / .NET 9 binds /// array.Contains(x) to. Produces an IN-clause (value is a row property, /// source is a constant collection) or an array-contains (source is the row's /// array property). /// protected FilterExpression VisitContainsCore(Expression sourceExpression, Expression valueExpression) { // Peel conversions before looking for a property. Under `Nullable enable` on .NET 10 the // span overload of array.Contains wraps the collection twice: op_Implicit around a Convert // around the member access. Unwrapping only the op_Implicit leaves a Convert node, which is // not a MemberExpression, so both branches below missed and every `x.Tags.Contains(...)` // over a `T[]?` property threw "Unsupported Contains expression structure". sourceExpression = StripConversions(sourceExpression); valueExpression = StripConversions(valueExpression); if (IsPropertyAccess(valueExpression)) { var property = ExtractProperty(valueExpression); var values = EvaluateExpression(sourceExpression); if (values is System.Collections.IEnumerable enumerable) return InListExpression(property, enumerable); if (values == null) throw NullContainsList(sourceExpression); } else if (IsPropertyAccess(sourceExpression)) { var arrayProperty = ExtractProperty(sourceExpression); var value = EvaluateExpression(valueExpression); if (value is IRedbListItem listItem) value = listItem.Id; return new ComparisonExpression(arrayProperty, ComparisonOperator.ArrayContains, value); } throw new NotSupportedException("Unsupported Contains expression structure"); } /// /// The membership test of list.Contains(p.F). Each value is spelled as a single comparison value of the /// same kind is (a list item by its id, an enum by its name). A null in the list is dropped: [a, null] filters /// as [a], and a list of nulls only as an empty list. This is the one place the rule for a null in the list is /// decided (the owner's choice, 2026-11-19). Objects without a value for the field match neither Contains nor /// !Contains, as they match neither == nor != (write || p.F == null to include them). /// /// The list of a Contains filter is itself null: said as such, not as an unsupported expression. private static ArgumentNullException NullContainsList(Expression list) => new("list", $"The list of a Contains filter is null ('{list}'). Pass an empty list to match no object."); private static InExpression InListExpression(QueryExpressions.PropertyInfo property, System.Collections.IEnumerable list) { var raw = list.Cast().ToList(); var values = raw.Where(v => v != null).Select(v => v switch { IRedbListItem item => item.Id, Enum e => e.ToString(), _ => v }).ToList(); if (values.Count > 0 && raw.Any(v => v is IRedbListItem) && !property.Name.Contains('.')) property = property with { Name = property.Name + ".Id", Type = typeof(long) }; return new InExpression(property, values!.Cast().ToList()); } /// /// Removes Convert / ConvertChecked wrappers the compiler puts around an operand. They carry no /// meaning for us: the value is evaluated the same either way, and the property behind them is /// the one we need to name. Written as a loop because the wrappers nest. /// private static Expression StripConversions(Expression expression) { while (expression is UnaryExpression { NodeType: ExpressionType.Convert or ExpressionType.ConvertChecked } unary) { expression = unary.Operand; } return expression; } /// /// Enumerable.Any visitor. /// protected virtual FilterExpression VisitEnumerableAny(MethodCallExpression method) { // Enumerable.Any(source) — 1-arg form. Translate to: element count of source > 0, parsed as list.Count is // (the count an int, the collection its source), so the Pro builders emit array_length / json_array_length // and the facet builder the array-aware .$count modifier of the modules. It used to be PropertyFunction.Length // with no source type, the length of a text: PostgreSQL refused length(text[]), SQLite measured the JSON text // of the array (an empty or missing array counted as non-empty), and SQL Server answered !Any() with nothing. if (method.Arguments.Count == 1) { var only = method.Arguments[0]; if (!IsPropertyAccess(only)) throw new NotSupportedException("Any() must be called on a property collection"); var prop = ExtractProperty(only); var countProp = prop with { Type = typeof(int), Function = PropertyFunction.Count, FunctionSourceType = prop.Type }; return new ComparisonExpression(countProp, ComparisonOperator.GreaterThan, 0); } if (method.Arguments.Count != 2) throw new ArgumentException("Any method with predicate must have exactly 2 arguments"); var sourceExpression = method.Arguments[0]; var predicateExpression = method.Arguments[1]; if (!IsPropertyAccess(sourceExpression)) throw new NotSupportedException("Any() must be called on a property collection"); var collectionProperty = ExtractProperty(sourceExpression); // An array or list of classes: the predicate is a filter over the fields of one element. if (predicateExpression is LambdaExpression classLambda && IsCollectionOfClasses(collectionProperty.Type)) return VisitAnyOverClasses(collectionProperty, classLambda); if (predicateExpression is LambdaExpression lambda) { if (lambda.Body is BinaryExpression binaryBody) { // The form asks whether some item has that value: its comparison is built as "the array contains", so // another operator would get the answer for == (r.Value != x read as r.Value == x). if (binaryBody.NodeType != ExpressionType.Equal) throw new NotSupportedException( $"Any() over '{collectionProperty.Name}' compares an item property only with ==, not with " + $"'{binaryBody.NodeType}'. For \"no item has that value\" write !{collectionProperty.Name}.Any(r => r.X == value)."); var left = binaryBody.Left; var right = binaryBody.Right; QueryExpressions.PropertyInfo? itemProperty = null; object? value = null; if (left is MemberExpression leftMember && leftMember.Expression == lambda.Parameters[0]) { itemProperty = new QueryExpressions.PropertyInfo( leftMember.Member.Name, leftMember.Type, _isBaseFieldContext); value = EvaluateExpression(right); } else if (right is MemberExpression rightMember && rightMember.Expression == lambda.Parameters[0]) { itemProperty = new QueryExpressions.PropertyInfo( rightMember.Member.Name, rightMember.Type, _isBaseFieldContext); value = EvaluateExpression(left); } else { throw new NotSupportedException("Any() predicate must compare an item property with a value"); } if (value is IRedbListItem listItem) { value = listItem.Id; } var arrayFieldPath = $"{collectionProperty.Name}[].{itemProperty.Name}"; var arrayProperty = new QueryExpressions.PropertyInfo( arrayFieldPath, itemProperty.Type, _isBaseFieldContext); // For nested fields (like Roles[].Value), use Equal instead of ArrayContains // The path already contains [] so SQL will handle array iteration return new ComparisonExpression(arrayProperty, ComparisonOperator.Equal, value); } else { throw new NotSupportedException("Any() predicate must be a comparison expression"); } } throw new NotSupportedException("Any() must have a lambda predicate"); } /// /// True for an array or list whose element is a class stored field by field: not a text, a simple value, a list /// item or an object reference (those have their own Any forms). /// private static bool IsCollectionOfClasses(Type collectionType) { var element = collectionType.IsArray ? collectionType.GetElementType() : collectionType.IsGenericType && collectionType.GetGenericArguments().Length == 1 ? collectionType.GetGenericArguments()[0] : null; if (element == null || !element.IsClass || element == typeof(string) || element == typeof(byte[])) return false; if (typeof(IRedbListItem).IsAssignableFrom(element) || typeof(IRedbObject).IsAssignableFrom(element)) return false; return true; } /// /// p.Rows.Any(r => ...) over an array of classes: the predicate is parsed as a filter over the fields of /// the element, and its paths are placed under the collection (r.Kind becomes Rows[].Kind). The /// conditions are comparisons, null checks, Contains of a list of values, and &&, || and ! of those; every /// one is asked of the same element. A predicate that reads the outer object is refused. /// private FilterExpression VisitAnyOverClasses(QueryExpressions.PropertyInfo collection, LambdaExpression lambda) { var element = lambda.Parameters[0]; var outer = new OtherParameterFinder(element); outer.Visit(lambda.Body); if (outer.Found) throw new NotSupportedException( $"Any() over '{collection.Name}': the condition reads only the fields of the element; it reads another value of the query here."); var inner = VisitExpression(lambda.Body); var prefix = collection.Name + "[]."; return new ArrayElementAnyExpression(collection, UnderCollection(inner, prefix, collection.Name)); } private static FilterExpression UnderCollection(FilterExpression filter, string prefix, string collection) => filter switch { ComparisonExpression { LeftExpression: null, RightExpression: null } c when c.Property.Name is not ("__constant" or "__computed") => c with { Property = c.Property with { Name = prefix + c.Property.Name } }, NullCheckExpression n => n with { Property = n.Property with { Name = prefix + n.Property.Name } }, InExpression i => i with { Property = i.Property with { Name = prefix + i.Property.Name } }, LogicalExpression l => l with { Operands = l.Operands.Select(o => UnderCollection(o, prefix, collection)).ToList() }, _ => throw new NotSupportedException( $"Any() over '{collection}': a condition on a field of the element compares it with a value, checks it for null or " + "takes Contains of a list, joined with &&, || or !; this one does something else.") }; private sealed class OtherParameterFinder(ParameterExpression element) : ExpressionVisitor { public bool Found { get; private set; } protected override Expression VisitParameter(ParameterExpression node) { if (node != element) Found = true; return node; } } /// /// Collection.Contains visitor. /// protected virtual FilterExpression VisitCollectionContains(MethodCallExpression method) { if (method.Arguments.Count != 1) throw new ArgumentException("Collection Contains method must have exactly 1 argument"); var collectionExpression = method.Object!; var valueExpression = method.Arguments[0]; if (IsPropertyAccess(valueExpression)) { var property = ExtractProperty(valueExpression); var values = EvaluateExpression(collectionExpression); if (values is System.Collections.IEnumerable enumerable) return InListExpression(property, enumerable); else if (values == null) throw NullContainsList(collectionExpression); else { throw new ArgumentException("Collection expression must evaluate to IEnumerable"); } } else if (IsPropertyAccess(collectionExpression)) { var arrayProperty = ExtractProperty(collectionExpression); var value = EvaluateExpression(valueExpression); if (value is IRedbListItem listItem) value = listItem.Id; return new ComparisonExpression(arrayProperty, ComparisonOperator.ArrayContains, value); } else { throw new NotSupportedException("Unsupported Contains expression structure"); } } #endregion #region Dictionary Methods /// /// Dictionary.ContainsKey visitor. /// protected virtual FilterExpression VisitDictionaryContainsKey(MethodCallExpression method) { string dictionaryPath; if (method.Object is MemberExpression dictMember) { var (path, _) = BuildPropertyPath(dictMember); dictionaryPath = path; } else { throw new NotSupportedException(UnsupportedFieldPathMessage(method.Object!)); } var keyValue = EvaluateExpression(method.Arguments[0]); var keyType = method.Arguments[0].Type; var serializedKey = RedbKeySerializer.SerializeObject(keyValue!, keyType); var propertyPath = $"{dictionaryPath}.ContainsKey"; var property = new QueryExpressions.PropertyInfo(propertyPath, typeof(string), _isBaseFieldContext); return new ComparisonExpression(property, ComparisonOperator.Equal, serializedKey); } protected bool IsDictionaryType(Type? type) { if (type == null) return false; if (!type.IsGenericType) return false; var genericDef = type.GetGenericTypeDefinition(); return genericDef == typeof(Dictionary<,>) || genericDef == typeof(IDictionary<,>); } #endregion #region Arithmetic & Functions protected bool IsArithmeticExpression(BinaryExpression binary) { return binary.NodeType is ExpressionType.Add or ExpressionType.Subtract or ExpressionType.Multiply or ExpressionType.Divide or ExpressionType.Modulo; } protected ValueExpression CreateArithmeticExpression(BinaryExpression binary) { var op = binary.NodeType switch { ExpressionType.Add => ArithmeticOperator.Add, ExpressionType.Subtract => ArithmeticOperator.Subtract, ExpressionType.Multiply => ArithmeticOperator.Multiply, ExpressionType.Divide => ArithmeticOperator.Divide, ExpressionType.Modulo => ArithmeticOperator.Modulo, _ => throw new NotSupportedException($"Arithmetic operator {binary.NodeType} is not supported") }; var left = ExtractValueExpression(binary.Left); var right = ExtractValueExpression(binary.Right); return new ArithmeticExpression(left, op, right); } /// /// Builds a from a chain of ?? operators. /// C# parses a ?? b ?? c right-associatively as a ?? (b ?? c); this helper /// flattens that into a single n-ary node [a, b, c] so the downstream SQL emitter /// produces COALESCE(a, b, c) instead of COALESCE(a, COALESCE(b, c)). /// protected ValueExpression CreateCoalesceExpression(BinaryExpression binary) { var args = new List(); void Flatten(Expression node) { if (node is BinaryExpression be && be.NodeType == ExpressionType.Coalesce) { Flatten(be.Left); Flatten(be.Right); } else { args.Add(ExtractValueExpression(node)); } } Flatten(binary); return new CoalesceExpression(args); } /// /// Builds a from a C# ternary ?:. /// Test is parsed as a full boolean via ; /// IfTrue / IfFalse are parsed as value expressions via . /// protected ValueExpression CreateConditionalValueExpression(System.Linq.Expressions.ConditionalExpression cond) { var test = VisitExpression(cond.Test); var ifTrue = ExtractValueExpression(cond.IfTrue); var ifFalse = ExtractValueExpression(cond.IfFalse); return new ConditionalValueExpression(test, ifTrue, ifFalse); } /// /// Recursively extract ValueExpression from any Expression. /// protected ValueExpression ExtractValueExpression(Expression expression) { return expression switch { BinaryExpression binary when IsArithmeticExpression(binary) => CreateArithmeticExpression(binary), // x ?? y — Coalesce operator (binary, right-associative chained into n-ary) BinaryExpression binary when binary.NodeType == ExpressionType.Coalesce => CreateCoalesceExpression(binary), // C# ternary: cond ? a : b System.Linq.Expressions.ConditionalExpression cond => CreateConditionalValueExpression(cond), UnaryExpression unary when unary.NodeType == ExpressionType.Convert => ExtractValueExpression(unary.Operand), MethodCallExpression method when IsCustomFunctionCall(method) => CreateCustomFunctionExpression(method), MethodCallExpression method when IsProFunctionCall(method) => CreateFunctionCallExpression(method), MemberExpression member when IsDateTimePropertyAccess(member) => CreateDateTimeFunctionExpression(member), MemberExpression member when member.Member.Name == "Length" && member.Expression is MethodCallExpression innerMethod && IsProFunctionCall(innerMethod) => new FunctionCallExpression(PropertyFunction.Length, CreateFunctionCallExpression(innerMethod)), // arr.Length inside an arithmetic/function chain (ArrayLength is array-only). UnaryExpression unaryArr when unaryArr.NodeType == ExpressionType.ArrayLength && unaryArr.Operand is MemberExpression arrMember => new FunctionCallExpression( PropertyFunction.Count, new PropertyValueExpression(ExtractPropertyFromMember(arrMember))), MemberExpression member when (member.Member is System.Reflection.PropertyInfo || member.Member is System.Reflection.FieldInfo) && ReferencesLambdaParameter(member) => new PropertyValueExpression(ExtractPropertyFromMember(member)), ConstantExpression constant => new ConstantValueExpression(constant.Value, constant.Type), MemberExpression member when !ReferencesLambdaParameter(member) => new ConstantValueExpression(EvaluateExpression(member), member.Type), _ => throw new NotSupportedException($"Cannot extract ValueExpression from {expression.NodeType}: {expression}") }; } protected bool IsProFunctionCall(MethodCallExpression method) { var name = method.Method.Name; var declaringType = method.Method.DeclaringType; if (declaringType == typeof(string)) { return name is "ToLower" or "ToLowerInvariant" or "ToUpper" or "ToUpperInvariant" or "Trim" or "TrimStart" or "TrimEnd" or "Substring" or "Replace" or "IndexOf" or "PadLeft" or "PadRight"; } if (declaringType == typeof(Math)) { return name is "Abs" or "Round" or "Floor" or "Ceiling" or "Truncate" or "Sqrt" or "Sign" or "Exp" or "Log" or "Log10" or "Pow"; } if (declaringType == typeof(DateTime) || declaringType == typeof(DateTimeOffset)) { // Instance arithmetic methods AddDays/AddYears/AddMonths/AddHours/AddMinutes/AddSeconds. return name is "AddDays" or "AddYears" or "AddMonths" or "AddHours" or "AddMinutes" or "AddSeconds"; } if (declaringType == typeof(System.Text.RegularExpressions.Regex)) { // Regex.Replace(input, pattern, replacement) — static; returns string. return name == "Replace"; } return false; } protected bool IsCustomFunctionCall(MethodCallExpression method) { return method.Method.DeclaringType?.FullName == "redb.Core.Query.Sql" && method.Method.Name == "Function"; } protected ValueExpression CreateCustomFunctionExpression(MethodCallExpression method) { var funcNameExpr = method.Arguments[0]; var funcName = (string)EvaluateExpression(funcNameExpr)!; var argsExpr = method.Arguments[1]; var arguments = new List(); if (argsExpr is NewArrayExpression newArrayExpr) { foreach (var argExpr in newArrayExpr.Expressions) { arguments.Add(ExtractValueExpression(argExpr)); } } else { throw new NotSupportedException( $"Sql.Function arguments must be inline (not a variable). Got: {argsExpr.NodeType} ({argsExpr.GetType().Name})"); } return new CustomFunctionExpression(funcName, arguments); } protected ValueExpression CreateFunctionCallExpression(MethodCallExpression method) { var name = method.Method.Name; var declaringType = method.Method.DeclaringType; PropertyFunction func; ValueExpression argument; if (declaringType == typeof(string)) { // Multi-arg string functions (Substring/Replace/IndexOf/PadLeft/PadRight) // use MultiArgFunctionCallExpression and handle index translation here. if (name is "Substring" or "Replace" or "IndexOf" or "PadLeft" or "PadRight") { return CreateMultiArgFunctionCallExpression(method); } func = name switch { "ToLower" or "ToLowerInvariant" => PropertyFunction.ToLower, "ToUpper" or "ToUpperInvariant" => PropertyFunction.ToUpper, "Trim" => PropertyFunction.Trim, "TrimStart" => PropertyFunction.TrimStart, "TrimEnd" => PropertyFunction.TrimEnd, _ => throw new NotSupportedException($"String method {name} is not supported") }; argument = ExtractValueExpression(method.Object!); } else if (declaringType == typeof(Math)) { // Multi-arg Math overloads dispatch to MultiArgFunctionCallExpression // (Math is static, so method.Object is null — these are handled // separately below in CreateMultiArgFunctionCallExpression). if (name == "Pow" || name == "Log10" || (name == "Log" && method.Arguments.Count == 2) || (name == "Round" && method.Arguments.Count == 2)) { return CreateMultiArgFunctionCallExpression(method); } func = name switch { "Abs" => PropertyFunction.Abs, "Round" => PropertyFunction.Round, "Floor" => PropertyFunction.Floor, "Ceiling" => PropertyFunction.Ceiling, "Truncate" => PropertyFunction.Floor, "Sqrt" => PropertyFunction.Sqrt, "Sign" => PropertyFunction.Sign, "Exp" => PropertyFunction.Exp, "Log" => PropertyFunction.Log, // 1-arg: natural log _ => throw new NotSupportedException($"Math method {name} is not supported") }; argument = ExtractValueExpression(method.Arguments[0]); } else if (declaringType == typeof(DateTime) || declaringType == typeof(DateTimeOffset)) { // All DateTime AddX methods are 2-arg in our AST [date, n] -> dispatch to MultiArg. return CreateMultiArgFunctionCallExpression(method); } else if (declaringType == typeof(System.Text.RegularExpressions.Regex)) { // Regex.Replace -> MultiArg with 3 args (static method, no receiver). return CreateMultiArgFunctionCallExpression(method); } else { throw new NotSupportedException($"Method {declaringType?.Name}.{name} is not supported"); } return new FunctionCallExpression(func, argument); } /// /// Builds a for the multi-arg string /// functions Substring/Replace/IndexOf/PadLeft/PadRight. Performs index /// translation so the same AST works on both tiers (Free PVT and Pro): /// /// C# string.Substring(start[, length]) is 0-based; SQL SUBSTRING /// is 1-based -> the start argument is wrapped in start + 1. /// C# string.IndexOf(needle) returns -1 for not-found; SQL POSITION /// returns 0 -> the whole call is wrapped in (POSITION(...) - 1). /// /// protected ValueExpression CreateMultiArgFunctionCallExpression(MethodCallExpression method) { var name = method.Method.Name; var declaringType = method.Method.DeclaringType; // DateTime.AddX(n) — instance call: receiver is the date, single arg is the delta. if (declaringType == typeof(DateTime) || declaringType == typeof(DateTimeOffset)) { var fn = name switch { "AddDays" => PropertyFunction.AddDays, "AddYears" => PropertyFunction.AddYears, "AddMonths" => PropertyFunction.AddMonths, "AddHours" => PropertyFunction.AddHours, "AddMinutes" => PropertyFunction.AddMinutes, "AddSeconds" => PropertyFunction.AddSeconds, _ => throw new NotSupportedException($"DateTime method {name} is not supported.") }; return new MultiArgFunctionCallExpression(fn, new List { ExtractValueExpression(method.Object!), ExtractValueExpression(method.Arguments[0]), }); } // Regex.Replace(input, pattern, replacement) — static; ignore optional flags overloads. if (declaringType == typeof(System.Text.RegularExpressions.Regex) && name == "Replace") { if (method.Arguments.Count < 3) throw new NotSupportedException("Regex.Replace requires (input, pattern, replacement)."); return new MultiArgFunctionCallExpression(PropertyFunction.RegexReplace, new List { ExtractValueExpression(method.Arguments[0]), // input ExtractValueExpression(method.Arguments[1]), // pattern ExtractValueExpression(method.Arguments[2]), // replacement }); } // Math.* are static — method.Object is null. Build args directly from method.Arguments. if (declaringType == typeof(Math)) { switch (name) { case "Pow": // Math.Pow(x, y) -> POWER(x, y) return new MultiArgFunctionCallExpression(PropertyFunction.Pow, new List { ExtractValueExpression(method.Arguments[0]), ExtractValueExpression(method.Arguments[1]), }); case "Log": // C# Math.Log(value, base); PG LOG(base, value) — argument SWAP at parse time. return new MultiArgFunctionCallExpression(PropertyFunction.LogBase, new List { ExtractValueExpression(method.Arguments[1]), // base ExtractValueExpression(method.Arguments[0]), // value }); case "Log10": // Math.Log10(x) -> LOG(10, x). Synthesize base=10 constant. return new MultiArgFunctionCallExpression(PropertyFunction.LogBase, new List { new ConstantValueExpression(10.0, typeof(double)), ExtractValueExpression(method.Arguments[0]), }); case "Round": // Math.Round(value, digits) -> ROUND(value, digits). 1-arg form goes through the // single-arg FunctionCallExpression path (PropertyFunction.Round). return new MultiArgFunctionCallExpression(PropertyFunction.Round, new List { ExtractValueExpression(method.Arguments[0]), ExtractValueExpression(method.Arguments[1]), }); default: throw new NotSupportedException($"Multi-arg Math method {name} is not supported."); } } var receiver = ExtractValueExpression(method.Object!); var args = new List { receiver }; switch (name) { case "Substring": { // s.Substring(start) | s.Substring(start, length) var start = ExtractValueExpression(method.Arguments[0]); args.Add(new ArithmeticExpression(start, ArithmeticOperator.Add, new ConstantValueExpression(1, typeof(int)))); if (method.Arguments.Count == 2) args.Add(ExtractValueExpression(method.Arguments[1])); return new MultiArgFunctionCallExpression(PropertyFunction.Substring, args); } case "Replace": { // s.Replace(oldValue, newValue) — string-only overload supported if (method.Arguments.Count != 2) throw new NotSupportedException("Only string.Replace(oldValue, newValue) is supported."); args.Add(ExtractValueExpression(method.Arguments[0])); args.Add(ExtractValueExpression(method.Arguments[1])); return new MultiArgFunctionCallExpression(PropertyFunction.Replace, args); } case "IndexOf": { // s.IndexOf(needle) — wrap with `- 1` to map POSITION(1-based, 0=miss) to C# semantics. if (method.Arguments.Count != 1) throw new NotSupportedException("Only string.IndexOf(value) (single argument) is supported."); args.Add(ExtractValueExpression(method.Arguments[0])); var inner = new MultiArgFunctionCallExpression(PropertyFunction.IndexOf, args); return new ArithmeticExpression(inner, ArithmeticOperator.Subtract, new ConstantValueExpression(1, typeof(int))); } case "PadLeft": case "PadRight": { // s.PadLeft(width) | s.PadLeft(width, padChar) args.Add(ExtractValueExpression(method.Arguments[0])); if (method.Arguments.Count == 2) { // PadChar (char) — coerce to single-char string so PG LPAD/RPAD accept it. var padArg = method.Arguments[1]; if (padArg is ConstantExpression ce && ce.Value is char ch) args.Add(new ConstantValueExpression(ch.ToString(), typeof(string))); else args.Add(ExtractValueExpression(padArg)); } var fn = name == "PadLeft" ? PropertyFunction.PadLeft : PropertyFunction.PadRight; return new MultiArgFunctionCallExpression(fn, args); } default: throw new NotSupportedException($"Multi-arg string method {name} is not supported."); } } protected bool IsDateTimePropertyAccess(MemberExpression member) { var exprType = member.Expression?.Type; if (exprType != typeof(DateTime) && exprType != typeof(DateTime?) && exprType != typeof(DateTimeOffset) && exprType != typeof(DateTimeOffset?)) return false; return member.Member.Name is "Year" or "Month" or "Day" or "Hour" or "Minute" or "Second" or "DayOfWeek" or "DayOfYear"; } protected ValueExpression CreateDateTimeFunctionExpression(MemberExpression member) { var func = member.Member.Name switch { "Year" => PropertyFunction.Year, "Month" => PropertyFunction.Month, "Day" => PropertyFunction.Day, "Hour" => PropertyFunction.Hour, "Minute" => PropertyFunction.Minute, "Second" => PropertyFunction.Second, "DayOfWeek" => PropertyFunction.DayOfWeek, "DayOfYear" => PropertyFunction.DayOfYear, _ => throw new NotSupportedException($"DateTime property {member.Member.Name} is not supported") }; var argument = ExtractValueExpression(member.Expression!); return new FunctionCallExpression(func, argument); } #endregion #region Property Extraction /// /// Check if expression references lambda parameter. /// protected bool ReferencesLambdaParameter(Expression? expr) { while (expr != null) { if (expr is ParameterExpression) return true; if (expr is MemberExpression member) expr = member.Expression; else if (expr is UnaryExpression unary) expr = unary.Operand; else break; } return false; } /// /// Extract property and value from binary expression. /// protected (QueryExpressions.PropertyInfo Property, object? Value) ExtractPropertyAndValue(BinaryExpression binary) { if (IsPropertyAccess(binary.Left)) { var property = ExtractProperty(binary.Left); var value = EvaluateExpression(binary.Right); return (property, value); } else if (IsPropertyAccess(binary.Right)) { var property = ExtractProperty(binary.Right); var value = EvaluateExpression(binary.Left); return (property, value); } else { throw new NotSupportedException("At least one side of comparison must be a property access"); } } /// /// Check if expression is property access. /// protected bool IsPropertyAccess(Expression expression) { if (expression is MemberExpression member && member.Member is System.Reflection.PropertyInfo) return true; if (expression is MethodCallExpression methodCall && methodCall.Method.Name == "get_Item" && IsDictionaryType(methodCall.Object?.Type)) return true; if (TryElementByIndex(expression, out _, out _)) return true; return false; } /// /// Whether a filter reads an element of an array or a list of the queried object by its index (Tags[0] == v, /// Contacts[0].Value == v). The base parser refuses it with the field path message; redb Pro reads it. /// protected virtual bool ReadsElementsByIndex => false; /// /// An element of an array (Items[0], an ArrayIndex node) or of a list (Parts[0], get_Item with an int) /// whose collection is a field. Only when ; an element of something that is not a /// field (Items[0][1]) is not one, and the caller refuses it as before. /// private bool TryElementByIndex(Expression? expression, out MemberExpression collection, out Expression index) { collection = null!; index = null!; if (!ReadsElementsByIndex) return false; switch (expression) { case BinaryExpression { NodeType: ExpressionType.ArrayIndex, Left: MemberExpression array } arrayIndex: collection = array; index = arrayIndex.Right; return true; case MethodCallExpression { Method.Name: "get_Item", Object: MemberExpression list } call when call.Arguments.Count == 1 && call.Arguments[0].Type == typeof(int) && !IsDictionaryType(list.Type) && list.Type.GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IList<>)): collection = list; index = call.Arguments[0]; return true; default: return false; } } /// /// The path of an element by index: Items[0]. It is stored as a dictionary entry is, the index in the place /// of the key, so it is resolved and read as one. The collection is a field of the queried object itself, and at /// most one field of the element follows (): the resolver reads an entry or an element /// of a top-level field and one field of its value, and anything else used to get, and keeps, the field path /// message. The index is a constant or a value of the caller, not negative. /// private string ElementPath(MemberExpression collection, Expression index, Expression path, int fieldsAfter) { var owner = collection.Expression; while (owner is UnaryExpression { NodeType: ExpressionType.Convert or ExpressionType.ConvertChecked or ExpressionType.TypeAs } conversion) owner = conversion.Operand; // An element that is a list item or an object reference is not read by index (Statuses[0].Value): the resolver // has no field of such an element, and the refusal is this message, not a late "Failed to resolve". var elementType = collection.Type.IsArray ? collection.Type.GetElementType() : collection.Type.GetGenericArguments().FirstOrDefault(); var referenceElement = elementType != null && (typeof(IRedbListItem).IsAssignableFrom(elementType) || typeof(IRedbObject).IsAssignableFrom(elementType)); if (fieldsAfter > 1 || referenceElement || collection.Member is not System.Reflection.PropertyInfo || owner is not ParameterExpression || ReadsParameter(index)) throw new NotSupportedException(UnsupportedFieldPathMessage(path)); if (EvaluateExpression(index) is not int position) throw new NotSupportedException(UnsupportedFieldPathMessage(path)); if (position < 0) throw new NotSupportedException( $"A query cannot read '{path}': the index of an element is not negative, and {position} is."); return $"{collection.Member.Name}[{position.ToString(System.Globalization.CultureInfo.InvariantCulture)}]"; } /// /// The shapes reads as a field reference: a property, a dictionary indexer, and the /// string functions ToLower, ToUpper and Trim over one of those. Whether the path inside is a chain of fields of /// the queried object is ExtractProperty's check, which refuses it otherwise. /// protected bool IsPropertyPathShape(Expression expression) => expression switch { MemberExpression { Member: System.Reflection.PropertyInfo } => true, MethodCallExpression { Method.Name: "get_Item" } call when IsDictionaryType(call.Object?.Type) => true, _ when TryElementByIndex(expression, out _, out _) => true, MethodCallExpression { Object: { } inner } call when call.Method.DeclaringType == typeof(string) && call.Method.Name is "ToLower" or "ToLowerInvariant" or "ToUpper" or "ToUpperInvariant" or "Trim" or "TrimStart" or "TrimEnd" => IsPropertyPathShape(inner), _ => false }; /// /// Extract property info from expression. /// Supports: property access, Dictionary indexer, string functions (ToLower, ToUpper, Trim). /// protected QueryExpressions.PropertyInfo ExtractProperty(Expression expression) { if (expression is MethodCallExpression methodCall && methodCall.Method.Name == "get_Item" && IsDictionaryType(methodCall.Object?.Type)) { return ExtractDictionaryIndexerProperty(methodCall); } // An element of an array or a list by index, itself the value: Tags[0] == "x". if (TryElementByIndex(expression, out var elementCollection, out var elementIndex)) return new QueryExpressions.PropertyInfo( ElementPath(elementCollection, elementIndex, expression, fieldsAfter: 0), expression.Type, _isBaseFieldContext); // Support chain calls: property.ToLower(), property.ToUpper(), property.Trim() if (expression is MethodCallExpression stringMethodCall && stringMethodCall.Method.DeclaringType == typeof(string) && stringMethodCall.Object != null) { var func = stringMethodCall.Method.Name switch { "ToLower" or "ToLowerInvariant" => PropertyFunction.ToLower, "ToUpper" or "ToUpperInvariant" => PropertyFunction.ToUpper, "Trim" => PropertyFunction.Trim, "TrimStart" => PropertyFunction.TrimStart, "TrimEnd" => PropertyFunction.TrimEnd, _ => (PropertyFunction?)null }; if (func.HasValue) { // Recursively extract property from inner expression var innerProperty = ExtractProperty(stringMethodCall.Object); return new QueryExpressions.PropertyInfo(innerProperty.Name, typeof(string), innerProperty.IsBaseField, func.Value); } } if (expression is MemberExpression member && member.Member is System.Reflection.PropertyInfo propInfo) { var (fullPath, function) = BuildPropertyPath(member); Type? sourceType = (function == PropertyFunction.Length || function == PropertyFunction.Count) ? member.Expression?.Type : null; return new QueryExpressions.PropertyInfo(fullPath, propInfo.PropertyType, _isBaseFieldContext, function, sourceType); } throw new NotSupportedException(UnsupportedFieldPathMessage(expression)); } /// /// Extract property from Dictionary indexer. /// protected QueryExpressions.PropertyInfo ExtractDictionaryIndexerProperty(MethodCallExpression methodCall) { string dictionaryPath; if (methodCall.Object is MemberExpression dictMember) { var (path, _) = BuildPropertyPath(dictMember); dictionaryPath = path; } else { throw new NotSupportedException(UnsupportedFieldPathMessage(methodCall.Object!)); } var keyValue = EvaluateExpression(methodCall.Arguments[0]); var keyType = methodCall.Arguments[0].Type; var keyString = RedbKeySerializer.SerializeObject(keyValue!, keyType); var fullPath = $"{dictionaryPath}[{keyString}]"; var dictType = methodCall.Object!.Type; var valueType = dictType.GetGenericArguments()[1]; return new QueryExpressions.PropertyInfo(fullPath, valueType, _isBaseFieldContext); } /// /// Extract PropertyInfo from MemberExpression. /// protected QueryExpressions.PropertyInfo ExtractPropertyFromMember(MemberExpression member) { var memberType = member.Member switch { System.Reflection.PropertyInfo p => p.PropertyType, System.Reflection.FieldInfo f => f.FieldType, _ => typeof(object) }; var (fullPath, function) = BuildPropertyPath(member); Type? sourceType = (function == PropertyFunction.Length || function == PropertyFunction.Count) ? member.Expression?.Type : null; return new QueryExpressions.PropertyInfo(fullPath, memberType, _isBaseFieldContext, function, sourceType); } /// /// A field path of a filter starts at the object of the query (a lambda parameter, also behind a cast). Anything /// else at the start - an array or list element by index, a method call, a value of the caller - is refused: the /// walk used to stop there and keep the tail, so Items[0].Name was read as the field Name of the object itself. /// private static void EnsurePathStartsAtQueryObject(Expression? start, Expression path) { var root = start; while (root is UnaryExpression { NodeType: ExpressionType.Convert or ExpressionType.ConvertChecked or ExpressionType.TypeAs } conversion) root = conversion.Operand; if (root is ParameterExpression) return; throw new NotSupportedException(UnsupportedFieldPathMessage(path)); } /// The one wording for a path that is not a chain of fields of the queried object, see . internal static string UnsupportedFieldPathMessage(Expression path) => FieldPathRefusal.Message(path.ToString()); /// /// Build property path from member expression chain. /// Handles nested properties, Length, Count, Dictionary indexers. /// protected (string Path, PropertyFunction? Function) BuildPropertyPath(MemberExpression memberExpression) { var pathParts = new List(); var current = memberExpression; PropertyFunction? function = null; while (current != null && current.Member is System.Reflection.PropertyInfo) { var memberName = current.Member.Name; // .Value/.HasValue on Nullable are C# accessors, not fields: the path is the one of the nullable they are // read from (a field, or a dictionary entry: Scores["a"].Value, whose path used to come out empty). if ((memberName == "Value" || memberName == "HasValue") && IsNullableAccessor(current)) { // the accessor adds no part } // Length and Count of a string, an array or a collection are functions; a field of the object of that name is // a field. Every member called Count or Length used to be taken for the function, and a filter on such a // field failed. else if (memberName == "Length" && IsSizeOf(current, collection: false)) { function = PropertyFunction.Length; } else if (memberName == "Count" && IsSizeOf(current, collection: true)) { function = PropertyFunction.Count; } else { pathParts.Add(memberName); } if (current.Expression is MemberExpression parentMember) { current = parentMember; } else if (current.Expression is MethodCallExpression methodCall && methodCall.Method.Name == "get_Item" && IsDictionaryType(methodCall.Object?.Type)) { string dictionaryPath; if (methodCall.Object is MemberExpression dictMember) { var (dictPath, _) = BuildPropertyPath(dictMember); dictionaryPath = dictPath; } else { // Not a field of the queried object: a made-up path would reach the database and fail there. throw new NotSupportedException(UnsupportedFieldPathMessage(methodCall.Object!)); } // The key as it is stored, as for an entry read without a field (ExtractDictionaryIndexerProperty): a // tuple, a bool, a DateTime or a double written by ToString() found no entry. var keyValue = EvaluateExpression(methodCall.Arguments[0]); var keyString = RedbKeySerializer.SerializeObject(keyValue!, methodCall.Arguments[0].Type); pathParts.Add($"{dictionaryPath}[{keyString}]"); break; } else if (TryElementByIndex(current.Expression, out var collection, out var index)) { // A field of an element by index: Contacts[0].Value. The parts so far are the fields after the element. pathParts.Add(ElementPath(collection, index, memberExpression, fieldsAfter: pathParts.Count)); break; } else { // The start of the chain. It is the object of the query, or the part of the path before it would be lost. EnsurePathStartsAtQueryObject(current.Expression, memberExpression); break; } } // The walk left the loop on a member that is not a property (a field: a captured variable of the caller). if (current != null && current.Member is not System.Reflection.PropertyInfo) EnsurePathStartsAtQueryObject(current, memberExpression); pathParts.Reverse(); var fullPath = string.Join(".", pathParts); // Check nesting depth (FREE version limits to 2 levels) CheckPathDepth(pathParts.Count, fullPath); return (fullPath, function); } /// /// Checks if member expression is a Nullable<T> accessor (.Value or .HasValue). /// /// /// Whether a Length ( false) or Count member is the size of what it is read on: Length /// of a string or an array, Count of a collection. Not when the member is a field of a class of the model. /// private static bool IsSizeOf(MemberExpression member, bool collection) { var owner = member.Expression?.Type; if (owner == null) return false; if (!collection) return owner == typeof(string) || owner.IsArray; return owner != typeof(string) && typeof(System.Collections.IEnumerable).IsAssignableFrom(owner); } private static bool IsNullableAccessor(MemberExpression member) { var declaringType = member.Member.DeclaringType; return declaringType != null && declaringType.IsGenericType && declaringType.GetGenericTypeDefinition() == typeof(Nullable<>); } /// /// Evaluate expression to get constant value. /// protected object? EvaluateExpression(Expression expression) { if (expression is ConstantExpression constant) { return constant.Value; } var lambda = Expression.Lambda(expression); var compiled = lambda.Compile(); return compiled.DynamicInvoke(); } #endregion } Path: redb/redb.Core/Query/Parsing/FilterExpressionParser.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/Parsing/FilterExpressionParser.cs ---- namespace redb.Core.Query.Parsing; /// /// OpenSource implementation of FilterExpressionParser. /// All parsing logic is inherited from BaseFilterExpressionParser; no /// artificial license-based gates are applied. /// public class FilterExpressionParser : BaseFilterExpressionParser { } Path: redb/redb.Core/Query/Projection/ProjectionFieldExtractor.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/Projection/ProjectionFieldExtractor.cs ---- using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using redb.Core.Query.Aggregation; namespace redb.Core.Query.Projection; /// /// Extracts structure_ids from Select expression to optimize _values loading. /// SUPPORTS: simple fields, Class fields, arrays, nested arrays (graph of any depth) /// public class ProjectionFieldExtractor { /// /// Extracts HashSet of structure_ids for optimized BULK SELECT. /// /// /// Three different answers, and the caller must not mix them up: /// null - the selector could not be reduced to a list of fields (a node was not recognized, the /// object or its Props is used whole, a field is unknown to the scheme): load everything; /// an empty set - the selector was read completely and touches no Props field (base fields /// only): nothing has to be loaded; /// a non-empty set - exactly these structures are read. /// public HashSet? ExtractStructureIds( IRedbScheme scheme, Expression, TResult>> selector) where TProps : class, new() { try { var result = new HashSet(); var paths = ExtractFieldPaths(selector.Body, selector.Parameters[0]); foreach (var path in paths) { // A member of Props the scheme does not know is not a stored field: a computed // property, most likely, reading fields this method cannot see. if (!AddStructureIdsForPath(scheme, path, result)) return null; } return result; } catch (NotSupportedException) { // Явный сигнал «узел не разобран» из CollectFieldPaths/CollectBindings - откат на // полную загрузку. Ловим ТОЛЬКО его: любая другая ошибка - баг экстрактора и обязана // быть громкой (решение владельца 2026-09-03: никаких глухих catch). return null; } } /// /// Whether the selector was read completely and touches no Props field (base fields only). It is the empty-set answer /// of , which needs no scheme: such a projection reads no value row. /// public bool ReadsNoPropsField(Expression, TResult>> selector) where TProps : class, new() { try { return ExtractFieldPaths(selector.Body, selector.Parameters[0]).Count == 0; } catch (NotSupportedException) { return false; } } /// /// Extracts text field paths for SQL function search_objects_with_projection_by_paths. /// Format: ["Name", "AddressBook[home].City", "Items[0].Price"] /// /// /// List of text paths or null (if parsing failed) /// public List? ExtractFieldPathStrings( Expression, TResult>> selector) where TProps : class, new() { try { var paths = ExtractFieldPaths(selector.Body, selector.Parameters[0]); if (paths.Count == 0) return null; var result = paths .Where(p => p.Segments.Count > 0) .Select(p => p.FullPath) .Distinct() .ToList(); return result.Count > 0 ? result : null; } catch (NotSupportedException) { // Тот же явный fail-safe, что и в ExtractStructureIds; прочие ошибки - громкие. return null; } } /// /// Checks if expression contains aggregation calls (Agg.Sum, etc.) /// public bool HasAggregations( Expression, TResult>> selector) where TProps : class, new() { return ContainsAggCall(selector.Body); } /// /// Extracts information about requested aggregations /// public List ExtractAggregations( Expression, TResult>> selector) where TProps : class, new() { var result = new List(); CollectAggregations(selector.Body, result); return result; } #region Private Methods - Path Extraction /// /// Extracts all field paths from expression /// /// Expression to read. /// /// The selector's own parameter (the object). With it the walk can tell the object read whole /// (Map(o), new { O = o }, o.Props) from a field of it, and throws /// NotSupportedException for the former: such a selector needs every field. Null where there is /// no such parameter (arguments of aggregates). /// private List ExtractFieldPaths(Expression expression, ParameterExpression? source) { var paths = new List(); CollectFieldPaths(expression, paths, source); return paths; } /// /// Recursively collects field paths from expression. /// FAIL-SAFE contract (ревью 2026-09-03, S-5): каждый вид узла либо явно разобран, либо /// метод бросает NotSupportedException - и публичные Extract* через свой try/catch отдают /// null, что означает «грузим объект целиком». Раньше неизвестный узел молча давал ноль /// путей из поддерева: при ЧАСТИЧНОМ разборе лямбды поле молча не загружалось и проекция /// отдавала default вместо значения. /// private void CollectFieldPaths(Expression expression, List paths, ParameterExpression? source) { switch (expression) { case NewExpression newExpr: foreach (var arg in newExpr.Arguments) { CollectFieldPaths(arg, paths, source); } break; case MemberInitExpression initExpr: CollectFieldPaths(initExpr.NewExpression, paths, source); CollectBindings(initExpr.Bindings, paths, source); break; case MemberExpression memberExpr: CollectFromMemberChain(memberExpr, paths, source); break; case MethodCallExpression methodExpr: CollectFromMethodCall(methodExpr, paths, source); break; case UnaryExpression unaryExpr: CollectFieldPaths(unaryExpr.Operand, paths, source); break; case ConditionalExpression condExpr: // S-5b: условие тернарника раньше НЕ сканировалось - поле из условия молча не // загружалось и ветка выбиралась по default-значению. CollectFieldPaths(condExpr.Test, paths, source); CollectFieldPaths(condExpr.IfTrue, paths, source); CollectFieldPaths(condExpr.IfFalse, paths, source); break; case BinaryExpression binaryExpr: // o == null and o.Props != null read no field: the usual guard in front of a field // must not turn the whole selector into a full load. if (IsNullCheckOfSource(binaryExpr, source)) break; CollectFieldPaths(binaryExpr.Left, paths, source); CollectFieldPaths(binaryExpr.Right, paths, source); break; case LambdaExpression lambdaExpr: CollectFieldPaths(lambdaExpr.Body, paths, source); break; case NewArrayExpression newArrayExpr: foreach (var el in newArrayExpr.Expressions) CollectFieldPaths(el, paths, source); break; case ListInitExpression listInitExpr: CollectFieldPaths(listInitExpr.NewExpression, paths, source); foreach (var init in listInitExpr.Initializers) foreach (var arg in init.Arguments) CollectFieldPaths(arg, paths, source); break; case InvocationExpression invocationExpr: CollectFieldPaths(invocationExpr.Expression, paths, source); foreach (var arg in invocationExpr.Arguments) CollectFieldPaths(arg, paths, source); break; case TypeBinaryExpression typeBinaryExpr: CollectFieldPaths(typeBinaryExpr.Expression, paths, source); break; case IndexExpression indexExpr: if (indexExpr.Object != null) CollectFieldPaths(indexExpr.Object, paths, source); foreach (var arg in indexExpr.Arguments) CollectFieldPaths(arg, paths, source); break; case ParameterExpression parameterExpr: // The object itself handed on (Map(o), new { O = o }): whatever receives it may read // any field. Parameters of inner lambdas are plain leaves. if (source != null && parameterExpr == source) throw new NotSupportedException( "ProjectionFieldExtractor: the object is used whole - full load."); break; case ConstantExpression: case DefaultExpression: break; // листья без полей default: throw new NotSupportedException( $"ProjectionFieldExtractor: unrecognized expression node {expression.NodeType} " + "- falling back to full load (fail-safe)."); } } /// /// Reads a member chain (a.b.c, indexers included) by what it hangs on. /// On the selector's parameter it is a field of the object: a Props path is recorded, a base /// field needs nothing, Props taken whole or a computed property of Props means a full load. /// On anything else that is an expression of its own - a call, ??, a conditional, a cast - /// that expression is read in turn: (o.Props.A ?? "").Length reads A, and before this /// method existed the chain simply ended there and A was never loaded. /// private void CollectFromMemberChain(MemberExpression memberExpr, List paths, ParameterExpression? source) { // Same walk as ExtractMemberPath: members and indexers down to whatever carries them. var members = new List(); Expression? root = memberExpr; while (true) { if (root is MemberExpression member) { members.Insert(0, member.Member); root = member.Expression; } else if (root is MethodCallExpression { Method.Name: "get_Item", Object: not null } indexer) { // The key of an indexer may itself read a field: Dict[o.Props.Key]. foreach (var arg in indexer.Arguments) CollectFieldPaths(arg, paths, source); root = indexer.Object; } else { break; } } // A cast of the object changes nothing about which field is read: ((IRedbObject)o).Name. var carrier = root; while (carrier is UnaryExpression { NodeType: ExpressionType.Convert or ExpressionType.ConvertChecked or ExpressionType.TypeAs } cast) carrier = cast.Operand; switch (carrier) { case null: // static member case ConstantExpression: // captured variable return; case ParameterExpression parameter when source == null || parameter == source: var propsIndex = members.FindIndex(m => m.Name == "Props"); if (propsIndex < 0) return; // base field of the object if (source != null) { if (propsIndex == members.Count - 1) throw new NotSupportedException( "ProjectionFieldExtractor: Props is used whole - full load."); // A property without a setter is not stored; what it computes from is unknown here. if (members[propsIndex + 1] is PropertyInfo { CanWrite: false }) throw new NotSupportedException( $"ProjectionFieldExtractor: {members[propsIndex + 1].Name} is a computed property - full load."); // Behind a cast ExtractMemberPath cannot follow the chain; rare enough to load everything. if (!ReferenceEquals(carrier, root)) throw new NotSupportedException( "ProjectionFieldExtractor: Props read through a cast of the object - full load."); } var path = ExtractMemberPath(memberExpr); if (path != null) paths.Add(path); return; case ParameterExpression: return; // parameter of an inner lambda: its collection is already recorded with all children default: CollectFieldPaths(root!, paths, source); return; } } /// /// True for a comparison of the object or of its Props with null. /// private static bool IsNullCheckOfSource(BinaryExpression binaryExpr, ParameterExpression? source) { if (source == null || binaryExpr.NodeType is not (ExpressionType.Equal or ExpressionType.NotEqual)) return false; return (IsNullConstant(binaryExpr.Right) && IsSourceOrItsProps(binaryExpr.Left)) || (IsNullConstant(binaryExpr.Left) && IsSourceOrItsProps(binaryExpr.Right)); static Expression StripCasts(Expression e) { while (e is UnaryExpression { NodeType: ExpressionType.Convert or ExpressionType.ConvertChecked or ExpressionType.TypeAs } cast) e = cast.Operand; return e; } static bool IsNullConstant(Expression e) => StripCasts(e) is ConstantExpression { Value: null }; bool IsSourceOrItsProps(Expression e) { e = StripCasts(e); if (e == source) return true; return e is MemberExpression { Member.Name: "Props" } member && StripCasts(member.Expression!) == source; } } /// /// Разбор всех видов member-биндингов, включая вложенные объектные инициализаторы /// (MemberMemberBinding: new Dto { Sub = { X = p.Props.N } }) и списковые (MemberListBinding). /// private void CollectBindings(System.Collections.ObjectModel.ReadOnlyCollection bindings, List paths, ParameterExpression? source) { foreach (var binding in bindings) { switch (binding) { case MemberAssignment assignment: CollectFieldPaths(assignment.Expression, paths, source); break; case MemberMemberBinding nested: CollectBindings(nested.Bindings, paths, source); break; case MemberListBinding list: foreach (var init in list.Initializers) foreach (var arg in init.Arguments) CollectFieldPaths(arg, paths, source); break; default: throw new NotSupportedException( $"ProjectionFieldExtractor: unrecognized member binding {binding.BindingType}."); } } } /// /// Extracts path from MemberExpression (x.Props.Customer.Name → ["Customer", "Name"]) /// Supports Dictionary indexer: x.Props.AddressBook["home"].City → ["AddressBook[home]", "City"] /// private FieldPathInfo? ExtractMemberPath(MemberExpression memberExpr) { var segments = new List(); string? dictKey = null; int dictKeyInsertPosition = -1; Expression? current = memberExpr; while (current != null) { switch (current) { case MemberExpression member: segments.Insert(0, member.Member.Name); current = member.Expression; break; case MethodCallExpression indexerCall when indexerCall.Method.Name == "get_Item": // Dictionary indexer: AddressBook["home"] if (indexerCall.Arguments.Count > 0 && indexerCall.Arguments[0] is ConstantExpression keyConst) { dictKey = keyConst.Value?.ToString(); // Remember position where key needs to be inserted (after processing Object) dictKeyInsertPosition = segments.Count; } current = indexerCall.Object; break; default: current = null; break; } } // Check that path starts with Props var propsIndex = segments.FindIndex(s => s == "Props"); if (propsIndex < 0) return null; // Take segments after Props var propsSegments = segments.Skip(propsIndex + 1).ToList(); if (propsSegments.Count == 0) return null; // If there's a dictionary key, add it to the appropriate segment // x.Props.AddressBook["home"].City → segments = ["Props", "AddressBook", "City"] // dictKeyInsertPosition shows how many segments were AFTER indexer (in this case 1 = "City") // So key should be added to segment at index (propsSegments.Count - dictKeyInsertPosition - 1) if (dictKey != null && propsSegments.Count > 0) { // Index of segment to add key to int targetIdx = propsSegments.Count - dictKeyInsertPosition - 1; if (targetIdx >= 0 && targetIdx < propsSegments.Count) { propsSegments[targetIdx] = $"{propsSegments[targetIdx]}[{dictKey}]"; } else if (propsSegments.Count > 0) { // Fallback: add to first segment propsSegments[0] = $"{propsSegments[0]}[{dictKey}]"; } } return new FieldPathInfo { Segments = propsSegments, IsArray = false, DictKey = dictKey }; } /// /// Processes method calls: Select, Agg.Sum, Dictionary indexer, etc. /// private void CollectFromMethodCall(MethodCallExpression methodExpr, List paths, ParameterExpression? source) { var methodName = methodExpr.Method.Name; var declaringType = methodExpr.Method.DeclaringType; // Dictionary indexer: x.Props.AddressBook["home"] or x.Props.AddressBook["home"].City if (methodName == "get_Item" && declaringType != null && declaringType.IsGenericType) { var genericDef = declaringType.GetGenericTypeDefinition(); if (genericDef == typeof(Dictionary<,>) || genericDef == typeof(IDictionary<,>)) { var dictPath = ExtractDictionaryIndexerPath(methodExpr); if (dictPath != null) { paths.Add(dictPath); } return; } } // Agg.Sum, Agg.Average, etc. if (declaringType == typeof(Agg)) { foreach (var arg in methodExpr.Arguments) { CollectFieldPaths(arg, paths, source); } return; } // LINQ Select: x.Props.Items.Select(i => i.Price) if (methodName == "Select" && methodExpr.Arguments.Count >= 1) { // Base collection CollectFieldPaths(methodExpr.Arguments[0], paths, source); // Lambda inside Select if (methodExpr.Arguments.Count >= 2 && methodExpr.Arguments[1] is LambdaExpression lambda) { CollectFieldPaths(lambda.Body, paths, source); } return; } // LINQ ToList if (methodName == "ToList" && methodExpr.Arguments.Count >= 1) { CollectFieldPaths(methodExpr.Arguments[0], paths, source); return; } // Extension methods (FirstOrDefault, etc.) if (methodExpr.Object != null) { CollectFieldPaths(methodExpr.Object, paths, source); } foreach (var arg in methodExpr.Arguments) { CollectFieldPaths(arg, paths, source); } } /// /// Extracts path from Dictionary indexer expression: x.Props.AddressBook["home"].City /// private FieldPathInfo? ExtractDictionaryIndexerPath(MethodCallExpression indexerExpr) { var segments = new List(); string? dictKey = null; // Extract dictionary key if (indexerExpr.Arguments.Count > 0 && indexerExpr.Arguments[0] is ConstantExpression keyConst) { dictKey = keyConst.Value?.ToString(); } // Recursively extract path to dictionary (x.Props.AddressBook) Expression? current = indexerExpr.Object; while (current != null) { switch (current) { case MemberExpression member: segments.Insert(0, member.Member.Name); current = member.Expression; break; case MethodCallExpression nestedIndexer when nestedIndexer.Method.Name == "get_Item": // Nested Dictionary indexer - not supported yet current = nestedIndexer.Object; break; default: current = null; break; } } // Check that path starts with Props var propsIndex = segments.FindIndex(s => s == "Props"); if (propsIndex < 0) return null; // Take segments after Props var propsSegments = segments.Skip(propsIndex + 1).ToList(); if (propsSegments.Count == 0) return null; // Add key to dictionary name: AddressBook -> AddressBook[home] if (dictKey != null && propsSegments.Count > 0) { propsSegments[propsSegments.Count - 1] = $"{propsSegments[propsSegments.Count - 1]}[{dictKey}]"; } return new FieldPathInfo { Segments = propsSegments, IsArray = false, DictKey = dictKey }; } #endregion #region Private Methods - Structure IDs /// /// Adds structure_ids for path considering NESTED arrays /// /// /// False when the first segment is not a structure of the scheme. Deeper segments may well be /// missing: Name.Length or Date.Value.Year read a member of a loaded value, not a field. /// private bool AddStructureIdsForPath(IRedbScheme scheme, FieldPathInfo pathInfo, HashSet result) { long? parentId = null; foreach (var segment in pathInfo.Segments) { var cleanName = CleanSegmentName(segment); var structure = scheme.Structures .FirstOrDefault(s => s.Name == cleanName && s.IdParent == parentId); if (structure == null) return parentId != null; result.Add(structure.Id); // KEY LOGIC: For any Class/Array add ALL children RECURSIVELY if (structure.CollectionType != null || IsClassField(scheme, structure)) { AddAllChildStructuresRecursive(scheme, structure.Id, result); } parentId = structure.Id; } return true; } /// /// RECURSIVELY adds all child structures at ANY DEPTH /// private void AddAllChildStructuresRecursive(IRedbScheme scheme, long parentId, HashSet result) { var children = scheme.Structures.Where(s => s.IdParent == parentId); foreach (var child in children) { result.Add(child.Id); // Recursion for nested arrays and Class inside arrays AddAllChildStructuresRecursive(scheme, child.Id, result); } } /// /// Cleans segment name from [] and indices /// private string CleanSegmentName(string segment) { var bracketIndex = segment.IndexOf('['); return bracketIndex >= 0 ? segment.Substring(0, bracketIndex) : segment; } /// /// Checks if structure is a Class field (has child structures) /// private bool IsClassField(IRedbScheme scheme, IRedbStructure structure) { // Class field = has child structures and is not a collection if (structure.CollectionType != null) return false; return scheme.Structures.Any(s => s.IdParent == structure.Id); } #endregion #region Private Methods - Aggregation Detection /// /// Checks if expression contains Agg.* calls /// private bool ContainsAggCall(Expression expression) { switch (expression) { case MethodCallExpression methodExpr: if (methodExpr.Method.DeclaringType == typeof(Agg)) return true; return methodExpr.Arguments.Any(ContainsAggCall) || (methodExpr.Object != null && ContainsAggCall(methodExpr.Object)); case NewExpression newExpr: return newExpr.Arguments.Any(ContainsAggCall); case MemberInitExpression initExpr: return initExpr.Bindings.OfType() .Any(b => ContainsAggCall(b.Expression)); case UnaryExpression unaryExpr: return ContainsAggCall(unaryExpr.Operand); case BinaryExpression binaryExpr: return ContainsAggCall(binaryExpr.Left) || ContainsAggCall(binaryExpr.Right); case LambdaExpression lambdaExpr: return ContainsAggCall(lambdaExpr.Body); default: return false; } } /// /// Collects aggregation information /// private void CollectAggregations(Expression expression, List result) { switch (expression) { case MethodCallExpression methodExpr when methodExpr.Method.DeclaringType == typeof(Agg): var aggInfo = new AggregationInfo { Function = ParseAggFunction(methodExpr.Method.Name), FieldPaths = new List() }; foreach (var arg in methodExpr.Arguments) { var argPaths = ExtractFieldPaths(arg, source: null); aggInfo.FieldPaths.AddRange(argPaths); } result.Add(aggInfo); break; case NewExpression newExpr: foreach (var arg in newExpr.Arguments) CollectAggregations(arg, result); break; case MemberInitExpression initExpr: foreach (var binding in initExpr.Bindings.OfType()) CollectAggregations(binding.Expression, result); break; case UnaryExpression unaryExpr: CollectAggregations(unaryExpr.Operand, result); break; case BinaryExpression binaryExpr: CollectAggregations(binaryExpr.Left, result); CollectAggregations(binaryExpr.Right, result); break; } } private AggregateFunction ParseAggFunction(string methodName) { return methodName switch { "Sum" => AggregateFunction.Sum, "Average" => AggregateFunction.Average, "Min" => AggregateFunction.Min, "Max" => AggregateFunction.Max, "Count" => AggregateFunction.Count, _ => throw new NotSupportedException($"Unknown aggregation: {methodName}") }; } #endregion } /// /// Field path information /// public record FieldPathInfo { /// Path segments: ["Contacts", "Email"] or ["AddressBook[home]", "City"] public List Segments { get; init; } = new(); /// Is array? public bool IsArray { get; init; } /// Array element index (for Tags[0]) public int? ArrayIndex { get; init; } /// Dictionary key (for AddressBook["home"]) public string? DictKey { get; init; } /// Full path as string public string FullPath => string.Join(".", Segments); } /// /// Aggregation information /// public record AggregationInfo { public AggregateFunction Function { get; init; } public List FieldPaths { get; init; } = new(); } Path: redb/redb.Core/Query/QueryContext.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/QueryContext.cs ---- using System.Collections.Generic; using redb.Core.Query.QueryExpressions; namespace redb.Core.Query; /// /// Query context - contains all information about LINQ query /// public class QueryContext where TProps : class, new() { public long SchemeId { get; init; } public long? UserId { get; init; } public bool CheckPermissions { get; init; } // SYNC WITH RUSLAN VERSION: Add tree query support public long? ParentId { get; init; } // For single parent public long[]? ParentIds { get; set; } // For batch operations public int? MaxDepth { get; init; } // Maximum search depth public FilterExpression? Filter { get; set; } public List Orderings { get; set; } = new(); /// /// DistinctBy / DistinctByRedb: the ordering by the key goes first, once, in the direction the query gave it /// (ascending when it gave none). DISTINCT ON needs the key first, and the providers keep one row per key in that /// order. The key used to be inserted ascending in front of the query's own ordering by it, so /// OrderByDescending(key).DistinctBy(key) held both: the Free providers took the first and came back ascending. /// internal void PutDistinctKeyFirst(OrderingExpression key) { bool SameKey(OrderingExpression o) => !o.HasExpression && o.Property.IsBaseField == key.Property.IsBaseField && o.Property.Name == key.Property.Name; var given = Orderings.LastOrDefault(SameKey); Orderings.RemoveAll(SameKey); Orderings.Insert(0, given ?? key); } public int? Limit { get; set; } public int? Offset { get; set; } public bool IsDistinct { get; set; } /// /// DISTINCT by base IRedbObject fields (Name, ValueLong, ParentId, etc.) excluding Id. /// Used for finding duplicates by base fields. /// public bool IsDistinctRedb { get; set; } /// /// Field for DISTINCT ON (field) - one object per each unique field value /// public OrderingExpression? DistinctByField { get; set; } /// /// true = DistinctByField is a base IRedbObject field /// false = DistinctByField is a Props field /// public bool DistinctByIsBaseField { get; set; } public int? MaxRecursionDepth { get; set; } /// /// NEW FLAG: Indicates that query should return empty result /// Used for Where(x => false) and similar cases /// public bool IsEmpty { get; set; } /// /// V4 (LAZY Л2): per-query override of EnableLazyReferences. null = use the global /// option; the executor toggles the session flag of the context's connection around the /// query when the override differs from it. /// public bool? LazyReferences { get; set; } /// /// PROJECTION: Structure IDs for optimized Props loading /// null = load ALL Props fields /// HashSet = load ONLY specified structure_ids /// public HashSet? ProjectedStructureIds { get; set; } /// /// PROJECTION: Text field paths for SQL function search_objects_with_projection_by_paths /// Format: ["Name", "AddressBook[home].City", "Items[0].Price"] /// Used instead of ProjectedStructureIds for human-readable queries /// public List? ProjectedFieldPaths { get; set; } /// /// PROJECTION: Skip ALL Props post-processing in MaterializeResultsFromJson. /// When true, neither LoadPropsForManyAsync (eager) nor lazy loader setup will run. /// Used by projections: SQL projection function already returns partial Props in JSON, /// deserialized via Props setter. Re-loading would overwrite them with full object data. /// public bool SkipPropsLoading { get; set; } /// /// PROJECTION: the selector was read completely and touches no Props field (base fields only), /// so no Props has to be loaded at all. Not the same as being /// null, which means "load every field". A provider that does not know this flag loads everything, /// which is slower and still correct. /// public bool ProjectionReadsNoProps { get; set; } /// /// Maximum depth for loading nested RedbObject in Props. /// Controls recursion when Props contain references to other RedbObjects via _values._Object. /// null = use global DefaultMaxTreeDepth from config. /// public int? PropsDepth { get; set; } public QueryContext(long schemeId, long? userId = null, bool checkPermissions = false, long? parentId = null, int? maxDepth = null) { SchemeId = schemeId; UserId = userId; CheckPermissions = checkPermissions; ParentId = parentId; // SYNC: add initialization MaxDepth = maxDepth; // SYNC: add initialization } /// /// Create a copy of context /// public QueryContext Clone() { return new QueryContext(SchemeId, UserId, CheckPermissions, ParentId, 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 LazyReferences = LazyReferences, ProjectedStructureIds = ProjectedStructureIds, ProjectedFieldPaths = ProjectedFieldPaths, SkipPropsLoading = SkipPropsLoading, ProjectionReadsNoProps = ProjectionReadsNoProps, PropsDepth = PropsDepth }; } } Path: redb/redb.Core/Query/QueryExpressions/FilterExpression.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/QueryExpressions/FilterExpression.cs ---- using System; using System.Collections.Generic; namespace redb.Core.Query.QueryExpressions; /// /// Base class for filter expressions /// public abstract record FilterExpression; #region Value Expressions (Pro: arithmetic and functions) /// /// Base class for value expressions (Pro version) /// Used for arithmetic, functions and complex expressions /// public abstract record ValueExpression; /// /// Reference to object property /// public record PropertyValueExpression(PropertyInfo Property) : ValueExpression; /// /// Constant value /// public record ConstantValueExpression(object? Value, Type Type) : ValueExpression; /// /// Arithmetic expression (Pro Only) /// Examples: p.Price * 2, p.Stock - p.Reserved /// public record ArithmeticExpression( ValueExpression Left, ArithmeticOperator Operator, ValueExpression Right ) : ValueExpression; /// /// Function call on value (Pro Only) /// Examples: LOWER(p.Name), EXTRACT(YEAR FROM p.Date) /// public record FunctionCallExpression( PropertyFunction Function, ValueExpression Argument ) : ValueExpression; /// /// Multi-argument function call (Pro Only). /// Used for the string functions Substring, Replace, IndexOf, /// PadLeft, PadRight where the SQL counterpart accepts 2-3 arguments. /// Translated by the Free PVT engine (e.g. $substring, $replace, /// $indexof, $padleft, $padright in 17_pvt_expr.sql) and by /// the Pro SQL mapper to native PostgreSQL functions (SUBSTRING/REPLACE/POSITION/LPAD/RPAD). /// public record MultiArgFunctionCallExpression( PropertyFunction Function, IReadOnlyList Arguments ) : ValueExpression; /// /// Custom SQL function (Pro Only) /// Examples: Sql.Function("COALESCE", p.Stock, 0), Sql.Function("POWER", p.Age, 2) /// public record CustomFunctionExpression( string FunctionName, IReadOnlyList Arguments ) : ValueExpression; /// /// Coalesce expression for the C# ?? operator and n-ary -style fallbacks. /// Examples: x.Bonus ?? 0, x.Name ?? x.LegalName ?? "(n/a)". /// Emitted by the shared parser when it sees ; /// translated to COALESCE(arg1, arg2, ...) by both the Free PVT engine ($coalesce) and the Pro SQL mapper. /// Chained a ?? b ?? c is parsed right-associatively, so the parser flattens it into a single n-ary node. /// public record CoalesceExpression( IReadOnlyList Arguments ) : ValueExpression; /// /// Conditional value (C# ternary ?: operator). /// Examples: e.IsRemote ? e.Salary : e.Salary * 0.5m, /// (e.Rating > 4 ? "TOP" : "STD"). /// Test is a full (comparison / logical / null-check). /// Translated to CASE WHEN test THEN ifTrue ELSE ifFalse END by both the Free /// PVT engine ($if in 17_pvt_expr.sql) and the Pro SQL mapper. /// Named with the Value suffix to avoid collision with /// . /// public record ConditionalValueExpression( FilterExpression Test, ValueExpression IfTrue, ValueExpression IfFalse ) : ValueExpression; #endregion #region Filter Expressions /// /// Comparison expression (property operator value) /// Backward compatibility: Left can be PropertyInfo directly /// public record ComparisonExpression( PropertyInfo Property, ComparisonOperator Operator, object? Value ) : FilterExpression { /// /// Pro: Left side as ValueExpression (for arithmetic/functions) /// If null - Property is used /// public ValueExpression? LeftExpression { get; init; } /// /// Pro: Right side as ValueExpression (for arithmetic/functions) /// If null - Value is used /// public ValueExpression? RightExpression { get; init; } } /// /// Logical expression (AND, OR, NOT) /// public record LogicalExpression( LogicalOperator Operator, IReadOnlyList Operands ) : FilterExpression; /// /// Expression for null check /// public record NullCheckExpression( PropertyInfo Property, bool IsNull ) : FilterExpression; /// /// Expression for checking inclusion in list /// public record InExpression( PropertyInfo Property, IReadOnlyList Values ) : FilterExpression; /// /// Some element of an array or list of classes satisfies : p.Rows.Any(r => r.Kind == "a" /// && r.Active == true). The paths inside Element name the fields of the element under the collection /// (Rows[].Kind, Rows[].Place.City), and every condition of Element is asked of the same element. /// public record ArrayElementAnyExpression( PropertyInfo Collection, FilterExpression Element ) : FilterExpression; #endregion /// /// Sorting information. /// Supports simple property sorting and complex expressions (arithmetic, functions). /// /// Property for simple sorting (Name, Price, etc.) /// Sort direction (Ascending/Descending) /// Optional: Complex expression for Pro features (p.Price * 2, LOWER(p.Name)) public record OrderingExpression( PropertyInfo Property, SortDirection Direction, ValueExpression? Expression = null ) { /// /// Returns true if this ordering uses complex expression (arithmetic/functions). /// public bool HasExpression => Expression != null; /// /// Extracts all field paths used in this ordering (for field resolution). /// public IEnumerable GetFieldPaths() { if (Expression != null) { return ExtractFieldPaths(Expression); } return Property.IsBaseField ? [] : [Property.Name]; } private static IEnumerable ExtractFieldPaths(ValueExpression expr) => expr switch { PropertyValueExpression pve => pve.Property.IsBaseField ? [] : [pve.Property.Name], ArithmeticExpression ae => ExtractFieldPaths(ae.Left).Concat(ExtractFieldPaths(ae.Right)), FunctionCallExpression fce => ExtractFieldPaths(fce.Argument), MultiArgFunctionCallExpression mfce => mfce.Arguments.SelectMany(ExtractFieldPaths), CustomFunctionExpression cfe => cfe.Arguments .OfType() .Where(p => !p.Property.IsBaseField) .Select(p => p.Property.Name), _ => [] }; }; Path: redb/redb.Core/Query/QueryExpressions/IExpressionVisitor.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/QueryExpressions/IExpressionVisitor.cs ---- using System.Linq.Expressions; namespace redb.Core.Query.QueryExpressions; /// /// Interface for processing Expression Tree /// public interface IExpressionVisitor { /// /// Process expression and return result /// TResult Visit(Expression expression); } /// /// Field information in expression /// /// /// Property information for filtering /// /// Property name /// Property type /// true if this is a base field of IRedbObject (Id, ParentId, ValueLong, etc.) /// Optional: function applied to property (Length, Count) /// Optional: the underlying source type the function is applied to /// (e.g. string[] for arr.Length, or string for name.Length). Lets the /// filter builder distinguish array-Length from string-Length when alone is ambiguous. public record PropertyInfo(string Name, Type Type, bool IsBaseField = false, PropertyFunction? Function = null, Type? FunctionSourceType = null); /// /// Functions that can be applied to property /// public enum PropertyFunction { // Existing /// String length (string.Length) Length, /// Collection element count (array.Count) Count, // Pro: String functions /// Convert to lowercase (string.ToLower()) ToLower, /// Convert to uppercase (string.ToUpper()) ToUpper, /// Remove whitespace from both sides (string.Trim()) Trim, /// Remove whitespace from start (string.TrimStart()) TrimStart, /// Remove whitespace from end (string.TrimEnd()) TrimEnd, /// Substring (string.Substring(start[, length])). Multi-arg. Substring, /// String replacement (string.Replace(oldValue, newValue)). Multi-arg. Replace, /// Substring search position, 0-based with -1 for not-found (string.IndexOf(value)). Multi-arg. IndexOf, /// Left-pad to width (string.PadLeft(width[, padChar])). Multi-arg. PadLeft, /// Right-pad to width (string.PadRight(width[, padChar])). Multi-arg. PadRight, // Pro: Mathematical functions /// Absolute value (Math.Abs()) Abs, /// Rounding (Math.Round()). 1-arg via FunctionCall; 2-arg [value, digits] via Multi-arg. Round, /// Round down (Math.Floor()) Floor, /// Round up (Math.Ceiling()) Ceiling, /// Square root (Math.Sqrt()) Sqrt, /// Sign of value: -1/0/+1 (Math.Sign()) Sign, /// e raised to the power (Math.Exp()) Exp, /// Natural logarithm (Math.Log() single-arg) Log, /// Logarithm with explicit base: Math.Log(value, base) / Math.Log10(value). Multi-arg [base, value] (PG LOG order). LogBase, /// Exponentiation (Math.Pow(x, y)). Multi-arg. Pow, // Pro: Date/time functions /// Year from date (DateTime.Year) Year, /// Month from date (DateTime.Month) Month, /// Day from date (DateTime.Day) Day, /// Hour from date (DateTime.Hour) Hour, /// Minute from date (DateTime.Minute) Minute, /// Second from date (DateTime.Second) Second, /// Day-of-week from date (DateTime.DayOfWeek, 0=Sunday for PG DOW). DayOfWeek, /// Day-of-year from date (DateTime.DayOfYear, 1-based). DayOfYear, /// DateTime.AddDays(n) — multi-arg [date, n]. AddDays, /// DateTime.AddYears(n) — multi-arg [date, n]. AddYears, /// DateTime.AddMonths(n) — multi-arg [date, n]. AddMonths, /// DateTime.AddHours(n) — multi-arg [date, n]. AddHours, /// DateTime.AddMinutes(n) — multi-arg [date, n]. AddMinutes, /// DateTime.AddSeconds(n) — multi-arg [date, n]. AddSeconds, /// Regex.Replace(input, pattern, replacement) — multi-arg [input, pattern, replacement]. RegexReplace } /// /// Arithmetic operators (Pro Only). /// public enum ArithmeticOperator { /// Addition (+) Add, /// Subtraction (-) Subtract, /// Multiplication (*) Multiply, /// Division (/) Divide, /// Modulo (%) Modulo } /// /// Comparison operators /// UPDATED: Support for new paradigm with 25+ array operators /// public enum ComparisonOperator { // Basic operators Equal, NotEqual, GreaterThan, GreaterThanOrEqual, LessThan, LessThanOrEqual, Contains, ContainsIgnoreCase, // Contains with case insensitive StartsWith, StartsWithIgnoreCase, // StartsWith with case insensitive EndsWith, EndsWithIgnoreCase, // EndsWith with case insensitive RegexMatch, // POSIX regex match (Regex.IsMatch) — PG '~' RegexMatchIgnoreCase, // POSIX regex match, IgnoreCase — PG '~*' In, // membership in a constant set; the value carries the whole list // NULL semantics Exists, // $exists - explicit field existence check // Basic array operators ArrayContains, // $arrayContains - search value in array ArrayAny, // $arrayAny - check that array is not empty ArrayEmpty, // $arrayEmpty - check that array is empty ArrayCount, // $arrayCount - exact element count ArrayCountGt, // $arrayCountGt - element count greater than N ArrayCountGte, // $arrayCountGte - element count greater than or equal to N ArrayCountLt, // $arrayCountLt - element count less than N ArrayCountLte, // $arrayCountLte - element count less than or equal to N // Positional array operators ArrayAt, // $arrayAt - array element by index ArrayFirst, // $arrayFirst - first array element ArrayLast, // $arrayLast - last array element // Search array operators (for strings) ArrayStartsWith, // $arrayStartsWith - string values starting with prefix ArrayEndsWith, // $arrayEndsWith - string values ending with suffix ArrayMatches, // $arrayMatches - search by regular expression // Aggregation array operators ArraySum, // $arraySum - sum of numeric elements ArrayAvg, // $arrayAvg - arithmetic average ArrayMin, // $arrayMin - minimum value ArrayMax // $arrayMax - maximum value } /// /// Logical operators /// public enum LogicalOperator { And, Or, Not, /// /// The single operand is not TRUE: false, or unknown because a value it reads is absent. The counterexample of /// AllAsync: an object with no value for the field fails the check, as it does in the two counts AllAsync is /// otherwise answered by. Built only by AllAsync, and only for a provider that compiles it /// (). /// NotTrue } /// /// Sort direction /// public enum SortDirection { Ascending, Descending } Path: redb/redb.Core/Query/QueryExpressions/IFilterExpressionParser.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/QueryExpressions/IFilterExpressionParser.cs ---- using System; using System.Linq.Expressions; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; namespace redb.Core.Query.QueryExpressions; /// /// Parser for converting Where expressions to FilterExpression /// public interface IFilterExpressionParser { /// /// Parse lambda expression for filtering by Props fields /// FilterExpression ParseFilter(Expression> predicate) where TProps : class; /// /// Parse lambda expression for filtering by base IRedbObject fields /// (Id, Name, ParentId, DateCreate, ValueLong, ValueString, etc.) /// Uses IRedbObject for compile-time safety - Props not visible! /// FilterExpression ParseRedbFilter(Expression> predicate); } Path: redb/redb.Core/Query/QueryExpressions/IOrderingExpressionParser.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/QueryExpressions/IOrderingExpressionParser.cs ---- using System; using System.Collections.Generic; using System.Linq.Expressions; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; namespace redb.Core.Query.QueryExpressions; /// /// Parser for converting OrderBy expressions to OrderingExpression /// public interface IOrderingExpressionParser { /// /// Parse sorting expression (Props fields) /// OrderingExpression ParseOrdering(Expression> keySelector, SortDirection direction) where TProps : class; /// /// Parse sorting expression by base IRedbObject fields (id, name, date_create, etc.) /// Uses IRedbObject for compile-time safety - Props not visible! /// OrderingExpression ParseRedbOrdering(Expression> keySelector, SortDirection direction); /// /// Parse multiple sorting /// IReadOnlyList ParseMultipleOrderings(IEnumerable<(LambdaExpression KeySelector, SortDirection Direction)> orderings) where TProps : class; } Path: redb/redb.Core/Query/QueryPlannerScope.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/QueryPlannerScope.cs ---- using System; using System.Threading; using redb.Core.Models.Configuration; namespace redb.Core.Query; /// /// The query planner () switched for a block of code: /// using (redb.WithQueryPlanner(false)) { ... }. The configuration is one object per process, and changing it /// changes every concurrent request; a block changes only the calling flow (an ), the awaits /// and tasks inside it included, and disposing it restores what was in effect before. Blocks nest. /// /// Pro reads the planner through ; Free has no planner and ignores it. /// /// public static class QueryPlannerScope { private sealed class Restore : IDisposable { private readonly bool? _previous; private bool _disposed; public Restore(bool? previous) => _previous = previous; public void Dispose() { if (_disposed) return; _disposed = true; Current.Value = _previous; } } private static readonly AsyncLocal Current = new(); /// The value set by the innermost block of the calling flow; null outside any block. public static bool? BlockValue => Current.Value; /// Whether the planner is on for the calling flow: the innermost block, else the configuration. public static bool IsEnabled(RedbServiceConfiguration configuration) => Current.Value ?? configuration.EnablePvtPrefilter; private sealed class NoChange : IDisposable { public void Dispose() { } } /// The block of a tier without a planner: it changes nothing. internal static IDisposable Unchanged { get; } = new NoChange(); /// Sets the planner for a block of the calling flow; disposing restores the previous value. internal static IDisposable Push(bool enabled) { var previous = Current.Value; Current.Value = enabled; return new Restore(previous); } } Path: redb/redb.Core/Query/RedbProjectedQueryable.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/RedbProjectedQueryable.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.Query.Projection; namespace redb.Core.Query; /// /// Implementation of LINQ query projections in REDB with filtering and sorting support /// OPTIMIZED: Uses ProjectionFieldExtractor to load only required fields /// public class RedbProjectedQueryable : IRedbProjectedQueryable where TProps : class, new() { private readonly IRedbQueryable _sourceQuery; private readonly Expression, TResult>> _projection; // Provider and SchemeId for optimized loading private readonly IRedbQueryProvider? _provider; private readonly long _schemeId; // Chain of operations to execute after projection private readonly List>> _wherePredicates = new(); private readonly List<(Expression KeySelector, bool IsDescending)> _orderByExpressions = new(); private readonly bool _isDistinct; // Distinct flag for projection // S-4 (решение владельца 2026-09-04): Take/Skip, вызванные ПОСЛЕ операций, исполняемых в // памяти (Where/OrderBy/Distinct после Select), не уходят в источник - иначе сервер отрезал // бы страницу ДО фильтра и строки молча терялись. Такие Take/Skip копятся здесь и // применяются в памяти. Конвейер: Where* -> OrderBy* -> Distinct -> Skip/Take (в порядке // вызова). Take/Skip ДО первой in-memory операции уходят в источник, как раньше. private readonly List<(bool IsSkip, int Count)> _pagingOps = new(); // Источник уже получил серверный Take/Skip (fast-path): пуш последующих Where в источник // запрещён - иначе фильтр применился бы ДО лимита и порядок вызовов был бы нарушен. private readonly bool _sourcePaged; // The ordering after Select went to the source (OrderBy of a member the source can sort by, nothing in memory // before it): a ThenBy continues it there, and a later Take/Skip stays a LIMIT/OFFSET of the source. private readonly bool _sourceOrdered; // Extracted structure_ids for optimized loading private HashSet? _projectedStructureIds; // Text field paths for SQL function search_objects_with_projection_by_paths private List? _projectedFieldPaths; private readonly ProjectionFieldExtractor _fieldExtractor = new(); public RedbProjectedQueryable( IRedbQueryable sourceQuery, Expression, TResult>> projection) { _sourceQuery = sourceQuery; _projection = projection; } /// /// Constructor with provider for optimized loading /// public RedbProjectedQueryable( IRedbQueryable sourceQuery, Expression, TResult>> projection, IRedbQueryProvider provider, long schemeId) { _sourceQuery = sourceQuery; _projection = projection; _provider = provider; _schemeId = schemeId; } // Private constructor for creating copies with additional operations private RedbProjectedQueryable( IRedbQueryable sourceQuery, Expression, TResult>> projection, List>> wherePredicates, List<(Expression KeySelector, bool IsDescending)> orderByExpressions, HashSet? projectedStructureIds, List? projectedFieldPaths, IRedbQueryProvider? provider, long schemeId, bool isDistinct = false, List<(bool IsSkip, int Count)>? pagingOps = null, bool sourcePaged = false, bool sourceOrdered = false) { _sourceOrdered = sourceOrdered; _sourceQuery = sourceQuery; _projection = projection; _wherePredicates = new List>>(wherePredicates); _orderByExpressions = new List<(Expression, bool)>(orderByExpressions); _projectedStructureIds = projectedStructureIds; _projectedFieldPaths = projectedFieldPaths; _provider = provider; _schemeId = schemeId; _isDistinct = isDistinct; if (pagingOps != null) _pagingOps = new List<(bool IsSkip, int Count)>(pagingOps); _sourcePaged = sourcePaged; } /// /// Extracted structure_ids for optimization (for provider access) /// public HashSet? ProjectedStructureIds => _projectedStructureIds; /// /// Text field paths for SQL function search_objects_with_projection_by_paths /// public List? ProjectedFieldPaths => _projectedFieldPaths; /// /// Projection expression (for provider access) /// public Expression, TResult>> Projection => _projection; public IRedbProjectedQueryable Where(Expression> predicate) { if (predicate == null) throw new ArgumentNullException(nameof(predicate)); // S-4 шаг 2 (решение владельца 2026-09-04): предикат по простым спроецированным // props-членам транслируется ОБРАТНО В ИСТОЧНИК - фильтр и последующие Take/Skip // остаются серверными. Всё нетранслируемое (вычисляемые члены, базовые поля, r целиком) // корректно фильтруется в памяти, как раньше - страдает только скорость. При уже // накопленном локальном Take/Skip пуш запрещён: фильтр обязан видеть отрезанную // страницу (семантика порядка вызовов). if (!_sourcePaged && _pagingOps.Count == 0 && TryPushPredicateToSource(predicate, out var pushedSource)) { return new RedbProjectedQueryable( pushedSource, _projection, _wherePredicates, _orderByExpressions, _projectedStructureIds, _projectedFieldPaths, _provider, _schemeId, _isDistinct, _pagingOps, _sourcePaged, _sourceOrdered); } var newWherePredicates = new List>>(_wherePredicates) { predicate }; return new RedbProjectedQueryable( _sourceQuery, _projection, newWherePredicates, _orderByExpressions, _projectedStructureIds, _projectedFieldPaths, _provider, _schemeId, _isDistinct, _pagingOps, _sourcePaged, _sourceOrdered); } /// /// Пытается переписать предикат над результатом проекции в предикат над TProps: члены /// результата подставляются их проекционными выражениями, цепочки x.Props.* переносятся на /// параметр TProps. Транслируются только простые member-проекции props-полей; любой другой /// случай - false, и предикат остаётся в памяти (fail-safe: корректность не зависит от пуша). /// private bool TryPushPredicateToSource( Expression> predicate, out IRedbQueryable pushed) { pushed = _sourceQuery; var map = ProjectionMembers(); if (map == null) return false; var pParam = Expression.Parameter(typeof(TProps), "p"); var rewriter = new ProjectedPredicateRewriter( predicate.Parameters[0], map, _projection.Parameters[0], pParam); var body = rewriter.Visit(predicate.Body); if (!rewriter.Success || body == null) return false; pushed = _sourceQuery.Where(Expression.Lambda>(body, pParam)); return true; } private sealed class ProjectedPredicateRewriter : ExpressionVisitor { private readonly ParameterExpression _rParam; private readonly Dictionary _map; private readonly ParameterExpression _xParam; private readonly ParameterExpression _pParam; public bool Success { get; private set; } = true; public ProjectedPredicateRewriter( ParameterExpression rParam, Dictionary map, ParameterExpression xParam, ParameterExpression pParam) { _rParam = rParam; _map = map; _xParam = xParam; _pParam = pParam; } protected override Expression VisitMember(MemberExpression node) { if (node.Expression == _rParam) { if (!_map.TryGetValue(node.Member.Name, out var mapped)) { Success = false; return node; } var translated = TranslateProjectionExpr(mapped); if (translated == null) { Success = false; return node; } return translated; } return base.VisitMember(node); } protected override Expression VisitParameter(ParameterExpression node) { if (node == _rParam) Success = false; // r используется целиком - такое не транслируем return base.VisitParameter(node); } /// x.Props.<chain> -> p.<chain>; всё прочее (x.Id, вычисления) - null. private Expression? TranslateProjectionExpr(Expression expr) { while (expr is UnaryExpression u && (u.NodeType == ExpressionType.Convert || u.NodeType == ExpressionType.ConvertChecked)) expr = u.Operand; var chain = new Stack(); var cur = expr; while (cur is MemberExpression m) { if (m.Member.Name == "Props" && m.Expression == _xParam) { Expression acc = _pParam; while (chain.Count > 0) acc = Expression.MakeMemberAccess(acc, chain.Pop()); return acc; } chain.Push(m.Member); cur = m.Expression; } return null; } } // The ordering after Select is the ordering of the objects the projection reads: a key that is a projected Props // member or one of the object's own fields sorts the source, in SQL, and // a later Take/Skip stays a LIMIT/OFFSET there. Select only shapes what the page materializes. A key the source // cannot sort by, or an ordering after operations that run in memory, sorts in memory as before (S-4). public IRedbProjectedQueryable OrderBy(Expression> keySelector) => Order(keySelector, descending: false, thenBy: false); public IRedbProjectedQueryable OrderByDescending(Expression> keySelector) => Order(keySelector, descending: true, thenBy: false); public IRedbProjectedQueryable ThenBy(Expression> keySelector) => Order(keySelector, descending: false, thenBy: true); public IRedbProjectedQueryable ThenByDescending(Expression> keySelector) => Order(keySelector, descending: true, thenBy: true); private IRedbProjectedQueryable Order(Expression> keySelector, bool descending, bool thenBy) { if (keySelector == null) throw new ArgumentNullException(nameof(keySelector)); if (thenBy && _orderByExpressions.Count == 0 && !_sourceOrdered) throw new InvalidOperationException("ThenBy continues an ordering: call OrderBy or OrderByDescending first."); // OrderBy starts an ordering, ThenBy continues the one that exists: in the source or in memory. var inSource = !thenBy || _orderByExpressions.Count == 0; if (inSource && !_sourcePaged && !HasInMemoryOps && TryPushOrdering(keySelector, descending, thenBy, out var ordered)) return Copy(source: ordered, sourceOrdered: true); if (thenBy && _orderByExpressions.Count == 0) throw new InvalidOperationException( "This ThenBy cannot continue the ordering the database applies (its key is not a projected Props member " + "or field of the object, or Take/Skip/Distinct came in between): put the ordering before Select."); // In memory, as before: OrderBy replaces the ordering, ThenBy adds a key to it. var keys = thenBy ? new List<(Expression, bool)>(_orderByExpressions) : new List<(Expression, bool)>(); keys.Add((keySelector, descending)); return Copy(orderBy: keys, sourceOrdered: false); } private RedbProjectedQueryable Copy( IRedbQueryable? source = null, List<(Expression KeySelector, bool IsDescending)>? orderBy = null, bool? sourceOrdered = null) => new( source ?? _sourceQuery, _projection, _wherePredicates, orderBy ?? _orderByExpressions, _projectedStructureIds, _projectedFieldPaths, _provider, _schemeId, _isDistinct, _pagingOps, _sourcePaged, sourceOrdered ?? _sourceOrdered); /// Members of the projection by name, mapped to their expressions over the object; null for another shape. private Dictionary? ProjectionMembers() { if (_projection.Body is NewExpression ne && ne.Members != null) { var map = new Dictionary(); for (int i = 0; i < ne.Members.Count; i++) map[ne.Members[i].Name] = ne.Arguments[i]; return map; } if (_projection.Body is MemberInitExpression mi && mi.NewExpression.Arguments.Count == 0) { var map = new Dictionary(); foreach (var binding in mi.Bindings) { if (binding is not MemberAssignment assignment) return null; map[assignment.Member.Name] = assignment.Expression; } return map; } return null; } // Fields of the object the source sorts by (OrderByRedb), by their IRedbObject property names. private static readonly HashSet SortableObjectFields = new(StringComparer.Ordinal) { "Id", "Name", "ParentId", "SchemeId", "DateCreate", "DateModify", "ValueLong", "ValueString", "ValueGuid", "ValueBool", "ValueDouble", "ValueNumeric", "ValueDatetime" }; /// /// The ordering of a projected member sent to the source: OrderByRedb for a field of the object, OrderBy over /// TProps for a member that reads a Props path (rewritten as Where after Select is). /// private bool TryPushOrdering( Expression> keySelector, bool descending, bool thenBy, out IRedbQueryable ordered) { ordered = _sourceQuery; // Only a provider whose ordering matches the in-memory one: Free drops objects without a value for the key // and does not apply ThenBy everywhere, so its projections keep sorting in memory. if (_provider is not Base.QueryProviderBase { SortsByPropsLikeLinq: true }) return false; var map = ProjectionMembers(); if (map == null) return false; var sorted = _sourceQuery as IOrderedRedbQueryable; if (thenBy && sorted == null) return false; if (keySelector.Body is MemberExpression member && member.Expression == keySelector.Parameters[0] && map.TryGetValue(member.Member.Name, out var mapped) && ObjectField(mapped) is { } field && field.PropertyType == typeof(TKey)) { var o = Expression.Parameter(typeof(redb.Core.Models.Contracts.IRedbObject), "o"); var byField = Expression.Lambda>(Expression.Property(o, field), o); ordered = thenBy ? descending ? sorted!.ThenByDescendingRedb(byField) : sorted!.ThenByRedb(byField) : descending ? _sourceQuery.OrderByDescendingRedb(byField) : _sourceQuery.OrderByRedb(byField); return true; } var p = Expression.Parameter(typeof(TProps), "p"); var rewriter = new ProjectedPredicateRewriter(keySelector.Parameters[0], map, _projection.Parameters[0], p); var body = rewriter.Visit(keySelector.Body); if (!rewriter.Success || body == null || body.Type != typeof(TKey) || !IsMemberChainOf(body, p)) return false; var byProps = Expression.Lambda>(body, p); ordered = thenBy ? descending ? sorted!.ThenByDescending(byProps) : sorted!.ThenBy(byProps) : descending ? _sourceQuery.OrderByDescending(byProps) : _sourceQuery.OrderBy(byProps); return true; } /// /// A plain path of Props fields (p.HomeAddress.City): the ordering of the source sorts by such a path. A key /// computed over Props members is not sent there, the ordering parser need not translate it; it sorts in memory. /// private static bool IsMemberChainOf(Expression expr, ParameterExpression p) { while (expr is MemberExpression m) expr = m.Expression!; return expr == p; } /// The field of the object a projected member reads (x.DateCreate), if the source can sort by it. private System.Reflection.PropertyInfo? ObjectField(Expression mapped) { while (mapped is UnaryExpression u && (u.NodeType == ExpressionType.Convert || u.NodeType == ExpressionType.ConvertChecked)) mapped = u.Operand; if (mapped is not MemberExpression m || m.Expression != _projection.Parameters[0] || !SortableObjectFields.Contains(m.Member.Name)) return null; var contract = typeof(redb.Core.Models.Contracts.IRedbObject); return contract.GetProperty(m.Member.Name) ?? contract.GetInterfaces().Select(i => i.GetProperty(m.Member.Name)).FirstOrDefault(pi => pi != null); } public IRedbProjectedQueryable Take(int count) { // S-4: после in-memory операций Take применяется в памяти (_pagingOps), иначе сервер // отрежет страницу до фильтра; без них - прежний быстрый путь, LIMIT уходит в SQL. if (HasInMemoryOps) return WithPagingOp(isSkip: false, count); return new RedbProjectedQueryable( _sourceQuery.Take(count), _projection, _wherePredicates, _orderByExpressions, _projectedStructureIds, _projectedFieldPaths, _provider, _schemeId, _isDistinct, _pagingOps, sourcePaged: true, sourceOrdered: _sourceOrdered); } public IRedbProjectedQueryable Skip(int count) { if (HasInMemoryOps) return WithPagingOp(isSkip: true, count); return new RedbProjectedQueryable( _sourceQuery.Skip(count), _projection, _wherePredicates, _orderByExpressions, _projectedStructureIds, _projectedFieldPaths, _provider, _schemeId, _isDistinct, _pagingOps, sourcePaged: true, sourceOrdered: _sourceOrdered); } private bool HasInMemoryOps => _wherePredicates.Count > 0 || _orderByExpressions.Count > 0 || _isDistinct || _pagingOps.Count > 0; private RedbProjectedQueryable WithPagingOp(bool isSkip, int count) { var copy = new RedbProjectedQueryable( _sourceQuery, _projection, _wherePredicates, _orderByExpressions, _projectedStructureIds, _projectedFieldPaths, _provider, _schemeId, _isDistinct, _pagingOps, _sourcePaged, _sourceOrdered); copy._pagingOps.Add((isSkip, count)); return copy; } public IRedbProjectedQueryable Distinct() { // Distinct for projection is applied in memory after projection return new RedbProjectedQueryable( _sourceQuery, _projection, _wherePredicates, _orderByExpressions, _projectedStructureIds, _projectedFieldPaths, _provider, _schemeId, isDistinct: true, pagingOps: _pagingOps, sourcePaged: _sourcePaged, sourceOrdered: _sourceOrdered); } public async Task> ToListAsync(CancellationToken cancellationToken = default) { // S-7 (решение владельца 2026-09-03): Select с Agg.* маршрутизируется в аггрегатный путь - // одна строка агрегатов. Раньше пример из XML-доки Agg // (.Select(x => new { Total = Agg.Sum(...) })) бросал NotSupportedException из // скомпилированного маркера при материализации. if (_fieldExtractor.HasAggregations(_projection)) { var aggregated = await _sourceQuery.AggregateAsync(_projection); IEnumerable aggRows = [aggregated]; foreach (var aggWhere in _wherePredicates) aggRows = aggRows.Where(aggWhere.Compile()); return aggRows.ToList(); } // OPTIMIZATION: Load only required structure_ids if possible List> fullObjects; // LOG: Projection information // Extract text paths and structure_ids from projection if not yet extracted if (_projectedStructureIds == null && _fieldExtractor.ReadsNoPropsField(_projection)) { // Base fields only: no value row is read, so the scheme is not needed either. _projectedStructureIds = []; } else if (_projectedFieldPaths == null && _provider != null && _schemeId > 0) { // Extract text paths for SQL projection function (search_objects_with_projection_by_paths) _projectedFieldPaths = _fieldExtractor.ExtractFieldPathStrings(_projection); // Also extract structure_ids (used by Pro's ProLazyPropsLoader for filtered _values loading) var scheme = await _provider.GetSchemeAsync(_schemeId, cancellationToken: cancellationToken); if (scheme != null) { _projectedStructureIds = _fieldExtractor.ExtractStructureIds(scheme, _projection); } } // FIX: ALWAYS skip Props re-loading during projection. // // Projection flow is two-phase: // Phase 1 (SQL): search_objects_with_projection_by_paths returns JSON with // "properties" containing ONLY the projected fields. // Phase 2 (C#): Deserialization maps "properties" → Props via setter, // which sets _propsLoaded = true. Props is PARTIAL but sufficient. // Phase 3 (C#): compiledProjection(redbObj) extracts needed fields → TResult. // RedbObject is then discarded. // // Without skipProps=true, MaterializeResultsFromJson would: // - In EAGER mode: call LazyPropsLoader.LoadPropsForManyAsync which re-loads // the FULL object via get_object_json, OVERWRITING the partial Props from SQL // projection. This causes double DB round-trip and defeats the projection. // - In LAZY mode: set _lazyLoader + _propsLoaded=false, causing the lazy loader // to load full Props on first .Props access, again defeating projection. // // In both cases the final TResult is correct (projection extracts the right fields), // but the optimization is wasted — we load full object data anyway. // // The fix: tell MaterializeResultsFromJson to skip ALL Props post-processing. // Props data is already in the deserialized object from the SQL projection JSON. bool skipProps = true; // Try to use optimized loading via internal method if (_sourceQuery is RedbQueryable redbQueryable) { // The settings of the projection go into a copy: the source query stays as it was // and can be run again, as a list or under another projection. var working = redbQueryable.CloneForProjection(); // Set text paths in context BEFORE call // Context is read in PostgresQueryProvider to select SQL function working.SetProjectedFieldPaths(_projectedFieldPaths); fullObjects = await working.ToListWithProjectionAsync(_projectedStructureIds, skipProps, cancellationToken); } else { fullObjects = await _sourceQuery.ToListAsync(cancellationToken: cancellationToken); } // CRITICAL: Disable lazy loading BEFORE applying projection! // Data already loaded from SQL (search_objects_with_projection_by_paths), // result will be anonymous type — lazy loading not needed and dangerous. foreach (var obj in fullObjects) { obj._lazyLoader = null; // Ревью 2026-09-03: у объекта, в чьей ЧАСТИЧНОЙ выборке не нашлось ни одной строки // _values (все проецируемые поля null), Props приезжает null - а лямбда проекции // обязана исполниться. Внутри проекционного пути null-Props означает «пусто», а не // «не загружено»: RedbObject тут же выбрасывается, V4-семантика чтения не затронута. // Raw access: the getter of an object without loaded Props is a lazy load (or nothing, the loader is gone). if (obj.GetPropsDirectly() is null) obj.Props = new TProps(); } var compiledProjection = _projection.Compile(); // Apply projection to each object var projectedResults = fullObjects.Select(redbObj => compiledProjection(redbObj)); // Apply Where filters after projection foreach (var wherePredicate in _wherePredicates) { var compiledPredicate = wherePredicate.Compile(); projectedResults = projectedResults.Where(compiledPredicate); } // Apply OrderBy sorting after projection if (_orderByExpressions.Count > 0) { IOrderedEnumerable? orderedResults = null; // S-2 (ревью 2026-09-03): null-ключ раньше подменялся new object(), и Comparer // валил запрос ("does not implement IComparable"). Ключи сравниваются null-безопасно // с LINQ-семантикой: null меньше любого значения. var nullSafe = Comparer.Create(static (a, b) => a == null && b == null ? 0 : a == null ? -1 : b == null ? 1 : System.Collections.Comparer.Default.Compare(a, b)); for (int i = 0; i < _orderByExpressions.Count; i++) { var (keySelector, isDescending) = _orderByExpressions[i]; var compiledDelegate = ((LambdaExpression)keySelector).Compile(); Func key = item => compiledDelegate.DynamicInvoke(item); if (i == 0) orderedResults = isDescending ? projectedResults.OrderByDescending(key, nullSafe) : projectedResults.OrderBy(key, nullSafe); else orderedResults = isDescending ? orderedResults!.ThenByDescending(key, nullSafe) : orderedResults!.ThenBy(key, nullSafe); } if (orderedResults != null) projectedResults = orderedResults; } // Apply Distinct if flag is set if (_isDistinct) { projectedResults = projectedResults.Distinct(); } // S-4: Take/Skip, вызванные после in-memory операций, применяются здесь в порядке вызова. foreach (var (isSkip, n) in _pagingOps) projectedResults = isSkip ? projectedResults.Skip(n) : projectedResults.Take(n); return projectedResults.ToList(); } public async Task CountAsync(CancellationToken cancellationToken = default) { // S-3 (ревью 2026-09-03): Distinct применяется в памяти в ToListAsync - Count обязан // считать то же самое. Агрегатная проекция (S-7) тем же путём: всегда одна строка. if (_wherePredicates.Count > 0 || _isDistinct || _pagingOps.Count > 0 || _fieldExtractor.HasAggregations(_projection)) { var results = await ToListAsync(cancellationToken: cancellationToken); return results.Count; } // Otherwise count does not depend on the projection return await _sourceQuery.CountAsync(cancellationToken: cancellationToken); } public async Task FirstOrDefaultAsync(CancellationToken cancellationToken = default) { // For FirstOrDefault apply all operations and take first element var results = await ToListAsync(cancellationToken: cancellationToken); return results.FirstOrDefault(); } /// /// Get projection info: SQL function and structure_ids that will be loaded. /// public async Task GetProjectionInfoAsync(CancellationToken cancellationToken = default) { HashSet? structureIds = _projectedStructureIds; if (structureIds == null && _provider != null && _schemeId > 0) { var scheme = await _provider.GetSchemeAsync(_schemeId, cancellationToken: cancellationToken); if (scheme != null) { structureIds = _fieldExtractor.ExtractStructureIds(scheme, _projection); _projectedStructureIds = structureIds; } } if (structureIds == null) return "Full load"; return structureIds.Count > 0 ? $"Projection: {structureIds.Count} structure_ids" : "Projection: base fields only"; } } Path: redb/redb.Core/Query/RedbQueryable.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/RedbQueryable.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.Models.Entities; using redb.Core.Models.Contracts; using redb.Core.Query.QueryExpressions; using redb.Core.Query.FacetFilters; namespace redb.Core.Query; /// /// Basic implementation of IRedbQueryable /// public class RedbQueryable : IRedbQueryable, IOrderedRedbQueryable where TProps : class, new() { protected readonly IRedbQueryProvider _provider; internal IRedbQueryProvider QueryProvider => _provider; protected readonly QueryContext _context; protected readonly IFilterExpressionParser _filterParser; protected readonly IOrderingExpressionParser _orderingParser; protected readonly IFacetFilterBuilder? _facetBuilder; public RedbQueryable( IRedbQueryProvider provider, QueryContext context, IFilterExpressionParser filterParser, IOrderingExpressionParser orderingParser, IFacetFilterBuilder? facetBuilder = null) { _provider = provider; _context = context; _filterParser = filterParser; _orderingParser = orderingParser; _facetBuilder = facetBuilder; } public virtual IRedbQueryable Where(Expression> predicate) { var newContext = _context.Clone(); var filterExpression = _filterParser.ParseFilter(predicate); // FIX: Check for empty filter (Where(x => false)) if (IsEmptyFilter(filterExpression)) { newContext.IsEmpty = true; } // If filter already exists, combine via AND if (newContext.Filter != null) { newContext.Filter = new LogicalExpression( LogicalOperator.And, new[] { newContext.Filter, filterExpression } ); } else { newContext.Filter = filterExpression; } return new RedbQueryable(_provider, newContext, _filterParser, _orderingParser, _facetBuilder); } public virtual IRedbQueryable WhereRedb(Expression> predicate) { if (predicate == null) throw new ArgumentNullException(nameof(predicate)); var newContext = _context.Clone(); // Parse expression for base IRedbObject fields var filterExpression = _filterParser.ParseRedbFilter(predicate); // Check for empty filter if (IsEmptyFilter(filterExpression)) { newContext.IsEmpty = true; } // If filter already exists, combine via AND if (newContext.Filter != null) { newContext.Filter = new LogicalExpression( LogicalOperator.And, new[] { newContext.Filter, filterExpression } ); } else { newContext.Filter = filterExpression; } return new RedbQueryable(_provider, newContext, _filterParser, _orderingParser, _facetBuilder); } public virtual IOrderedRedbQueryable OrderBy(Expression> keySelector) { var newContext = _context.Clone(); newContext.Orderings.Clear(); // OrderBy replaces previous sorting var ordering = _orderingParser.ParseOrdering(keySelector, SortDirection.Ascending); newContext.Orderings.Add(ordering); // FIX: Preserve IsEmpty flag after OrderBy // Even if ordering is added, query can remain empty (Where(x => false)) return new RedbQueryable(_provider, newContext, _filterParser, _orderingParser, _facetBuilder); } public virtual IOrderedRedbQueryable OrderByDescending(Expression> keySelector) { var newContext = _context.Clone(); newContext.Orderings.Clear(); // OrderByDescending replaces previous sorting var ordering = _orderingParser.ParseOrdering(keySelector, SortDirection.Descending); newContext.Orderings.Add(ordering); // FIX: Preserve IsEmpty flag after OrderByDescending // IsEmpty is already copied in Clone(), no additional actions required return new RedbQueryable(_provider, newContext, _filterParser, _orderingParser, _facetBuilder); } public virtual IOrderedRedbQueryable ThenBy(Expression> keySelector) { var newContext = _context.Clone(); var ordering = _orderingParser.ParseOrdering(keySelector, SortDirection.Ascending); newContext.Orderings.Add(ordering); // FIX: Preserve IsEmpty flag after ThenBy // IsEmpty is already copied in Clone(), no additional actions required return new RedbQueryable(_provider, newContext, _filterParser, _orderingParser, _facetBuilder); } public virtual IOrderedRedbQueryable ThenByDescending(Expression> keySelector) { var newContext = _context.Clone(); var ordering = _orderingParser.ParseOrdering(keySelector, SortDirection.Descending); newContext.Orderings.Add(ordering); // FIX: Preserve IsEmpty flag after ThenByDescending // IsEmpty is already copied in Clone(), no additional actions required return new RedbQueryable(_provider, newContext, _filterParser, _orderingParser, _facetBuilder); } // ═══════════════════════════════════════════════════════════════════════════ // SORTING BY BASE RedbObject FIELDS (OrderByRedb, ThenByRedb) // ═══════════════════════════════════════════════════════════════════════════ public virtual IOrderedRedbQueryable OrderByRedb(Expression> keySelector) { var newContext = _context.Clone(); newContext.Orderings.Clear(); // OrderByRedb replaces previous sorting var ordering = _orderingParser.ParseRedbOrdering(keySelector, SortDirection.Ascending); newContext.Orderings.Add(ordering); return new RedbQueryable(_provider, newContext, _filterParser, _orderingParser, _facetBuilder); } public virtual IOrderedRedbQueryable OrderByDescendingRedb(Expression> keySelector) { var newContext = _context.Clone(); newContext.Orderings.Clear(); // OrderByDescendingRedb replaces previous sorting var ordering = _orderingParser.ParseRedbOrdering(keySelector, SortDirection.Descending); newContext.Orderings.Add(ordering); return new RedbQueryable(_provider, newContext, _filterParser, _orderingParser, _facetBuilder); } public virtual IOrderedRedbQueryable ThenByRedb(Expression> keySelector) { var newContext = _context.Clone(); var ordering = _orderingParser.ParseRedbOrdering(keySelector, SortDirection.Ascending); newContext.Orderings.Add(ordering); // ThenByRedb adds to existing sorting return new RedbQueryable(_provider, newContext, _filterParser, _orderingParser, _facetBuilder); } public virtual IOrderedRedbQueryable ThenByDescendingRedb(Expression> keySelector) { var newContext = _context.Clone(); var ordering = _orderingParser.ParseRedbOrdering(keySelector, SortDirection.Descending); newContext.Orderings.Add(ordering); // ThenByDescendingRedb adds to existing sorting return new RedbQueryable(_provider, newContext, _filterParser, _orderingParser, _facetBuilder); } public virtual IRedbQueryable Take(int count) { if (count < 0) throw new ArgumentException("Take count must be non-negative", nameof(count)); var newContext = _context.Clone(); newContext.Limit = count; return new RedbQueryable(_provider, newContext, _filterParser, _orderingParser, _facetBuilder); } public virtual IRedbQueryable Skip(int count) { if (count < 0) throw new ArgumentException("Skip count must be non-negative", nameof(count)); var newContext = _context.Clone(); newContext.Offset = count; return new RedbQueryable(_provider, newContext, _filterParser, _orderingParser, _facetBuilder); } public virtual async Task>> ToListAsync(CancellationToken cancellationToken = default) { var result = await _provider.ExecuteAsync(BuildExpression(), typeof(List>), cancellationToken: cancellationToken); return (List>)result; } /// /// Number of rows of the same query returns, Take and Skip included. /// The providers count the filtered set and leave paging out, so Take(10).CountAsync() /// used to answer with the size of the whole set. The set is counted without paging and the /// page is cut from that number here, the same way for every provider. /// public virtual async Task CountAsync(CancellationToken cancellationToken = default) { if (!IsPaged(_context)) return await CountWholeSetAsync(cancellationToken); var unpaged = _context.Clone(); unpaged.Limit = null; unpaged.Offset = null; var total = await new RedbQueryable(_provider, unpaged, _filterParser, _orderingParser, _facetBuilder) .CountWholeSetAsync(cancellationToken); return PagedCount(total, _context.Offset, _context.Limit); } /// Count as the provider computes it: the filtered set, whatever Take and Skip say. private protected async Task CountWholeSetAsync(CancellationToken cancellationToken) { var result = await _provider.ExecuteAsync(BuildCountExpression(), typeof(int), cancellationToken: cancellationToken); return (int)result; } /// Is there an object in the whole set filtered by , Take and Skip aside. private async Task AnyOfWholeSetAsync(FilterExpression? filter, CancellationToken cancellationToken) { if (_context.IsEmpty) return false; var whole = _context.Clone(); whole.Limit = null; whole.Offset = null; whole.Filter = filter; var result = await _provider.ExecuteAsync(Expression.Constant(whole), typeof(bool), cancellationToken: cancellationToken); return (bool)result; } /// /// The filter reads Props fields directly, nothing else: no field of the object itself, no computed value /// (arithmetic, functions). The constant of Where(x => true / false) passes. /// private static bool ReadsPropsFieldsOnly(FilterExpression filter) => filter switch { ComparisonExpression c => c.Property.Name == "__constant" || (c.LeftExpression == null && c.RightExpression == null && !c.Property.IsBaseField), InExpression i => !i.Property.IsBaseField, NullCheckExpression n => !n.Property.IsBaseField, LogicalExpression l => l.Operator != LogicalOperator.NotTrue && l.Operands.All(ReadsPropsFieldsOnly), _ => false }; internal static bool IsPaged(QueryContext context) => context.Limit != null || (context.Offset ?? 0) > 0; /// Rows left of after skipping and taking. internal static int PagedCount(int total, int? offset, int? limit) { var afterSkip = Math.Max(0, total - (offset ?? 0)); return limit is { } take ? Math.Min(take, afterSkip) : afterSkip; } public virtual async Task?> FirstOrDefaultAsync(CancellationToken cancellationToken = default) { // For FirstOrDefault limit to 1 record var limitedContext = _context.Clone(); limitedContext.Limit = 1; var tempQueryable = new RedbQueryable(_provider, limitedContext, _filterParser, _orderingParser); var result = await tempQueryable.ToListAsync(cancellationToken: cancellationToken); return result.FirstOrDefault(); } public virtual async Task?> FirstOrDefaultAsync(Expression> predicate, CancellationToken cancellationToken = default) { return await Where(predicate).FirstOrDefaultAsync(cancellationToken: cancellationToken); } public virtual 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(_context)) return await CountAsync(cancellationToken) > 0; // Asked of the provider as its own operation: one that can stop at the first match does // not have to count the whole set. The provider default is still "count is above zero". var result = await _provider.ExecuteAsync(BuildCountExpression(), typeof(bool), cancellationToken: cancellationToken); return (bool)result; } public virtual 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 virtual 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 virtual 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 virtual async Task AllAsync(Expression> predicate, CancellationToken cancellationToken = default) { if (predicate == null) throw new ArgumentNullException(nameof(predicate)); // All() == true if all records satisfy the condition: no object of the whole filtered set (Take and Skip // aside) is a counterexample, an object for which the predicate is not TRUE. A provider that compiles NotTrue // answers that as one existence check, which stops at the first counterexample. The predicate must read Props // fields only: a provider compiles the fields of the object and Props in separate parts of a statement, and // NotTrue cannot be split across them. var predicateFilter = _filterParser.ParseFilter(predicate); // All(x => true), or a predicate that folds to it: true for any set. It must not reach NotTrue: a provider // drops a true operand from a logical node, so "not true" would compile to "every object is a counterexample". if (predicateFilter is ComparisonExpression { Property.Name: "__constant", Operator: ComparisonOperator.Equal, Value: true }) return true; // A provider may answer All over the whole scheme in one statement of its own (QueryProviderBase.TryAllWithoutFilterAsync). // Only for the plain set of the scheme: WhereRedb and WhereInRedb sit in the filter, the tree queryables have an // AllAsync of their own, and Take and Skip are set aside here as by the counts below. A distinct set is not the // set of objects: DistinctBy keeps one object per key, and the counts below compare keys. if (_context.Filter == null && !_context.IsEmpty && _context.DistinctByField == null && !_context.IsDistinct && !_context.IsDistinctRedb && _provider is Base.QueryProviderBase provider && ReadsPropsFieldsOnly(predicateFilter) && !IsEmptyFilter(predicateFilter) && await provider.TryAllWithoutFilterAsync(_context, predicateFilter, cancellationToken) is bool all) return all; if (_provider is Base.QueryProviderBase { CompilesNotTrue: true } && ReadsPropsFieldsOnly(predicateFilter)) { if (IsEmptyFilter(predicateFilter)) return !await AnyOfWholeSetAsync(_context.Filter, cancellationToken); // All(x => false): only an empty set var notTrue = new LogicalExpression(LogicalOperator.NotTrue, new[] { predicateFilter }); var counterexamples = _context.Filter == null ? notTrue : new LogicalExpression(LogicalOperator.And, new[] { _context.Filter, notTrue }); return !await AnyOfWholeSetAsync(counterexamples, cancellationToken); } // Otherwise both counts are of the whole filtered set: two counts cut to the same page size would // come out equal whenever enough rows match, whether or not all of them do. var totalCount = await CountWholeSetAsync(cancellationToken); if (totalCount == 0) return true; // All elements of empty set satisfy any condition var matching = Where(predicate); var matchingCount = matching is RedbQueryable flat ? await flat.CountWholeSetAsync(cancellationToken) : await matching.CountAsync(cancellationToken: cancellationToken); return totalCount == matchingCount; } public virtual IRedbProjectedQueryable Select(Expression, TResult>> selector) { if (selector == null) throw new ArgumentNullException(nameof(selector)); return new RedbProjectedQueryable(this, selector, _provider, _context.SchemeId); } /// /// Internal method for optimized loading with structure_ids filter. /// Virtual for overriding in PostgresTreeQueryable (List TreeRedbObject → List RedbObject). /// Text paths are taken from context (_context.ProjectedFieldPaths). /// /// /// Structure IDs extracted from projection expression. Used by Pro's ProLazyPropsLoader /// to load only matching _values rows. Null = no projection filter. /// /// /// When true, tells MaterializeResultsFromJson to skip ALL Props post-processing /// (both eager LoadPropsForManyAsync and lazy loader setup). This is required for /// projections because Props data already comes from the SQL projection function /// (search_objects_with_projection_by_paths) embedded in the JSON "properties" field. /// Re-loading would overwrite partial Props with full object data, wasting the projection. /// /// Cancels the operation (OCE only; a rollback in flight always completes). protected internal virtual async Task>> ToListWithProjectionAsync( HashSet? projectedStructureIds, bool skipPropsLoading = false, CancellationToken cancellationToken = default) { // Set structure_ids in context for passing to provider if (projectedStructureIds != null && projectedStructureIds.Count > 0) { _context.ProjectedStructureIds = projectedStructureIds; } // An empty set is an answer of its own: the selector reads base fields only. _context.ProjectionReadsNoProps = projectedStructureIds is { Count: 0 }; if (skipPropsLoading) { // FIX: Skip BOTH Props loading AND lazy loader setup. // Projection SQL already returns "properties" with only the needed fields. // Deserializer maps them to Props via setter (_propsLoaded = true). // Any post-processing (eager or lazy) would overwrite partial Props with full data. _context.SkipPropsLoading = true; } // Delegate to provider using the same BuildExpression() as ToListAsync() var result = await _provider.ExecuteAsync(BuildExpression(), typeof(List>), cancellationToken: cancellationToken); return (List>)result; } /// /// A copy of this query for a projection to configure and run. The projection writes its /// settings (fields to load, skipping of Props) into the context; written into the query itself /// they stayed there, and the same query run again as ToListAsync returned objects with part /// of their Props. /// internal virtual RedbQueryable CloneForProjection() => new RedbQueryable(_provider, _context.Clone(), _filterParser, _orderingParser, _facetBuilder); /// /// Scheme ID for access from projections /// internal long SchemeId => _context.SchemeId; /// /// Provider for access from projections /// internal IRedbQueryProvider Provider => _provider; /// /// Sets text paths for SQL function search_objects_with_projection_by_paths. /// Called from RedbProjectedQueryable before ToListWithProjectionAsync. /// internal void SetProjectedFieldPaths(List? paths) { if (paths != null && paths.Count > 0) { _context.ProjectedFieldPaths = paths; } } public virtual IRedbQueryable Distinct() { var newContext = _context.Clone(); newContext.IsDistinct = true; return new RedbQueryable(_provider, newContext, _filterParser, _orderingParser, _facetBuilder); } public virtual IRedbQueryable DistinctRedb() { var newContext = _context.Clone(); newContext.IsDistinctRedb = true; return new RedbQueryable(_provider, newContext, _filterParser, _orderingParser, _facetBuilder); } public virtual IRedbQueryable DistinctBy(Expression> keySelector) { if (keySelector == null) throw new ArgumentNullException(nameof(keySelector)); var newContext = _context.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 new RedbQueryable(_provider, newContext, _filterParser, _orderingParser, _facetBuilder); } public virtual IRedbQueryable DistinctByRedb(Expression> keySelector) { if (keySelector == null) throw new ArgumentNullException(nameof(keySelector)); var newContext = _context.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 new RedbQueryable(_provider, newContext, _filterParser, _orderingParser, _facetBuilder); } public virtual IRedbQueryable WithMaxRecursionDepth(int depth) { if (depth < 1) throw new ArgumentException("Max recursion depth must be positive", nameof(depth)); var newContext = _context.Clone(); newContext.MaxRecursionDepth = depth; return new RedbQueryable(_provider, newContext, _filterParser, _orderingParser, _facetBuilder); } public virtual IRedbQueryable WithLazyReferences(bool enabled = true) { var newContext = _context.Clone(); newContext.LazyReferences = enabled; return new RedbQueryable(_provider, newContext, _filterParser, _orderingParser, _facetBuilder); } /// /// Builds expression for query execution /// protected virtual Expression BuildExpression() { // Expression representing the entire query will be created here // Return stub for now - concrete implementation will be in provider return Expression.Constant(_context); } /// /// Builds expression for record count /// protected virtual Expression BuildCountExpression() { // Similarly for Count return Expression.Constant(_context); } /// /// 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; } // ===== TREE METHODS ===== // For base RedbQueryable these methods throw NotSupportedException // PostgresTreeQueryable overrides them with real implementation public virtual IRedbQueryable WhereHasAncestor( Expression> ancestorCondition, int? maxDepth = null) where TTarget : class { throw new NotSupportedException( "Tree methods are not supported in non-tree queries. " + "Use ITreeQueryProvider.CreateTreeQuery() to create queries with tree support."); } public virtual IRedbQueryable WhereHasDescendant( Expression> descendantCondition, int? maxDepth = null) where TTarget : class { throw new NotSupportedException( "Tree methods are not supported in non-tree queries. " + "Use ITreeQueryProvider.CreateTreeQuery() to create queries with tree support."); } public virtual IRedbQueryable WhereLevel(int level) { throw new NotSupportedException( "Tree methods are not supported in non-tree queries. " + "Use ITreeQueryProvider.CreateTreeQuery() to create queries with tree support."); } public virtual IRedbQueryable WhereLevel(Expression> levelCondition) { throw new NotSupportedException( "Tree methods are not supported in non-tree queries. " + "Use ITreeQueryProvider.CreateTreeQuery() to create queries with tree support."); } public virtual IRedbQueryable WhereRoots() { throw new NotSupportedException( "Tree methods are not supported in non-tree queries. " + "Use ITreeQueryProvider.CreateTreeQuery() to create queries with tree support."); } public virtual IRedbQueryable WhereLeaves() { throw new NotSupportedException( "Tree methods are not supported in non-tree queries. " + "Use ITreeQueryProvider.CreateTreeQuery() to create queries with tree support."); } public virtual IRedbQueryable WhereChildrenOf(long parentId) { throw new NotSupportedException( "Tree methods are not supported in non-tree queries. " + "Use ITreeQueryProvider.CreateTreeQuery() to create queries with tree support."); } public virtual IRedbQueryable WhereChildrenOf(IRedbObject parentObject) { throw new NotSupportedException( "Tree methods are not supported in non-tree queries. " + "Use ITreeQueryProvider.CreateTreeQuery() to create queries with tree support."); } public virtual IRedbQueryable WhereDescendantsOf(long ancestorId, int? maxDepth = null) { throw new NotSupportedException( "Tree methods are not supported in non-tree queries. " + "Use ITreeQueryProvider.CreateTreeQuery() to create queries with tree support."); } public virtual IRedbQueryable WhereDescendantsOf(IRedbObject ancestorObject, int? maxDepth = null) { throw new NotSupportedException( "Tree methods are not supported in non-tree queries. " + "Use ITreeQueryProvider.CreateTreeQuery() to create queries with tree support."); } public virtual IRedbQueryable WithMaxDepth(int depth) { throw new NotSupportedException( "Tree methods are not supported in non-tree queries. " + "Use ITreeQueryProvider.CreateTreeQuery() to create queries with tree support."); } public virtual IRedbQueryable WithPropsDepth(int depth) { var newContext = _context.Clone(); newContext.PropsDepth = depth; return new RedbQueryable(_provider, newContext, _filterParser, _orderingParser, _facetBuilder); } // ===== MATERIALIZATION METHODS ===== public virtual async Task>> ToTreeListAsync(CancellationToken cancellationToken = default) { throw new NotSupportedException( "ToTreeListAsync is not supported in non-tree queries. " + "Use ITreeQueryProvider.CreateTreeQuery() to create queries with tree support."); } public virtual async Task>> ToFlatListAsync(CancellationToken cancellationToken = default) { throw new NotSupportedException( "ToFlatListAsync is not supported in non-tree queries. " + "Use ITreeQueryProvider.CreateTreeQuery() to create queries with tree support."); } public virtual async Task> ToRootListAsync(CancellationToken cancellationToken = default) { throw new NotSupportedException( "ToRootListAsync is not supported in non-tree queries. " + "Use ITreeQueryProvider.CreateTreeQuery() to create queries with tree support."); } public virtual async Task DeleteAsync(CancellationToken cancellationToken = default) { // Pass FilterExpression directly (Pro uses it for PVT-based deletion, OpenSource falls back to facet-JSON) return await _provider.ExecuteDeleteAsync(_context.SchemeId, _context.Filter, cancellationToken: cancellationToken); } // ===== AGGREGATIONS ===== // Every aggregate method below ends in one of these three provider calls. They are the seam a // derived queryable overrides to aggregate over its own object set: a tree query has to range // over its subtree, and the flat provider calls know nothing but the scheme. /// One aggregate over a Props field of the objects this query selects. protected virtual Task ExecuteAggregateCoreAsync( string fieldPath, Aggregation.AggregateFunction function, CancellationToken cancellationToken) => _provider.ExecuteAggregateAsync(_context.SchemeId, fieldPath, function, _context.Filter, cancellationToken: cancellationToken); /// Several aggregates in one statement over the objects this query selects. protected virtual Task ExecuteAggregateBatchCoreAsync( IEnumerable requests, CancellationToken cancellationToken) => _provider.ExecuteAggregateBatchAsync(_context.SchemeId, requests, _context.Filter, cancellationToken: cancellationToken); /// Grouped aggregates; with no group fields, one row over the objects this query selects. protected virtual Task ExecuteGroupedAggregateCoreAsync( IEnumerable groupFields, IEnumerable aggregations, CancellationToken cancellationToken) => _provider.ExecuteGroupedAggregateAsync(_context.SchemeId, groupFields, aggregations, _context.Filter, cancellationToken: cancellationToken); public virtual async Task SumAsync(Expression> selector, CancellationToken cancellationToken = default) where TField : struct { var fieldPath = ExtractFieldPath(selector); // Pass FilterExpression directly (Pro uses it, Free falls back to facet-JSON) var result = await ExecuteAggregateCoreAsync(fieldPath, Aggregation.AggregateFunction.Sum, cancellationToken); return result ?? 0m; } public virtual async Task AverageAsync(Expression> selector, CancellationToken cancellationToken = default) where TField : struct { var fieldPath = ExtractFieldPath(selector); // Pass FilterExpression directly (Pro uses it, Free falls back to facet-JSON) var result = await ExecuteAggregateCoreAsync(fieldPath, Aggregation.AggregateFunction.Average, cancellationToken); return result ?? 0m; } public virtual async Task MinAsync(Expression> selector, CancellationToken cancellationToken = default) where TField : struct { var fieldPath = ExtractFieldPath(selector); // Pass FilterExpression directly (Pro uses it, Free falls back to facet-JSON) var result = await ExecuteAggregateCoreAsync(fieldPath, Aggregation.AggregateFunction.Min, cancellationToken); if (result == null) return null; return (TField)Utils.TemporalDecoder.ChangeType(result.Value, typeof(TField)); } public virtual async Task MaxAsync(Expression> selector, CancellationToken cancellationToken = default) where TField : struct { var fieldPath = ExtractFieldPath(selector); // Pass FilterExpression directly (Pro uses it, Free falls back to facet-JSON) var result = await ExecuteAggregateCoreAsync(fieldPath, Aggregation.AggregateFunction.Max, cancellationToken); if (result == null) return null; return (TField)Utils.TemporalDecoder.ChangeType(result.Value, typeof(TField)); } // ===== AGGREGATIONS FOR BASE FIELDS ===== /// /// Sum of base IRedbObject field values (ValueLong, Key, etc.) /// SQL: uses aggregate_grouped with empty grouping for base fields /// public virtual async Task SumRedbAsync(Expression> selector, CancellationToken cancellationToken = default) where TField : struct { var fieldPath = ExtractFieldPathRedb(selector); // Use aggregate_grouped with empty group_fields var groupFields = Array.Empty(); var aggregations = new[] { new Aggregation.AggregateRequest { FieldPath = $"0$:{fieldPath}", Function = Aggregation.AggregateFunction.Sum, Alias = "result" }}; // Pass FilterExpression directly: Pro's filterJson grouped-overload drops the filter and // aggregates the whole scheme (same defect fixed in AggregateAsync). Free converts it to facet-JSON. var jsonResult = await ExecuteGroupedAggregateCoreAsync(groupFields, aggregations, cancellationToken); if (jsonResult != null && jsonResult.RootElement.GetArrayLength() > 0) { var firstRow = jsonResult.RootElement[0]; // SUM over an EMPTY selection is NULL in SQL (an aggregate with no GROUP BY still returns one // row). Now that the filter is honoured, WhereRedb(...) matching nothing produces exactly that. // Read it as a number and it throws (JsonElement.GetDecimal requires a Number kind) — so treat // NULL as 0m: an empty sum is 0 (Enumerable.Sum semantics; a ledger with no movements is 0). if (firstRow.TryGetProperty("result", out var value) && value.ValueKind != JsonValueKind.Null) { return value.GetDecimal(); } } return 0m; } /// /// Average value of base IRedbObject field /// SQL: uses aggregate_grouped with empty grouping /// public virtual async Task AverageRedbAsync(Expression> selector, CancellationToken cancellationToken = default) where TField : struct { var fieldPath = ExtractFieldPathRedb(selector); var groupFields = Array.Empty(); var aggregations = new[] { new Aggregation.AggregateRequest { FieldPath = $"0$:{fieldPath}", Function = Aggregation.AggregateFunction.Average, Alias = "result" }}; // Pass FilterExpression directly (Pro drops filterJson here — see SumRedbAsync). var jsonResult = await ExecuteGroupedAggregateCoreAsync(groupFields, aggregations, cancellationToken); if (jsonResult != null && jsonResult.RootElement.GetArrayLength() > 0) { var firstRow = jsonResult.RootElement[0]; // AVG over an empty selection is NULL (see SumRedbAsync) — guard against GetDecimal throwing. if (firstRow.TryGetProperty("result", out var value) && value.ValueKind != JsonValueKind.Null) return value.GetDecimal(); } return 0m; } /// /// Minimum value of base IRedbObject field (ValueLong, Key, DateCreate, etc.) /// SQL: uses aggregate_grouped with empty grouping /// public virtual async Task MinRedbAsync(Expression> selector, CancellationToken cancellationToken = default) where TField : struct { var fieldPath = ExtractFieldPathRedb(selector); var groupFields = Array.Empty(); var aggregations = new[] { new Aggregation.AggregateRequest { FieldPath = $"0$:{fieldPath}", Function = Aggregation.AggregateFunction.Min, Alias = "result" }}; // Pass FilterExpression directly (Pro drops filterJson here — see SumRedbAsync). var jsonResult = await ExecuteGroupedAggregateCoreAsync(groupFields, aggregations, cancellationToken); if (jsonResult != null && jsonResult.RootElement.GetArrayLength() > 0) { var firstRow = jsonResult.RootElement[0]; if (firstRow.TryGetProperty("result", out var value) && value.ValueKind != JsonValueKind.Null) return (TField?)Utils.JsonValueConverter.Convert(value, typeof(TField)); } return null; } /// /// Maximum value of base IRedbObject field (ValueLong, Key, DateCreate, etc.) /// SQL: uses aggregate_grouped with empty grouping /// public virtual async Task MaxRedbAsync(Expression> selector, CancellationToken cancellationToken = default) where TField : struct { var fieldPath = ExtractFieldPathRedb(selector); var groupFields = Array.Empty(); var aggregations = new[] { new Aggregation.AggregateRequest { FieldPath = $"0$:{fieldPath}", Function = Aggregation.AggregateFunction.Max, Alias = "result" }}; // Pass FilterExpression directly (Pro drops filterJson here — see SumRedbAsync). var jsonResult = await ExecuteGroupedAggregateCoreAsync(groupFields, aggregations, cancellationToken); if (jsonResult != null && jsonResult.RootElement.GetArrayLength() > 0) { var firstRow = jsonResult.RootElement[0]; if (firstRow.TryGetProperty("result", out var value) && value.ValueKind != JsonValueKind.Null) return (TField?)Utils.JsonValueConverter.Convert(value, typeof(TField)); } return null; } /// /// Get field statistics (Sum, Avg, Min, Max, Count) in one call /// Executed as ONE SQL query! /// public virtual async Task> GetStatisticsAsync( Expression> selector, CancellationToken cancellationToken = default) where TField : struct { var fieldPath = ExtractFieldPath(selector); var schemeId = _context.SchemeId; // ONE SQL query for all aggregations! var requests = new[] { new Aggregation.AggregateRequest { FieldPath = fieldPath, Function = Aggregation.AggregateFunction.Sum, Alias = "Sum" }, new Aggregation.AggregateRequest { FieldPath = fieldPath, Function = Aggregation.AggregateFunction.Average, Alias = "Average" }, new Aggregation.AggregateRequest { FieldPath = fieldPath, Function = Aggregation.AggregateFunction.Min, Alias = "Min" }, new Aggregation.AggregateRequest { FieldPath = fieldPath, Function = Aggregation.AggregateFunction.Max, Alias = "Max" }, new Aggregation.AggregateRequest { FieldPath = fieldPath, Function = Aggregation.AggregateFunction.Count, Alias = "Count" } }; // Pass FilterExpression directly: Pro's filterJson batch-overload drops the filter (whole-scheme // stats). Same fix as AggregateAsync; Free converts to facet-JSON. var batchResult = await ExecuteAggregateBatchCoreAsync(requests, cancellationToken); return new Aggregation.FieldStatistics { Sum = batchResult.Get("Sum") ?? 0m, Average = batchResult.Get("Average") ?? 0m, Min = batchResult.Get("Min"), Max = batchResult.Get("Max"), Count = batchResult.Get("Count") ?? 0 }; } /// /// Flexible aggregation - choose what to aggregate via Agg.Sum/Avg/Min/Max/Count /// Executed as ONE SQL query (aggregate_batch)! /// public virtual async Task AggregateAsync(Expression, TResult>> selector, CancellationToken cancellationToken = default) { var schemeId = _context.SchemeId; // Every Agg.* call of the selector; the SQL preview of the aggregate reads the same requests. var requests = Aggregation.AggregateSelectorParser.Parse(selector); // BUG FIX: pass the FilterExpression directly so providers that only // honour the typed overload (e.g. Pro) don't silently drop the outer Where. var batchResult = await ExecuteAggregateBatchCoreAsync(requests, cancellationToken); // Build result return BuildAggregateResult(selector, batchResult.Values); } /// /// Flexible aggregation ONLY for base IRedbObject fields /// Executed as ONE SQL query (aggregate_grouped without grouping) /// public virtual async Task AggregateRedbAsync(Expression> selector, CancellationToken cancellationToken = default) { var schemeId = _context.SchemeId; // Parse expression and find all Agg.* calls var aggregations = ParseAggregateRedbExpression(selector); // Use aggregate_grouped with EMPTY grouping var groupFields = Array.Empty(); var requests = aggregations.Select(agg => new Aggregation.AggregateRequest { // COUNT(*) - don't add 0$: (field is empty or "*") // For other base fields - add 0$: FieldPath = (agg.Function == Aggregation.AggregateFunction.Count && (string.IsNullOrEmpty(agg.FieldPath) || agg.FieldPath == "*")) ? agg.FieldPath // COUNT(*) - leave as is : $"0$:{agg.FieldPath}", // Base field - add prefix Function = agg.Function, Alias = agg.PropertyName }); // Pass FilterExpression directly (Pro drops filterJson here — see SumRedbAsync). var jsonResult = await ExecuteGroupedAggregateCoreAsync(groupFields, requests, cancellationToken); // Parse result (first row, since no grouping) if (jsonResult != null && jsonResult.RootElement.GetArrayLength() > 0) { var firstRow = jsonResult.RootElement[0]; return BuildAggregateRedbResultFromJson(selector, firstRow); } throw new InvalidOperationException("AggregateRedbAsync returned no results"); } /// /// Parses AggregateRedbAsync expression for base IRedbObject fields /// private List<(string PropertyName, string FieldPath, Aggregation.AggregateFunction Function)> ParseAggregateRedbExpression( Expression> selector) { var result = new List<(string PropertyName, string FieldPath, Aggregation.AggregateFunction Function)>(); if (selector.Body is NewExpression newExpr) { for (int i = 0; i < newExpr.Arguments.Count; i++) { var propName = newExpr.Members?[i].Name ?? $"Item{i}"; var arg = newExpr.Arguments[i]; if (arg is MethodCallExpression methodCall && methodCall.Method.DeclaringType == typeof(Aggregation.Agg)) { var funcName = methodCall.Method.Name; var function = funcName switch { "Sum" => Aggregation.AggregateFunction.Sum, "Average" => Aggregation.AggregateFunction.Average, "Min" => Aggregation.AggregateFunction.Min, "Max" => Aggregation.AggregateFunction.Max, "Count" => Aggregation.AggregateFunction.Count, _ => throw new NotSupportedException($"Unknown aggregation: {funcName}") }; // Extract base field path (without Props!) string fieldPath = "*"; // for Count() if (methodCall.Arguments.Count > 0) { // For IRedbObject: extract property name directly if (methodCall.Arguments[0] is MemberExpression member) { fieldPath = member.Member.Name; // Id, ValueLong, DateCreate, etc. } } result.Add((propName, fieldPath, function)); } } } return result; } /// /// Builds AggregateRedbAsync result from JSON element /// private TResult BuildAggregateRedbResultFromJson( Expression> selector, JsonElement jsonRow) { if (selector.Body is NewExpression newExpr && newExpr.Constructor != null) { var args = new object?[newExpr.Arguments.Count]; for (int i = 0; i < newExpr.Arguments.Count; i++) { var propName = newExpr.Members?[i].Name ?? $"Item{i}"; var targetType = newExpr.Constructor.GetParameters()[i].ParameterType; object? value = null; if (jsonRow.TryGetProperty(propName, out var jsonValue)) { value = Query.Utils.JsonValueConverter.Convert(jsonValue, targetType); } args[i] = ConvertAggregateValue(value, targetType); } return (TResult)newExpr.Constructor.Invoke(args); } throw new ArgumentException("AggregateRedbAsync requires anonymous type creation (new { ... })", nameof(selector)); } /// /// Creates aggregation result from dictionary of values /// private TResult BuildAggregateResult( Expression, TResult>> selector, Dictionary results) { if (selector.Body is NewExpression newExpr && newExpr.Constructor != null) { var args = new object?[newExpr.Arguments.Count]; for (int i = 0; i < newExpr.Arguments.Count; i++) { var propName = newExpr.Members?[i].Name ?? $"Item{i}"; var targetType = newExpr.Constructor.GetParameters()[i].ParameterType; results.TryGetValue(propName, out var value); args[i] = ConvertAggregateValue(value, targetType); } return (TResult)newExpr.Constructor.Invoke(args); } throw new NotSupportedException("AggregateAsync supports only anonymous types"); } private object? ConvertAggregateValue(object? value, Type targetType) { if (value == null) { return targetType.IsValueType ? Activator.CreateInstance(targetType) : null; } var underlying = Nullable.GetUnderlyingType(targetType) ?? targetType; return underlying switch { Type t when t == typeof(int) => Convert.ToInt32(value), Type t when t == typeof(long) => Convert.ToInt64(value), Type t when t == typeof(decimal) => redb.Core.Utils.RedbDecimal.From(value), Type t when t == typeof(double) => Convert.ToDouble(value), Type t when t == typeof(float) => Convert.ToSingle(value), _ => Utils.TemporalDecoder.ChangeType(value, underlying) }; } /// /// The field path of a single aggregate's selector, read by the walker of AggregateAsync: an element, a dictionary /// entry and the Value of a nullable are read as such, and a path that is not a chain of fields is refused. /// protected string ExtractFieldPath(Expression> selector) => Aggregation.AggregateSelectorParser.ExtractFieldPath(selector.Body); /// /// Extracts base field path from IRedbObject expression /// Used for *RedbAsync methods (SumRedbAsync, GroupByRedb, etc.) /// protected string ExtractFieldPathRedb(Expression> selector) { var body = selector.Body; // Handle Convert (for nullable types) if (body is UnaryExpression unary && unary.NodeType == ExpressionType.Convert) { body = unary.Operand; } if (body is MemberExpression member) { // For IRedbObject: just property name (Id, Name, ValueLong, etc.) return member.Member.Name; } throw new ArgumentException("Cannot extract field path from IRedbObject selector", nameof(selector)); } /// /// Builds JSON filter from current query context /// protected virtual string? BuildFilterJson() { if (_context.Filter == null || _facetBuilder == null) return null; var json = _facetBuilder.BuildFacetFilters(_context.Filter); return string.IsNullOrEmpty(json) || json == "{}" ? null : json; } // ===== GROUPBY ===== /// /// Grouping with aggregations. /// Pro version receives FilterExpression directly for proper SQL compilation. /// public virtual Grouping.IRedbGroupedQueryable GroupBy( Expression> keySelector) { // Pass FilterExpression directly (Pro uses it, Free falls back to facet-JSON) return new Grouping.RedbGroupedQueryable( _provider, _context.SchemeId, _context.Filter, keySelector); } /// /// Grouping by base IRedbObject fields (id, scheme_id, parent_id, etc.) /// Uses IRedbObject for compile-time safety - Props not visible! /// Pro version receives FilterExpression directly for proper SQL compilation. /// public virtual Grouping.IRedbGroupedQueryable GroupByRedb( Expression> keySelector) { // Pass FilterExpression directly (Pro uses it, Free falls back to facet-JSON) return new Grouping.RedbGroupedQueryable( _provider, _context.SchemeId, _context.Filter, keySelector, isBaseFieldGrouping: true); } /// /// Grouping by array elements /// public virtual Grouping.IRedbGroupedQueryable GroupByArray( Expression>> arraySelector, Expression> keySelector) { return new Grouping.RedbArrayGroupedQueryable( _provider, _context.SchemeId, null, _context.Filter, arraySelector, keySelector); } // ===== WINDOW FUNCTIONS ===== /// /// Query with window functions. /// Pro version receives FilterExpression directly for proper SQL compilation. /// public virtual Window.IRedbWindowedQueryable WithWindow( Action> windowConfig) { var windowSpec = new Window.WindowSpec(); windowConfig(windowSpec); // Pass FilterExpression directly (Pro uses it, Free falls back to facet-JSON) return new Window.RedbWindowedQueryable( _provider, _context.SchemeId, _context.Filter, windowSpec, _context.Limit, _context.Offset); } // ===== SQL PREVIEW (like EF Core) ===== /// /// Get SQL representation of query (for debugging). /// Analog of EF Core ToQueryString(). /// Pro version shows PVT SQL, Open Source - redb_json_objects. /// Note: Uses Task.Run to avoid SynchronizationContext deadlock in Blazor/ASP.NET. /// public virtual string ToSqlString() { // Use Task.Run to avoid Blazor SynchronizationContext deadlock return Task.Run(() => _provider.GetSqlPreviewAsync(_context)).GetAwaiter().GetResult(); } /// /// Async version of getting SQL (recommended) /// public virtual Task ToSqlStringAsync(CancellationToken cancellationToken = default) { return _provider.GetSqlPreviewAsync(_context, cancellationToken: cancellationToken); } /// /// Get JSON filter that will be sent to SQL function (for diagnostics) /// public virtual Task ToFilterJsonAsync(CancellationToken cancellationToken = default) { return _provider.GetFilterJsonAsync(_context, cancellationToken: cancellationToken); } private string BuildOrderByJson() { if (!_context.Orderings.Any()) return "[]"; var orders = _context.Orderings.Select(o => new { field = o.Property.Name, dir = o.Direction.ToString().ToUpper() }); return System.Text.Json.JsonSerializer.Serialize(orders); } } Path: redb/redb.Core/Query/RedbQueryableExtensions.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/RedbQueryableExtensions.cs ---- using System; using System.Linq.Expressions; using System.Reflection; using System.Threading.Tasks; using redb.Core.Models.Entities; using redb.Core.Query.Aggregation; using redb.Core.Query.Base; namespace redb.Core.Query; /// /// Extension methods for IRedbQueryable. /// Adds ToSqlStringAsync() and ToAggregateSqlStringAsync() for SQL preview (debugging). /// public static class RedbQueryableExtensions { /// /// Returns the SQL query that will be executed (for debugging). /// Similar to .ToQueryString() from EF Core, but for REDB faceted queries. /// Works for both standard search and tree queries. /// /// Object properties type /// LINQ query /// Final SQL query as text /// If provider does not support SQL preview public static async Task ToSqlStringAsync( this IRedbQueryable query) where TProps : class, new() { if (query == null) throw new ArgumentNullException(nameof(query)); try { var queryType = query.GetType(); var contextField = queryType.GetField("_context", BindingFlags.NonPublic | BindingFlags.Instance); if (contextField == null) throw new InvalidOperationException($"Cannot get _context from {queryType.Name}"); var context = contextField.GetValue(query); if (context == null) throw new InvalidOperationException("Context is null"); var providerField = queryType.GetField("_provider", BindingFlags.NonPublic | BindingFlags.Instance); if (providerField == null) throw new InvalidOperationException($"Cannot get _provider from {queryType.Name}"); var provider = providerField.GetValue(query); if (provider == null) throw new InvalidOperationException("Provider is null"); if (provider is QueryProviderBase queryProvider) { if (context is QueryContext standardContext) return await queryProvider.GetSqlPreviewAsync(standardContext); throw new InvalidOperationException($"Context has unexpected type: {context.GetType().Name}"); } if (provider is TreeQueryProviderBase treeProvider) { if (context is TreeQueryContext treeContext) return await treeProvider.GetSqlPreviewAsync(treeContext); throw new InvalidOperationException($"Context has unexpected type: {context.GetType().Name}"); } throw new NotSupportedException( $"Provider type {provider.GetType().Name} does not support SQL preview."); } catch (Exception ex) when (ex is not NotSupportedException) { throw new InvalidOperationException($"Error getting SQL preview: {ex.Message}", ex); } } /// /// Returns the SQL query for aggregation (for debugging). /// Similar to .ToQueryString() from EF Core, but for REDB aggregations. /// /// Object properties type /// Aggregation result type /// LINQ query /// Aggregation expression (same as in AggregateAsync) /// SQL query that will be executed public static async Task ToAggregateSqlStringAsync( this IRedbQueryable query, Expression, TResult>> selector) where TProps : class, new() { if (query == null) throw new ArgumentNullException(nameof(query)); if (selector == null) throw new ArgumentNullException(nameof(selector)); try { var queryType = query.GetType(); var contextField = queryType.GetField("_context", BindingFlags.NonPublic | BindingFlags.Instance); var providerField = queryType.GetField("_provider", BindingFlags.NonPublic | BindingFlags.Instance); if (contextField == null || providerField == null) throw new InvalidOperationException("Cannot get _context or _provider"); var context = contextField.GetValue(query); var provider = providerField.GetValue(query); if (context == null || provider == null) throw new InvalidOperationException("Context or Provider is null"); if (provider is QueryProviderBase queryProvider && context is QueryContext standardContext) { return await queryProvider.GetAggregateSqlPreviewAsync(standardContext, selector); } throw new NotSupportedException( $"Provider type {provider.GetType().Name} does not support SQL preview for aggregations."); } catch (Exception ex) when (ex is not NotSupportedException) { throw new InvalidOperationException($"Error getting SQL preview: {ex.Message}", ex); } } } Path: redb/redb.Core/Query/Sql.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/Sql.cs ---- using System; namespace redb.Core.Query; /// /// SQL functions for use in LINQ expressions. /// Translated to native SQL by the active provider during query generation. /// public static class Sql { /// /// Call custom SQL function. /// /// Return value type /// SQL function name (e.g.: "COALESCE", "POWER", "my_custom_func") /// Function arguments (properties, constants, expressions) /// Function result (used only for typing) /// /// COALESCE(pvt."Stock", 0) /// .Where(p => Sql.Function<long>("COALESCE", p.Stock, 0) > 50) /// /// POWER(pvt."Age", 2) /// .Where(p => Sql.Function<double>("POWER", p.Age, 2) > 100) /// /// my_custom_func(pvt."Name", pvt."Code") /// .Where(p => Sql.Function<string>("my_custom_func", p.Name, p.Code) == "result") /// public static TResult Function(string functionName, params object?[] args) { throw new InvalidOperationException( "Sql.Function() can only be used within LINQ expressions (Where, WhereRedb, etc.). " + "It cannot be called directly."); } } Path: redb/redb.Core/Query/SqlPreviewResult.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/SqlPreviewResult.cs ---- namespace redb.Core.Query; /// /// Result of SQL preview function execution. /// Used for mapping result from get_search_sql_preview() and related functions. /// public class SqlPreviewResult { /// /// Final SQL query as text. /// public string sql_preview { get; set; } = string.Empty; } Path: redb/redb.Core/Query/TreeProjectedQueryable.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/TreeProjectedQueryable.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.Query; namespace redb.Core.Query; /// /// Implementation of projections for tree LINQ queries in REDB /// Specialized version for TreeRedbObject<TProps> /// public class TreeProjectedQueryable : IRedbProjectedQueryable where TProps : class, new() { private readonly IRedbQueryable _sourceQuery; private readonly Expression, TResult>> _projection; // Chain of operations to execute after projection private readonly List>> _wherePredicates = new(); private readonly List<(Expression KeySelector, bool IsDescending)> _orderByExpressions = new(); // TPQ-1 (review 2026-09-24), the tree twin of S-4 in RedbProjectedQueryable: Where/OrderBy run in memory after // the projection, so a Take/Skip called after them must too - sent to the source query it cut the page from // the unfiltered, unsorted rows. Distinct is over the projected rows, not over the source objects (every node // is distinct there). Pipeline: Where* -> OrderBy* -> Distinct -> Skip/Take in call order. A Take/Skip before // the first in-memory operation still goes to SQL. private readonly bool _isDistinct; private readonly List<(bool IsSkip, int Count)> _pagingOps = new(); public TreeProjectedQueryable( IRedbQueryable sourceQuery, Expression, TResult>> projection) { _sourceQuery = sourceQuery; _projection = projection; } // Private constructor for creating copies with additional operations private TreeProjectedQueryable( IRedbQueryable sourceQuery, Expression, TResult>> projection, List>> wherePredicates, List<(Expression KeySelector, bool IsDescending)> orderByExpressions, bool isDistinct, List<(bool IsSkip, int Count)> pagingOps) { _sourceQuery = sourceQuery; _projection = projection; _wherePredicates = new List>>(wherePredicates); _orderByExpressions = new List<(Expression, bool)>(orderByExpressions); _isDistinct = isDistinct; _pagingOps = new List<(bool, int)>(pagingOps); } private TreeProjectedQueryable With( IRedbQueryable? sourceQuery = null, List>>? wherePredicates = null, List<(Expression KeySelector, bool IsDescending)>? orderByExpressions = null, bool? isDistinct = null) => new(sourceQuery ?? _sourceQuery, _projection, wherePredicates ?? _wherePredicates, orderByExpressions ?? _orderByExpressions, isDistinct ?? _isDistinct, _pagingOps); private bool HasInMemoryOps => _wherePredicates.Count > 0 || _orderByExpressions.Count > 0 || _isDistinct || _pagingOps.Count > 0; public IRedbProjectedQueryable Where(Expression> predicate) { if (predicate == null) throw new ArgumentNullException(nameof(predicate)); // Add filter to operations chain return With(wherePredicates: new List>>(_wherePredicates) { predicate }); } public IRedbProjectedQueryable OrderBy(Expression> keySelector) { if (keySelector == null) throw new ArgumentNullException(nameof(keySelector)); // Replace existing sorting return With(orderByExpressions: new List<(Expression, bool)> { (keySelector, false) }); } public IRedbProjectedQueryable OrderByDescending(Expression> keySelector) { if (keySelector == null) throw new ArgumentNullException(nameof(keySelector)); // Replace existing sorting return With(orderByExpressions: new List<(Expression, bool)> { (keySelector, true) }); } public IRedbProjectedQueryable ThenBy(Expression> keySelector) => AddThenBy(keySelector, descending: false); public IRedbProjectedQueryable ThenByDescending(Expression> keySelector) => AddThenBy(keySelector, descending: true); // A tree is loaded whole and sorted in memory: ThenBy adds a key to that ordering. private IRedbProjectedQueryable AddThenBy(LambdaExpression keySelector, bool descending) { if (keySelector == null) throw new ArgumentNullException(nameof(keySelector)); if (_orderByExpressions.Count == 0) throw new InvalidOperationException("ThenBy continues an ordering: call OrderBy or OrderByDescending first."); return With(orderByExpressions: new List<(Expression, bool)>(_orderByExpressions) { (keySelector, descending) }); } public IRedbProjectedQueryable Take(int count) { if (HasInMemoryOps) return WithPagingOp(isSkip: false, count); return With(sourceQuery: _sourceQuery.Take(count)); } public IRedbProjectedQueryable Skip(int count) { if (HasInMemoryOps) return WithPagingOp(isSkip: true, count); return With(sourceQuery: _sourceQuery.Skip(count)); } private TreeProjectedQueryable WithPagingOp(bool isSkip, int count) { var copy = With(); copy._pagingOps.Add((isSkip, count)); return copy; } public IRedbProjectedQueryable Distinct() => With(isDistinct: true); public async Task> ToListAsync(CancellationToken cancellationToken = default) { // Everything after the projection runs in memory over the loaded nodes. var allObjects = await _sourceQuery.ToListAsync(cancellationToken: cancellationToken); var projection = _projection.Compile(); IEnumerable projectedResults = allObjects.Select(redbObj => projection((TreeRedbObject)redbObj)); foreach (var wherePredicate in _wherePredicates) projectedResults = projectedResults.Where(wherePredicate.Compile()); IOrderedEnumerable? orderedResults = null; foreach (var (keySelector, isDescending) in _orderByExpressions) { var compiledKeySelector = ((LambdaExpression)keySelector).Compile(); if (orderedResults == null) orderedResults = isDescending ? projectedResults.OrderByDescending(item => compiledKeySelector.DynamicInvoke(item)) : projectedResults.OrderBy(item => compiledKeySelector.DynamicInvoke(item)); else orderedResults = isDescending ? orderedResults.ThenByDescending(item => compiledKeySelector.DynamicInvoke(item)) : orderedResults.ThenBy(item => compiledKeySelector.DynamicInvoke(item)); } if (orderedResults != null) projectedResults = orderedResults; if (_isDistinct) projectedResults = projectedResults.Distinct(); foreach (var (isSkip, n) in _pagingOps) projectedResults = isSkip ? projectedResults.Skip(n) : projectedResults.Take(n); return projectedResults.ToList(); } public async Task CountAsync(CancellationToken cancellationToken = default) { var results = await ToListAsync(cancellationToken: cancellationToken); return results.Count; } public async Task FirstOrDefaultAsync(CancellationToken cancellationToken = default) { var results = await ToListAsync(cancellationToken: cancellationToken); return results.FirstOrDefault(); } /// /// Get projection info for tree queries (not optimized yet) /// public Task GetProjectionInfoAsync(CancellationToken cancellationToken = default) { var info = @"=== TREE PROJECTION INFO === SQL Function: search_objects_with_facets (full load) Note: Tree projections are not yet optimized for SQL projection All data is loaded and projected in memory"; return Task.FromResult(info); } } Path: redb/redb.Core/Query/Utils/JsonValueConverter.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/Utils/JsonValueConverter.cs ---- using System.Globalization; using System.Text.Json; using redb.Core.Models.Entities; namespace redb.Core.Query.Utils; /// /// Unified converter JsonElement → CLR types for redb props values /// Supports all types: string, numeric, bool, DateTime, Guid /// public static class JsonValueConverter { /// /// Converts JsonElement to specified CLR type /// public static object? Convert(JsonElement elem, Type targetType) { if (elem.ValueKind == JsonValueKind.Null) return null; var underlyingType = Nullable.GetUnderlyingType(targetType) ?? targetType; return underlyingType switch { // Strings — accept any scalar JSON kind, stringify Number/Bool fallbacks Type t when t == typeof(string) => elem.ValueKind == JsonValueKind.String ? elem.GetString() : (elem.ValueKind == JsonValueKind.Number || elem.ValueKind == JsonValueKind.True || elem.ValueKind == JsonValueKind.False ? elem.GetRawText() : null), // RedbListItem — projected from grouping/aggregations as scalar (Id or Value). // Build a minimal stub so callers can surface the key without an extra ListProvider lookup. Type t when t == typeof(RedbListItem) => BuildListItemStub(elem), // Integers (all mapped to _Long). Read via ReadIntegral, NOT bare TryGetInt64: MSSql renders // SUM/MIN/MAX of a base bigint field as numeric(38,10), so FOR JSON emits "2130762.0000000000". // TryGetInt64 rejects any number carrying a decimal point and would silently fall back to 0 — // ReadIntegral truncates the zero fraction instead. Same provider-rendering tolerance already // applied to bool (SQLite 0/1) and DateTime formats below. Type t when t == typeof(long) => (long)ReadIntegral(elem), Type t when t == typeof(int) => (int)ReadIntegral(elem), Type t when t == typeof(short) => (short)ReadIntegral(elem), Type t when t == typeof(byte) => (byte)ReadIntegral(elem), // Decimals Type t when t == typeof(decimal) => elem.TryGetDecimal(out var d) ? d : 0m, Type t when t == typeof(double) => elem.TryGetDouble(out var dbl) ? dbl : 0.0, Type t when t == typeof(float) => elem.TryGetSingle(out var f) ? f : 0f, // Boolean — PostgreSQL emits JSON true/false; SQLite has no native bool and stores it as // INTEGER 0/1, so a grouping/projection column arrives as a JSON Number → treat nonzero as true. Type t when t == typeof(bool) => elem.ValueKind == JsonValueKind.True || (elem.ValueKind == JsonValueKind.Number && elem.TryGetDouble(out var bn) && bn != 0) || (elem.ValueKind == JsonValueKind.String && bool.TryParse(elem.GetString(), out var bl) && bl), // DateTime / DateTimeOffset — with PostgreSQL row_to_json() format support Type t when t == typeof(DateTime) => ParseDateTime(elem), Type t when t == typeof(DateTimeOffset) => ParseDateTimeOffset(elem), // TimeSpan and TimeOnly are stored as their Ticks in _Long: a group key, a MIN/MAX or an average arrives as // a number (an average with a fraction is truncated to whole ticks). They fell to the raw-text fallback // and the result constructor refused the string. Type t when t == typeof(TimeSpan) => TimeSpan.FromTicks((long)ReadIntegral(elem)), Type t when t == typeof(TimeOnly) => new TimeOnly((long)ReadIntegral(elem)), // Guid Type t when t == typeof(Guid) => elem.TryGetGuid(out var g) ? g : Guid.Empty, // Enums are stored by name; a number is read as the underlying value. Type t when t.IsEnum => elem.ValueKind == JsonValueKind.String ? Enum.Parse(t, elem.GetString()!, ignoreCase: false) : Enum.ToObject(t, (long)ReadIntegral(elem)), // Fallback _ => elem.GetRawText() }; } /// /// Reads a JSON scalar as an integral value, tolerating provider-specific numeric rendering. /// A plain integer takes the fast path; a number with a /// (zero) fraction — MSSql's numeric(38,10) aggregate rendering — is read as decimal and truncated; /// an integer-as-string is parsed defensively. Returns 0 for a non-numeric scalar. The caller casts /// the returned decimal to the concrete integer type, so a value beyond that type's range overflows /// loudly rather than silently collapsing to 0. /// private static decimal ReadIntegral(JsonElement elem) { if (elem.ValueKind == JsonValueKind.Number) { if (elem.TryGetInt64(out var l)) return l; if (elem.TryGetDecimal(out var d)) return decimal.Truncate(d); if (elem.TryGetDouble(out var db)) return redb.Core.Utils.RedbDecimal.FromDouble(Math.Truncate(db)); } else if (elem.ValueKind == JsonValueKind.String && decimal.TryParse(elem.GetString(), NumberStyles.Any, CultureInfo.InvariantCulture, out var ds)) { return decimal.Truncate(ds); } return 0m; } /// /// Builds a minimal from a scalar JSON value. /// Number → Id; String → Value; Object → full deserialization of known fields. /// private static RedbListItem? BuildListItemStub(JsonElement elem) { switch (elem.ValueKind) { case JsonValueKind.Number: return elem.TryGetInt64(out var id) ? new RedbListItem { Id = id } : null; case JsonValueKind.String: return new RedbListItem { Value = elem.GetString() ?? string.Empty }; case JsonValueKind.Object: var item = new RedbListItem(); if (elem.TryGetProperty("Id", out var idProp) && idProp.TryGetInt64(out var idVal)) item.Id = idVal; if (elem.TryGetProperty("Value", out var valProp) && valProp.ValueKind == JsonValueKind.String) item.Value = valProp.GetString() ?? string.Empty; if (elem.TryGetProperty("Alias", out var aliasProp) && aliasProp.ValueKind == JsonValueKind.String) item.Alias = aliasProp.GetString(); if (elem.TryGetProperty("IdList", out var listProp) && listProp.TryGetInt64(out var listVal)) item.IdList = listVal; return item; default: return null; } } /// /// Typed version /// public static T? Convert(JsonElement elem) => (T?)Convert(elem, typeof(T)); /// /// Get default value for type /// public static object? GetDefault(Type type) => type.IsValueType ? Activator.CreateInstance(type) : null; /// /// Parses DateTime with fallback for PostgreSQL row_to_json() format. /// private static DateTime ParseDateTime(JsonElement elem) { if (elem.ValueKind == JsonValueKind.Number) { // A numeric datetime → ask the registered backend decoder (e.g. SQLite REAL Julian day). if (elem.TryGetDouble(out var num) && TemporalDecoder.TryDecode(num, typeof(DateTime), out var dec) && dec != null) return (DateTime)dec; // Legacy fallback: Unix timestamp seconds. return DateTimeOffset.FromUnixTimeSeconds(elem.GetInt64()).DateTime; } var str = elem.GetString(); if (string.IsNullOrEmpty(str)) return DateTime.MinValue; // Parse as DateTimeOffset, then take the UTC instant — identical to the object // materialization path (PostgresInfinityDateTimeConverter). A bare DateTime.TryParse // with DateTimeStyles.None converts a zoned ISO string INTO THE CALLER'S LOCAL ZONE, // so the same field read through analytics (Min/Max/GroupBy/Window/projection) came // back shifted relative to the same field read through the object. REDB's contract is // that DateTime carries no zone: 14:00 written is 14:00 read, on any machine. if (DateTimeOffset.TryParse(str, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out var dto)) return Core.Utils.DateTimeConverter.DenormalizeFromStorage(dto); return DateTime.MinValue; } private static DateTimeOffset ParseDateTimeOffset(JsonElement elem) { if (elem.ValueKind == JsonValueKind.Number) { // A numeric datetime → ask the registered backend decoder (e.g. SQLite REAL Julian day). if (elem.TryGetDouble(out var num) && TemporalDecoder.TryDecode(num, typeof(DateTimeOffset), out var dec) && dec != null) return (DateTimeOffset)dec; // Legacy fallback: Unix timestamp seconds. return DateTimeOffset.FromUnixTimeSeconds(elem.GetInt64()); } var str = elem.GetString(); if (string.IsNullOrEmpty(str)) return DateTimeOffset.MinValue; // Invariant culture + ToUniversalTime, so the analytics path returns exactly what the // object materialization path returns (PostgresDateTimeOffsetConverter). DateTimeOffset // keeps native .NET semantics — it carries an instant, unlike DateTime. if (DateTimeOffset.TryParse(str, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out var dto)) return dto.ToUniversalTime(); return DateTimeOffset.MinValue; } } Path: redb/redb.Core/Query/Utils/TemporalDecoder.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/Utils/TemporalDecoder.cs ---- using System; namespace redb.Core.Query.Utils; /// /// Optional, provider-registered decoder for the case where a numeric database value /// targets a temporal CLR type (// /// ). This only arises when a backend stores datetimes as a number — /// e.g. SQLite, which stores them as a REAL Julian-day. Object reads go through that backend's /// own JSON projection (which already emits ISO text), but analytics paths (Min/Max, /// AggregateRedbAsync, Window, GroupBy) select the raw column and return the bare number. /// /// Core stays storage-agnostic: it knows nothing about Julian days or any epoch — it merely /// asks the registered decoder. The decoder is null by default, so providers that never return /// a number for a temporal column (PostgreSQL, SQL Server) are completely unaffected. The /// numeric backend (redb.SQLite) registers the decoder when it is configured. /// public static class TemporalDecoder { /// /// Set by the numeric-datetime backend at registration. Maps /// (rawNumber, targetTemporalType) → a // /// . Global by design (a process-wide codec), and idempotent — the same /// backend always registers the same function. /// public static Func? NumericDecoder; /// True for the temporal target types this decoder handles. public static bool IsTemporal(Type t) => t == typeof(DateTime) || t == typeof(DateTimeOffset) || t == typeof(DateOnly); /// /// If a decoder is registered, is numeric, and /// (or its underlying non-nullable type) is temporal, decode it /// and return true. Otherwise is null and the caller keeps its /// existing conversion path. /// public static bool TryDecode(object? value, Type targetType, out object? result) { result = null; if (NumericDecoder == null || value == null) return false; var t = Nullable.GetUnderlyingType(targetType) ?? targetType; if (!IsTemporal(t)) return false; double d; switch (value) { case double dd: d = dd; break; case float f: d = f; break; case decimal dec: d = (double)dec; break; case long l: d = l; break; case int i: d = i; break; case short s: d = s; break; default: return false; // already a DateTime/string/etc — not our case } result = NumericDecoder(d, t); return true; } /// /// that first lets a numeric value /// destined for a temporal type be decoded by the registered backend decoder. Non-temporal /// or non-numeric inputs fall straight through to . /// public static object ChangeType(object value, Type targetType) { if (TryTicks(value, targetType, out var fromTicks)) return fromTicks!; return TryDecode(value, targetType, out var decoded) && decoded != null ? decoded : redb.Core.Utils.RedbDecimal.ChangeType(value, targetType); } /// /// TimeSpan and TimeOnly are stored as their Ticks in _Long on every provider, so a number read back for one of them /// (a Min/Max, a group key, an average with a fraction, truncated) is its Ticks. /// private static bool TryTicks(object value, Type targetType, out object? result) { result = null; var t = Nullable.GetUnderlyingType(targetType) ?? targetType; if (t != typeof(TimeSpan) && t != typeof(TimeOnly)) return false; long ticks; switch (value) { case long l: ticks = l; break; case int i: ticks = i; break; case decimal m: ticks = (long)decimal.Truncate(m); break; case double d: ticks = (long)Math.Truncate(d); break; default: return false; } result = t == typeof(TimeSpan) ? TimeSpan.FromTicks(ticks) : new TimeOnly(ticks); return true; } } Path: redb/redb.Core/Query/Window/Frame.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/Window/Frame.cs ---- namespace redb.Core.Query.Window; /// /// Window boundary type /// public enum FrameBoundType { UnboundedPreceding, // UNBOUNDED PRECEDING Preceding, // N PRECEDING CurrentRow, // CURRENT ROW Following, // N FOLLOWING UnboundedFollowing // UNBOUNDED FOLLOWING } /// /// Frame type: ROWS or RANGE /// public enum FrameType { Rows, // ROWS BETWEEN Range // RANGE BETWEEN } /// /// Frame boundary /// public class FrameBound { public FrameBoundType Type { get; set; } public int? Offset { get; set; } // For N PRECEDING / N FOLLOWING public static FrameBound UnboundedPreceding() => new() { Type = FrameBoundType.UnboundedPreceding }; public static FrameBound Preceding(int n) => new() { Type = FrameBoundType.Preceding, Offset = n }; public static FrameBound CurrentRow() => new() { Type = FrameBoundType.CurrentRow }; public static FrameBound Following(int n) => new() { Type = FrameBoundType.Following, Offset = n }; public static FrameBound UnboundedFollowing() => new() { Type = FrameBoundType.UnboundedFollowing }; } /// /// Frame specification for window functions /// public class FrameSpec { public FrameType Type { get; set; } = FrameType.Rows; public FrameBound Start { get; set; } = FrameBound.UnboundedPreceding(); public FrameBound End { get; set; } = FrameBound.CurrentRow(); } /// /// Builder for creating FrameSpec /// public class FrameBuilder { private readonly FrameSpec _spec = new(); public FrameBuilder(FrameType type = FrameType.Rows) { _spec.Type = type; } /// /// ROWS BETWEEN n PRECEDING AND CURRENT ROW /// public FrameBuilder Preceding(int n) { _spec.Start = FrameBound.Preceding(n); _spec.End = FrameBound.CurrentRow(); return this; } /// /// ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW /// public FrameBuilder UnboundedPreceding() { _spec.Start = FrameBound.UnboundedPreceding(); _spec.End = FrameBound.CurrentRow(); return this; } /// /// ... AND n FOLLOWING /// public FrameBuilder AndFollowing(int n) { _spec.End = FrameBound.Following(n); return this; } /// /// ... AND CURRENT ROW /// public FrameBuilder AndCurrentRow() { _spec.End = FrameBound.CurrentRow(); return this; } /// /// ... AND UNBOUNDED FOLLOWING /// public FrameBuilder AndUnboundedFollowing() { _spec.End = FrameBound.UnboundedFollowing(); return this; } public FrameSpec Build() => _spec; public static implicit operator FrameSpec(FrameBuilder builder) => builder.Build(); } /// /// Static helper for creating frames /// public static class Frame { /// /// ROWS BETWEEN ... /// public static FrameBuilder Rows() => new(FrameType.Rows); /// /// ROWS BETWEEN n PRECEDING AND CURRENT ROW (sliding window) /// public static FrameBuilder Rows(int preceding) => new FrameBuilder(FrameType.Rows).Preceding(preceding); /// /// RANGE BETWEEN ... /// public static FrameBuilder Range() => new(FrameType.Range); } Path: redb/redb.Core/Query/Window/IRedbWindowedQueryable.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/Window/IRedbWindowedQueryable.cs ---- using System.Linq.Expressions; using redb.Core.Models.Entities; namespace redb.Core.Query.Window; /// /// Interface for queries with window functions. /// public interface IRedbWindowedQueryable where TProps : class, new() { /// /// Projection with window functions. /// Task> SelectAsync( Expression, TResult>> selector, CancellationToken cancellationToken = default); /// /// Returns SQL string for debugging (like EF Core ToQueryString). /// Task ToSqlStringAsync( Expression, TResult>> selector, CancellationToken cancellationToken = default); } Path: redb/redb.Core/Query/Window/IWindowSpec.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/Window/IWindowSpec.cs ---- using System.Linq.Expressions; using redb.Core.Models.Contracts; namespace redb.Core.Query.Window; /// /// Window specification for Window Functions. /// public interface IWindowSpec where TProps : class, new() { // ===== PARTITION BY ===== /// /// Partition by Props field. /// IWindowSpec PartitionBy(Expression> keySelector); /// /// Partition by IRedbObject base field (SchemeId, OwnerId, etc.). /// Uses IRedbObject for compile-time safety - Props not visible! /// IWindowSpec PartitionByRedb(Expression> keySelector); // ===== ORDER BY ===== /// /// Sort within window by Props field (ascending). /// IWindowSpec OrderBy(Expression> keySelector); /// /// Sort within window by Props field (descending). /// IWindowSpec OrderByDesc(Expression> keySelector); /// /// Sort within window by IRedbObject base field (ascending). /// Uses IRedbObject for compile-time safety - Props not visible! /// IWindowSpec OrderByRedb(Expression> keySelector); /// /// Sort within window by IRedbObject base field (descending). /// Uses IRedbObject for compile-time safety - Props not visible! /// IWindowSpec OrderByDescRedb(Expression> keySelector); // ===== FRAME ===== /// /// Sets Frame (ROWS BETWEEN) for sliding windows. /// IWindowSpec Frame(FrameSpec frame); } Path: redb/redb.Core/Query/Window/RedbWindowedQueryable.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/Window/RedbWindowedQueryable.cs ---- using System.Linq.Expressions; using System.Text.Json; using redb.Core.Models.Entities; using redb.Core.Query.QueryExpressions; using redb.Core.Query.Utils; namespace redb.Core.Query.Window; /// /// Implementation of queries with window functions /// public class RedbWindowedQueryable : IRedbWindowedQueryable where TProps : class, new() { private readonly IRedbQueryProvider _provider; private readonly long _schemeId; private readonly string? _filterJson; private readonly FilterExpression? _filter; private readonly WindowSpec _windowSpec; private readonly int? _take; private readonly int? _skip; /// /// Constructor with filterJson (legacy compatibility). /// public RedbWindowedQueryable( IRedbQueryProvider provider, long schemeId, string? filterJson, WindowSpec windowSpec, int? take = null, int? skip = null) { _provider = provider; _schemeId = schemeId; _filterJson = filterJson; _filter = null; _windowSpec = windowSpec; _take = take; _skip = skip; } /// /// Constructor with FilterExpression (Pro version). /// public RedbWindowedQueryable( IRedbQueryProvider provider, long schemeId, FilterExpression? filter, WindowSpec windowSpec, int? take = null, int? skip = null) { _provider = provider; _schemeId = schemeId; _filter = filter; _filterJson = null; _windowSpec = windowSpec; _take = take; _skip = skip; } public async Task> SelectAsync( Expression, TResult>> selector, CancellationToken cancellationToken = default) { // Parse SELECT fields and Win.* functions var (selectFields, windowFuncs) = ParseSelector(selector); var partitionBy = ParsePartitionBy(); var orderBy = ParseOrderBy(); var frameJson = SerializeFrame(); // Call SQL - use FilterExpression if available, otherwise filterJson var jsonResult = _filter != null ? await _provider.ExecuteWindowQueryAsync(_schemeId, selectFields, windowFuncs, partitionBy, orderBy, _filter, frameJson, _take, _skip, cancellationToken: cancellationToken) : await _provider.ExecuteWindowQueryAsync(_schemeId, selectFields, windowFuncs, partitionBy, orderBy, _filterJson, frameJson, _take, _skip, cancellationToken: cancellationToken); // Materialize return MaterializeResults(jsonResult, selector); } /// /// Returns SQL string for debugging. /// public async Task ToSqlStringAsync( Expression, TResult>> selector, CancellationToken cancellationToken = default) { var (selectFields, windowFuncs) = ParseSelector(selector); var partitionBy = ParsePartitionBy(); var orderBy = ParseOrderBy(); var frameJson = SerializeFrame(); // The same filter as SelectAsync: the preview is the SQL that runs. return _filter != null ? await _provider.GetWindowSqlPreviewAsync( _schemeId, selectFields, windowFuncs, partitionBy, orderBy, _filter, frameJson, _take, _skip, cancellationToken: cancellationToken) : await _provider.GetWindowSqlPreviewAsync( _schemeId, selectFields, windowFuncs, partitionBy, orderBy, _filterJson, frameJson, _take, _skip, cancellationToken: cancellationToken); } private string? SerializeFrame() { if (_windowSpec.FrameSpec == null) return null; var f = _windowSpec.FrameSpec; return JsonSerializer.Serialize(new { type = f.Type.ToString().ToUpper(), start = new { kind = f.Start.Type.ToString().ToUpper(), offset = f.Start.Offset }, end = new { kind = f.End.Type.ToString().ToUpper(), offset = f.End.Offset } }); } private (List Fields, List Funcs) ParseSelector( Expression, TResult>> selector) { var fields = new List(); var funcs = new List(); var param = selector.Parameters[0]; foreach (var (alias, _, rawExpr) in Grouping.GroupSelectorMembers.Extract(selector, "WithWindow.SelectAsync")) { var arg = Grouping.GroupSelectorMembers.StripConvert(rawExpr); // Win.RowNumber(), Win.Sum(x.Props.Field), Win.Lag(x.Props.Field), Win.Ntile(4), etc. if (arg is MethodCallExpression mc && mc.Method.DeclaringType == typeof(Aggregation.Win)) { // Convert method names to SQL-compatible var sqlFunc = mc.Method.Name switch { "RowNumber" => "ROW_NUMBER", "DenseRank" => "DENSE_RANK", "FirstValue" => "FIRST_VALUE", "LastValue" => "LAST_VALUE", _ => mc.Method.Name.ToUpper() }; string fieldPath = ""; int? buckets = null; // Win.Ntile(4) - extract buckets constant if (mc.Method.Name == "Ntile" && mc.Arguments.Count > 0) { if (mc.Arguments[0] is ConstantExpression ce && ce.Value is int b) buckets = b; } // Extract field for aggregates (Win.Sum(field), Win.Lag(field)) else if (mc.Arguments.Count > 0) { fieldPath = ExtractFieldPathFromArg(mc.Arguments[0]); } funcs.Add(new WindowFuncRequest { Func = sqlFunc, FieldPath = fieldPath, Alias = alias, Buckets = buckets }); continue; } // Regular field if (arg is MemberExpression member && Grouping.GroupSelectorMembers.ReferencesParameter(member, param)) { var path = ExtractFieldPath(member); if (string.IsNullOrEmpty(path)) throw new NotSupportedException( $"WithWindow.SelectAsync: член '{alias}' не разобран как поле ('{member}')."); // CRITICAL: Determine if this is a base field (Name, Id) or props path (Props.Stock) bool isBaseField = IsBaseFieldAccess(member); fields.Add(new WindowFieldRequest { FieldPath = path, Alias = alias, IsBaseField = isBaseField }); continue; } if (!Grouping.GroupSelectorMembers.ReferencesParameter(arg, param)) continue; // клиентское значение - вычислится при материализации throw new NotSupportedException( $"WithWindow.SelectAsync: член '{alias}' использует строку, но не является ни полем, " + $"ни Win.* вызовом ('{arg}')."); } return (fields, funcs); } private List ParsePartitionBy() { var result = new List(); foreach (var (expr, isBaseField) in _windowSpec.PartitionByFields) { result.Add(new WindowFieldRequest { FieldPath = WindowFieldPath.Of(((LambdaExpression)expr).Body), IsBaseField = isBaseField }); } return result; } private List ParseOrderBy() { var result = new List(); foreach (var (expr, desc, isBaseField) in _windowSpec.OrderByFields) { result.Add(new WindowOrderRequest { FieldPath = WindowFieldPath.Of(((LambdaExpression)expr).Body), Descending = desc, IsBaseField = isBaseField }); } return result; } private static string ExtractFieldPath(MemberExpression member) => WindowFieldPath.Of(member); /// /// Determines if field access is base (Name, Id, SchemeId) /// or a Props field (Props.Stock, Props.Category). /// Base field: path does NOT contain "Props" (x.Name, x.Id) /// Props field: path contains "Props" (x.Props.Stock) /// private bool IsBaseFieldAccess(MemberExpression member) { Expression? current = member; while (current is MemberExpression m) { if (m.Member.Name == "Props") return false; // Contains Props → Props field current = m.Expression; } return true; // Does not contain Props → base field } /// /// Extracts field path from Win.Sum(x.Props.Field) argument /// private static string ExtractFieldPathFromArg(Expression arg) => WindowFieldPath.Of(arg); private List MaterializeResults(JsonDocument? json, Expression, TResult>> selector) { var results = new List(); if (json == null) return results; var members = Grouping.GroupSelectorMembers.Extract(selector, "WithWindow.SelectAsync"); var param = selector.Parameters[0]; // Клиентские значения - раз на запрос; Win-вызовы клиентскими не считаются // (Win.RowNumber() не ссылается на параметр, но его значение приходит из JSON). var clientValues = new object?[members.Count]; var isClient = new bool[members.Count]; for (int i = 0; i < members.Count; i++) { var e = Grouping.GroupSelectorMembers.StripConvert(members[i].Expr); var serverCall = e is MethodCallExpression mcx && mcx.Method.DeclaringType == typeof(Aggregation.Win); if (!serverCall && !Grouping.GroupSelectorMembers.ReferencesParameter(e, param)) { isClient[i] = true; clientValues[i] = Expression.Lambda(members[i].Expr).Compile().DynamicInvoke(); } } foreach (var element in json.RootElement.EnumerateArray()) { var values = new object?[members.Count]; for (int i = 0; i < members.Count; i++) { if (isClient[i]) { values[i] = clientValues[i]; continue; } if (element.TryGetProperty(members[i].Name, out var prop)) values[i] = JsonValueConverter.Convert(prop, members[i].Type); } results.Add(Grouping.GroupSelectorMembers.Construct(selector, values)); } return results; } } public class WindowFieldRequest { public string FieldPath { get; set; } = ""; public string Alias { get; set; } = ""; public bool IsBaseField { get; set; } = false; // Base field from _objects } public class WindowFuncRequest { public string Func { get; set; } = ""; // SUM, AVG, LAG, ROW_NUMBER, NTILE... public string FieldPath { get; set; } = ""; // Field for aggregate (empty for ROW_NUMBER) public string Alias { get; set; } = ""; public int? Buckets { get; set; } // For NTILE(n) public bool IsBaseField { get; set; } = false; // Base field from _objects } public class WindowOrderRequest { public string FieldPath { get; set; } = ""; public bool Descending { get; set; } public bool IsBaseField { get; set; } = false; // Base field from _objects } Path: redb/redb.Core/Query/Window/TreeWindowedQueryable.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/Window/TreeWindowedQueryable.cs ---- using System.Linq.Expressions; using System.Text.Json; using redb.Core.Models.Entities; using redb.Core.Query.Base; using redb.Core.Query.Utils; namespace redb.Core.Query.Window; /// /// Implementation of queries with window functions for TreeQueryable. /// Preserves TreeQueryContext for tree-aware Window Functions execution. /// public class TreeWindowedQueryable : IRedbWindowedQueryable where TProps : class, new() { private readonly ITreeQueryProvider _treeProvider; private readonly TreeQueryContext _treeContext; private readonly string? _filterJson; private readonly WindowSpec _windowSpec; /// /// Creates tree-aware windowed queryable. /// /// Tree query provider with tree-aware execution /// Tree query context with rootObjectId, maxDepth, filters /// Filter JSON from Where clauses /// Window specification (partition, order, frame) public TreeWindowedQueryable( ITreeQueryProvider treeProvider, TreeQueryContext treeContext, string? filterJson, WindowSpec windowSpec) { _treeProvider = treeProvider; _treeContext = treeContext; _filterJson = filterJson; _windowSpec = windowSpec; } /// /// Execute window query with tree context and materialize results. /// public async Task> SelectAsync( Expression, TResult>> selector, CancellationToken cancellationToken = default) { var (selectFields, windowFuncs) = ParseSelector(selector); var partitionBy = ParsePartitionBy(); var orderBy = ParseOrderBy(); var frameJson = SerializeFrame(); // Use tree-aware execution with full context var jsonResult = await _treeProvider.ExecuteTreeWindowQueryAsync( _treeContext, selectFields, windowFuncs, partitionBy, orderBy, frameJson, cancellationToken: cancellationToken); return MaterializeResults(jsonResult, selector); } /// /// Returns SQL string for debugging. /// public async Task ToSqlStringAsync( Expression, TResult>> selector, CancellationToken cancellationToken = default) { var (selectFields, windowFuncs) = ParseSelector(selector); var partitionBy = ParsePartitionBy(); var orderBy = ParseOrderBy(); var frameJson = SerializeFrame(); return await _treeProvider.GetTreeWindowSqlPreviewAsync( _treeContext, selectFields, windowFuncs, partitionBy, orderBy, frameJson, cancellationToken: cancellationToken); } private string? SerializeFrame() { if (_windowSpec.FrameSpec == null) return null; var f = _windowSpec.FrameSpec; return JsonSerializer.Serialize(new { type = f.Type.ToString().ToUpper(), start = new { kind = f.Start.Type.ToString().ToUpper(), offset = f.Start.Offset }, end = new { kind = f.End.Type.ToString().ToUpper(), offset = f.End.Offset } }); } private (List Fields, List Funcs) ParseSelector( Expression, TResult>> selector) { var fields = new List(); var funcs = new List(); if (selector.Body is NewExpression newExpr) { for (int i = 0; i < newExpr.Arguments.Count; i++) { var alias = newExpr.Members?[i].Name ?? $"Col{i}"; var arg = newExpr.Arguments[i]; // Win.RowNumber(), Win.Sum(x.Props.Field), Win.Lag(x.Props.Field), etc. if (arg is MethodCallExpression mc && mc.Method.DeclaringType == typeof(Aggregation.Win)) { var sqlFunc = mc.Method.Name switch { "RowNumber" => "ROW_NUMBER", "DenseRank" => "DENSE_RANK", "FirstValue" => "FIRST_VALUE", "LastValue" => "LAST_VALUE", _ => mc.Method.Name.ToUpper() }; string fieldPath = ""; int? buckets = null; if (mc.Method.Name == "Ntile" && mc.Arguments.Count > 0) { if (mc.Arguments[0] is ConstantExpression ce && ce.Value is int b) buckets = b; } else if (mc.Arguments.Count > 0) { fieldPath = ExtractFieldPathFromArg(mc.Arguments[0]); } funcs.Add(new WindowFuncRequest { Func = sqlFunc, FieldPath = fieldPath, Alias = alias, Buckets = buckets }); } else if (arg is MemberExpression member && Grouping.GroupSelectorMembers.ReferencesParameter(member, selector.Parameters[0])) { var path = ExtractFieldPath(member); if (!string.IsNullOrEmpty(path)) { bool isBaseField = IsBaseFieldAccess(member); fields.Add(new WindowFieldRequest { FieldPath = path, Alias = alias, IsBaseField = isBaseField }); } } } } return (fields, funcs); } private List ParsePartitionBy() { var result = new List(); foreach (var (expr, isBaseField) in _windowSpec.PartitionByFields) { result.Add(new WindowFieldRequest { FieldPath = WindowFieldPath.Of(((LambdaExpression)expr).Body), IsBaseField = isBaseField }); } return result; } private List ParseOrderBy() { var result = new List(); foreach (var (expr, desc, isBaseField) in _windowSpec.OrderByFields) { result.Add(new WindowOrderRequest { FieldPath = WindowFieldPath.Of(((LambdaExpression)expr).Body), Descending = desc, IsBaseField = isBaseField }); } return result; } private static string ExtractFieldPath(MemberExpression member) => WindowFieldPath.Of(member); private bool IsBaseFieldAccess(MemberExpression member) { Expression? current = member; while (current is MemberExpression m) { if (m.Member.Name == "Props") return false; current = m.Expression; } return true; } private static string ExtractFieldPathFromArg(Expression arg) => WindowFieldPath.Of(arg); private List MaterializeResults(JsonDocument? json, Expression, TResult>> selector) { var results = new List(); if (json == null) return results; foreach (var element in json.RootElement.EnumerateArray()) { var result = MaterializeSingle(element, selector); if (result != null) results.Add(result); } return results; } private TResult? MaterializeSingle(JsonElement element, Expression, TResult>> selector) { if (selector.Body is NewExpression newExpr && newExpr.Constructor != null) { var args = new object?[newExpr.Arguments.Count]; for (int i = 0; i < newExpr.Arguments.Count; i++) { var alias = newExpr.Members?[i].Name ?? $"Col{i}"; var propType = (newExpr.Members?[i] as System.Reflection.PropertyInfo)?.PropertyType ?? typeof(object); if (element.TryGetProperty(alias, out var prop)) args[i] = JsonValueConverter.Convert(prop, propType); } return (TResult)newExpr.Constructor.Invoke(args); } return default; } } Path: redb/redb.Core/Query/Window/WindowFieldPath.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/Window/WindowFieldPath.cs ---- using System; using System.Collections.Generic; using System.Linq.Expressions; using redb.Core.Models.Contracts; namespace redb.Core.Query.Window; /// /// The field path of a window key, a selected field or a Win.* argument (flat and tree windows). A window reads plain /// chains of fields: p.Category, p.Address.City, x.Props.Price, x.Name; the Value of a nullable is the nullable. Anything /// else (an element by index, a dictionary entry, a method call) is refused with : /// the walk used to stop at the first node it did not know and partition or sort by the field after it, so /// PartitionBy(p => p.Items[0].Name) partitioned by the object's own Name. /// internal static class WindowFieldPath { public static string Of(Expression expression) { var parts = new List(); var current = StripConvert(expression); while (true) { switch (current) { case ParameterExpression when parts.Count > 0: parts.Reverse(); return string.Join(".", parts); // x.Props of the object adds no part. case MemberExpression { Member.Name: "Props", Expression: ParameterExpression parameter } when typeof(IRedbObject).IsAssignableFrom(parameter.Type): current = parameter; continue; // Score.Value of a Nullable is Score. case MemberExpression { Member.Name: "Value", Expression: { } nullable } when Nullable.GetUnderlyingType(nullable.Type) != null: current = StripConvert(nullable); continue; case MemberExpression { Expression: { } owner } member: parts.Add(member.Member.Name); current = StripConvert(owner); continue; default: throw new NotSupportedException(Parsing.BaseFilterExpressionParser.UnsupportedFieldPathMessage(expression)); } } } private static Expression? StripConvert(Expression? e) { while (e is UnaryExpression { NodeType: ExpressionType.Convert or ExpressionType.ConvertChecked } unary) e = unary.Operand; return e; } } Path: redb/redb.Core/Query/Window/WindowFunctionName.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/Window/WindowFunctionName.cs ---- using System; namespace redb.Core.Query.Window; /// /// Validates a caller-supplied window function name before it is emitted into SQL. /// /// /// The name arrives from , a public settable string, so it is /// data and not SQL. Every provider used to append it to the call text as-is /// (func + "()"), which let a quote, a bracket or a comment marker reach the statement and /// turn the remainder of the name into live SQL (SQLI-PoC: window function name fallback, all /// dialects including Pro). Providers call this helper instead: a name that is not a plain /// identifier is refused rather than pasted. /// public static class WindowFunctionName { /// Longest accepted name. T-SQL caps an identifier at 128 characters; 64 is ample. public const int MaxLength = 64; /// True when holds only letters, digits and underscores. public static bool IsPlainIdentifier(string? name) { if (string.IsNullOrEmpty(name) || name.Length > MaxLength) return false; foreach (var c in name) { if (!char.IsLetterOrDigit(c) && c != '_') return false; } return true; } /// /// Renders a zero-argument call for , or throws when the name is not a /// plain identifier. Throwing is deliberate: the previous behaviour appended the raw string. /// public static string ZeroArgCall(string? name) { if (!IsPlainIdentifier(name)) throw new ArgumentException( $"Unsupported window function: '{name}'. The name must be a plain identifier.", nameof(name)); return name!.ToUpperInvariant() + "()"; } } Path: redb/redb.Core/Query/Window/WindowSpec.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/Window/WindowSpec.cs ---- using System.Linq.Expressions; using redb.Core.Models.Contracts; namespace redb.Core.Query.Window; /// /// Implementation of window specification /// public class WindowSpec : IWindowSpec where TProps : class, new() { // CHANGED: Store IsBaseField flag for each field internal List<(Expression Field, bool IsBaseField)> PartitionByFields { get; } = new(); internal List<(Expression Field, bool Descending, bool IsBaseField)> OrderByFields { get; } = new(); internal FrameSpec? FrameSpec { get; private set; } // ===== PARTITION BY ===== public IWindowSpec PartitionBy(Expression> keySelector) { PartitionByFields.Add((keySelector, IsBaseField: false)); return this; } public IWindowSpec PartitionByRedb(Expression> keySelector) { PartitionByFields.Add((keySelector, IsBaseField: true)); return this; } // ===== ORDER BY ===== public IWindowSpec OrderBy(Expression> keySelector) { OrderByFields.Add((keySelector, Descending: false, IsBaseField: false)); return this; } public IWindowSpec OrderByDesc(Expression> keySelector) { OrderByFields.Add((keySelector, Descending: true, IsBaseField: false)); return this; } public IWindowSpec OrderByRedb(Expression> keySelector) { OrderByFields.Add((keySelector, Descending: false, IsBaseField: true)); return this; } public IWindowSpec OrderByDescRedb(Expression> keySelector) { OrderByFields.Add((keySelector, Descending: true, IsBaseField: true)); return this; } // ===== FRAME ===== public IWindowSpec Frame(FrameSpec frame) { FrameSpec = frame; return this; } } Path: redb/redb.Core/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/README.md ---- # redb.Core Core library for **RedBase (REDB)** — Entity Database for .NET. [![NuGet](https://img.shields.io/nuget/v/redb.Core?label=NuGet&color=blue)](https://www.nuget.org/packages/redb.Core) [![Downloads](https://img.shields.io/nuget/dt/redb.Core?label=Downloads&color=green)](https://www.nuget.org/packages/redb.Core) [![License: Apache 2.0](https://img.shields.io/badge/license-Apache%202.0-blue)](../LICENSE) ## What's inside - `IRedbService` — main service interface (CRUD, queries, trees, lists) - LINQ query builder with SQL translation - Schema management via `[RedbScheme]` attribute - Typed Props storage engine — every property maps to a typed column, not a JSON blob - Tree structures (CTE-based), list items, object references - Aggregation (Sum, Avg, Min, Max, GroupBy) and window functions - Caching, serialization, security providers ## Platforms Runs on any .NET 10 or .NET 11 target, including **Blazor WebAssembly** and **mobile** (with the SQLite Pro provider). Object and scheme hashing goes through `RedbMd5`, which uses the platform MD5 provider where one exists and a managed RFC 1321 implementation where none does — browser-wasm ships no MD5 provider. The two are bit-for-bit identical, so hashes written by a browser and by a server are interchangeable. ## Installation ```bash # You typically install a provider package, which pulls in redb.Core automatically: dotnet add package redb.Postgres # PostgreSQL dotnet add package redb.MSSql # SQL Server ``` ## Quick Start ```csharp using redb.Core; using redb.Core.Extensions; using redb.Postgres.Extensions; builder.Services.AddRedb(options => options .UsePostgres("Host=localhost;Database=mydb;Username=postgres;Password=pass")); var redb = app.Services.GetRequiredService(); await redb.InitializeAsync(); await redb.SyncSchemeAsync(); // Save await redb.SaveAsync(new RedbObject { Name = "Alice", Props = new() { Age = 28 } }); // Query var results = await redb.Query().Where(e => e.Salary > 75000m).ToListAsync(); ``` ## Links - Documentation (EN): [redbase.app](https://redbase.app) - Documentation (RU): [redb.ru](https://redb.ru) - API Reference: [redbase-app.github.io/redb](https://redbase-app.github.io/redb/) - Examples: [redb.Examples](../redb.Examples/) - GitHub: [github.com/redbase-app/redb](https://github.com/redbase-app/redb) ## License Apache License 2.0 — see [LICENSE](https://github.com/redbase-app/redb/blob/main/LICENSE). Path: redb/redb.Core/RedbAmbientScope.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/RedbAmbientScope.cs ---- using System; using System.Threading; namespace redb.Core; /// /// The redb scope a lazy load runs on: a data object owns no connection, and /// or the Props of a reference stub load on the live scope of whoever /// reads them. A service makes itself current for the flow that resolved it (its constructor) and for a block /// (); a read takes the nearest live service of its database. /// /// A frame holds its service weakly and is live while the service's context is not disposed: an ended scope never /// answers, and a flow that outlives it simply finds the next live frame - or none. The old model opened a fresh scope and /// pooled connection per read wherever no loader of the right scope was attached (production reports, 2026-09-09 and 2026-09-15). /// /// internal static class RedbAmbientScope { private sealed class Frame { private readonly WeakReference _service; public Frame(RedbServiceBase service, Frame? parent) { _service = new WeakReference(service); Domain = service.CacheDomain; Parent = parent; } public string Domain { get; } public Frame? Parent { get; } public RedbServiceBase? Live => _service.TryGetTarget(out var service) && !service.IsScopeEnded ? service : null; } private sealed class Restore : IDisposable { private readonly Frame? _previous; private bool _disposed; public Restore(Frame? previous) => _previous = previous; public void Dispose() { if (_disposed) return; _disposed = true; Current.Value = _previous; } } private static readonly AsyncLocal Current = new(); /// The cache domain of the nearest live service of the calling flow; null when none is current. public static string? CurrentDomain => FirstLive(Current.Value)?.Domain; /// Makes current for the rest of the calling flow. public static void Enter(RedbServiceBase service) => Current.Value = new Frame(service, FirstLive(Current.Value)); /// Makes current for a block; disposing restores what was current before. public static IDisposable Push(RedbServiceBase service) { var previous = Current.Value; Current.Value = new Frame(service, FirstLive(previous)); return new Restore(previous); } /// /// The nearest live service of in the calling flow. With no domain - an item built in user /// code - the nearest live service, provided every live service in the flow reads the same database: an item of /// unknown origin is never read from a database it may not belong to. Null when no live redb scope reads here. /// public static RedbServiceBase? Resolve(string? domain) { RedbServiceBase? found = null; for (var frame = Current.Value; frame != null; frame = frame.Parent) { if (domain != null && frame.Domain != domain) continue; var live = frame.Live; if (live == null) continue; if (domain != null) return live; if (found == null) { found = live; continue; } if (found.CacheDomain != live.CacheDomain) throw new InvalidOperationException( "A list item that carries no database is read while live redb scopes of two databases " + $"('{found.CacheDomain}', '{live.CacheDomain}') are current, so which one it belongs to is unknown. " + "Load its object explicitly on the right service: redb.LoadAsync(item.IdObject) or " + "redb.LoadLinkedObjectsAsync(items)."); } return found; } /// /// The service behind - the scope that materialized an instance - if it still lives. Asked /// only when no scope is current for the reader, and never for a shared instance (owner decision 2026-09-15). /// public static RedbServiceBase? LiveOrigin(WeakReference? origin) => origin != null && origin.TryGetTarget(out var service) && !service.IsScopeEnded ? service : null; // A flow that creates a scope per iteration would otherwise chain every ended one behind the new frame. private static Frame? FirstLive(Frame? frame) { while (frame != null && frame.Live == null) frame = frame.Parent; return frame; } } Path: redb/redb.Core/RedbDeprecation.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/RedbDeprecation.cs ---- namespace redb.Core; /// The messages of the public members marked . internal static class RedbDeprecation { /// Object permissions and roles: kept as they are in the 4.x line, no further development. public const string PermissionsAndRoles = "Object permissions and roles are deprecated and will be removed in a future major version. Authorise in the " + "application (as redb.Identity does) or use the database's own roles and row-level security."; } Path: redb/redb.Core/RedbDomainRegistry.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/RedbDomainRegistry.cs ---- using System; using System.Collections.Concurrent; using System.Linq; using System.Threading.Tasks; using System.Transactions; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Core.Models.Configuration; namespace redb.Core; /// /// Per database (cache domain): the root scope factory and the configuration a lazy load needs when no live redb scope /// reads it. By default such a load is refused; = /// opens a scope for that one load, outside any ambient transaction, and /// warns once the rate gets high (owner decision 2026-09-15). Every service registers its database; the last registration /// of a database wins. /// internal static class RedbDomainRegistry { private sealed class Entry { public Entry(IServiceScopeFactory? scopes, RedbServiceConfiguration configuration, ILogger? logger) { Scopes = scopes; Configuration = configuration; Logger = logger; } public IServiceScopeFactory? Scopes { get; } public RedbServiceConfiguration Configuration { get; } public ILogger? Logger { get; } /// The entry this one replaced, set by the registration that replaced it. public Entry? Replaced { get; set; } } private const int FreshScopeLoadThreshold = 200; private static readonly ConcurrentDictionary ByDomain = new(); private static readonly ConcurrentDictionary Rates = new(); private static readonly ConcurrentDictionary ConflictReported = new(); /// /// Registers the database of a service. The last registration wins: a host rebuilt in place (tests, hot reload) /// takes over from the disposed one. Two hosts of one database that disagree on /// flip the policy with every service constructed; /// that is reported once per database. /// public static void Register(string domain, IServiceScopeFactory? scopes, RedbServiceConfiguration configuration, ILogger? logger) { var entry = new Entry(scopes, configuration, logger); var previous = ByDomain.AddOrUpdate(domain, entry, (_, old) => { entry.Replaced = old; return entry; }).Replaced; if (previous == null || previous.Configuration.LazyLoadWithoutScope == configuration.LazyLoadWithoutScope || !ConflictReported.TryAdd(domain, 0)) return; logger?.LogWarning( "Database '{Domain}' is used by two redb configurations that differ in LazyLoadWithoutScope ({Previous} and " + "{Current}). The registration of the most recently constructed service wins, so which policy a lazy load " + "with no live scope gets depends on which host constructed a service last. Give the hosts one policy.", domain, previous.Configuration.LazyLoadWithoutScope, configuration.LazyLoadWithoutScope); } /// /// Runs on a service of a fresh scope of the captive reader's container: a service of the root /// provider lends lazy loads its scope factory, never its one connection. No option is asked - the container the /// reader came from is known - and no ambient transaction is joined: the load reads committed state. /// public static T InScopeOf(RedbServiceBase captive, Func load) { using var outside = new TransactionScope(TransactionScopeOption.Suppress, TransactionScopeAsyncFlowOption.Enabled); using var scope = captive.ScopeFactory!.CreateScope(); ReportCaptive(captive); return load(Lent(scope.ServiceProvider, captive)); } /// Asynchronous twin of . public static async Task InScopeOfAsync(RedbServiceBase captive, Func> load) { using var outside = new TransactionScope(TransactionScopeOption.Suppress, TransactionScopeAsyncFlowOption.Enabled); await using var scope = captive.ScopeFactory!.CreateAsyncScope(); ReportCaptive(captive); return await load(Lent(scope.ServiceProvider, captive)).ConfigureAwait(false); } // What the lent scope materializes belongs to the captive reader: its stubs name the captive service as their origin. private static RedbServiceBase Lent(IServiceProvider scope, RedbServiceBase captive) { var service = (RedbServiceBase)scope.GetRequiredService(); service.LentTo = captive; return service; } private static void ReportCaptive(RedbServiceBase captive) { var inWindow = Rates.GetOrAdd(captive.CacheDomain + "|captive", _ => new Utils.RateWindow(TimeSpan.FromSeconds(10), FreshScopeLoadThreshold)).Add(); if (inWindow > 0) captive.Logger?.LogWarning( "Lazy loads through a captive service: {Count} within 10s - code reads lazy Object or Props on a service " + "resolved from the root provider, and every such load runs in a fresh scope on a pooled connection. " + "Resolve a scoped IRedbService per flow, or load explicitly.", inWindow); } /// Runs on a service of a fresh scope, or throws . public static T InFreshScope(string? domain, Func load, Func refusal) { var (entry, key) = FreshScopeEntry(domain, refusal); // A fresh-scope load reads committed state on a connection of its own and must not join an ambient transaction of // the caller. Declared first: disposed last. using var outside = new TransactionScope(TransactionScopeOption.Suppress, TransactionScopeAsyncFlowOption.Enabled); using var scope = entry.Scopes!.CreateScope(); Report(entry, key); return load((RedbServiceBase)scope.ServiceProvider.GetRequiredService()); } /// Asynchronous twin of . public static async Task InFreshScopeAsync(string? domain, Func> load, Func refusal) { var (entry, key) = FreshScopeEntry(domain, refusal); using var outside = new TransactionScope(TransactionScopeOption.Suppress, TransactionScopeAsyncFlowOption.Enabled); await using var scope = entry.Scopes!.CreateAsyncScope(); Report(entry, key); return await load((RedbServiceBase)scope.ServiceProvider.GetRequiredService()).ConfigureAwait(false); } private static (Entry Entry, string Domain) FreshScopeEntry(string? domain, Func refusal) { Entry? entry = null; var key = domain; if (domain != null) ByDomain.TryGetValue(domain, out entry); else if (ByDomain.Count == 1) { var only = ByDomain.First(); (key, entry) = (only.Key, only.Value); } if (entry is not { Scopes: not null } || key == null || entry.Configuration.LazyLoadWithoutScope != LazyLoadWithoutScopeMode.FreshScope) throw refusal(); return (entry, key); } private static void Report(Entry entry, string domain) { var inWindow = Rates.GetOrAdd(domain, _ => new Utils.RateWindow(TimeSpan.FromSeconds(10), FreshScopeLoadThreshold)).Add(); if (inWindow > 0) entry.Logger?.LogWarning( "Lazy loads in fresh scopes: {Count} within 10s (LazyLoadWithoutScope = FreshScope) - code reads lazy " + "Object or Props with no live redb scope, and every such load rents a pooled connection. Load explicitly " + "inside a scope, or wrap the reads in redb.BeginAccess().", inWindow); } } Path: redb/redb.Core/RedbScope.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/RedbScope.cs ---- using System; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; namespace redb.Core; /// /// A scope opened from a service () and the service of the same database /// inside it. The holder owns the scope: disposing it ends the service and returns its connection. /// public sealed class RedbScope : IDisposable, IAsyncDisposable { private readonly IServiceScope? _scope; /// /// Wraps with the scope that owns it. A null scope is for a service owned elsewhere /// (a test double); disposing then does nothing. /// public RedbScope(IRedbService service, IServiceScope? scope) { ArgumentNullException.ThrowIfNull(service); Service = service; _scope = scope; } /// The service inside the scope. public IRedbService Service { get; } /// The scope's provider, for other scoped services of the same unit of work; null without a scope. public IServiceProvider? ServiceProvider => _scope?.ServiceProvider; /// public void Dispose() => _scope?.Dispose(); /// public ValueTask DisposeAsync() { if (_scope is IAsyncDisposable asyncScope) return asyncScope.DisposeAsync(); _scope?.Dispose(); return default; } } Path: redb/redb.Core/RedbServiceBase.Indexes.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Core/RedbServiceBase.Indexes.cs ---- using Microsoft.Extensions.Logging; using redb.Core.Models; namespace redb.Core; // The index check and the repair (CheckBaseIndexesAsync, RepairBaseIndexesAsync, CheckBaseIndexesOnStart). The expected // indexes are a table per provider, generated from a fresh database of this build and pinned by a test against one; the // actual ones come from the catalog in one read. Start-up only reports: an operator may have dropped an index on purpose. public abstract partial class RedbServiceBase { /// /// Whether this service moved the database to the module version of this build (created the schema, or applied the /// module bundle), and from which version: null for a database it created. A Pro module builds its indexes at such a /// step only, and only when the step comes from below the version that brought them; at any other start a missing /// one is reported by the index check, not built. /// protected (bool Applied, string? From) ModuleStep { get; private set; } /// /// Whether the module step of this start () is the one that brings a set of module indexes /// introduced at : a database created now, or one coming from a module older than that. /// protected bool ModuleStepBrings(string since) => ModuleStep.Applied && (string.IsNullOrEmpty(ModuleStep.From) || Data.ModuleCompatibility.IsNewer(since, ModuleStep.From)); /// /// The indexes a fresh database of this build has, for the provider (and with Pro, the module indexes in use). Empty /// where the provider has no table: the check then reports nothing. /// protected virtual IReadOnlyList ExpectedIndexes => Array.Empty(); /// /// Every index of the redb tables as the catalog has it: name, table, uniqueness, key and included columns, and /// whether it is valid. Read through . /// protected virtual async Task> ReadIndexShapesAsync(CancellationToken cancellationToken) { var sql = SqlDialect.Schema_SelectIndexShapes(); if (string.IsNullOrEmpty(sql)) return Array.Empty(); var rows = await _context.QueryAsync(sql, Array.Empty(), cancellationToken); return rows.Select(r => new RedbIndexShape { Name = r.Name ?? string.Empty, Table = r.Table ?? string.Empty, IsUnique = r.IsUnique, KeyColumns = Split(r.KeyColumnsCsv), IncludedColumns = Split(r.IncludedColumnsCsv), IsValid = r.IsValid, }).ToList(); static IReadOnlyList Split(string? csv) => string.IsNullOrWhiteSpace(csv) ? Array.Empty() : csv.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) .Select(c => c.ToLowerInvariant()).ToArray(); } /// public async Task CheckBaseIndexesAsync(CancellationToken cancellationToken = default) { var expected = ExpectedIndexes; if (expected.Count == 0) return new RedbIndexReport(Array.Empty(), 0); return RedbIndexComparer.Compare(expected, await ReadIndexShapesAsync(cancellationToken)); } /// public async Task RepairBaseIndexesAsync(IReadOnlyCollection? names = null, bool allowOffline = false, CancellationToken cancellationToken = default) { bool Wanted(RedbIndexFinding f) => names == null || names.Contains(f.Name, StringComparer.OrdinalIgnoreCase); await using (await AcquireSchemaLockAsync(cancellationToken)) { // Asked again under the lock: another process may have built some meanwhile. var report = await CheckBaseIndexesAsync(cancellationToken); var differs = report.Findings.Where(f => f.State == RedbIndexState.Differs && Wanted(f)).ToList(); var todo = report.Repairable.Where(Wanted).ToList(); if (todo.Count == 0) return new RedbIndexRepairResult(Array.Empty(), differs, Array.Empty(), null); var refusal = await RefuseIndexBuildAsync(allowOffline, cancellationToken); if (refusal != null) { var statements = todo.Select(f => IndexBuildStatement(f.Expected, online: false)).ToList(); _logger?.LogWarning("Indexes not built: {Reason} Statements: {Statements}", refusal, string.Join("; ", statements)); return new RedbIndexRepairResult(Array.Empty(), todo.Concat(differs).ToList(), statements, refusal); } var built = new List(); var blocked = new List(); var duplicates = new List(); foreach (var finding in todo) { cancellationToken.ThrowIfCancellationRequested(); var found = await FindValueIndexDuplicatesAsync(finding.Expected, cancellationToken); if (found.Count > 0) { _logger?.LogWarning("Index {Index} not built: {Count} places hold more than one row, first {First}.", finding.Name, found.Count, found[0]); blocked.Add(finding); duplicates.AddRange(found); continue; } if (finding.State == RedbIndexState.Invalid) await ExecuteIndexDdlAsync(IndexDropStatement(finding.Expected), cancellationToken); var statement = IndexBuildStatement(finding.Expected, online: !allowOffline || await CanBuildOnlineAsync(cancellationToken)); _logger?.LogInformation("Building index {Index}: {Statement}", finding.Name, statement); await ExecuteIndexDdlAsync(statement, cancellationToken); built.Add(finding.Name); } if (blocked.Count == 0) return new RedbIndexRepairResult(built, differs, Array.Empty(), null); var reason = $"Some places in _values hold more than one row where a unique index allows one, so " + $"{string.Join(", ", blocked.Select(f => f.Name))} not built; nothing was deleted. Duplicates lists the places."; return new RedbIndexRepairResult(built, blocked.Concat(differs).ToList(), Array.Empty(), reason, duplicates); } } /// /// The places a unique index of _values keyed on the object and the structure would refuse: read through /// with the index's own key and filter. Empty for /// any other index and where the provider does not look. /// private async Task> FindValueIndexDuplicatesAsync(RedbExpectedIndex index, CancellationToken cancellationToken) { if (!index.IsUnique || !string.Equals(index.Table, "_values", StringComparison.OrdinalIgnoreCase) || !index.KeyColumns.Contains("_id_object", StringComparer.OrdinalIgnoreCase) || !index.KeyColumns.Contains("_id_structure", StringComparer.OrdinalIgnoreCase)) return Array.Empty(); var where = index.CreateSql.LastIndexOf(" WHERE ", StringComparison.OrdinalIgnoreCase); var predicate = where < 0 ? null : index.CreateSql[(where + " WHERE ".Length)..]; var sql = SqlDialect.Schema_SelectValueIndexDuplicates(index.KeyColumns, predicate); if (string.IsNullOrEmpty(sql)) return Array.Empty(); var rows = await _context.QueryAsync(sql, Array.Empty(), cancellationToken); return rows.Select(r => new RedbIndexDuplicate(index.Name, r.ObjectId, r.StructureId, r.Rows)).ToList(); } /// /// Why the repair must not build here, or null when it may. The base answer is null; SQL Server refuses on an edition /// without ONLINE index operations unless is set. /// protected virtual Task RefuseIndexBuildAsync(bool allowOffline, CancellationToken cancellationToken) => Task.FromResult(null); /// Whether the engine builds an index online (SQL Server: the edition). True elsewhere. protected virtual Task CanBuildOnlineAsync(CancellationToken cancellationToken) => Task.FromResult(true); /// /// The statement that builds : the provider's own form of /// (PostgreSQL CONCURRENTLY, SQL Server ONLINE = ON when ). /// protected virtual string IndexBuildStatement(RedbExpectedIndex index, bool online) => index.CreateSql; /// The statement that drops an INVALID leftover of (PostgreSQL). protected virtual string IndexDropStatement(RedbExpectedIndex index) => $"DROP INDEX IF EXISTS \"{index.Name}\""; /// Runs an index statement; PostgreSQL runs it on a connection of its own, outside any transaction. protected virtual Task ExecuteIndexDdlAsync(string sql, CancellationToken cancellationToken) => _context.ExecuteAsync(sql); /// /// The start-up step of CheckBaseIndexesOnStart: one catalog read, one Warning naming what differs, nothing /// built. A failure of the read is logged and the start goes on. /// protected async Task ReportIndexesOnStartAsync() { if (!_configuration.CheckBaseIndexesOnStart || ExpectedIndexes.Count == 0) return; try { var report = await CheckBaseIndexesAsync(); if (report.IsClean) return; _logger?.LogWarning( "{Count} of {Expected} expected indexes are missing, INVALID or defined otherwise: {Findings}. " + "Nothing is built at start-up; RepairBaseIndexesAsync or 'redb indexes repair' builds the missing ones, " + "CheckBaseIndexesOnStart = false silences this line.", report.Findings.Count, report.ExpectedCount, string.Join("; ", report.Findings)); } catch (Exception ex) when (ex is not OperationCanceledException) { _logger?.LogWarning(ex, "The index check at start-up failed; the start goes on."); } } private sealed class IndexShapeRow { public string? Name { get; set; } public string? Table { get; set; } public bool IsUnique { get; set; } public string? KeyColumnsCsv { get; set; } public string? IncludedColumnsCsv { get; set; } public bool IsValid { get; set; } = true; } private sealed class DuplicateRow { public long ObjectId { get; set; } public long StructureId { get; set; } public long Rows { get; set; } } } Path: redb/redb.Core/RedbServiceBase.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Core/RedbServiceBase.cs ---- #pragma warning disable CS0618 // implements or uses the deprecated object permissions and roles (RedbDeprecation) using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Core.Caching; using redb.Core.Data; using redb.Core.Providers; using redb.Core.Query; using redb.Core.Serialization; using redb.Core.Utils; using redb.Core.Models.Enums; using redb.Core.Models.Permissions; using redb.Core.Models.Contracts; using redb.Core.Models.Security; using redb.Core.Models.Entities; using redb.Core.Models.Configuration; using redb.Core.Attributes; using redb.Core.Exceptions; using redb.Core.Models; using redb.Core.Services; using System.Reflection; using System.Threading; using System.Runtime.Loader; namespace redb.Core; /// /// Base abstract class for RedbService implementations. /// Contains all common logic for delegating to providers. /// Provider-specific implementations (Postgres, MSSQL) inherit from this class. /// public abstract partial class RedbServiceBase : IRedbService { private readonly IRedbContext _context; private readonly ISchemeSyncProvider _schemeSync; protected IObjectStorageProvider _objectStorage; protected ITreeProvider _treeProvider; private readonly IPermissionProvider _permissionProvider; protected IQueryableProvider _queryProvider; // The query provider every query goes through. The groupings of its queries read their list item keys through // the list provider (Query.Grouping.ListItemGroupKeys): it is handed over here, on use, because a Pro service // replaces _queryProvider after this constructor. An implementation not derived from QueryableProviderBase has // none, and such a grouping refuses with the reason. private IQueryableProvider Queries { get { if (_queryProvider is Providers.Base.QueryableProviderBase queryables && queryables.ListItems == null) queryables.ListItems = _listProvider; return _queryProvider; } } private readonly IValidationProvider _validationProvider; private readonly IRedbSecurityContext _securityContext; private readonly IUserProvider _userProvider; private readonly IRoleProvider _roleProvider; private readonly IListProvider _listProvider; private readonly IServiceProvider _serviceProvider; // readonly: the providers hold this instance, so it is only ever changed in place (UpdateConfiguration). private readonly RedbServiceConfiguration _configuration; private readonly IRedbObjectSerializer _serializer; private readonly ILogger? _logger; /// /// Cache domain identifier for isolating caches between different database connections. /// protected readonly string _cacheDomain; /// /// Database context for direct data access. /// public IRedbContext Context => _context; public IRedbSecurityContext SecurityContext => _securityContext; public IUserProvider UserProvider => _userProvider; public IRoleProvider RoleProvider => _roleProvider; public IListProvider ListProvider => _listProvider; public RedbServiceConfiguration Configuration => _configuration; /// /// Cache domain identifier for this service instance. /// public string CacheDomain => _cacheDomain; // === ABSTRACT METHODS FOR PROVIDER-SPECIFIC IMPLEMENTATIONS === /// /// Database provider name (e.g., "PostgreSQL", "MSSql"). /// protected abstract string DatabaseTypeName { get; } /// /// SQL query to get database version. /// protected abstract string GetVersionSql { get; } /// /// SQL query to get database size in bytes. /// protected abstract string GetDatabaseSizeSql { get; } /// /// Error message when IRedbContext is not registered. /// protected abstract string ContextNotRegisteredError { get; } /// /// Create scheme sync provider. /// protected abstract ISchemeSyncProvider CreateSchemeSyncProvider( IRedbContext context, RedbServiceConfiguration config, string cacheDomain, ILogger? logger); /// /// Create permission provider. /// protected abstract IPermissionProvider CreatePermissionProvider( IRedbContext context, IRedbSecurityContext securityContext, ILogger? logger); /// /// Create user provider. /// protected abstract IUserProvider CreateUserProvider( IRedbContext context, IRedbSecurityContext securityContext, ILogger? logger); /// /// Create role provider. /// protected abstract IRoleProvider CreateRoleProvider( IRedbContext context, IRedbSecurityContext securityContext, ILogger? logger); /// /// Create list provider. /// protected abstract IListProvider CreateListProvider( IRedbContext context, RedbServiceConfiguration config, ISchemeSyncProvider schemeSync, ILogger? logger); /// /// Save-pipeline interceptors (discussion #12) handed to the storage provider: the DI registrations, resolved /// once, and the run-time subscriptions of the , read on /// every save. Pro services building their own storage call this too. /// protected Interception.RedbSaveInterceptorPipeline ResolveSaveInterceptors() => new( _serviceProvider.GetService(typeof(IEnumerable)) as IEnumerable, _serviceProvider.GetService(typeof(Interception.IRedbSaveInterceptorRegistry)) as Interception.IRedbSaveInterceptorRegistry); /// /// Password hasher for the user provider: a DI registration wins, the fallback is bcrypt. /// Never SimplePasswordHasher - a bare redb deployment must not default to salted SHA256 /// (external security report, 2026-09-08). Legacy SHA256+salt hashes keep validating: /// BcryptPasswordHasher recognizes both formats. /// protected Security.IPasswordHasher ResolvePasswordHasher() => _serviceProvider.GetService(typeof(Security.IPasswordHasher)) as Security.IPasswordHasher ?? new Security.BcryptPasswordHasher(); /// /// Create object storage provider. /// protected abstract IObjectStorageProvider CreateObjectStorageProvider( IRedbContext context, IRedbObjectSerializer serializer, IPermissionProvider permissionProvider, IRedbSecurityContext securityContext, ISchemeSyncProvider schemeSync, RedbServiceConfiguration config, IListProvider listProvider, ILogger? logger, Interception.RedbSaveInterceptorPipeline? saveInterceptors); /// /// Create tree provider. /// protected abstract ITreeProvider CreateTreeProvider( IRedbContext context, IObjectStorageProvider objectStorage, IPermissionProvider permissionProvider, IRedbObjectSerializer serializer, IRedbSecurityContext securityContext, ISchemeSyncProvider schemeSync, RedbServiceConfiguration config, ILogger? logger, Interception.RedbSaveInterceptorPipeline? saveInterceptors); /// /// Create lazy props loader. /// protected abstract ILazyPropsLoader CreateLazyPropsLoader( IRedbContext context, ISchemeSyncProvider schemeSync, IRedbObjectSerializer serializer, RedbServiceConfiguration config, string cacheDomain, IListProvider listProvider, ILogger? logger); /// /// Create queryable provider. /// protected abstract IQueryableProvider CreateQueryableProvider( IRedbContext context, IRedbObjectSerializer serializer, ISchemeSyncProvider schemeSync, IRedbSecurityContext securityContext, ILazyPropsLoader lazyPropsLoader, RedbServiceConfiguration config, string cacheDomain, ILogger? logger); /// /// Create validation provider. /// protected abstract IValidationProvider CreateValidationProvider( IRedbContext context, ILogger? logger); /// /// Factory for the maintenance provider (planner statistics, index health). Lazy: most /// scopes never touch maintenance, so nothing is built until the first access. /// protected abstract IMaintenanceProvider CreateMaintenanceProvider( IRedbContext context, int analysisLimit, ILogger? logger); private IMaintenanceProvider? _maintenance; /// public IMaintenanceProvider Maintenance => _maintenance ??= CreateMaintenanceProvider(_context, _configuration.MaintenanceAnalysisLimit, _logger); /// /// SQL dialect for database-specific queries. /// protected abstract ISqlDialect SqlDialect { get; } /// /// Initialize RedbServiceBase with dependency injection. /// protected RedbServiceBase(IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; _context = serviceProvider.GetService() ?? throw new InvalidOperationException(ContextNotRegisteredError); _serializer = serviceProvider.GetService() ?? new SystemTextJsonRedbSerializer(); _logger = serviceProvider.GetService>() as ILogger; // Process-wide caches forget a collectible AssemblyLoadContext (a module) when it unloads. Caching.CollectibleContextCleanup.EnsureWatching(_logger); _configuration = serviceProvider.GetService() ?? new RedbServiceConfiguration(); _securityContext = serviceProvider.GetService() ?? AmbientSecurityContext.GetOrCreateDefault(); // Compute cache domain for this service instance _cacheDomain = _configuration.GetEffectiveCacheDomain(); // Create providers using abstract factory methods (passing cacheDomain) _schemeSync = CreateSchemeSyncProvider(_context, _configuration, _cacheDomain, _logger); // A scheme sync that has to write takes the schema lock of this service (see SchemeSyncProviderBase). if (_schemeSync is Providers.Base.SchemeSyncProviderBase schemeSyncBase) { schemeSyncBase.RunUnderSchemaLock = RunUnderSchemaLockAsync; schemeSyncBase.SchemaProblemFound = ReportSchemaProblem; } _permissionProvider =CreatePermissionProvider(_context, _securityContext, _logger); // Permission cache keys carry the database: ids are per database (review 2026-09-24, C-1). if (_permissionProvider is Providers.Base.PermissionProviderBase permissionBase) permissionBase.CacheDomain = _cacheDomain; _userProvider = CreateUserProvider(_context, _securityContext, _logger); _roleProvider = CreateRoleProvider(_context, _securityContext, _logger); _listProvider = CreateListProvider(_context, _configuration, _schemeSync, _logger); // One interceptor pipeline for the storage and the tree: DeleteSubtreeAsync fires the delete interceptors too. var saveInterceptors = ResolveSaveInterceptors(); _objectStorage = CreateObjectStorageProvider(_context, _serializer, _permissionProvider, _securityContext, _schemeSync, _configuration, _listProvider, _logger, saveInterceptors); _treeProvider = CreateTreeProvider(_context, _objectStorage, _permissionProvider, _serializer, _securityContext, _schemeSync, _configuration, _logger, saveInterceptors); // A data object owns no connection: RedbListItem.Object and the Props of reference stubs load on the live // scope of whoever reads them. This service becomes current for the flow that resolved it, and registers its // database for the loads that find no live scope (refused by default, a fresh scope by explicit option). The // per-item and process-wide loader delegates it installed before opened a fresh scope and pooled connection per // read. _listProvider.LinkedObjectsBatchLoader = LoadLinkedObjectsBatchAsync; ScopeFactory = serviceProvider.GetService(); RedbDomainRegistry.Register(_cacheDomain, ScopeFactory, _configuration, _logger); // A service of the root provider is captive: it lives as long as the process, and the frame it enters below is // inherited by every flow. It lends lazy loads its scope factory, never its one connection (RedbDomainRegistry. // InScopeOf) - parallel lazy loads of shared instances collided on that connection (review after 4.0.0). IsCaptive = ScopeFactory != null && RedbServiceProviders.IsRoot(serviceProvider); LazyPropsLoader = CreateLazyPropsLoader(_context, _schemeSync, _serializer, _configuration, _cacheDomain, _listProvider, _logger); _queryProvider = CreateQueryableProvider(_context, _serializer, _schemeSync, _securityContext, LazyPropsLoader, _configuration, _cacheDomain, _logger); _validationProvider = CreateValidationProvider(_context, _logger); SelfReference = new WeakReference(this); ServicesByContext.AddOrUpdate(_context, this); RedbAmbientScope.Enter(this); } // === Lazy loads on the reader's scope === // Context (one scope, one connection) -> the service of that scope: how a scope-bound loader names the origin of the // instances it materializes. Weak both ways: an ended scope leaves nothing behind. private static readonly System.Runtime.CompilerServices.ConditionalWeakTable ServicesByContext = new(); /// The service whose scope owns ; null for an unknown context. internal static RedbServiceBase? ServiceOf(IRedbContext? context) => context != null && ServicesByContext.TryGetValue(context, out var service) ? service : null; /// A weak reference to this service, shared by every instance it is the origin of. internal WeakReference SelfReference { get; } /// /// This service's own lazy Props loader, bound to its context. Reference stubs never carry it: they carry the /// scope-free loader of this database, which calls the loader of whichever live service reads them. /// protected internal ILazyPropsLoader LazyPropsLoader { get; protected set; } = null!; /// Whether this service's scope has ended (its context is disposed): it no longer answers lazy loads. internal bool IsScopeEnded => _context.IsDisposed; /// The service was resolved from the root provider of its container (see ). internal bool IsCaptive { get; } /// /// Whether a lazy load resolved to this reader runs in a fresh scope of its container instead of on its connection: a /// captive service outside a transaction. Inside its transaction the connection is the transaction, and the load is /// part of it - it reads what the transaction wrote, as it did before. /// internal bool LendsScope => IsCaptive && !_context.IsInTransaction; /// The logger of this service; null when the host registered none. protected internal ILogger? Logger => _logger; /// The scope factory of the container that resolved this service; null outside DI. internal IServiceScopeFactory? ScopeFactory { get; } /// /// The captive service this scope was lent to for one load (); null for a /// scope of its own. /// internal RedbServiceBase? LentTo { get; set; } /// /// The service that instances materialized by this one name as their origin: itself, or the captive service it was lent /// to. A lent scope ends with its load, while what it loaded lives on with the captive reader - the stubs under it /// load through a lent scope of their own. /// internal RedbServiceBase AsOrigin => LentTo ?? this; // === A scope of this service's container (IRedbScopeSource) === /// public bool CanCreateScope => ScopeFactory != null; /// public RedbScope CreateScope() { if (ScopeFactory == null) throw new InvalidOperationException( "This IRedbService was built without a DI container (its provider has no IServiceScopeFactory), so it " + "cannot open a scope of its own. Resolve services from a container to get one per unit of work."); var scope = ScopeFactory.CreateAsyncScope(); RedbScope? opened = null; try { var service = scope.ServiceProvider.GetRequiredService(); if (!string.Equals(service.CacheDomain, CacheDomain, StringComparison.Ordinal)) throw new InvalidOperationException( $"A scope of this service's container resolves IRedbService for database '{service.CacheDomain}', not " + $"'{CacheDomain}': the container registers IRedbService differently per resolution. A scope opened from " + "a service must read that service's database; register one IRedbService per container."); opened = new RedbScope(service, scope); return opened; } finally { if (opened == null) scope.Dispose(); } } /// public IDisposable BeginAccess() => RedbAmbientScope.Push(this); /// public virtual IDisposable WithQueryPlanner(bool enabled) => redb.Core.Query.QueryPlannerScope.Unchanged; /// Opens a query planner block for the calling flow; the tiers that have a planner return it from . protected static IDisposable PushQueryPlanner(bool enabled) => redb.Core.Query.QueryPlannerScope.Push(enabled); /// public async Task> LoadLinkedObjectsAsync( IEnumerable items, CancellationToken cancellationToken = default) { var pending = items.Where(i => !i.IsObjectLoaded && i.IdObject.HasValue).ToList(); if (pending.Count == 0) return new Dictionary(); var byId = await LoadLinkedObjectsBatchAsync(pending.Select(i => i.IdObject!.Value).Distinct().ToList(), cancellationToken); foreach (var item in pending) if (byId.TryGetValue(item.IdObject!.Value, out var obj)) item.Publish(obj, _context); return byId; } /// /// Batch resolver behind the list hand-out preload: one polymorphic load for all linked /// objects of a list. Depth 10 - the SAME depth the lazy getter path uses (LoadTypedAsync), /// so a preloaded extension object is indistinguishable from a lazily loaded one (dictionary /// extension objects are used actively and may carry nested references). Missing ids are /// simply absent from the result - their items keep the lazy path. /// private async Task> LoadLinkedObjectsBatchAsync( IReadOnlyCollection objectIds, CancellationToken cancellationToken) { var loaded = await _objectStorage.LoadAsync(objectIds, depth: 10, cancellationToken: cancellationToken); var byId = new Dictionary(loaded.Count); foreach (var obj in loaded) byId[obj.Id] = obj; return byId; } /// /// The object behind a list item, loaded on this service's connection - the scope of whoever reads the item. A scope /// that tears down meanwhile refuses the command (ObjectDisposedException); nothing falls back to another scope. /// internal Task LoadLinkedObjectAsync(long objectId, CancellationToken cancellationToken) => LoadLinkedObjectCoreAsync(this, objectId, cancellationToken); private static async Task LoadLinkedObjectCoreAsync(IRedbService service, long objectId, CancellationToken cancellationToken) { var dialect = (service as RedbServiceBase)?.SqlDialect; var schemeId = dialect != null ? await service.Context.ExecuteScalarAsync( dialect.ObjectStorage_SelectSchemeIdByObjectId(), new object[] { objectId }, cancellationToken) : 0; if (schemeId == 0) return null; // A scheme this node has never cached (a fresh process, another cluster node) is resolved by // its id; the cache-only lookup fell through to the untyped get_object_json path below. var propsType = await service.Cache.ResolveClrTypeAsync(schemeId, service); if (propsType != null) { // The generic method is our own, so its shape is under our control: the previous // lookup of IObjectStorageProvider.LoadAsync by parameter list silently returned null // (NRE at runtime) the moment that signature grew a CancellationToken. var load = typeof(RedbServiceBase) .GetMethod(nameof(LoadTypedAsync), BindingFlags.NonPublic | BindingFlags.Static)! .MakeGenericMethod(propsType); return await (Task)load.Invoke(null, new object[] { service, objectId, cancellationToken })!; } if (service is not RedbServiceBase typed) return null; var json = await service.Context.ExecuteJsonAsync( typed.SqlDialect.ObjectStorage_GetObjectJson(), new object[] { objectId, 10 }, cancellationToken); return string.IsNullOrEmpty(json) ? null : typed._serializer.DeserializeDynamic(json, typeof(object)); } private static async Task LoadTypedAsync(IObjectStorageProvider storage, long objectId, CancellationToken cancellationToken) where TProps : class, new() => await storage.LoadAsync(objectId, 10, cancellationToken); // === Synchronous twins (thread-pool-free lazy path) === // The sync getter of RedbListItem.Object prefers these: the whole load - scheme lookup, // permission check, get_object_json, deserialization - runs on the calling thread down to // ADO.NET, so a saturated thread pool cannot slow or deadlock a touch of Object. Mirrors of // the async chain above, same depth, same diagnostics. /// Synchronous twin of , on the calling thread down to ADO.NET. internal IRedbObject? LoadLinkedObjectSync(long objectId) => LoadLinkedObjectCoreSync(this, objectId); private static IRedbObject? LoadLinkedObjectCoreSync(IRedbService service, long objectId) { var dialect = (service as RedbServiceBase)?.SqlDialect; var schemeId = dialect != null ? service.Context.ExecuteScalar(dialect.ObjectStorage_SelectSchemeIdByObjectId(), objectId) : 0; if (schemeId == 0) return null; // Same cold resolution as the async twin, on the calling thread. var propsType = service.Cache.ResolveClrType(schemeId, service); if (propsType != null) { // Same reflection shape as the async twin (and the same lesson: our own method, found // by name, never by parameter list). var load = typeof(RedbServiceBase) .GetMethod(nameof(LoadTypedSync), BindingFlags.NonPublic | BindingFlags.Static)! .MakeGenericMethod(propsType); return (IRedbObject?)load.Invoke(null, new object[] { service, objectId }); } if (service is not RedbServiceBase typed) return null; var json = service.Context.ExecuteJson(typed.SqlDialect.ObjectStorage_GetObjectJson(), objectId, 10); return string.IsNullOrEmpty(json) ? null : typed._serializer.DeserializeDynamic(json, typeof(object)); } private static IRedbObject? LoadTypedSync(IObjectStorageProvider storage, long objectId) where TProps : class, new() => storage.Load(objectId, 10); /// /// Get tree provider for extended scenarios. /// public ITreeProvider GetTreeProvider() => _treeProvider; // === DATABASE METADATA === // Sync properties ride the true sync path (calling thread down to ADO.NET) - the previous // .Result over the async form parked a thread on pool-scheduled continuations (debug-era // leftover; same class as the lazy-getter fix). public string dbVersion => _context.ExecuteScalar(GetVersionSql) ?? "unknown"; public string dbType => DatabaseTypeName; public string dbMigration => "ADO.NET"; public long? dbSize => _context.ExecuteScalar(GetDatabaseSizeSql); /// public Task GetDbVersionAsync(CancellationToken cancellationToken = default) => _context.ExecuteScalarAsync(GetVersionSql); // === ISchemeSyncProvider DELEGATION === public Task EnsureSchemeFromTypeAsync(CancellationToken cancellationToken = default) where TProps : class => _schemeSync.EnsureSchemeFromTypeAsync(cancellationToken); public Task> SyncStructuresFromTypeAsync(IRedbScheme scheme, bool strictDeleteExtra = true, CancellationToken cancellationToken = default) where TProps : class => _schemeSync.SyncStructuresFromTypeAsync(scheme, strictDeleteExtra, cancellationToken); public Task SyncSchemeAsync(CancellationToken cancellationToken = default) where TProps : class => _schemeSync.SyncSchemeAsync(cancellationToken); /// public Task DropUnknownStructuresAsync(bool dryRun = true, CancellationToken cancellationToken = default) where TProps : class => _schemeSync.DropUnknownStructuresAsync(dryRun, cancellationToken); public Task GetSchemeByTypeAsync(CancellationToken cancellationToken = default) where TProps : class => _schemeSync.GetSchemeByTypeAsync(cancellationToken); public Task GetSchemeByTypeAsync(Type type, CancellationToken cancellationToken = default) => _schemeSync.GetSchemeByTypeAsync(type, cancellationToken); public IRedbScheme? GetSchemeFromCache() where TProps : class => _schemeSync.GetSchemeFromCache(); public IRedbScheme? GetSchemeFromCache(string schemeName) => _schemeSync.GetSchemeFromCache(schemeName); public Task LoadSchemeByTypeAsync(CancellationToken cancellationToken = default) where TProps : class => _schemeSync.LoadSchemeByTypeAsync(cancellationToken); public Task LoadSchemeByTypeAsync(Type type, CancellationToken cancellationToken = default) => _schemeSync.LoadSchemeByTypeAsync(type, cancellationToken); public Task> GetStructuresByTypeAsync(CancellationToken cancellationToken = default) where TProps : class => _schemeSync.GetStructuresByTypeAsync(cancellationToken); public Task> GetStructuresByTypeAsync(Type type, CancellationToken cancellationToken = default) => _schemeSync.GetStructuresByTypeAsync(type, cancellationToken); public Task SchemeExistsForTypeAsync(CancellationToken cancellationToken = default) where TProps : class => _schemeSync.SchemeExistsForTypeAsync(cancellationToken); public Task SchemeExistsForTypeAsync(Type type, CancellationToken cancellationToken = default) => _schemeSync.SchemeExistsForTypeAsync(type, cancellationToken); public Task SchemeExistsByNameAsync(string schemeName, CancellationToken cancellationToken = default) => _schemeSync.SchemeExistsByNameAsync(schemeName, cancellationToken); public string GetSchemeNameForType() where TProps : class => _schemeSync.GetSchemeNameForType(); public string GetSchemeNameForType(Type type) => _schemeSync.GetSchemeNameForType(type); public string? GetSchemeAliasForType() where TProps : class => _schemeSync.GetSchemeAliasForType(); public string? GetSchemeAliasForType(Type type) => _schemeSync.GetSchemeAliasForType(type); public Task GetSchemeByIdAsync(long schemeId, CancellationToken cancellationToken = default) => _schemeSync.GetSchemeByIdAsync(schemeId, cancellationToken); public IRedbScheme? GetSchemeById(long schemeId) => _schemeSync.GetSchemeById(schemeId); public Task GetSchemeByNameAsync(string schemeName, CancellationToken cancellationToken = default) => _schemeSync.GetSchemeByNameAsync(schemeName, cancellationToken); public Task EnsureObjectSchemeAsync(string name, CancellationToken cancellationToken = default) => _schemeSync.EnsureObjectSchemeAsync(name, cancellationToken); public Task GetObjectSchemeAsync(string name, CancellationToken cancellationToken = default) => _schemeSync.GetObjectSchemeAsync(name, cancellationToken); public Task> GetSchemesAsync(CancellationToken cancellationToken = default) => _schemeSync.GetSchemesAsync(cancellationToken); public GlobalMetadataCache Cache => _schemeSync.Cache; public GlobalListCache ListCache => _schemeSync.ListCache; public GlobalPropsCache PropsCache => _schemeSync.PropsCache; public Task> GetStructuresAsync(IRedbScheme scheme, CancellationToken cancellationToken = default) => _schemeSync.GetStructuresAsync(scheme, cancellationToken); public Task MigrateStructureTypeAsync(long structureId, string oldTypeName, string newTypeName, bool dryRun = false, CancellationToken cancellationToken = default) => _schemeSync.MigrateStructureTypeAsync(structureId, oldTypeName, newTypeName, dryRun, cancellationToken); public Task RecomputeUniqueAsync(string propertyName, CancellationToken cancellationToken = default) where TProps : class => _schemeSync.RecomputeUniqueAsync(propertyName, cancellationToken); public Task> GetStructureTreeAsync(long schemeId, CancellationToken cancellationToken = default) => _schemeSync.GetStructureTreeAsync(schemeId, cancellationToken); public Task> GetSubtreeAsync(long schemeId, long? parentStructureId, CancellationToken cancellationToken = default) => _schemeSync.GetSubtreeAsync(schemeId, parentStructureId, cancellationToken); public void InvalidateStructureTreeCache(long schemeId) => _schemeSync.InvalidateStructureTreeCache(schemeId); public (int TreesCount, int SubtreesCount, long MemoryEstimate) GetStructureTreeCacheStats() => _schemeSync.GetStructureTreeCacheStats(); // === IObjectStorageProvider DELEGATION === public Task?> LoadAsync(long objectId, int depth = 10, CancellationToken cancellationToken = default) where TProps : class, new() => _objectStorage.LoadAsync(objectId, depth, cancellationToken); // Without this delegation the facade would satisfy IObjectStorageProvider.Load with the // interface DEFAULT - the blocking-over-async fallback - and the sync lazy path would quietly // lose its thread-pool freedom (caught by the starvation stand: 4 capped threads, total // freeze inside ConfiguredTaskAwaiter.GetResult under IObjectStorageProvider.Load). public RedbObject? Load(long objectId, int depth = 10) where TProps : class, new() => _objectStorage.Load(objectId, depth); public Task?> GetByUniqueAsync(System.Linq.Expressions.Expression> keyProperty, object? value, int depth = 10, CancellationToken cancellationToken = default) where TProps : class, new() => _objectStorage.GetByUniqueAsync(keyProperty, value, depth, cancellationToken); public Task?> GetByUniqueAsync(string propertyName, object? value, int depth = 10, CancellationToken cancellationToken = default) where TProps : class, new() => _objectStorage.GetByUniqueAsync(propertyName, value, depth, cancellationToken); public Task SaveByUniqueAsync(RedbObject obj, CancellationToken cancellationToken = default) where TProps : class, new() => _objectStorage.SaveByUniqueAsync(obj, cancellationToken); public Task?> LoadAsync(IRedbObject obj, int depth = 10, CancellationToken cancellationToken = default) where TProps : class, new() => _objectStorage.LoadAsync(obj, depth, cancellationToken); public Task?> LoadAsync(IRedbObject obj, IRedbUser user, int depth = 10, CancellationToken cancellationToken = default) where TProps : class, new() => _objectStorage.LoadAsync(obj, user, depth, cancellationToken); public Task SaveAsync(IRedbObject obj, CancellationToken cancellationToken = default) => _objectStorage.SaveAsync(obj, cancellationToken); public Task SaveAsync(IRedbObject obj, CancellationToken cancellationToken = default) where TProps : class, new() => _objectStorage.SaveAsync(obj, cancellationToken); public Task DeleteAsync(IRedbObject obj, CancellationToken cancellationToken = default) => _objectStorage.DeleteAsync(obj, cancellationToken); public Task?> LoadAsync(long objectId, IRedbUser user, int depth = 10, CancellationToken cancellationToken = default) where TProps : class, new() => _objectStorage.LoadAsync(objectId, user, depth, cancellationToken); public Task LoadJsonAsync(long objectId, int depth = 10, CancellationToken cancellationToken = default) => _objectStorage.LoadJsonAsync(objectId, depth, cancellationToken); public Task LoadJsonAsync(long objectId, IRedbUser user, int depth = 10, CancellationToken cancellationToken = default) => _objectStorage.LoadJsonAsync(objectId, user, depth, cancellationToken); public Task SaveAsync(IRedbObject obj, IRedbUser user, CancellationToken cancellationToken = default) => _objectStorage.SaveAsync(obj, user, cancellationToken); public Task SaveAsync(IRedbObject obj, IRedbUser user, CancellationToken cancellationToken = default) where TProps : class, new() => _objectStorage.SaveAsync(obj, user, cancellationToken); public Task DeleteAsync(IRedbObject obj, IRedbUser user, CancellationToken cancellationToken = default) => _objectStorage.DeleteAsync(obj, user, cancellationToken); public Task DeleteAsync(long objectId, CancellationToken cancellationToken = default) => _objectStorage.DeleteAsync(objectId, cancellationToken); public Task DeleteAsync(long objectId, IRedbUser user, CancellationToken cancellationToken = default) => _objectStorage.DeleteAsync(objectId, user, cancellationToken); public Task> AddNewObjectsAsync(IEnumerable> objects, CancellationToken cancellationToken = default) where TProps : class, new() => _objectStorage.AddNewObjectsAsync(objects, cancellationToken); public Task> AddNewObjectsAsync(IEnumerable> objects, IRedbUser user, CancellationToken cancellationToken = default) where TProps : class, new() => _objectStorage.AddNewObjectsAsync(objects, user, cancellationToken); public Task DeleteAsync(IEnumerable objectIds, CancellationToken cancellationToken = default) => _objectStorage.DeleteAsync(objectIds, cancellationToken); public Task DeleteAsync(IEnumerable objectIds, IRedbUser user, CancellationToken cancellationToken = default) => _objectStorage.DeleteAsync(objectIds, user, cancellationToken); public Task DeleteAsync(IEnumerable objects, CancellationToken cancellationToken = default) => _objectStorage.DeleteAsync(objects, cancellationToken); public Task DeleteAsync(IEnumerable objects, IRedbUser user, CancellationToken cancellationToken = default) => _objectStorage.DeleteAsync(objects, user, cancellationToken); public Task SoftDeleteAsync(IEnumerable objectIds, long? trashParentId = null, CancellationToken cancellationToken = default) => _objectStorage.SoftDeleteAsync(objectIds, trashParentId, cancellationToken); public Task SoftDeleteAsync(IEnumerable objectIds, IRedbUser user, long? trashParentId = null, CancellationToken cancellationToken = default) => _objectStorage.SoftDeleteAsync(objectIds, user, trashParentId, cancellationToken); public Task SoftDeleteAsync(IEnumerable objects, long? trashParentId = null, CancellationToken cancellationToken = default) => _objectStorage.SoftDeleteAsync(objects, trashParentId, cancellationToken); public Task SoftDeleteAsync(IEnumerable objects, IRedbUser user, long? trashParentId = null, CancellationToken cancellationToken = default) => _objectStorage.SoftDeleteAsync(objects, user, trashParentId, cancellationToken); public Task DeleteWithPurgeAsync( IEnumerable objectIds, int batchSize = 10, IProgress? progress = null, CancellationToken cancellationToken = default, long? trashParentId = null) => _objectStorage.DeleteWithPurgeAsync(objectIds, batchSize, progress, cancellationToken, trashParentId); public Task PurgeTrashAsync( long trashId, int totalCount, int batchSize = 10, IProgress? progress = null, CancellationToken cancellationToken = default) => _objectStorage.PurgeTrashAsync(trashId, totalCount, batchSize, progress, cancellationToken); public Task GetDeletionProgressAsync(long trashId, CancellationToken cancellationToken = default) => _objectStorage.GetDeletionProgressAsync(trashId, cancellationToken); public Task> GetUserActiveDeletionsAsync(long userId, CancellationToken cancellationToken = default) => _objectStorage.GetUserActiveDeletionsAsync(userId, cancellationToken); public Task> GetOrphanedDeletionTasksAsync(int timeoutMinutes = 30, CancellationToken cancellationToken = default) => _objectStorage.GetOrphanedDeletionTasksAsync(timeoutMinutes, cancellationToken); public Task TryClaimOrphanedTaskAsync(long trashId, int timeoutMinutes = 30, CancellationToken cancellationToken = default) => _objectStorage.TryClaimOrphanedTaskAsync(trashId, timeoutMinutes, cancellationToken); public Task LockForUpdateAsync(params long[] objectIds) => _objectStorage.LockForUpdateAsync(objectIds); public Task LockForUpdateAsync(long[] objectIds, CancellationToken cancellationToken) => _objectStorage.LockForUpdateAsync(objectIds, cancellationToken); public Task LockForUpdateRequiredAsync(params long[] objectIds) => _objectStorage.LockForUpdateRequiredAsync(objectIds); public Task LockForUpdateRequiredAsync(long[] objectIds, CancellationToken cancellationToken) => _objectStorage.LockForUpdateRequiredAsync(objectIds, cancellationToken); public Task> LoadAsync(IEnumerable objectIds, int depth = 10, CancellationToken cancellationToken = default) => _objectStorage.LoadAsync(objectIds, depth, cancellationToken); public Task> LoadAsync(IEnumerable objectIds, IRedbUser user, int depth = 10, CancellationToken cancellationToken = default) => _objectStorage.LoadAsync(objectIds, user, depth, cancellationToken); public Task> SaveAsync(IEnumerable objects, CancellationToken cancellationToken = default) => _objectStorage.SaveAsync(objects, cancellationToken); public Task> SaveAsync(IEnumerable objects, IRedbUser user, CancellationToken cancellationToken = default) => _objectStorage.SaveAsync(objects, user, cancellationToken); // V4 (LAZY Л2 §4.6): batch reload of reference stubs public Task LoadReferencesAsync(RedbObject parent, Func?>?> references, CancellationToken cancellationToken = default) where TProps : class, new() where TRef : class, new() => _objectStorage.LoadReferencesAsync(parent, references, cancellationToken); public Task LoadReferencesAsync(RedbObject parent, Func?> reference, CancellationToken cancellationToken = default) where TProps : class, new() where TRef : class, new() => _objectStorage.LoadReferencesAsync(parent, reference, cancellationToken); // LoadWithParentsAsync - Load with parent chain to root Task?> IObjectStorageProvider.LoadWithParentsAsync(long objectId, int depth, CancellationToken cancellationToken) => _objectStorage.LoadWithParentsAsync(objectId, depth, cancellationToken); Task?> IObjectStorageProvider.LoadWithParentsAsync(IRedbObject obj, int depth, CancellationToken cancellationToken) => _objectStorage.LoadWithParentsAsync(obj, depth, cancellationToken); Task?> IObjectStorageProvider.LoadWithParentsAsync(long objectId, IRedbUser user, int depth, CancellationToken cancellationToken) => _objectStorage.LoadWithParentsAsync(objectId, user, depth, cancellationToken); Task?> IObjectStorageProvider.LoadWithParentsAsync(IRedbObject obj, IRedbUser user, int depth, CancellationToken cancellationToken) => _objectStorage.LoadWithParentsAsync(obj, user, depth, cancellationToken); Task>> IObjectStorageProvider.LoadWithParentsAsync(IEnumerable objectIds, int depth, CancellationToken cancellationToken) => _objectStorage.LoadWithParentsAsync(objectIds, depth, cancellationToken); Task>> IObjectStorageProvider.LoadWithParentsAsync(IEnumerable objectIds, IRedbUser user, int depth, CancellationToken cancellationToken) => _objectStorage.LoadWithParentsAsync(objectIds, user, depth, cancellationToken); Task> IObjectStorageProvider.LoadWithParentsAsync(IEnumerable objectIds, int depth, CancellationToken cancellationToken) => _objectStorage.LoadWithParentsAsync(objectIds, depth, cancellationToken); Task> IObjectStorageProvider.LoadWithParentsAsync(IEnumerable objectIds, IRedbUser user, int depth, CancellationToken cancellationToken) => _objectStorage.LoadWithParentsAsync(objectIds, user, depth, cancellationToken); // === ITreeProvider DELEGATION === public Task DeleteSubtreeAsync(IRedbObject parentObj, CancellationToken cancellationToken = default) => _treeProvider.DeleteSubtreeAsync(parentObj, cancellationToken); public Task DeleteSubtreeAsync(IRedbObject parentObj, IRedbUser user, CancellationToken cancellationToken = default) => _treeProvider.DeleteSubtreeAsync(parentObj, user, cancellationToken); public Task DeleteSubtreeAsync(RedbObject parentObj, CancellationToken cancellationToken = default) => _treeProvider.DeleteSubtreeAsync(parentObj, cancellationToken); public Task DeleteSubtreeAsync(RedbObject parentObj, IRedbUser user, CancellationToken cancellationToken = default) => _treeProvider.DeleteSubtreeAsync(parentObj, user, cancellationToken); public Task> LoadTreeAsync(long rootObjectId, int? maxDepth = null, CancellationToken cancellationToken = default) where TProps : class, new() => _treeProvider.LoadTreeAsync(rootObjectId, maxDepth, cancellationToken); public Task> LoadTreeAsync(IRedbObject rootObj, int? maxDepth = null, CancellationToken cancellationToken = default) where TProps : class, new() => _treeProvider.LoadTreeAsync(rootObj, maxDepth, cancellationToken); public Task>> GetChildrenAsync(IRedbObject parentObj, CancellationToken cancellationToken = default) where TProps : class, new() => _treeProvider.GetChildrenAsync(parentObj, cancellationToken); public Task>> GetPathToRootAsync(IRedbObject obj, CancellationToken cancellationToken = default) where TProps : class, new() => _treeProvider.GetPathToRootAsync(obj, cancellationToken); public Task>> GetDescendantsAsync(IRedbObject parentObj, int? maxDepth = null, CancellationToken cancellationToken = default) where TProps : class, new() => _treeProvider.GetDescendantsAsync(parentObj, maxDepth, cancellationToken); public Task MoveObjectAsync(IRedbObject obj, IRedbObject? newParentObj, CancellationToken cancellationToken = default) => _treeProvider.MoveObjectAsync(obj, newParentObj, cancellationToken); public Task CreateChildAsync(TreeRedbObject obj, IRedbObject parentObj, CancellationToken cancellationToken = default) where TProps : class, new() => _treeProvider.CreateChildAsync(obj, parentObj, cancellationToken); public Task> LoadTreeAsync(long rootObjectId, IRedbUser user, int? maxDepth = null, CancellationToken cancellationToken = default) where TProps : class, new() => _treeProvider.LoadTreeAsync(rootObjectId, user, maxDepth, cancellationToken); public Task> LoadTreeAsync(IRedbObject rootObj, IRedbUser user, int? maxDepth = null, CancellationToken cancellationToken = default) where TProps : class, new() => _treeProvider.LoadTreeAsync(rootObj, user, maxDepth, cancellationToken); public Task>> GetChildrenAsync(IRedbObject parentObj, IRedbUser user, CancellationToken cancellationToken = default) where TProps : class, new() => _treeProvider.GetChildrenAsync(parentObj, user, cancellationToken); public Task>> GetPathToRootAsync(IRedbObject obj, IRedbUser user, CancellationToken cancellationToken = default) where TProps : class, new() => _treeProvider.GetPathToRootAsync(obj, user, cancellationToken); public Task>> GetDescendantsAsync(IRedbObject parentObj, IRedbUser user, int? maxDepth = null, CancellationToken cancellationToken = default) where TProps : class, new() => _treeProvider.GetDescendantsAsync(parentObj, user, maxDepth, cancellationToken); public Task MoveObjectAsync(IRedbObject obj, IRedbObject? newParentObj, IRedbUser user, CancellationToken cancellationToken = default) => _treeProvider.MoveObjectAsync(obj, newParentObj, user, cancellationToken); public Task CreateChildAsync(TreeRedbObject obj, IRedbObject parentObj, IRedbUser user, CancellationToken cancellationToken = default) where TProps : class, new() => _treeProvider.CreateChildAsync(obj, parentObj, user, cancellationToken); public Task LoadPolymorphicTreeAsync(IRedbObject rootObj, int? maxDepth = null, CancellationToken cancellationToken = default) => _treeProvider.LoadPolymorphicTreeAsync(rootObj, maxDepth, cancellationToken); public Task> GetPolymorphicChildrenAsync(IRedbObject parentObj, CancellationToken cancellationToken = default) => _treeProvider.GetPolymorphicChildrenAsync(parentObj, cancellationToken); public Task> GetPolymorphicPathToRootAsync(IRedbObject obj, CancellationToken cancellationToken = default) => _treeProvider.GetPolymorphicPathToRootAsync(obj, cancellationToken); public Task> GetPolymorphicDescendantsAsync(IRedbObject parentObj, int? maxDepth = null, CancellationToken cancellationToken = default) => _treeProvider.GetPolymorphicDescendantsAsync(parentObj, maxDepth, cancellationToken); public Task LoadPolymorphicTreeAsync(IRedbObject rootObj, IRedbUser user, int? maxDepth = null, CancellationToken cancellationToken = default) => _treeProvider.LoadPolymorphicTreeAsync(rootObj, user, maxDepth, cancellationToken); public Task> GetPolymorphicChildrenAsync(IRedbObject parentObj, IRedbUser user, CancellationToken cancellationToken = default) => _treeProvider.GetPolymorphicChildrenAsync(parentObj, user, cancellationToken); public Task> GetPolymorphicPathToRootAsync(IRedbObject obj, IRedbUser user, CancellationToken cancellationToken = default) => _treeProvider.GetPolymorphicPathToRootAsync(obj, user, cancellationToken); public Task> GetPolymorphicDescendantsAsync(IRedbObject parentObj, IRedbUser user, int? maxDepth = null, CancellationToken cancellationToken = default) => _treeProvider.GetPolymorphicDescendantsAsync(parentObj, user, maxDepth, cancellationToken); public Task InitializeTypeRegistryAsync(CancellationToken cancellationToken = default) => _treeProvider.InitializeTypeRegistryAsync(cancellationToken); // === IPermissionProvider DELEGATION === public IQueryable GetReadableObjectIds() => _permissionProvider.GetReadableObjectIds(); public Task CanUserEditObject(IRedbObject obj, CancellationToken cancellationToken = default) => _permissionProvider.CanUserEditObject(obj, cancellationToken); public Task CanUserSelectObject(IRedbObject obj, CancellationToken cancellationToken = default) => _permissionProvider.CanUserSelectObject(obj, cancellationToken); public Task CanUserInsertScheme(IRedbScheme scheme, CancellationToken cancellationToken = default) => _permissionProvider.CanUserInsertScheme(scheme, cancellationToken); public Task CanUserInsertScheme(IRedbScheme scheme, IRedbUser user, CancellationToken cancellationToken = default) => _permissionProvider.CanUserInsertScheme(scheme, user, cancellationToken); public Task CanUserDeleteObject(IRedbObject obj, CancellationToken cancellationToken = default) => _permissionProvider.CanUserDeleteObject(obj, cancellationToken); public IQueryable GetReadableObjectIds(IRedbUser user) => _permissionProvider.GetReadableObjectIds(user); public Task CanUserEditObject(IRedbObject obj, IRedbUser user, CancellationToken cancellationToken = default) => _permissionProvider.CanUserEditObject(obj, user, cancellationToken); public Task CanUserSelectObject(IRedbObject obj, IRedbUser user, CancellationToken cancellationToken = default) => _permissionProvider.CanUserSelectObject(obj, user, cancellationToken); public Task CanUserDeleteObject(IRedbObject obj, IRedbUser user, CancellationToken cancellationToken = default) => _permissionProvider.CanUserDeleteObject(obj, user, cancellationToken); public Task CanUserEditObject(RedbObject obj, CancellationToken cancellationToken = default) => _permissionProvider.CanUserEditObject(obj, cancellationToken); public Task CanUserSelectObject(RedbObject obj, CancellationToken cancellationToken = default) => _permissionProvider.CanUserSelectObject(obj, cancellationToken); public Task CanUserDeleteObject(RedbObject obj, CancellationToken cancellationToken = default) => _permissionProvider.CanUserDeleteObject(obj, cancellationToken); public Task CanUserEditObject(RedbObject obj, IRedbUser user, CancellationToken cancellationToken = default) => _permissionProvider.CanUserEditObject(obj, user, cancellationToken); public Task CanUserSelectObject(RedbObject obj, IRedbUser user, CancellationToken cancellationToken = default) => _permissionProvider.CanUserSelectObject(obj, user, cancellationToken); public Task CanUserDeleteObject(RedbObject obj, IRedbUser user, CancellationToken cancellationToken = default) => _permissionProvider.CanUserDeleteObject(obj, user, cancellationToken); public Task CanUserInsertScheme(RedbObject obj, IRedbUser user, CancellationToken cancellationToken = default) => _permissionProvider.CanUserInsertScheme(obj, user, cancellationToken); public Task CreatePermissionAsync(PermissionRequest request, IRedbUser? currentUser = null, CancellationToken cancellationToken = default) => _permissionProvider.CreatePermissionAsync(request, currentUser, cancellationToken); public Task UpdatePermissionAsync(IRedbPermission permission, PermissionRequest request, IRedbUser? currentUser = null, CancellationToken cancellationToken = default) => _permissionProvider.UpdatePermissionAsync(permission, request, currentUser, cancellationToken); public Task DeletePermissionAsync(IRedbPermission permission, IRedbUser? currentUser = null, CancellationToken cancellationToken = default) => _permissionProvider.DeletePermissionAsync(permission, currentUser, cancellationToken); public Task> GetPermissionsByUserAsync(IRedbUser user, CancellationToken cancellationToken = default) => _permissionProvider.GetPermissionsByUserAsync(user, cancellationToken); public Task> GetPermissionsByRoleAsync(IRedbRole role, CancellationToken cancellationToken = default) => _permissionProvider.GetPermissionsByRoleAsync(role, cancellationToken); public Task> GetPermissionsByObjectAsync(IRedbObject obj, CancellationToken cancellationToken = default) => _permissionProvider.GetPermissionsByObjectAsync(obj, cancellationToken); public Task GetPermissionByIdAsync(long permissionId, CancellationToken cancellationToken = default) => _permissionProvider.GetPermissionByIdAsync(permissionId, cancellationToken); public Task CanUserEditObject(long objectId, long userId, CancellationToken cancellationToken = default) => _permissionProvider.CanUserEditObject(objectId, userId, cancellationToken); public Task CanUserSelectObject(long objectId, long userId, CancellationToken cancellationToken = default) => _permissionProvider.CanUserSelectObject(objectId, userId, cancellationToken); public Task CanUserInsertScheme(long schemeId, long userId, CancellationToken cancellationToken = default) => _permissionProvider.CanUserInsertScheme(schemeId, userId, cancellationToken); public Task CanUserDeleteObject(long objectId, long userId, CancellationToken cancellationToken = default) => _permissionProvider.CanUserDeleteObject(objectId, userId, cancellationToken); public Task GrantPermissionAsync(IRedbUser user, IRedbObject obj, PermissionAction actions, IRedbUser? currentUser = null, CancellationToken cancellationToken = default) => _permissionProvider.GrantPermissionAsync(user, obj, actions, currentUser, cancellationToken); public Task GrantPermissionAsync(IRedbRole role, IRedbObject obj, PermissionAction actions, IRedbUser? currentUser = null, CancellationToken cancellationToken = default) => _permissionProvider.GrantPermissionAsync(role, obj, actions, currentUser, cancellationToken); public Task RevokePermissionAsync(IRedbUser user, IRedbObject obj, IRedbUser? currentUser = null, CancellationToken cancellationToken = default) => _permissionProvider.RevokePermissionAsync(user, obj, currentUser, cancellationToken); public Task RevokePermissionAsync(IRedbRole role, IRedbObject obj, IRedbUser? currentUser = null, CancellationToken cancellationToken = default) => _permissionProvider.RevokePermissionAsync(role, obj, currentUser, cancellationToken); public Task RevokeAllUserPermissionsAsync(IRedbUser user, IRedbUser? currentUser = null, CancellationToken cancellationToken = default) => _permissionProvider.RevokeAllUserPermissionsAsync(user, currentUser, cancellationToken); public Task RevokeAllRolePermissionsAsync(IRedbRole role, IRedbUser? currentUser = null, CancellationToken cancellationToken = default) => _permissionProvider.RevokeAllRolePermissionsAsync(role, currentUser, cancellationToken); public Task GetEffectivePermissionsAsync(IRedbUser user, IRedbObject obj, CancellationToken cancellationToken = default) => _permissionProvider.GetEffectivePermissionsAsync(user, obj, cancellationToken); public Task> GetEffectivePermissionsBatchAsync(IRedbUser user, IRedbObject[] objects, CancellationToken cancellationToken = default) => _permissionProvider.GetEffectivePermissionsBatchAsync(user, objects, cancellationToken); public Task> GetAllEffectivePermissionsAsync(IRedbUser user, CancellationToken cancellationToken = default) => _permissionProvider.GetAllEffectivePermissionsAsync(user, cancellationToken); public Task GetPermissionCountAsync(CancellationToken cancellationToken = default) => _permissionProvider.GetPermissionCountAsync(cancellationToken); public Task GetUserPermissionCountAsync(IRedbUser user, CancellationToken cancellationToken = default) => _permissionProvider.GetUserPermissionCountAsync(user, cancellationToken); public Task GetRolePermissionCountAsync(IRedbRole role, CancellationToken cancellationToken = default) => _permissionProvider.GetRolePermissionCountAsync(role, cancellationToken); // === IQueryableProvider DELEGATION === public IRedbQueryable Query() where TProps : class, new() => Queries.Query(); public IRedbQueryable Query(IRedbUser user) where TProps : class, new() => Queries.Query(user); public IRedbQueryable TreeQuery() where TProps : class, new() => Queries.TreeQuery(); public IRedbQueryable TreeQuery(IRedbUser user) where TProps : class, new() => Queries.TreeQuery(user); public IRedbQueryable TreeQuery(long rootObjectId, int? maxDepth = null) where TProps : class, new() => Queries.TreeQuery(rootObjectId, maxDepth); public IRedbQueryable TreeQuery(IRedbObject? rootObject, int? maxDepth = null) where TProps : class, new() => Queries.TreeQuery(rootObject, maxDepth); public IRedbQueryable TreeQuery(IEnumerable rootObjects, int? maxDepth = null) where TProps : class, new() => Queries.TreeQuery(rootObjects, maxDepth); public IRedbQueryable TreeQuery(IEnumerable rootObjectIds, int? maxDepth = null) where TProps : class, new() => Queries.TreeQuery(rootObjectIds, maxDepth); public IRedbQueryable TreeQuery(long rootObjectId, IRedbUser user, int? maxDepth = null) where TProps : class, new() => Queries.TreeQuery(rootObjectId, user, maxDepth); public IRedbQueryable TreeQuery(IRedbObject? rootObject, IRedbUser user, int? maxDepth = null) where TProps : class, new() => Queries.TreeQuery(rootObject, user, maxDepth); public IRedbQueryable TreeQuery(IEnumerable rootObjects, IRedbUser user, int? maxDepth = null) where TProps : class, new() => Queries.TreeQuery(rootObjects, user, maxDepth); public IRedbQueryable TreeQuery(IEnumerable rootObjectIds, IRedbUser user, int? maxDepth = null) where TProps : class, new() => Queries.TreeQuery(rootObjectIds, user, maxDepth); // === IValidationProvider DELEGATION === public Task> GetSupportedTypesAsync(CancellationToken cancellationToken = default) => _validationProvider.GetSupportedTypesAsync(cancellationToken); public Task ValidateTypeAsync(Type csharpType, string propertyName, CancellationToken cancellationToken = default) => _validationProvider.ValidateTypeAsync(csharpType, propertyName, cancellationToken); public Task ValidateSchemaAsync(string schemeName, bool strictDeleteExtra = true, CancellationToken cancellationToken = default) where TProps : class => _validationProvider.ValidateSchemaAsync(schemeName, strictDeleteExtra, cancellationToken); public ValidationIssue? ValidatePropertyConstraints(Type propertyType, string propertyName, bool isRequired, bool isArray) => _validationProvider.ValidatePropertyConstraints(propertyType, propertyName, isRequired, isArray); public Task ValidateSchemaAsync(IRedbScheme scheme, bool strictDeleteExtra = true, CancellationToken cancellationToken = default) where TProps : class => _validationProvider.ValidateSchemaAsync(scheme, strictDeleteExtra, cancellationToken); public Task AnalyzeSchemaChangesAsync(IRedbScheme scheme, CancellationToken cancellationToken = default) where TProps : class => _validationProvider.AnalyzeSchemaChangesAsync(scheme, cancellationToken); // === SECURITY CONTEXT MANAGEMENT === public void SetCurrentUser(IRedbUser user) => _securityContext.SetCurrentUser(user); public IDisposable CreateSystemContext() => _securityContext.CreateSystemContext(); public long GetEffectiveUserId() => _securityContext.GetEffectiveUserId(); // === CONFIGURATION MANAGEMENT === public void UpdateConfiguration(Action configure) { configure(_configuration); } public void UpdateConfiguration(Action configureBuilder) { // The providers hold this same configuration instance, so it is changed in place and never replaced. // Most builder steps edit the instance they were given, but ForIntegrationTesting starts from a fresh // copy: assigned here, it left this service on the new settings and every provider on the old ones. var builder = new RedbServiceConfigurationBuilder(_configuration); configureBuilder(builder); var built = builder.Build(); if (!ReferenceEquals(built, _configuration)) _configuration.CopyBehaviourFrom(built); } // === INITIALIZATION === /// /// Initialize REDB system at application startup. /// public async Task InitializeAsync(params Assembly[] assemblies) { // An empty database is named as such before any start-up query can fail on it: schema // creation is opt-in (ensureCreated), and without this check the module probe or the // scheme sync below surfaced a raw driver error ("relation _structures does not exist") // that said nothing about how to proceed. if (!await TableExistsAsync("_schemes")) throw new Exceptions.RedbSchemaMissingException(DatabaseTypeName); // 0. Verify v2-pvt SQL module is deployed (only for dialects that ship one). await EnsurePvtModuleDeployedAsync(); // 1. Polymorphic deserialization resolves scheme ids in this domain when no service is current for the flow // (by name: a static closure over this service kept it alive for the life of the process). SystemTextJsonRedbSerializer.SetInitializedDomain(_cacheDomain); // 1a. Problems of the schema that need a person: logged as errors at every start, listed by SchemaProblems. await CheckSchemaCoreAsync(logAll: true, CancellationToken.None); // 1b. Indexes the database lacks or has otherwise than a fresh one: reported, never built at start-up. await ReportIndexesOnStartAsync(); // 2-3. Sync all schemes with RedbSchemeAttribute, then the UserConfigurationProps scheme. Each sync takes the // schema lock itself, and only when it has something to write: a start with nothing changed takes no lock. await AutoSyncSchemesAsync(assemblies); await SyncSchemeAsync(); // 4. Initialize default user configuration // Disabled: config ID=-100 is for cache quotas, not needed for every DB // var configInitializer = new Configuration.DefaultUserConfigurationInitializer(this); // await configInitializer.InitializeAsync(); // 5. Initialize object factory RedbObjectFactory.Initialize(this); // 6. Set global provider for RedbObject RedbObject.SetSchemeSyncProvider(_schemeSync); // 7. Warmup metadata cache await WarmupMetadataCacheAsync(); // 8. Initialize GlobalPropsCache InitializePropsCache(); // 9. Initialize type registry for polymorphic operations await _treeProvider.InitializeTypeRegistryAsync(); } // === v2-pvt MODULE GUARD === /// /// Verifies that the v2-pvt SQL module is deployed at the version this /// dialect's bundle ships. A missing or older module is replaced by the /// embedded bundle automatically — so a simple `git pull` + restart /// upgrades the in-database UDFs without any manual `psql` / `sqlcmd` /// step. A newer module is never replaced: it is used when it serves this /// package (), and /// start-up stops with /// when it does not. Dialects that do not ship v2-pvt opt out by /// returning null from /// and this check becomes a no-op. /// protected virtual async Task EnsurePvtModuleDeployedAsync() { var versionFn = SqlDialect.Query_PvtModuleVersionFunction(); if (string.IsNullOrEmpty(versionFn)) return; var required = SqlDialect.Query_PvtRequiredVersion(); if (string.IsNullOrWhiteSpace(required)) return; string? deployed = null; try { deployed = await _context.ExecuteScalarAsync($"SELECT {versionFn}()"); } catch (Exception ex) when (Data.DbErrorClassifier.IsUndefinedFunction(ex)) { // Module missing entirely — fall through to deploy. } if (!string.IsNullOrWhiteSpace(deployed) && string.Equals(deployed, required, StringComparison.Ordinal)) { return; } if (Data.ModuleCompatibility.IsNewer(deployed, required)) { await AcceptNewerModuleAsync(deployed!, required); return; } // The operator asked that the schema be changed by the DBA only. Say so, with the script to // hand over, and touch nothing. if (!_configuration.AutoApplyDatabaseUpgrades) throw new Exceptions.RedbSchemaOutdatedException(DatabaseTypeName, deployed, required, cause: null); var bundleSql = ReadEmbeddedPvtBundleSql(); if (string.IsNullOrEmpty(bundleSql)) { throw new InvalidOperationException( $"v2-pvt module version mismatch: deployed='{deployed ?? ""}', required='{required}'. " + "The provider does not ship an embedded bundle; redeploy the SQL files manually " + "(redb.Postgres/sql/v2-pvt/*.sql for PostgreSQL or redb.MSSql/sql/v2-pvt/pvt_bundle.sql for SQL Server)."); } // Under the schema lock, and the version asked again under it: another node that met the same old database // may have deployed the bundle while this one waited. await using (await AcquireSchemaLockAsync()) { deployed = await ReadPvtModuleVersionAsync(versionFn); if (string.Equals(deployed, required, StringComparison.Ordinal)) { _logger?.LogInformation("v2-pvt module {Required} was deployed by another process while this one waited.", required); return; } // A node of a newer version deployed its module while this one waited. if (Data.ModuleCompatibility.IsNewer(deployed, required)) { await AcceptNewerModuleAsync(deployed!, required); return; } _logger?.LogInformation( "v2-pvt module {State} (deployed='{Deployed}', required='{Required}'); applying embedded bundle...", string.IsNullOrEmpty(deployed) ? "missing" : "out of date", deployed ?? "", required); try { await ExecuteSchemaScriptAsync(bundleSql); } catch (Exception ex) when (Data.DbErrorClassifier.IsInsufficientPrivilege(ex)) { // The connected role may run the application but not change the schema: the DBA granted // owner rights for the initial installation and took them back. That is a supported // deployment, not a fault, and it deserves an instruction rather than a driver error. // Any other failure of the bundle propagates as is — it is a defect, not a policy. throw new Exceptions.RedbSchemaOutdatedException(DatabaseTypeName, deployed, required, cause: ex); } catch (Exception ex) { // A process that does not take the schema lock (a build before it) finished the same bundle meanwhile. // The database is at the required version, which is all start-up needs. Anything else is a defect. if (!string.Equals(await TryReadPvtModuleVersionAsync(versionFn), required, StringComparison.Ordinal)) throw; _logger?.LogWarning(ex, "v2-pvt module bundle failed, but the database reports the required version {Required}: " + "another process deployed it concurrently. Start-up goes on.", required); return; } _logger?.LogInformation("v2-pvt module bundle applied."); ModuleStep = (true, deployed); // With every module upgrade, under the same lock. await EnsureRootStructureKeyAsync(); } } // The list lives per database (SchemaProblemRegistry), not per instance: the service is scoped, and the instance of // a health check is not the one that ran the start. /// public IReadOnlyList SchemaProblems => SchemaProblemRegistry.Get(_cacheDomain); /// public Task> CheckSchemaAsync(CancellationToken cancellationToken = default) // Asked again (a health check): only problems new to the database are logged. => CheckSchemaCoreAsync(logAll: false, cancellationToken); private async Task> CheckSchemaCoreAsync(bool logAll, CancellationToken cancellationToken) { var found = new List(); if (await IsRootStructureKeyMissingAsync()) found.AddRange(await Data.RootStructureKey.FindDuplicatesAsync(_context, SqlDialect, cancellationToken)); return SchemaProblemRegistry.Replace(_cacheDomain, found, logAll, _logger); } /// A problem met by a scheme sync: logged and listed unless already known for the database. private void ReportSchemaProblem(Models.RedbSchemaProblem problem) => SchemaProblemRegistry.Report(_cacheDomain, problem, _logger); /// /// Whether the engine needs the unique key of root structures () and the /// database lacks it. False on SQL Server, whose structure key holds for root rows already. /// protected async Task IsRootStructureKeyMissingAsync() { var existsSql = SqlDialect.Structures_RootKeyExists(); return existsSql != null && await _context.ExecuteScalarAsync(existsSql) == null; } /// /// Builds the unique key of root structures when it is missing, removing empty duplicates first. Called under the /// schema lock: by the module pass after the bundle (PostgreSQL), by the upgrade pass of the file (SQLite). /// protected async Task EnsureRootStructureKeyAsync() { if (!await IsRootStructureKeyMissingAsync()) return; await Data.RootStructureKey.EnsureAsync(_context, SqlDialect, await TableExistsAsync("_migrations"), _logger); } /// /// The database holds a module newer than this package's: never replaced. Used, with one warning per process, when /// it serves this package; otherwise start-up stops with . A newer /// module without the compatibility function states nothing and is treated as not serving. /// private async Task AcceptNewerModuleAsync(string deployed, string required) { var compatFn = SqlDialect.Query_PvtModuleCompatFunction(); string? compat = null; if (!string.IsNullOrEmpty(compatFn)) { try { compat = await _context.ExecuteScalarAsync($"SELECT {compatFn}()"); } catch (Exception ex) when (Data.DbErrorClassifier.IsUndefinedFunction(ex)) { compat = null; } } if (!Data.ModuleCompatibility.Serves(compat, required, out var fromPackage)) throw new Exceptions.RedbSchemaNewerException(DatabaseTypeName, deployed, required, fromPackage); WarnNewerOnce(DatabaseTypeName, deployed, required, _logger); } private static readonly HashSet NewerWarned = new(StringComparer.Ordinal); /// One warning per process for one newer module: every scoped service runs the start-up check. protected static void WarnNewerOnce(string provider, string deployed, string own, ILogger? logger) { lock (NewerWarned) { if (!NewerWarned.Add(provider + "|" + deployed + "|" + own)) return; } logger?.LogWarning( "The {Provider} database carries the redb module {Deployed}, newer than {Own} of this package; it serves this " + "package and was left as it is. Upgrade the redb packages of this application when convenient.", provider, deployed, own); } private async Task ReadPvtModuleVersionAsync(string versionFn) { try { return await _context.ExecuteScalarAsync($"SELECT {versionFn}()"); } catch (Exception ex) when (Data.DbErrorClassifier.IsUndefinedFunction(ex)) { return null; } } private async Task TryReadPvtModuleVersionAsync(string versionFn) { try { return await ReadPvtModuleVersionAsync(versionFn); } catch { return null; } } // === SCHEMA LOCK === /// /// The schema lock of this database, not yet taken (see ). A provider that has /// no way to lock returns a handle that always succeeds. /// protected abstract Task OpenSchemaLockAsync(CancellationToken cancellationToken); /// /// Takes the schema lock, waiting while another process holds it: one attempt every half second, a line in the log /// when the wait starts and every thirty seconds after, /// past . The work done under it asks its own precondition /// again: the process that held the lock has usually done it already. Disposing releases the lock. /// protected async Task AcquireSchemaLockAsync(CancellationToken cancellationToken = default) { // Asked again inside work already under the lock (RunUnderSchemaLockAsync), the lock is already this flow's: // a second one on a connection of its own would wait for the first. if (_holdsSchemaLock.Value) return Data.SchemaLockHandle.None; var handle = await OpenSchemaLockAsync(cancellationToken); try { var timeout = _configuration.SchemaLockTimeout; var waited = System.Diagnostics.Stopwatch.StartNew(); var nextReport = TimeSpan.Zero; while (!await handle.TryAcquireAsync(cancellationToken)) { if (waited.Elapsed >= timeout) throw new Exceptions.RedbSchemaLockTimeoutException(DatabaseTypeName, handle.Name, waited.Elapsed); if (waited.Elapsed >= nextReport) { _logger?.LogInformation( "The schema lock '{Lock}' is held by another process, most likely upgrading this database; " + "waiting ({Waited:mm\\:ss} of {Timeout}).", handle.Name, waited.Elapsed, timeout); nextReport = waited.Elapsed + TimeSpan.FromSeconds(30); } await Task.Delay(TimeSpan.FromMilliseconds(500), cancellationToken); } if (waited.Elapsed > TimeSpan.FromSeconds(1)) _logger?.LogInformation("The schema lock '{Lock}' taken after {Waited:mm\\:ss}.", handle.Name, waited.Elapsed); return handle; } catch { await handle.DisposeAsync(); throw; } } // True in the flow of work running under RunUnderSchemaLockAsync: the lock is held there, not to be taken again. private readonly AsyncLocal _holdsSchemaLock = new(); /// /// Runs under the schema lock (). Reentrant: called /// again from inside the work, it runs the inner work directly instead of waiting for the lock this flow holds. /// The schema sync of the schemes takes the lock through it when it has something to write. /// protected async Task RunUnderSchemaLockAsync(Func work, CancellationToken cancellationToken = default) { if (_holdsSchemaLock.Value) { await work(); return; } await using (await AcquireSchemaLockAsync(cancellationToken)) { // Set inside this method, the flag reaches the work it awaits and is gone when the method returns. _holdsSchemaLock.Value = true; await work(); } } // === DATABASE SCHEMA MANAGEMENT === /// /// Checks whether the specified table exists in the database. /// protected abstract Task TableExistsAsync(string tableName); /// /// Reads the embedded combined SQL initialization script (redb_init.sql). /// protected abstract string ReadEmbeddedSql(); /// /// Executes the full schema initialization SQL script against the database. /// Provider-specific: e.g. MSSQL splits by GO batch separators. /// protected abstract Task ExecuteSchemaScriptAsync(string sql); /// /// Returns the embedded v2-pvt module bundle (pvt_bundle.sql) or /// null when the provider doesn't ship a standalone bundle. /// Used by to auto-upgrade databases /// that were created before the v2-pvt module was added to /// redb_init.sql (so the full init script is skipped, but the /// module is still missing or outdated). /// protected virtual string? ReadEmbeddedPvtBundleSql() => null; /// public virtual async Task EnsureDatabaseAsync() { // Asked first without the lock: a database already created, nearly every start, takes no lock at all, and a // login that may not take it (a schema deployed by a DBA) starts. Only a missing schema goes to the lock, and // the question is asked again under it: nodes starting together against an empty database would otherwise all // run the creation script, and every one but the first fail on the tables it found. Exception? unreadable = null; bool exists; try { exists = await TableExistsAsync("_schemes"); } catch (Exception ex) when (IsDatabaseClosedForSchemaWork(ex)) { // Another node is creating the schema and holds the database alone for a moment (SQL Server turning on // READ_COMMITTED_SNAPSHOT): the answer comes under the lock, once that node is done. unreadable = ex; exists = false; } if (!exists) { IAsyncDisposable schemaLock; try { schemaLock = await AcquireSchemaLockAsync(); } catch when (unreadable != null) { // The lock could not be reached either: the first error says more (a wrong password fails both). System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(unreadable).Throw(); throw; } await using (schemaLock) { if (!await TableExistsAsync("_schemes")) { _logger?.LogInformation("REDB schema not found. Creating database schema..."); var sql = ReadEmbeddedSql(); await ExecuteSchemaScriptAsync(sql); _logger?.LogInformation("REDB database schema created successfully."); ModuleStep = (true, null); return; } } } // The module pass asks its own question first and takes the lock only when the module is behind. _logger?.LogInformation("REDB schema already exists, skipping creation."); await EnsurePvtModuleDeployedAsync(); } /// /// Whether an error of the first look at the database means that another process holds it alone for schema work, /// so the look is to be repeated under the schema lock. SQL Server refuses logins while /// ALTER DATABASE ... SET READ_COMMITTED_SNAPSHOT of a node creating the schema runs. /// protected virtual bool IsDatabaseClosedForSchemaWork(Exception exception) => false; /// public string GetSchemaScript() => ReadEmbeddedSql(); /// public string? GetUpgradeScript() => ReadEmbeddedPvtBundleSql(); /// public async Task InitializeAsync(bool ensureCreated, params Assembly[] assemblies) { if (ensureCreated) await EnsureDatabaseAsync(); await InitializeAsync(assemblies); } /// /// Warmup metadata cache. Override in derived classes for DB-specific SQL. /// protected virtual async Task WarmupMetadataCacheAsync() { if (!_configuration.WarmupMetadataCacheOnInit) return; try { var sw = System.Diagnostics.Stopwatch.StartNew(); var warmupSql = SqlDialect.Warmup_AllMetadataCaches(); var result = await _context.QueryAsync(warmupSql); sw.Stop(); if (result.Any()) { _logger?.LogInformation( "Metadata cache warmed up: {SchemeCount} schemes, {StructureCount} structures in {ElapsedMs} ms", result.Count, result.Sum(r => r.structures_count), sw.ElapsedMilliseconds); } } catch (Exception ex) { _logger?.LogWarning(ex, "Failed to warmup metadata cache during initialization"); } } /// /// Initialize GlobalPropsCache. /// private void InitializePropsCache() { if (!_configuration.EnablePropsCache) return; // The cache lives for the process: nothing scoped (a user, a configuration service) is captured into it. // Its logger is how a production host learns that the cache is too small or its hits are slow. var cache = new Caching.MemoryRedbObjectCache( maxSize: _configuration.PropsCacheMaxSize, ttl: _configuration.PropsCacheTtl, logger: _serviceProvider.GetService()?.CreateLogger(typeof(Caching.MemoryRedbObjectCache).FullName!)); // A cached graph carries nothing scope-bound: its stubs load on the reader's scope (owner decision 2026-09-15). _schemeSync.PropsCache.Initialize(cache); } /// /// Auto-sync all schemes with RedbSchemeAttribute. /// private async Task AutoSyncSchemesAsync(params Assembly[] assemblies) { IEnumerable assembliesToScan = assemblies.Length > 0 ? assemblies : GetAllLoadedAssemblies(); var typesToSync = assembliesToScan .SelectMany(GetTypesWithRedbSchemeAttribute) .ToList(); if (typesToSync.Count == 0) return; // Pre-flight: validate ALL explicit scheme names up front. A bad name is fatal by design // (a scheme with an invalid name must not boot), but failing on the first offender hides the // rest — the developer fixes one, reruns, hits the next. Reporting the full list in one // AggregateException lets them fix everything in a single pass (H2). var nameErrors = new List(); foreach (var type in typesToSync) { var explicitName = type.GetCustomAttribute()?.Name; if (!string.IsNullOrWhiteSpace(explicitName) && !SchemeNameValidator.IsValid(explicitName, out var reason)) nameErrors.Add(new RedbSchemeNameException(type, explicitName, reason!)); } if (nameErrors.Count == 1) throw nameErrors[0]; if (nameErrors.Count > 1) throw new AggregateException( $"{nameErrors.Count} types declare invalid explicit scheme names — fix all of them:", nameErrors); foreach (var type in typesToSync) { await SyncSchemeForTypeAsync(type); } } private static IEnumerable GetAllLoadedAssemblies() { return AssemblyLoadContext.Default.Assemblies; } private static IEnumerable GetTypesWithRedbSchemeAttribute(Assembly assembly) { try { return assembly.GetTypes() .Where(t => t.GetCustomAttribute() != null); } catch (ReflectionTypeLoadException ex) { return ex.Types .Where(t => t != null && t.GetCustomAttribute() != null)!; } catch { return Enumerable.Empty(); } } private async Task SyncSchemeForTypeAsync(Type type) { try { var method = typeof(ISchemeSyncProvider) .GetMethod(nameof(ISchemeSyncProvider.SyncSchemeAsync)) ?.MakeGenericMethod(type); if (method != null) { var task = method.Invoke(this, new object[] { CancellationToken.None }); // the generic overload takes a token now if (task is Task asyncTask) { await asyncTask; } } } catch (Exception ex) { _logger?.LogError(ex, "Failed to sync scheme for type '{TypeName}'", type.FullName); throw; } } } /// /// Result from warmup_all_metadata_caches() SQL function. /// internal class WarmupCacheResult { public long scheme_id { get; set; } public long structures_count { get; set; } public string? scheme_name { get; set; } } Path: redb/redb.Core/RedbServiceProviders.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/RedbServiceProviders.cs ---- using System; using Microsoft.Extensions.DependencyInjection; namespace redb.Core; /// /// Whether a service provider is the root of its container - the one whose lifetime is the container's. A service /// resolved from it is captive: it lives as long as the process and the ambient frame it enters is inherited by every /// flow. Such a service lends lazy loads its scope factory, never its one connection (review after 4.0.0, finding 4; /// owner decision 2026-09-17): a lazy load resolved to a captive reader runs in a fresh scope of its container. /// /// Microsoft.Extensions.DependencyInjection: the root scope's provider is its own , /// a child scope's is not (pinned by a unit test). Another container is not recognised: its services are never captive. /// /// public static class RedbServiceProviders { /// True when is the root provider of a Microsoft DI container. public static bool IsRoot(IServiceProvider serviceProvider) { ArgumentNullException.ThrowIfNull(serviceProvider); return ReferenceEquals(serviceProvider, serviceProvider.GetService()); } } Path: redb/redb.Core/Schema/ISchemeFieldResolver.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/Schema/ISchemeFieldResolver.cs ---- using redb.Core.Query.Models; namespace redb.Core.Schema; /// /// Resolves field paths to FieldInfo with structure_id and db_type. /// Supports: simple (Name), nested (Address.City), dictionary (PhoneBook[home]), /// nested dictionary (AddressBook[work].City), ListItem properties (Status.Value). /// public interface ISchemeFieldResolver { /// /// Resolve single field path to FieldInfo. /// /// ID of the scheme /// /// Field path. Examples: /// - "Name" - simple field /// - "Address.City" - nested field /// - "PhoneBook[home]" - dictionary access /// - "AddressBook[work].City" - nested dictionary field /// - "Status.Value" - ListItem property /// - "Roles[].Value" - array of ListItem property /// /// FieldInfo or null if field not found Task ResolveAsync(long schemeId, string fieldPath); /// /// Batch resolve multiple field paths. Uses internal caching. /// More efficient than multiple ResolveAsync calls. /// /// ID of the scheme /// Collection of field paths to resolve /// Dictionary mapping field path to FieldInfo (only resolved fields included) Task> ResolveManyAsync(long schemeId, IEnumerable fieldPaths); /// /// Clear internal cache. Useful for testing or after schema changes. /// void ClearCache(); } Path: redb/redb.Core/SchemaProblemRegistry.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/SchemaProblemRegistry.cs ---- using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using Microsoft.Extensions.Logging; using redb.Core.Models; namespace redb.Core; /// /// The schema problems of a database (cache domain), shared by every service of it. IRedbService is scoped: the start /// runs in a scope of its own, and a health check or a controller gets another instance, which must see what the start /// found. One list per domain, replaced whole, read without a lock. /// internal static class SchemaProblemRegistry { private sealed class Entry { public readonly object Gate = new(); public IReadOnlyList Problems = Array.Empty(); } private static readonly ConcurrentDictionary ByDomain = new(); private static Entry For(string domain) => ByDomain.GetOrAdd(domain, _ => new Entry()); /// The problems of the database as last found. public static IReadOnlyList Get(string domain) => ByDomain.TryGetValue(domain, out var entry) ? entry.Problems : Array.Empty(); /// /// Replaces the list with what a look at the database found. A start logs every problem (one error per field and /// start); a look asked again (a health check) logs only the ones new to the list. /// public static IReadOnlyList Replace(string domain, IReadOnlyList found, bool logAll, ILogger? logger) { var entry = For(domain); lock (entry.Gate) { foreach (var problem in found.Where(p => logAll || !entry.Problems.Any(known => Same(known, p)))) logger?.LogError("{Problem}", problem.Message); entry.Problems = found.ToArray(); return entry.Problems; } } /// A problem met by a scheme sync: logged and listed unless already known for the database. public static void Report(string domain, RedbSchemaProblem problem, ILogger? logger) { var entry = For(domain); lock (entry.Gate) { if (entry.Problems.Any(known => Same(known, problem))) return; logger?.LogError("{Problem}", problem.Message); entry.Problems = entry.Problems.Append(problem).ToArray(); } } private static bool Same(RedbSchemaProblem a, RedbSchemaProblem b) => a.Kind == b.Kind && a.SchemeId == b.SchemeId && a.Field == b.Field; } Path: redb/redb.Core/Security/BcryptPasswordHasher.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/Security/BcryptPasswordHasher.cs ---- using System; using System.Security.Cryptography; using System.Text; namespace redb.Core.Security; /// /// Password hasher using BCrypt (recommended for production). /// Backward-compatible: can verify legacy SHA256+salt hashes from . /// New passwords are always hashed with BCrypt. /// public class BcryptPasswordHasher : IPasswordHasher { private readonly int _workFactor; /// /// Creates a BCrypt password hasher. /// /// BCrypt work factor (default: 12, ~250ms per hash). public BcryptPasswordHasher(int workFactor = 12) { if (workFactor < 4 || workFactor > 31) throw new ArgumentOutOfRangeException(nameof(workFactor), workFactor, "Work factor must be between 4 and 31."); _workFactor = workFactor; } /// public string HashPassword(string password) { if (string.IsNullOrEmpty(password)) throw new ArgumentException("Password cannot be empty", nameof(password)); return BCrypt.Net.BCrypt.HashPassword(password, _workFactor); } /// public bool VerifyPassword(string password, string hashedPassword) { if (string.IsNullOrEmpty(password) || string.IsNullOrEmpty(hashedPassword)) return false; try { // BCrypt hashes start with "$2a$", "$2b$", or "$2y$" if (hashedPassword.StartsWith("$2", StringComparison.Ordinal)) { return BCrypt.Net.BCrypt.Verify(password, hashedPassword); } // Legacy SHA256+salt format: "base64(salt):base64(hash)" if (hashedPassword.Contains(':')) { return VerifyLegacySha256(password, hashedPassword); } return false; } catch { return false; } } /// /// Checks whether the stored hash is in legacy SHA256 format and needs rehashing to BCrypt. /// Use this in login flow: if true, rehash with after successful verify. /// public static bool NeedsRehash(string hashedPassword) { if (string.IsNullOrEmpty(hashedPassword)) return true; // Legacy format (SHA256+salt) or unknown → needs rehash return !hashedPassword.StartsWith("$2", StringComparison.Ordinal); } /// /// Verify password against legacy SHA256+salt format from . /// private static bool VerifyLegacySha256(string password, string hashedPassword) { var parts = hashedPassword.Split(':'); if (parts.Length != 2) return false; var salt = Convert.FromBase64String(parts[0]); var storedHash = Convert.FromBase64String(parts[1]); var passwordBytes = Encoding.UTF8.GetBytes(password); var saltedPassword = new byte[passwordBytes.Length + salt.Length]; Array.Copy(passwordBytes, 0, saltedPassword, 0, passwordBytes.Length); Array.Copy(salt, 0, saltedPassword, passwordBytes.Length, salt.Length); var computedHash = SHA256.HashData(saltedPassword); return CryptographicOperations.FixedTimeEquals(storedHash, computedHash); } } Path: redb/redb.Core/Security/IPasswordHasher.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/Security/IPasswordHasher.cs ---- namespace redb.Core.Security; /// /// Interface for password hashing operations. /// Implementations should use secure hashing algorithms (bcrypt, PBKDF2, etc.) /// public interface IPasswordHasher { /// /// Hash a plain-text password. /// /// Plain-text password /// Hashed password string HashPassword(string password); /// /// Verify a password against a hash. /// /// Plain-text password to verify /// Stored hashed password /// True if password matches bool VerifyPassword(string password, string hashedPassword); } Path: redb/redb.Core/Security/SimplePasswordHasher.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/Security/SimplePasswordHasher.cs ---- using System; using System.Security.Cryptography; using System.Text; namespace redb.Core.Security; /// /// Password hasher implementation using SHA256 + salt. /// Implements IPasswordHasher interface for DI. /// Consider using for better brute-force resistance. /// public class SimplePasswordHasher : IPasswordHasher { /// /// Hash password with salt. /// /// Plain-text password /// Hashed password with salt in format: base64(salt):base64(hash) public string HashPassword(string password) { if (string.IsNullOrEmpty(password)) throw new ArgumentException("Password cannot be empty", nameof(password)); var salt = GenerateSalt(); var hash = ComputeHash(password, salt); return $"{Convert.ToBase64String(salt)}:{Convert.ToBase64String(hash)}"; } /// /// Verify password against stored hash. /// /// Plain-text password to verify /// Stored hashed password from DB /// True if password matches public bool VerifyPassword(string password, string hashedPassword) { if (string.IsNullOrEmpty(password) || string.IsNullOrEmpty(hashedPassword)) return false; try { var parts = hashedPassword.Split(':'); if (parts.Length != 2) return false; var salt = Convert.FromBase64String(parts[0]); var storedHash = Convert.FromBase64String(parts[1]); var computedHash = ComputeHash(password, salt); return CryptographicOperations.FixedTimeEquals(storedHash, computedHash); } catch { return false; } } /// /// Generate random salt (256 bits). /// private static byte[] GenerateSalt() { var salt = new byte[32]; using var rng = RandomNumberGenerator.Create(); rng.GetBytes(salt); return salt; } /// /// Compute SHA256 hash of password with salt. /// private static byte[] ComputeHash(string password, byte[] salt) { var passwordBytes = Encoding.UTF8.GetBytes(password); var saltedPassword = new byte[passwordBytes.Length + salt.Length]; Array.Copy(passwordBytes, 0, saltedPassword, 0, passwordBytes.Length); Array.Copy(salt, 0, saltedPassword, passwordBytes.Length, salt.Length); return SHA256.HashData(saltedPassword); } } Path: redb/redb.Core/Serialization/IRedbObjectSerializer.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/Serialization/IRedbObjectSerializer.cs ---- using System; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; namespace redb.Core.Serialization { // Abstraction for JSON object serialization from DB to typed wrapper public interface IRedbObjectSerializer { RedbObject Deserialize(string json) where TProps : class, new(); /// /// Dynamic JSON deserialization to typed object based on runtime type /// /// JSON string /// Type of properties for deserialization /// Deserialized object as interface IRedbObject DeserializeDynamic(string json, Type propsType); /// /// Polymorphic JSON deserialization to RedbObject based on runtime type /// Used for tree structures with different node types /// (conversion to TreeRedbObject happens at provider level) /// /// JSON string from v_objects_json /// Type of properties for deserialization /// Deserialized RedbObject or null RedbObject? DeserializeRedbDynamic(string json, Type propsType); } } Path: redb/redb.Core/Serialization/RedbObjectStubWriteConverter.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/Serialization/RedbObjectStubWriteConverter.cs ---- using System; using System.Runtime.CompilerServices; using System.Text.Json; using System.Text.Json.Serialization; using redb.Core.Models.Entities; namespace redb.Core.Serialization; /// /// V4 (L.4, LAZY plan §4.3): serializing a RedbObject<T> must never trigger lazy loading. /// The default object converter walks the public Props getter — for an unloaded reference stub /// that getter IS a load, so serializing a parent would pull the whole lazy graph (the classic ORM /// trap). This factory takes over WRITING: base fields are written by hand, and properties is /// emitted only when the object is actually loaded (via GetPropsDirectly, which never loads). /// Nested references inside the Props re-enter this factory, so a stub anywhere in the graph /// serializes as its base fields — the same shape the JSON builders emit at the depth boundary. /// /// /// READING is a pass-through: the payload is deserialized with the same options minus this factory, /// i.e. the exact pre-V4 default path - property mapping, the date/enum/tuple converters, the Props /// setter - with one rule on top: an object that arrives without Props (no properties key, /// or "properties": null, the shape a foreign serializer gives a loader-less stub) is NOT /// loaded, so a parent save leaves it alone as the reference it is. /// /// /// /// TreeRedbObject<T> deliberately keeps the default path: this converter would flatten it /// to a plain RedbObject<T> on read. Tree relations are not references (LAZY plan §4.12). /// /// public sealed class RedbObjectStubWriteConverterFactory : JsonConverterFactory { public override bool CanConvert(Type typeToConvert) => typeToConvert.IsGenericType && typeToConvert.GetGenericTypeDefinition() == typeof(RedbObject<>); public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options) { var propsType = typeToConvert.GetGenericArguments()[0]; return (JsonConverter)Activator.CreateInstance( typeof(StubWriteConverter<>).MakeGenericType(propsType))!; } /// One stripped copy per options instance (in practice: the static Options). private static readonly ConditionalWeakTable InnerCache = new(); internal static JsonSerializerOptions WithoutFactory(JsonSerializerOptions options) { return InnerCache.GetValue(options, static o => { var inner = new JsonSerializerOptions(o); for (var i = inner.Converters.Count - 1; i >= 0; i--) if (inner.Converters[i] is RedbObjectStubWriteConverterFactory) inner.Converters.RemoveAt(i); return inner; }); } private sealed class StubWriteConverter : JsonConverter> where TProps : class, new() { public override RedbObject? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { var obj = JsonSerializer.Deserialize>(ref reader, WithoutFactory(options)); // "properties": null - or no properties at all - is NOT a loaded object with nothing in it, // it is an object whose Props were not carried: a stub written by a foreign serializer // (the getter of a loader-less stub answers null), or a stub written by this one. The // setter marks any assignment as loaded, and a nested object marked loaded-with-nothing is // saved as such by the parent: its values deleted, nothing written (the wipe 9fa79c45 // closed for our own stubs). Null Props after reading therefore mean "not loaded"; for a // root that changes nothing - a root is saved whatever its loaded flag says (review). // The subtree was read with the default converter, so nested objects never pass through // here: one walk from the root applies the rule to every level. Utils.LazyReferenceInstaller.MarkUnloadedWherePropsAreNull(obj); return obj; } public override void Write(Utf8JsonWriter writer, RedbObject? value, JsonSerializerOptions options) { if (value == null) { writer.WriteNullValue(); return; } writer.WriteStartObject(); writer.WriteNumber("id", value.id); if (value.parent_id.HasValue) writer.WriteNumber("parent_id", value.parent_id.Value); writer.WriteNumber("scheme_id", value.scheme_id); if (value.owner_id != 0) writer.WriteNumber("owner_id", value.owner_id); if (value.who_change_id != 0) writer.WriteNumber("who_change_id", value.who_change_id); if (value.date_create != default) writer.WriteString("date_create", value.date_create); if (value.date_modify != default) writer.WriteString("date_modify", value.date_modify); if (value.date_begin.HasValue) writer.WriteString("date_begin", value.date_begin.Value); if (value.date_complete.HasValue) writer.WriteString("date_complete", value.date_complete.Value); if (value.key.HasValue) writer.WriteNumber("key", value.key.Value); if (value.value_long.HasValue) writer.WriteNumber("value_long", value.value_long.Value); if (value.value_string != null) writer.WriteString("value_string", value.value_string); if (value.value_guid.HasValue) writer.WriteString("value_guid", value.value_guid.Value); if (value.value_bool.HasValue) writer.WriteBoolean("value_bool", value.value_bool.Value); if (value.value_double.HasValue) writer.WriteNumber("value_double", value.value_double.Value); if (value.value_numeric.HasValue) writer.WriteNumber("value_numeric", value.value_numeric.Value); if (value.value_datetime.HasValue) writer.WriteString("value_datetime", value.value_datetime.Value); if (value.value_bytes != null) writer.WriteBase64String("value_bytes", value.value_bytes); if (value.value_unique != null) writer.WriteString("value_unique", value.value_unique); if (value.name != null) writer.WriteString("name", value.name); if (value.note != null) writer.WriteString("note", value.note); if (value.hash.HasValue) writer.WriteString("hash", value.hash.Value); // GetPropsDirectly never loads: an unloaded stub stops here — base fields only. var props = value.IsPropsLoaded ? value.GetPropsDirectly() : null; if (props != null) { writer.WritePropertyName("properties"); // Full options on purpose: nested RedbObject re-enter this factory. JsonSerializer.Serialize(writer, props, options); } writer.WriteEndObject(); } } } Path: redb/redb.Core/Serialization/SystemTextJsonRedbSerializer.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/Serialization/SystemTextJsonRedbSerializer.cs ---- using System; using System.Threading; using System.Text.Json; using System.Text.Json.Serialization; using redb.Core.Models.Entities; using redb.Core.Models.Contracts; using redb.Core.Utils; using redb.Core.Caching; namespace redb.Core.Serialization { // Implementation using System.Text.Json // Requirement: C# property names match JSON names (snake_case), so no custom NamingPolicy public class SystemTextJsonRedbSerializer : IRedbObjectSerializer { /// /// A type resolver set by the application, if any: it takes precedence over the per-domain resolution. /// private static Func? _typeResolver; /// The cache domain of the redb service initialized last; a name, never the service itself. private static string? _lastInitializedDomain; /// /// Set the type resolver function for polymorphic deserialization. Without one, a scheme id resolves in the /// cache domain of the redb service current for the calling flow, else of the service initialized last. /// public static void SetTypeResolver(Func resolver) { _typeResolver = resolver ?? throw new ArgumentNullException(nameof(resolver)); } /// Records the domain of a service that has just initialized (the fallback of ). internal static void SetInitializedDomain(string domain) => Volatile.Write(ref _lastInitializedDomain, domain); /// /// Resolve CLR type by scheme ID: a scheme id is a per-database fact, so it resolves in the domain of the /// service the calling flow reads through. Held as a domain name, the resolution keeps no service alive. /// internal static Type? ResolveType(long schemeId) { if (_typeResolver is { } resolver) return resolver(schemeId); var domain = RedbAmbientScope.CurrentDomain ?? Volatile.Read(ref _lastInitializedDomain); return domain == null ? null : new GlobalMetadataCache(domain).GetClrType(schemeId); } // The options cache the metadata of every type they handled, Props types of modules included: the caches of // System.Text.Json are cleared when a collectible AssemblyLoadContext unloads (CollectibleContextCleanup). static SystemTextJsonRedbSerializer() => CollectibleContextCleanup.EnsureWatching(); /// /// Public serialization options for use in other components /// (e.g., for polymorphic TreeRedbObject deserialization) /// public static readonly JsonSerializerOptions Options = new() { PropertyNameCaseInsensitive = true, ReadCommentHandling = JsonCommentHandling.Skip, AllowTrailingCommas = true, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingDefault, // Ignore empty arrays/null/default when serializing Converters = { new NullToDefaultConverterFactory(), // null → default(T) for value types (int, long, etc) new ValueTupleDictionaryConverterFactory(), // Dictionary with ValueTuple/Class keys (Base64) new RedbObjectStubWriteConverterFactory(), // V4 (L.4): writing never triggers lazy loading; a stub writes base fields only new PolymorphicRedbObjectConverter(), // Polymorphic IRedbObject deserialization based on scheme_id new PostgresDateTimeOffsetConverter(), // DateTimeOffset from PostgreSQL timestamptz new PostgresNullableDateTimeOffsetConverter(), // Nullable DateTimeOffset from PostgreSQL new PostgresInfinityDateTimeConverter(), // FIX: PostgreSQL "-infinity" support new PostgresInfinityNullableDateTimeConverter(), // FIX: PostgreSQL "-infinity" support for nullable DateTime new JsonStringEnumConverter(), // Enum as strings support new FlexibleTimeSpanConverter(), // TimeSpan from its Ticks new FlexibleNullableTimeSpanConverter(), // nullable TimeSpan support new FlexibleDateOnlyConverter(), // DateOnly from DateTime strings support new FlexibleNullableDateOnlyConverter(), // nullable DateOnly support new FlexibleTimeOnlyConverter(), // TimeOnly from its Ticks new FlexibleNullableTimeOnlyConverter() // nullable TimeOnly support } }; public RedbObject Deserialize(string json) where TProps : class, new() { var obj = JsonSerializer.Deserialize>(json, Options); if (obj == null) { throw new InvalidOperationException("Failed to deserialize get_object_json payload to RedbObject."); } // The root of a get_object_json payload is the object redb loaded: loaded by definition, with or without // Props (a scheme without properties, an object saved with null Props). The converter takes null Props for // "not loaded" - right for the nested references it also reads, wrong for the root. obj._propsLoaded = true; return obj; } public IRedbObject DeserializeDynamic(string json, Type propsType) { // Create generic type RedbObject<propsType> via reflection var redbObjectType = typeof(RedbObject<>).MakeGenericType(propsType); // Deserialize JSON to this type var deserializedObj = JsonSerializer.Deserialize(json, redbObjectType, Options); if (deserializedObj == null) { throw new InvalidOperationException($"Failed to deserialize get_object_json payload to RedbObject<{propsType.Name}>."); } // The root is loaded by definition (see Deserialize). redbObjectType.GetField("_propsLoaded")?.SetValue(deserializedObj, true); // Return as IRedbObject return (IRedbObject)deserializedObj; } public RedbObject? DeserializeRedbDynamic(string json, Type propsType) { // Simply deserialize to RedbObject<TProps> // Conversion to TreeRedbObject will happen in PostgresTreeQueryProvider var redbObjectType = typeof(RedbObject<>).MakeGenericType(propsType); var redbObj = JsonSerializer.Deserialize(json, redbObjectType, Options) as RedbObject; return redbObj; } } /// /// Polymorphic converter for IRedbObject /// Automatically determines type based on scheme_id from JSON and deserializes to RedbObject<TProps> /// Used for nested objects (e.g., RedbListItem.Object) /// public class PolymorphicRedbObjectConverter : JsonConverter { public override IRedbObject? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { // 1. Read JSON to JsonElement for analysis using var jsonDoc = JsonDocument.ParseValue(ref reader); var jsonElement = jsonDoc.RootElement; // 2. Extract scheme_id to determine type if (!jsonElement.TryGetProperty("scheme_id", out var schemeIdProp)) { // No scheme_id → cannot determine type return null; } var schemeId = schemeIdProp.GetInt64(); // 3. Get real C# type via type resolver var propsType = SystemTextJsonRedbSerializer.ResolveType(schemeId); if (propsType == null) { // Type not registered → skip return null; } // 4. Create RedbObject<TProps> dynamically via reflection var redbObjectType = typeof(RedbObject<>).MakeGenericType(propsType); // 5. Deserialize JSON to concrete type // CRITICAL: Use new JsonSerializerOptions WITHOUT this converter // Otherwise infinite recursion occurs with nested IRedbObject var optionsWithoutThisConverter = new JsonSerializerOptions(options); optionsWithoutThisConverter.Converters.Clear(); foreach (var converter in options.Converters) { if (converter is not PolymorphicRedbObjectConverter) { optionsWithoutThisConverter.Converters.Add(converter); } } var obj = JsonSerializer.Deserialize(jsonElement.GetRawText(), redbObjectType, optionsWithoutThisConverter); return obj as IRedbObject; } public override void Write(Utf8JsonWriter writer, IRedbObject? value, JsonSerializerOptions options) { if (value == null) { writer.WriteNullValue(); return; } // IRedbObject serialization may lead to circular references // For safety return null (navigation properties are not serialized) writer.WriteNullValue(); } } /// /// Flexible converter for DateOnly - supports DateTime strings /// public class FlexibleDateOnlyConverter : JsonConverter { public override DateOnly Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { if (reader.TokenType == JsonTokenType.String) { var dateString = reader.GetString(); if (Utils.RedbTemporalFormat.TryParseDateOnly(dateString, out var dateOnly)) { return dateOnly; } } throw new JsonException($"Unable to convert '{reader.GetString()}' to DateOnly."); } public override void Write(Utf8JsonWriter writer, DateOnly value, JsonSerializerOptions options) { writer.WriteStringValue(Utils.RedbTemporalFormat.ToText(value)); } } /// /// Flexible converter for nullable DateOnly /// public class FlexibleNullableDateOnlyConverter : JsonConverter { public override DateOnly? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { if (reader.TokenType == JsonTokenType.Null) return null; if (reader.TokenType == JsonTokenType.String) { var dateString = reader.GetString(); if (string.IsNullOrEmpty(dateString)) return null; if (Utils.RedbTemporalFormat.TryParseDateOnly(dateString, out var dateOnly)) { return dateOnly; } } throw new JsonException($"Unable to convert '{reader.GetString()}' to DateOnly?."); } public override void Write(Utf8JsonWriter writer, DateOnly? value, JsonSerializerOptions options) { if (value.HasValue) writer.WriteStringValue(Utils.RedbTemporalFormat.ToText(value.Value)); else writer.WriteNullValue(); } } /// /// TimeOnly from the object JSON of the modules: its Ticks, as _values._Long stores it. /// public class FlexibleTimeOnlyConverter : JsonConverter { public override TimeOnly Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { if (reader.TokenType == JsonTokenType.Number && reader.TryGetInt64(out var ticks)) return new TimeOnly(ticks); throw new JsonException($"Unable to convert a {reader.TokenType} token to TimeOnly: it is stored as Ticks."); } public override void Write(Utf8JsonWriter writer, TimeOnly value, JsonSerializerOptions options) => writer.WriteNumberValue(value.Ticks); } /// /// Nullable TimeOnly from the object JSON of the modules: its Ticks, or null. /// public class FlexibleNullableTimeOnlyConverter : JsonConverter { public override TimeOnly? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { if (reader.TokenType == JsonTokenType.Null) return null; if (reader.TokenType == JsonTokenType.Number && reader.TryGetInt64(out var ticks)) return new TimeOnly(ticks); throw new JsonException($"Unable to convert a {reader.TokenType} token to TimeOnly?: it is stored as Ticks."); } public override void Write(Utf8JsonWriter writer, TimeOnly? value, JsonSerializerOptions options) { if (value.HasValue) writer.WriteNumberValue(value.Value.Ticks); else writer.WriteNullValue(); } } /// /// TimeSpan from the object JSON of the modules: its Ticks, as _values._Long stores it. /// public class FlexibleTimeSpanConverter : JsonConverter { public override TimeSpan Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { if (reader.TokenType == JsonTokenType.Number && reader.TryGetInt64(out var ticks)) return TimeSpan.FromTicks(ticks); throw new JsonException($"Unable to convert a {reader.TokenType} token to TimeSpan: it is stored as Ticks."); } public override void Write(Utf8JsonWriter writer, TimeSpan value, JsonSerializerOptions options) => writer.WriteNumberValue(value.Ticks); } /// /// Nullable TimeSpan from the object JSON of the modules: its Ticks, or null. /// public class FlexibleNullableTimeSpanConverter : JsonConverter { public override TimeSpan? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { if (reader.TokenType == JsonTokenType.Null) return null; if (reader.TokenType == JsonTokenType.Number && reader.TryGetInt64(out var ticks)) return TimeSpan.FromTicks(ticks); throw new JsonException($"Unable to convert a {reader.TokenType} token to TimeSpan?: it is stored as Ticks."); } public override void Write(Utf8JsonWriter writer, TimeSpan? value, JsonSerializerOptions options) { if (value.HasValue) writer.WriteNumberValue(value.Value.Ticks); else writer.WriteNullValue(); } } /// /// DateTimeOffset converter for PostgreSQL timestamptz. /// public class PostgresDateTimeOffsetConverter : JsonConverter { public override DateTimeOffset Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { if (reader.TokenType == JsonTokenType.String) { var stringValue = reader.GetString(); // PostgreSQL infinity support if (stringValue == "-infinity") return DateTimeOffset.MinValue; if (stringValue == "infinity") return DateTimeOffset.MaxValue; // Parse standard ISO8601 with timezone. Invariant culture: the wire form is always // ISO, and the ambient culture must never influence how a stored value is read. if (DateTimeOffset.TryParse(stringValue, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.RoundtripKind, out var result)) { return result.ToUniversalTime(); } } if (reader.TokenType == JsonTokenType.Null) throw new JsonException("Cannot convert null to DateTimeOffset"); return JsonSerializer.Deserialize(ref reader, options); } public override void Write(Utf8JsonWriter writer, DateTimeOffset value, JsonSerializerOptions options) { if (value == DateTimeOffset.MinValue) writer.WriteStringValue("-infinity"); else if (value == DateTimeOffset.MaxValue) writer.WriteStringValue("infinity"); else writer.WriteStringValue(value.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffffffzzz", System.Globalization.CultureInfo.InvariantCulture)); } } /// /// Nullable DateTimeOffset converter for PostgreSQL timestamptz. /// public class PostgresNullableDateTimeOffsetConverter : JsonConverter { public override DateTimeOffset? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { if (reader.TokenType == JsonTokenType.Null) return null; if (reader.TokenType == JsonTokenType.String) { var stringValue = reader.GetString(); if (stringValue == "-infinity") return DateTimeOffset.MinValue; if (stringValue == "infinity") return DateTimeOffset.MaxValue; if (DateTimeOffset.TryParse(stringValue, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.RoundtripKind, out var result)) { return result.ToUniversalTime(); } } return JsonSerializer.Deserialize(ref reader, options); } public override void Write(Utf8JsonWriter writer, DateTimeOffset? value, JsonSerializerOptions options) { if (value == null) writer.WriteNullValue(); else if (value == DateTimeOffset.MinValue) writer.WriteStringValue("-infinity"); else if (value == DateTimeOffset.MaxValue) writer.WriteStringValue("infinity"); else writer.WriteStringValue(value.Value.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffffffzzz", System.Globalization.CultureInfo.InvariantCulture)); } } /// /// FIX FOR "-infinity" PROBLEM: DateTime converter for handling PostgreSQL "-infinity" /// Solves problem: The JSON value could not be converted to System.DateTime /// public class PostgresInfinityDateTimeConverter : JsonConverter { public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { if (reader.TokenType == JsonTokenType.String) { var stringValue = reader.GetString(); // HANDLE PostgreSQL "-infinity" if (stringValue == "-infinity") { return DateTime.MinValue; } // HANDLE PostgreSQL "infinity" if (stringValue == "infinity") { return DateTime.MaxValue; } // Regular DateTime deserialization. Parsed as DateTimeOffset and reduced to the UTC // instant, so the stored clock reading comes back unchanged regardless of the // reader's time zone — REDB's contract is that DateTime carries no zone. if (DateTimeOffset.TryParse(stringValue, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.RoundtripKind, out var dateTimeOffset)) { return Utils.DateTimeConverter.DenormalizeFromStorage(dateTimeOffset); } throw new JsonException($"Cannot parse '{stringValue}' as DateTimeOffset."); } if (reader.TokenType == JsonTokenType.Null) { throw new JsonException("Cannot convert null to DateTime"); } // Try standard deserialization var result = JsonSerializer.Deserialize(ref reader, options); return result; } public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options) { // REVERSE CONVERSION: DateTime.MinValue → "-infinity" for PostgreSQL if (value == DateTime.MinValue) { writer.WriteStringValue("-infinity"); } else if (value == DateTime.MaxValue) { writer.WriteStringValue("infinity"); } else { // Standard serialization writer.WriteStringValue(value.ToString("yyyy-MM-ddTHH:mm:ss.fffffffK", System.Globalization.CultureInfo.InvariantCulture)); } } } /// /// FIX FOR "-infinity" PROBLEM: Nullable DateTime converter for handling PostgreSQL "-infinity" /// public class PostgresInfinityNullableDateTimeConverter : JsonConverter { public override DateTime? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { if (reader.TokenType == JsonTokenType.Null) { return null; } if (reader.TokenType == JsonTokenType.String) { var stringValue = reader.GetString(); // HANDLE PostgreSQL "-infinity" if (stringValue == "-infinity") { return DateTime.MinValue; } // HANDLE PostgreSQL "infinity" if (stringValue == "infinity") { return DateTime.MaxValue; } // Standard DateTime deserialization if (DateTimeOffset.TryParse(stringValue, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.RoundtripKind, out var dateTime)) { // FIXED: Return UTC instead of Local return Utils.DateTimeConverter.DenormalizeFromStorage(dateTime); } } // Try standard deserialization return JsonSerializer.Deserialize(ref reader, options); } public override void Write(Utf8JsonWriter writer, DateTime? value, JsonSerializerOptions options) { if (!value.HasValue) { writer.WriteNullValue(); return; } // REVERSE CONVERSION: DateTime.MinValue → "-infinity" for PostgreSQL if (value.Value == DateTime.MinValue) { writer.WriteStringValue("-infinity"); } else if (value.Value == DateTime.MaxValue) { writer.WriteStringValue("infinity"); } else { // Standard serialization writer.WriteStringValue(value.Value.ToString("yyyy-MM-ddTHH:mm:ss.fffffffK", System.Globalization.CultureInfo.InvariantCulture)); } } } /// /// Factory that creates converters to handle JSON null → default(T) for non-nullable value types. /// Fixes MSSQL deserialization where null values are explicitly included in JSON. /// public class NullToDefaultConverterFactory : JsonConverterFactory { private static readonly HashSet SupportedTypes = new() { typeof(int), typeof(long), typeof(short), typeof(byte), typeof(uint), typeof(ulong), typeof(ushort), typeof(sbyte), typeof(float), typeof(double), typeof(decimal), typeof(bool), typeof(char) }; public override bool CanConvert(Type typeToConvert) { return SupportedTypes.Contains(typeToConvert); } public override JsonConverter? CreateConverter(Type typeToConvert, JsonSerializerOptions options) { var converterType = typeof(NullToDefaultConverter<>).MakeGenericType(typeToConvert); return (JsonConverter?)Activator.CreateInstance(converterType); } } /// /// Converter that returns default(T) when JSON contains null for a non-nullable value type. /// public class NullToDefaultConverter : JsonConverter where T : struct { public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { if (reader.TokenType == JsonTokenType.Null) { return default; } // Handle numeric types if (typeof(T) == typeof(int)) return (T)(object)reader.GetInt32(); if (typeof(T) == typeof(long)) return (T)(object)reader.GetInt64(); if (typeof(T) == typeof(short)) return (T)(object)reader.GetInt16(); if (typeof(T) == typeof(byte)) return (T)(object)reader.GetByte(); if (typeof(T) == typeof(uint)) return (T)(object)reader.GetUInt32(); if (typeof(T) == typeof(ulong)) return (T)(object)reader.GetUInt64(); if (typeof(T) == typeof(ushort)) return (T)(object)reader.GetUInt16(); if (typeof(T) == typeof(sbyte)) return (T)(object)reader.GetSByte(); if (typeof(T) == typeof(float)) return (T)(object)reader.GetSingle(); if (typeof(T) == typeof(double)) return (T)(object)reader.GetDouble(); if (typeof(T) == typeof(decimal)) return (T)(object)reader.GetDecimal(); if (typeof(T) == typeof(bool)) return (T)(object)reader.GetBoolean(); if (typeof(T) == typeof(char)) { var str = reader.GetString(); return (T)(object)(str?.Length > 0 ? str[0] : default(char)); } throw new JsonException($"Unsupported type {typeof(T).Name}"); } public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options) { // Direct writes only. The old body called JsonSerializer.Serialize(writer, value, // options) with the SAME options - which resolve back to this converter: infinite // recursion, StackOverflow, dead process. It lay dormant because the write side of // these options only ever met models whose value-type members were all default // (skipped by WhenWritingDefault before reaching the converter); the first non-zero // int serialized through them (RedbObject.ToString) blew up. if (typeof(T) == typeof(int)) { writer.WriteNumberValue((int)(object)value!); return; } if (typeof(T) == typeof(long)) { writer.WriteNumberValue((long)(object)value!); return; } if (typeof(T) == typeof(short)) { writer.WriteNumberValue((short)(object)value!); return; } if (typeof(T) == typeof(byte)) { writer.WriteNumberValue((byte)(object)value!); return; } if (typeof(T) == typeof(uint)) { writer.WriteNumberValue((uint)(object)value!); return; } if (typeof(T) == typeof(ulong)) { writer.WriteNumberValue((ulong)(object)value!); return; } if (typeof(T) == typeof(ushort)) { writer.WriteNumberValue((ushort)(object)value!); return; } if (typeof(T) == typeof(sbyte)) { writer.WriteNumberValue((sbyte)(object)value!); return; } if (typeof(T) == typeof(float)) { writer.WriteNumberValue((float)(object)value!); return; } if (typeof(T) == typeof(double)) { writer.WriteNumberValue((double)(object)value!); return; } if (typeof(T) == typeof(decimal)) { writer.WriteNumberValue((decimal)(object)value!); return; } if (typeof(T) == typeof(bool)) { writer.WriteBooleanValue((bool)(object)value!); return; } if (typeof(T) == typeof(char)) { writer.WriteStringValue(value!.ToString()); return; } throw new JsonException($"Unsupported type {typeof(T).Name}"); } } } Path: redb/redb.Core/Serialization/ValueTupleDictionaryConverterFactory.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/Serialization/ValueTupleDictionaryConverterFactory.cs ---- using System; using System.Collections; using System.Collections.Generic; using System.Text.Json; using System.Text.Json.Serialization; using redb.Core.Utils; namespace redb.Core.Serialization { /// /// Factory for the JsonConverters of Dictionary<K, V> and IDictionary<K, V>. A read lists the entries /// by key (), not in the order of the JSON the modules built, which differed /// between providers. Complex keys (ValueTuple, classes) are stored as Base64-encoded JSON strings; simple keys /// are read and written by the converter of the key type, as System.Text.Json does on its own. /// public class ValueTupleDictionaryConverterFactory : JsonConverterFactory { public override bool CanConvert(Type typeToConvert) { if (!typeToConvert.IsGenericType) return false; var genericDef = typeToConvert.GetGenericTypeDefinition(); return genericDef == typeof(Dictionary<,>) || genericDef == typeof(IDictionary<,>); } public override JsonConverter? CreateConverter(Type typeToConvert, JsonSerializerOptions options) { var args = typeToConvert.GetGenericArguments(); var keyType = args[0]; var valueType = args[1]; Type converterType; if (RedbKeySerializer.IsComplexKey(keyType)) converterType = typeof(ValueTupleDictionaryConverter<,>).MakeGenericType(keyType, valueType); else if (typeToConvert.GetGenericTypeDefinition() == typeof(Dictionary<,>)) converterType = typeof(KeyOrderedDictionaryConverter<,>).MakeGenericType(keyType, valueType); else converterType = typeof(KeyOrderedDictionaryInterfaceConverter<,>).MakeGenericType(keyType, valueType); return (JsonConverter?)Activator.CreateInstance(converterType); } } /// /// JsonConverter for Dictionary with complex keys (ValueTuple, classes). /// Keys are serialized to Base64-encoded JSON strings. /// public class ValueTupleDictionaryConverter : JsonConverter> where TKey : notnull { public override Dictionary? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { if (reader.TokenType == JsonTokenType.Null) return null; if (reader.TokenType != JsonTokenType.StartObject) throw new JsonException("Expected StartObject token"); var entries = new List>(); while (reader.Read()) { if (reader.TokenType == JsonTokenType.EndObject) return KeyOrderedDictionaryConverter.ToDictionary(entries); if (reader.TokenType != JsonTokenType.PropertyName) throw new JsonException("Expected PropertyName token"); // Key is Base64-encoded JSON var keyString = reader.GetString()!; var key = (TKey)RedbKeySerializer.DeserializeObject(keyString, typeof(TKey))!; // Read value reader.Read(); var value = JsonSerializer.Deserialize(ref reader, options); entries.Add(new KeyValuePair(key, value!)); } throw new JsonException("Unexpected end of JSON"); } public override void Write(Utf8JsonWriter writer, Dictionary? value, JsonSerializerOptions options) { if (value == null) { writer.WriteNullValue(); return; } writer.WriteStartObject(); foreach (var kvp in value) { // Key → Base64-encoded JSON var keyString = RedbKeySerializer.SerializeObject(kvp.Key, typeof(TKey)); writer.WritePropertyName(keyString); // Write value JsonSerializer.Serialize(writer, kvp.Value, options); } writer.WriteEndObject(); } } /// /// JsonConverter for Dictionary with a simple key: the key is read and written by the converter of its type, as /// System.Text.Json does without a converter; a read lists the entries by key. /// public class KeyOrderedDictionaryConverter : JsonConverter> where TKey : notnull { public override Dictionary? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) => ReadEntries(ref reader, options); public override void Write(Utf8JsonWriter writer, Dictionary? value, JsonSerializerOptions options) => WriteEntries(writer, value, options); internal static Dictionary? ReadEntries(ref Utf8JsonReader reader, JsonSerializerOptions options) { if (reader.TokenType == JsonTokenType.Null) return null; if (reader.TokenType != JsonTokenType.StartObject) throw new JsonException("Expected StartObject token"); var keyConverter = (JsonConverter)options.GetConverter(typeof(TKey)); var entries = new List>(); while (reader.Read()) { if (reader.TokenType == JsonTokenType.EndObject) return ToDictionary(entries); if (reader.TokenType != JsonTokenType.PropertyName) throw new JsonException("Expected PropertyName token"); var key = keyConverter.ReadAsPropertyName(ref reader, typeof(TKey), options); reader.Read(); var value = JsonSerializer.Deserialize(ref reader, options); entries.Add(new KeyValuePair(key, value!)); } throw new JsonException("Unexpected end of JSON"); } internal static void WriteEntries(Utf8JsonWriter writer, IDictionary? value, JsonSerializerOptions options) { if (value == null) { writer.WriteNullValue(); return; } var keyConverter = (JsonConverter)options.GetConverter(typeof(TKey)); writer.WriteStartObject(); foreach (var kvp in value) { keyConverter.WriteAsPropertyName(writer, kvp.Key, options); JsonSerializer.Serialize(writer, kvp.Value, options); } writer.WriteEndObject(); } /// The entries by key; a repeated key keeps its last value, as System.Text.Json reads one. internal static Dictionary ToDictionary(List> entries) { var last = new Dictionary(entries.Count); foreach (var entry in entries) last[entry.Key] = entry.Value; if (last.Count != entries.Count) entries = new List>(last); var dict = new Dictionary(entries.Count); foreach (var entry in RedbDictionaryOrder.Sort(entries)) dict[entry.Key] = entry.Value; return dict; } } /// The same for a property declared as IDictionary with a simple key; it reads a Dictionary. public class KeyOrderedDictionaryInterfaceConverter : JsonConverter> where TKey : notnull { public override IDictionary? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) => KeyOrderedDictionaryConverter.ReadEntries(ref reader, options); public override void Write(Utf8JsonWriter writer, IDictionary? value, JsonSerializerOptions options) => KeyOrderedDictionaryConverter.WriteEntries(writer, value, options); } } Path: redb/redb.Core/Services/BackgroundDeletionService.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/Services/BackgroundDeletionService.cs ---- using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using redb.Core.Models.Contracts; namespace redb.Core.Services; /// /// Background deletion service backed by DB polling. /// /// Earlier revisions used an in-memory Channel<PurgeTask> for low-latency /// wake-up plus a startup-only RecoverOrphanedTasksAsync sweep for crash /// recovery. That created a dual-state problem: state of truth split between the /// channel (in memory, lost on kill) and the DB (durable). Worker force-kills always /// left a tail of orphaned 'pending' rows that the next startup had to drain in a /// flood of single-item purges. The "fix" of a periodic sweeper would have raced /// against the live channel reader unless we added age filters to the SQL. /// /// /// This revision drops the channel entirely. The DB IS the queue. /// polls on a fixed /// interval, atomically claims each pending row via /// (cluster-safe), and /// purges each container with the existing batched . /// Force-kill leaves nothing in memory because nothing was in memory — the next poll /// cycle (or next startup) just claims whatever's still 'pending'. /// /// /// Trade-off: cleanup latency shifts from "milliseconds via channel" to "≤ poll /// interval", but cleanup is invisible to API consumers anyway (the object is /// re-parented under the trash scheme by SoftDeleteAsync synchronously, so /// it disappears from queries immediately — only the physical purge of the /// _values cascade is deferred). /// /// public class BackgroundDeletionService : BackgroundService, IBackgroundDeletionService { private readonly IServiceProvider _serviceProvider; private readonly ILogger? _logger; /// /// Minutes after which a 'running' task is considered orphaned and re-claimed. /// Conservative — covers the case where another live instance is still working it. /// private const int OrphanTimeoutMinutes = 30; /// Default batch size for trash-container purges. private const int DefaultBatchSize = 10; /// How often the polling loop scans the DB for pending purge work. private static readonly TimeSpan PollInterval = TimeSpan.FromSeconds(5); /// Maximum number of trash containers claimed per poll cycle. private const int PollPageSize = 50; /// /// Creates a new BackgroundDeletionService. /// public BackgroundDeletionService( IServiceProvider serviceProvider, ILogger? logger = null) { _serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider)); _logger = logger; } /// /// Always 0 in the DB-polling design — there is no in-memory queue. The "queue" lives /// in _objects as rows with _value_string='pending'; callers that need /// that count should call /// directly. /// public int QueueLength => 0; /// /// Mark objects for deletion. Returns once SoftDeleteAsync has re-parented /// the objects under the trash scheme (so they immediately disappear from regular /// queries). The physical purge runs in a future poll /// cycle on a separate DB connection. /// public async Task DeleteAsync( IEnumerable objectIds, IRedbUser user, int batchSize = 10, long? trashParentId = null) { var ids = objectIds.ToArray(); if (ids.Length == 0) return new DeletionMark(0, 0); await using var scope = _serviceProvider.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); // SoftDeleteAsync writes the trash container with status='pending' in DB. The // polling loop in ExecuteAsync picks it up on the next cycle (≤ PollInterval // wait, typically much less). No channel write — DB is the queue. return await redb.SoftDeleteAsync(ids, user, trashParentId); } /// /// No-op. Kept on the interface for backward compatibility with callers like /// GroupService.AddMemberAsync that did manual SoftDeleteAsync + /// EnqueuePurge. The trash row those callers created is picked up by the /// next poll cycle, so the explicit wake-up signal is no longer needed. /// public void EnqueuePurge(long trashId, int totalCount, long userId, int batchSize = 10) { // Intentionally empty — the polling loop finds the row by itself. } /// /// Get current progress for a trash container from database. /// public async Task GetProgressAsync(long trashId) { await using var scope = _serviceProvider.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); return await redb.GetDeletionProgressAsync(trashId); } /// /// Get all active deletions for a user from database. /// public async Task> GetUserActiveProgressAsync(long userId) { await using var scope = _serviceProvider.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); return await redb.GetUserActiveDeletionsAsync(userId); } /// /// Polling loop — every finds up to /// pending trash containers, atomically claims each via /// , and purges with /// . Cluster-safe by the claim's atomic UPDATE — if /// another worker instance grabbed the same row, the claim returns false and we /// skip it. /// protected override async Task ExecuteAsync(CancellationToken stoppingToken) { _logger?.LogInformation("BackgroundDeletionService started (DB polling, interval={Interval})", PollInterval); while (!stoppingToken.IsCancellationRequested) { try { var processed = await PollAndProcessAsync(stoppingToken).ConfigureAwait(false); // No back-off when we found work — drain as fast as the DB lets us; one // poll cycle handles up to PollPageSize containers. When the page is // empty, sleep PollInterval. Saturates only when there is real load. if (processed == 0) { try { await Task.Delay(PollInterval, stoppingToken).ConfigureAwait(false); } catch (OperationCanceledException) { break; } } } catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { break; } catch (Exception ex) { _logger?.LogError(ex, "BackgroundDeletionService poll cycle failed; backing off {Interval}", PollInterval); try { await Task.Delay(PollInterval, stoppingToken).ConfigureAwait(false); } catch (OperationCanceledException) { break; } } } _logger?.LogInformation("BackgroundDeletionService stopped"); } /// /// One poll cycle: scan, claim, and process up to tasks. /// Returns the number of tasks actually processed (after claim contention with /// peer workers) so the outer loop can decide whether to keep draining or sleep. /// private async Task PollAndProcessAsync(CancellationToken ct) { // Short scopes: the scan's scope (and its connection) ends before the first purge starts, // and each claim gets its own - no connection of this cycle stays checked out across the // purges, which open their own scopes per batch. List tasks; await using (var scanScope = _serviceProvider.CreateAsyncScope()) { var scanRedb = scanScope.ServiceProvider.GetRequiredService(); tasks = await scanRedb.GetOrphanedDeletionTasksAsync(OrphanTimeoutMinutes).ConfigureAwait(false); } if (tasks.Count == 0) return 0; // Cap per cycle so a giant backlog doesn't block shutdown — anything not handled // here gets picked up on the next cycle (or by another worker in a cluster). var page = tasks.Take(PollPageSize).ToList(); _logger?.LogDebug("Poll cycle found {Total} pending tasks, processing up to {Page}", tasks.Count, page.Count); var processed = 0; foreach (var task in page) { if (ct.IsCancellationRequested) break; // The claim sits inside the per-task try: one container whose claim fails must not end // the cycle for every container after it. try { bool claimed; await using (var claimScope = _serviceProvider.CreateAsyncScope()) { var claimRedb = claimScope.ServiceProvider.GetRequiredService(); claimed = await claimRedb.TryClaimOrphanedTaskAsync(task.TrashId, OrphanTimeoutMinutes).ConfigureAwait(false); } if (!claimed) { _logger?.LogDebug("Task TrashId={TrashId} already claimed by another worker", task.TrashId); continue; } await ProcessPurgeTask(task.TrashId, task.Total, ct).ConfigureAwait(false); processed++; } catch (OperationCanceledException) when (ct.IsCancellationRequested) { break; } catch (redb.Core.Exceptions.RedbObjectReferencedException ex) { // Handled outcome, not a crash: the container is 'failed' and no longer claimed. It // waits for someone to remove the references and purge it again. _logger?.LogWarning(ex, "Purge of TrashId={TrashId} stopped: objects are referenced by live objects; container marked failed", task.TrashId); processed++; } catch (Exception ex) { _logger?.LogError(ex, "Purge failed for TrashId={TrashId}; will be retried next cycle once stale", task.TrashId); } } return processed; } /// /// Drain one trash container in batches of . The /// inter-batch Task.Delay(50) is backpressure: a single user-delete can /// cascade to thousands of _values rows, and the small pause lets live /// traffic (token issuance, /me reads) fit between purge batches instead of /// fighting for the same row locks. /// private async Task ProcessPurgeTask(long trashId, int totalCount, CancellationToken ct) { _logger?.LogDebug("Processing purge: TrashId={TrashId}, Total={Total}", trashId, totalCount); while (!ct.IsCancellationRequested) { await using var scope = _serviceProvider.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); var progress = await redb.GetDeletionProgressAsync(trashId).ConfigureAwait(false); if (progress == null) { _logger?.LogDebug("Trash container {TrashId} already gone, purge done", trashId); break; } if (progress.Status == PurgeStatus.Completed) { _logger?.LogDebug("Purge completed: TrashId={TrashId}", trashId); break; } if (progress.Status == PurgeStatus.Failed) { _logger?.LogDebug("Purge of TrashId={TrashId} already failed; not retried automatically", trashId); break; } await redb.PurgeTrashAsync(trashId, totalCount, DefaultBatchSize, cancellationToken: ct).ConfigureAwait(false); try { await Task.Delay(50, ct).ConfigureAwait(false); } catch (OperationCanceledException) { break; } } } } Path: redb/redb.Core/Services/IBackgroundDeletionService.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/Services/IBackgroundDeletionService.cs ---- using System; using System.Collections.Generic; using System.Threading.Tasks; using redb.Core.Models.Contracts; namespace redb.Core.Services; /// /// Background deletion service. Fire-and-forget delete: callers mark objects, return /// immediately, and a polling worker physically purges the trash on a separate DB /// connection. State of truth lives entirely in _objects rows (trash containers /// with _value_string='pending') — the worker drives off DB polling, so a /// worker crash or force-kill leaves no in-memory state to recover from. /// public interface IBackgroundDeletionService { /// /// Mark objects for deletion. Returns once /// has re-parented the objects under the trash scheme — they disappear from regular /// queries immediately. The physical purge of the _values cascade runs in /// the next worker poll cycle. /// Task DeleteAsync( IEnumerable objectIds, IRedbUser user, int batchSize = 10, long? trashParentId = null); /// /// No-op in the DB-polling design. Kept on the interface so callers that did a /// manual SoftDeleteAsync + EnqueuePurge handshake don't break — the /// trash row they wrote is picked up by the worker's next poll cycle on its own. /// void EnqueuePurge(long trashId, int totalCount, long userId, int batchSize = 10); /// /// Get current progress for a trash container from database. /// Returns null if trash container not found or already deleted. /// Task GetProgressAsync(long trashId); /// /// Get all active (pending/running) deletions for a user from database. /// Task> GetUserActiveProgressAsync(long userId); /// /// Always 0 in the DB-polling design — there is no in-memory queue. Callers who /// want the actual count of pending trash containers should query the DB directly /// (see IObjectStorageProvider.GetOrphanedDeletionTasksAsync). /// int QueueLength { get; } } /// /// Result of marking objects for deletion. /// /// ID of the created trash container object /// Number of objects marked for deletion (including descendants) public record DeletionMark(long TrashId, int MarkedCount); /// /// Progress of trash purge operation. /// /// ID of the trash container being purged /// Number of objects already deleted /// Number of objects still remaining /// Current status of the purge operation /// When the purge operation started /// ID of the user who initiated the deletion public record PurgeProgress( long TrashId, int Deleted, int Remaining, PurgeStatus Status, DateTimeOffset StartedAt, long UserId) { /// /// Total number of objects to delete. /// public int Total => Deleted + Remaining; /// /// Whether the purge operation is complete. /// public bool IsCompleted => Status == PurgeStatus.Completed; } /// /// Status of a purge operation. /// public enum PurgeStatus { /// Objects marked for deletion, purge not started yet Pending, /// Purge is in progress Running, /// Purge completed successfully Completed, /// Purge failed with error Failed, /// Purge was cancelled Cancelled } /// /// Orphaned deletion task found at startup. /// Used for cluster-safe recovery of incomplete deletions. /// /// ID of the trash container /// Total objects to delete /// Already deleted count /// Current status /// User who initiated the deletion public record OrphanedTask(long TrashId, int Total, int Deleted, string Status, long OwnerId); Path: redb/redb.Core/Services/RedbInitHostedService.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/Services/RedbInitHostedService.cs ---- using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using redb.Core.Models.Configuration; namespace redb.Core.Services; /// /// Hosted service that initializes redb schema on startup. /// Registered before BackgroundDeletionService to guarantee the schema /// exists when other services start querying. /// internal sealed class RedbInitHostedService : IHostedService { private readonly IServiceProvider _serviceProvider; private readonly RedbServiceConfiguration _configuration; private readonly ILogger? _logger; public RedbInitHostedService( IServiceProvider serviceProvider, RedbServiceConfiguration configuration, ILogger? logger = null) { _serviceProvider = serviceProvider; _configuration = configuration; _logger = logger; } public async Task StartAsync(CancellationToken cancellationToken) { using var scope = _serviceProvider.CreateScope(); var redb = scope.ServiceProvider.GetService(); if (redb is null) return; await redb.InitializeAsync(ensureCreated: _configuration.EnsureCreated); _logger?.LogInformation("Redb initialized (EnsureCreated={EnsureCreated})", _configuration.EnsureCreated); } public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask; } Path: redb/redb.Core/Utils/DateTimeConverter.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/Utils/DateTimeConverter.cs ---- using System; namespace redb.Core.Utils { /// /// Centralized DateTime conversion logic. /// /// RULE: in REDB a carries NO time zone. The clock reading is the /// datum and is preserved end to end: 14:00 written is 14:00 read, on any machine, in any /// zone, through any read path. Kind is set to Utc purely so the value has one unambiguous /// representation on the wire and in the column; it is a label, not a conversion. /// /// CONTRACT (all three points use the SAME transform, which is why they agree): /// - On save: DateTime → same reading, Kind=Utc (NormalizeForStorage) /// - On search: DateTime → same reading, Kind=Utc (NormalizeForStorage) /// - On read: DateTimeOffset from DB → same reading, Kind=Utc (DenormalizeFromStorage) /// /// IMPORTANT: is a different contract and is NOT touched. It is /// the native .NET type and keeps native semantics: it carries a real instant with an offset. /// Base object fields (_date_create, _date_modify, _date_begin, _date_complete) are /// DateTimeOffset and are therefore instants, matching the DB-side now() defaults. /// Use DateTime for zone-less business data, DateTimeOffset when the moment matters. /// public static class DateTimeConverter { /// /// Normalize a for storage: relabel the clock reading as UTC /// WITHOUT shifting it. This is deliberate, not an oversight. /// /// /// In REDB a carries no zone. The number on the clock is the datum, /// and it must survive unchanged: 14:00 written on any machine is 14:00 read on any other. /// Converting Local to UTC here would make the stored value depend on where the writer /// happened to run, which is exactly what this type is defined not to do. Code that needs /// a zone-aware instant uses , which keeps native .NET /// semantics throughout REDB. /// /// /// Examples: /// - new DateTime(2025, 11, 16) [Unspecified] → 2025-11-16 00:00:00, Kind=Utc /// - DateTime.Now [Local MSK 14:00] → 14:00, Kind=Utc (the reading, not the instant) /// - DateTime.UtcNow [Utc] → unchanged /// /// Original DateTime value /// The same clock reading, with Kind=Utc public static DateTime NormalizeForStorage(DateTime dateTime) { return DateTime.SpecifyKind(dateTime, DateTimeKind.Utc); } /// /// Denormalize DateTime from DB for returning to user. /// Returns DateTime with Kind = Utc. /// /// Example: /// - DB: 2025-11-16 00:00:00+00 → DateTime(2025, 11, 16, 0, 0, 0, DateTimeKind.Utc) /// /// DateTimeOffset from DB (timestamptz) /// DateTime with Kind=Utc public static DateTime DenormalizeFromStorage(DateTimeOffset dateTimeOffset) { return DateTime.SpecifyKind(dateTimeOffset.UtcDateTime, DateTimeKind.Utc); } /// /// Parse DateTime from string (JSON/SQL) as UTC. /// /// Example: /// - "2025-11-16T12:00:00Z" → DateTime(2025, 11, 16, 12, 0, 0, DateTimeKind.Utc) /// - "2025-11-16T12:00:00+03:00" → DateTime(2025, 11, 16, 9, 0, 0, DateTimeKind.Utc) /// /// String with date/time /// DateTime with Kind=Utc /// If string cannot be parsed public static DateTime ParseAsUtc(string value) { if (DateTimeOffset.TryParse(value, out var dto)) { return DateTime.SpecifyKind(dto.UtcDateTime, DateTimeKind.Utc); } throw new FormatException($"Cannot parse '{value}' as DateTime"); } } } Path: redb/redb.Core/Utils/LazyReferenceInstaller.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/Utils/LazyReferenceInstaller.cs ---- using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using redb.Core.Models.Contracts; using redb.Core.Providers; namespace redb.Core.Utils; /// /// V4 (L.3, LAZY plan §3.5): after deserialization every UNLOADED reference stub in a Props graph gets the lazy loader /// attached, so the first access to its Props loads exactly that object — whose own references are again stubs (the /// loader passes depth 1, §4.7). The walk descends only into LOADED objects via their raw Props (never through the getter, /// which would trigger loading), mirrors the shape of CacheNestedObjects, and tracks visited instances against /// cycles. /// /// A data object owns no connection. A /// loader bound to one scope is never installed on a stub: the stub gets the scope-free loader of that loader's database, /// which loads on the scope current for the reader, else on the materializing scope (the origin) while it lives. List items /// are bound the same way. A cache marks its graph shared: its stubs and items lose the origin and load on the reader's /// scope only. /// /// public static class LazyReferenceInstaller { /// /// V4 (review): after deserialization, every RedbObject<T> in the graph whose Props are /// null is marked NOT loaded. The Props setter marks any assignment as loaded, so a stub written /// by a foreign serializer as "properties": null would otherwise come back as a loaded /// object with nothing in it - and a parent save would write it as such (values deleted). The /// reader deserializes the whole subtree with the default converter, so the rule is applied by /// one walk from the root; it descends through loaded objects only, via their raw Props. /// public static void MarkUnloadedWherePropsAreNull(object? root) { if (root == null) return; var visited = new HashSet(ReferenceEqualityComparer.Instance); MarkInto(root, visited); } private static void MarkInto(object? node, HashSet visited) { if (node == null) return; var type = node.GetType(); if (type.IsPrimitive || type.IsValueType || node is string) return; if (IsWalkLeaf(node)) return; if (!visited.Add(node)) return; if (node is Models.Entities.RedbObject) { var props = type.GetMethod("GetPropsDirectly")?.Invoke(node, null); if (props == null) { // The non-generic RedbObject has no such field; the probe is null-safe. type.GetField("_propsLoaded")?.SetValue(node, false); return; } MarkInto(props, visited); return; } if (node is IDictionary dict) { foreach (DictionaryEntry e in dict) MarkInto(e.Value, visited); return; } if (node is IEnumerable seq) { foreach (var item in seq) MarkInto(item, visited); return; } if (type.Namespace?.StartsWith("System", StringComparison.Ordinal) == true) return; foreach (var p in WalkedProperties(type)) { var value = p.GetValue(node); MarkInto(value, visited); } } /// /// Attach the loader of 's database to every unloaded reference stub under /// , and bind every list item under it to that database and origin. /// public static void Install(IRedbObject? root, ILazyPropsLoader? loader) { if (root == null || loader == null) return; var visited = new HashSet(ReferenceEqualityComparer.Instance); InstallInto(root, ForStubs(loader), visited); } /// /// Same walk from an arbitrary node - a Props object, a collection, a list item - for callers that hold no root. /// public static void InstallInto(object? node, ILazyPropsLoader? loader) { if (node == null || loader == null) return; var visited = new HashSet(ReferenceEqualityComparer.Instance); InstallInto(node, ForStubs(loader), visited); } /// /// Marks a graph handed to a cache as shared by every scope: the objects, the stubs and the list items in it. A shared /// instance loads lazily on the reader's scope only - its stubs and items lose their origin - and, inside the reader's /// transaction, keeps nothing (owner decision 2026-09-15). Descends through loaded objects via their raw Props. /// public static void MarkShared(object? root) { if (root == null) return; MarkSharedInto(root, new HashSet(ReferenceEqualityComparer.Instance), null); } /// /// The same walk as , and the loaded objects it passed are returned: one pass serves both /// the shared mark and the cache entries of the graph, which used to be two walks of the same Props. A stub is /// marked only; a list item is marked and its already loaded object is visited, never loaded by the walk. /// public static List MarkSharedAndCollect(object? root) { var collected = new List(); if (root == null) return collected; MarkSharedInto(root, new HashSet(ReferenceEqualityComparer.Instance), collected); return collected; } private static void MarkSharedInto(object? node, HashSet visited, List? collected) { if (node == null) return; var type = node.GetType(); if (type.IsPrimitive || type.IsValueType || node is string) return; if (node is Models.Entities.RedbListItem item) { item._isShared = true; item._origin = null; // The object the item already carries is shared with it. MarkSharedInto(item.LoadedObject, visited, collected); return; } if (IsWalkLeaf(node)) return; if (!visited.Add(node)) return; if (node is Models.Entities.RedbObject obj) { obj._isShared = true; if (!obj.IsPropsLoaded) { var field = type.GetField("_lazyLoader"); if (field?.GetValue(node) is AmbientLazyPropsLoader ambient) field.SetValue(node, ambient.Shared); return; } // The nested entries SetNested used to write in a second walk: a loaded object with a hash // of its own is served by id directly. if (collected != null && obj is IRedbObject { Hash: not null } loaded) collected.Add(loaded); MarkSharedInto(type.GetMethod("GetPropsDirectly")?.Invoke(node, null), visited, collected); return; } if (node is IDictionary dict) { foreach (DictionaryEntry e in dict) MarkSharedInto(e.Value, visited, collected); return; } if (node is IEnumerable seq) { foreach (var element in seq) MarkSharedInto(element, visited, collected); return; } if (type.Namespace?.StartsWith("System", StringComparison.Ordinal) == true) return; foreach (var p in WalkedProperties(type)) { MarkSharedInto(p.GetValue(node), visited, collected); } } /// /// True for a collection that can hold no reference at all - an array or a System generic /// collection whose element types are primitives, value types or strings (a byte[] /// payload above all). Walking such a collection element by element boxes every item for /// nothing; both graph walkers (this installer and the Pro stub collector) skip it. /// public static bool IsLeafCollection(object node) { var type = node.GetType(); if (type.IsArray) return IsLeafType(type.GetElementType()); if (type.IsGenericType && type.Namespace?.StartsWith("System.Collections", StringComparison.Ordinal) == true) { foreach (var arg in type.GetGenericArguments()) if (!IsLeafType(arg)) return false; return true; } return false; } /// /// True for a node no reflective walk of a loaded graph may descend into: a /// or a list item. A list item's lazy Object getter LOADS /// on read, so walking its properties fired a database load per linked item on every /// materialization of an object with list-item fields (~150 phantom loads a second on a /// production stand, 2026-09-09 - with not a single explicit .Object in the application). /// Every walker over loaded Props (this installer, the props-cache dirty guard, the cache /// collector, the Pro materialization walks) asks this one predicate, so the rule cannot drift. /// public static bool IsWalkLeaf(object node) => node is Models.Contracts.IRedbListItem || IsLeafCollection(node); /// /// True for a property a walk of a loaded graph reads: the set the scheme and the save take - public, not an /// indexer, not [RedbIgnore]. A getter's exception is not caught, as the save does not catch it (owner /// decision 2026-09-15); a computed property that is not data belongs under [RedbIgnore]. /// public static bool IsWalkedProperty(PropertyInfo property) => property.CanRead && property.GetIndexParameters().Length == 0 && !Extensions.PropertyInfoExtensions.ShouldIgnoreForRedb(property); // The walked properties of a type (public instance, IsWalkedProperty), once per type. Each walk of each node read // the properties of its type again and the [RedbIgnore] attribute of each of them. Keyed weakly: a Props type of a // module in a collectible AssemblyLoadContext must not keep that context alive. private static readonly System.Runtime.CompilerServices.ConditionalWeakTable WalkedPropertyCache = new(); private static PropertyInfo[] WalkedProperties(Type type) => WalkedPropertyCache.GetValue(type, static t => { var walked = new List(); foreach (var p in t.GetProperties(BindingFlags.Public | BindingFlags.Instance)) if (IsWalkedProperty(p)) walked.Add(p); return walked.ToArray(); }); private static bool IsLeafType(Type? t) => t != null && (t.IsPrimitive || t.IsValueType || t == typeof(string) || t == typeof(byte[])); // A loader that names its database is bound to one scope: the stub gets that database's scope-free loader, with the // service of that scope as its origin - or the captive service that scope was lent to (RedbServiceBase.AsOrigin). private static ILazyPropsLoader ForStubs(ILazyPropsLoader loader) => loader is not AmbientLazyPropsLoader && loader.CacheDomain is { } domain ? AmbientLazyPropsLoader.For(domain, RedbServiceBase.ServiceOf(loader.ScopeContext)?.AsOrigin) : loader; private static void InstallInto(object? node, ILazyPropsLoader loader, HashSet visited) { if (node == null) return; var type = node.GetType(); if (type.IsPrimitive || type.IsValueType || node is string) return; if (node is Models.Entities.RedbListItem item) { // Bound once: an item never moves to another database. Its Object is never read here. if (loader.CacheDomain is { } domain) item._cacheDomain ??= domain; if (!item._isShared && loader is AmbientLazyPropsLoader { Origin: { } origin }) item._origin ??= origin; return; } if (IsWalkLeaf(node)) return; // byte[], int[], List: nothing to attach, no walk if (!visited.Add(node)) return; if (node is Models.Entities.RedbObject baseObj && node is IRedbObject redbObj) { // RedbObject and TreeRedbObject alike: the public _lazyLoader field and // GetPropsDirectly are inherited, so Type.GetField/GetMethod see them on the derived // type. The non-generic RedbObject has neither, and both probes are null-safe. if (!baseObj.IsPropsLoaded && redbObj.Id > 0) { // The stub: attach the loader, do not descend — there is nothing loaded to walk. A shared stub never // regains an origin. var installed = baseObj._isShared && loader is AmbientLazyPropsLoader ambient ? ambient.Shared : loader; type.GetField("_lazyLoader")?.SetValue(node, installed); return; } // A loaded object: walk its raw Props for deeper stubs. Raw access only — // the Props getter of a stub is a load. var props = type.GetMethod("GetPropsDirectly")?.Invoke(node, null); InstallInto(props, loader, visited); return; } if (node is IDictionary dict) { foreach (DictionaryEntry e in dict) InstallInto(e.Value, loader, visited); return; } if (node is IEnumerable seq) { foreach (var element in seq) InstallInto(element, loader, visited); return; } // A business class (the Props object itself or a nested class): walk its properties. if (type.Namespace?.StartsWith("System", StringComparison.Ordinal) == true) return; foreach (var p in WalkedProperties(type)) { var value = p.GetValue(node); InstallInto(value, loader, visited); } } } Path: redb/redb.Core/Utils/LoadedGraphInspector.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/Utils/LoadedGraphInspector.cs ---- using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; namespace redb.Core.Utils; /// /// V4 (review, owner decision 2026-09-01): the props-cache dirty guard, one level deeper. /// /// /// The parent's own hash is composed of id:hash of its references (L.2), so an unsaved /// in-memory edit INSIDE a loaded nested object does not move it: the root check of the cache sees /// a clean object and would serve the graph with the phantom edit - the SetStatus-before-Save /// incident, one level down. This walk visits the LOADED part of a cached graph (raw Props only, /// stubs are neither touched nor woken) and asks each nested object whether its live content hash /// still equals its own persisted hash; after the V4 hash fixes the two are equal by construction /// for an unmodified object, so any drift means an unsaved edit somewhere in the graph. /// /// public static class LoadedGraphInspector { /// /// True when a LOADED object under carries a live content hash that /// differs from its own persisted hash - an unsaved in-memory edit. Stubs and objects /// that were never persisted (no hash) are skipped. /// public static bool HasDirtyLoadedReference(object? props) { if (props == null) return false; var visited = new HashSet(ReferenceEqualityComparer.Instance); return IsDirty(props, visited); } /// /// The LOADED objects under with the hash each was loaded with, by id: what a cached /// graph vouches for beyond its root. The root's own hash does not move when one of them changes or leaves for /// the trash on any node, so before the cache serves the graph these are checked against their rows. Stubs are /// neither touched nor woken: a stub loads its target from the database when it is read. /// public static Dictionary CollectLoadedReferences(object? props) { var found = new Dictionary(); if (props != null) Collect(props, found, new HashSet(ReferenceEqualityComparer.Instance)); return found; } /// /// True when the graph under references a persisted object that carries no header (scheme /// unknown): a hand-made reference such as new RedbObject<T> { id = 42 } handed to a save. Its lazy load /// fills Props only, so a cached graph would serve it without name, scheme and dates, and its hash would never /// match its row again. Nothing is loaded: stubs are read by their fields, not their Props. /// public static bool HasHeaderlessReference(object? props) { if (props == null) return false; return IsHeaderless(props, new HashSet(ReferenceEqualityComparer.Instance)); } private static bool IsHeaderless(object? node, HashSet visited) { if (node == null) return false; var type = node.GetType(); if (type.IsPrimitive || type.IsValueType || node is string) return false; if (LazyReferenceInstaller.IsWalkLeaf(node)) return false; if (!visited.Add(node)) return false; if (node is RedbObject baseObj && node is IRedbObject redbObj) { if (redbObj.Id > 0 && redbObj.SchemeId == 0) return true; if (!baseObj.IsPropsLoaded) return false; return IsHeaderless(type.GetMethod("GetPropsDirectly")?.Invoke(node, null), visited); } if (node is IDictionary dict) { foreach (DictionaryEntry e in dict) if (IsHeaderless(e.Value, visited)) return true; return false; } if (node is IEnumerable seq) { foreach (var item in seq) if (IsHeaderless(item, visited)) return true; return false; } if (type.Namespace?.StartsWith("System", StringComparison.Ordinal) == true) return false; foreach (var p in type.GetProperties(BindingFlags.Public | BindingFlags.Instance)) { if (!LazyReferenceInstaller.IsWalkedProperty(p)) continue; if (IsHeaderless(p.GetValue(node), visited)) return true; } return false; } private static void Collect(object? node, Dictionary found, HashSet visited) { if (node == null) return; var type = node.GetType(); if (type.IsPrimitive || type.IsValueType || node is string) return; if (LazyReferenceInstaller.IsWalkLeaf(node)) return; if (!visited.Add(node)) return; if (node is RedbObject baseObj && node is IRedbObject redbObj) { if (!baseObj.IsPropsLoaded) return; if (redbObj.Id > 0) found[redbObj.Id] = redbObj.Hash; Collect(type.GetMethod("GetPropsDirectly")?.Invoke(node, null), found, visited); return; } if (node is IDictionary dict) { foreach (DictionaryEntry e in dict) Collect(e.Value, found, visited); return; } if (node is IEnumerable seq) { foreach (var item in seq) Collect(item, found, visited); return; } if (type.Namespace?.StartsWith("System", StringComparison.Ordinal) == true) return; foreach (var p in type.GetProperties(BindingFlags.Public | BindingFlags.Instance)) { if (!LazyReferenceInstaller.IsWalkedProperty(p)) continue; Collect(p.GetValue(node), found, visited); } } private static bool IsDirty(object? node, HashSet visited) { if (node == null) return false; var type = node.GetType(); if (type.IsPrimitive || type.IsValueType || node is string) return false; if (LazyReferenceInstaller.IsWalkLeaf(node)) return false; // a list item's Object getter loads on read if (!visited.Add(node)) return false; if (node is RedbObject baseObj && node is IRedbObject redbObj) { // A stub is served exactly as it was stored - nothing loaded, nothing to have drifted. if (!baseObj.IsPropsLoaded) return false; var nestedProps = type.GetMethod("GetPropsDirectly")?.Invoke(node, null); if (nestedProps == null) return false; // an object without Props has no content to compare // A never-persisted object (hash null) cannot be judged - descend into it instead. if (redbObj.Hash is { } persisted && RedbHash.ComputeFor(redbObj) is { } live && live != persisted) return true; return IsDirty(nestedProps, visited); } if (node is IDictionary dict) { foreach (DictionaryEntry e in dict) if (IsDirty(e.Value, visited)) return true; return false; } if (node is IEnumerable seq) { foreach (var item in seq) if (IsDirty(item, visited)) return true; return false; } if (type.Namespace?.StartsWith("System", StringComparison.Ordinal) == true) return false; foreach (var p in type.GetProperties(BindingFlags.Public | BindingFlags.Instance)) { if (!LazyReferenceInstaller.IsWalkedProperty(p)) continue; var value = p.GetValue(node); if (IsDirty(value, visited)) return true; } return false; } } Path: redb/redb.Core/Utils/RateWindow.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/Utils/RateWindow.cs ---- using System; using System.Threading; namespace redb.Core.Utils { /// /// Counts events in fixed time windows and reports the moment a window's count reaches a threshold, once per /// window. Lock-free and meant for diagnostics: a race at a window boundary may lose a few counts. /// internal sealed class RateWindow { private readonly long _windowMs; private readonly int _threshold; private long _windowStartMs; private int _count; public RateWindow(TimeSpan window, int threshold) { if (window <= TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(window), "Must be greater than zero"); if (threshold <= 0) throw new ArgumentOutOfRangeException(nameof(threshold), "Must be greater than 0"); _windowMs = (long)window.TotalMilliseconds; _threshold = threshold; _windowStartMs = Environment.TickCount64; } /// Adds events; returns the window's count when this call reached the threshold, otherwise 0. public int Add(int events = 1) { var now = Environment.TickCount64; var start = Interlocked.Read(ref _windowStartMs); if (now - start > _windowMs && Interlocked.CompareExchange(ref _windowStartMs, now, start) == start) Interlocked.Exchange(ref _count, 0); var after = Interlocked.Add(ref _count, events); return after >= _threshold && after - events < _threshold ? after : 0; } } } Path: redb/redb.Core/Utils/RedbDecimal.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/Utils/RedbDecimal.cs ---- using System.Globalization; namespace redb.Core.Utils; /// /// A decimal from a binary floating-point value, the way a reader of a REAL or FLOAT column, an aggregate over one or a /// computed result needs it: the decimal of the shortest text that reads back as the same double ("R"). So 123.45 /// stored as REAL comes back as 123.45 on every runtime. /// /// /// The explicit conversion (decimal)double, which and /// use, rounds to 15 significant digits up to .NET 10 (12345678901234.56 /// became 12345678901234.6) and gives the exact binary value from .NET 11 on (123.45 became /// 123.45000000000000284217094304). Neither is the number that was stored. /// public static class RedbDecimal { /// The decimal the double stands for. A value outside the decimal range, NaN or an infinity throws /// , as the explicit conversion does. public static decimal FromDouble(double value) { if (double.IsNaN(value) || double.IsInfinity(value)) throw new OverflowException($"{value.ToString(CultureInfo.InvariantCulture)} has no decimal value."); // The shortest text of a double is at most 24 characters ("-1.7976931348623157E+308"): formatted on the stack, // parsed from the span, no string per value on the read path. Span text = stackalloc char[32]; value.TryFormat(text, out var written, "R", CultureInfo.InvariantCulture); return decimal.Parse(text[..written], NumberStyles.Float, CultureInfo.InvariantCulture); } /// The decimal the float stands for (the shortest text of the float itself, not of its widening to double). public static decimal FromSingle(float value) { if (float.IsNaN(value) || float.IsInfinity(value)) throw new OverflowException($"{value.ToString(CultureInfo.InvariantCulture)} has no decimal value."); Span text = stackalloc char[32]; value.TryFormat(text, out var written, "R", CultureInfo.InvariantCulture); return decimal.Parse(text[..written], NumberStyles.Float, CultureInfo.InvariantCulture); } /// /// with a double or a float read through /// / . Anything else converts as before. /// public static decimal From(object value) => value switch { decimal d => d, double dbl => FromDouble(dbl), float f => FromSingle(f), _ => Convert.ToDecimal(value, CultureInfo.InvariantCulture) }; /// /// , except that a double or a float asked for as a /// decimal goes through / . Every other pair converts exactly as /// does with the same provider (null: the current /// culture, as ). /// public static object ChangeType(object value, Type targetType, IFormatProvider? provider = null) => targetType == typeof(decimal) && value is double or float ? From(value) : Convert.ChangeType(value, targetType, provider); } Path: redb/redb.Core/Utils/RedbDictionaryOrder.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/Utils/RedbDictionaryOrder.cs ---- using System; using System.Collections.Generic; using System.Runtime.CompilerServices; namespace redb.Core.Utils; /// /// The order in which a dictionary read from the database lists its entries: by key, the same on every provider and /// in every read. A dictionary is stored as an unordered set (its hash ignores the order of entries), and a read used /// to list them in the order of its rows (Pro) or of the JSON the free modules built (by key length on PostgreSQL, by /// key text on SQL Server and SQLite), so the order moved between providers and, in Pro, between reads. /// Simple keys sort by their value: strings ordinally, numbers, dates, times, Guids and enums as values, byte arrays /// by their bytes. Composite keys (value tuples, classes) sort by the text they are stored under. /// public static class RedbDictionaryOrder { private static readonly ConditionalWeakTable> ByKeyType = new(); /// The comparer of keys of type . public static IComparer For(Type keyType) => ByKeyType.GetValue(keyType, Create); /// The entries in the order a read lists them. public static List> Sort(List> entries) where TKey : notnull { var comparer = For(typeof(TKey)); entries.Sort((a, b) => comparer.Compare(a.Key, b.Key)); return entries; } private static IComparer Create(Type keyType) { if (keyType == typeof(string)) return Comparer.Create(static (a, b) => string.CompareOrdinal((string)a, (string)b)); if (keyType == typeof(byte[])) return Comparer.Create(static (a, b) => ((byte[])a).AsSpan().SequenceCompareTo((byte[])b)); if (!RedbKeySerializer.IsComplexKey(keyType) && typeof(IComparable).IsAssignableFrom(keyType)) return Comparer.Create(static (a, b) => ((IComparable)a).CompareTo(b)); return Comparer.Create((a, b) => string.CompareOrdinal( RedbKeySerializer.SerializeObject(a, keyType), RedbKeySerializer.SerializeObject(b, keyType))); } } Path: redb/redb.Core/Utils/RedbHash.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/Utils/RedbHash.cs ---- using redb.Core.Models.Entities; using redb.Core.Models.Contracts; using redb.Core.Attributes; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Reflection; using System.Security.Cryptography; using System.Text; using System.Text.Json.Serialization; namespace redb.Core.Utils { /// /// Utility for computing the MD5 hash of an object. _hash covers the WHOLE object row: /// the header canon (see ) together with the Props content; a /// non-generic RedbObject (or a typed one without Props) hashes its header alone. /// public static class RedbHash { /// Canon of a null header value - distinct from an empty string. private const string NullMark = "\0"; /// /// Canonical string of the object header: every column of the _objects row except /// the hash itself, the identity (id, scheme id) and the audit trio /// (date_create, date_modify, who_change). The audit trio is stamped /// on the database record AFTER the hash is computed and never written back into the /// object, so a hash carrying it could never be reproduced from a reloaded row - the /// cache and the ChangeTracking hash shortcut would be dead for every object. The scheme /// id is assigned after the batch recomputes hashes (every new object would miss its /// first hits), and the id is 0 until the save assigns it. Header dates canonicalise at /// second precision in UTC: sub-second digits do not survive every database (SQLite /// stores REAL Julian days, ~40 microseconds) and MSSQL keeps the offset while /// PostgreSQL returns UTC. /// public static string HeaderCanon(IRedbObject obj) { var inv = CultureInfo.InvariantCulture; var parts = new List(16) { obj.ParentId?.ToString(inv) ?? NullMark, obj.OwnerId.ToString(inv), Escape(obj.Name, HeaderSeparators) ?? NullMark, Escape(obj.Note, HeaderSeparators) ?? NullMark, obj.Key?.ToString(inv) ?? NullMark, obj.ValueLong?.ToString(inv) ?? NullMark, Escape(obj.ValueString, HeaderSeparators) ?? NullMark, obj.ValueGuid?.ToString("N") ?? NullMark, obj.ValueBool?.ToString(inv) ?? NullMark, obj.ValueDouble?.ToString("R", inv) ?? NullMark, obj.ValueNumeric?.ToString("G29", inv) ?? NullMark, DateCanon(obj.ValueDatetime), obj.ValueBytes != null ? Convert.ToBase64String(obj.ValueBytes) : NullMark, Escape(obj.ValueUnique, HeaderSeparators) ?? NullMark, DateCanon(obj.DateBegin), DateCanon(obj.DateComplete), }; return string.Join("|", parts); } private static string DateCanon(DateTimeOffset? value) => value?.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss", CultureInfo.InvariantCulture) ?? NullMark; /// /// Hash of the header alone (Object schemes without Props): a non-generic RedbObject or a /// RedbObject{TProps} with Props=null. The same canon the typed hash starts from. /// public static Guid ComputeForBaseFields(IRedbObject obj) { return new Guid(RedbMd5.ComputeHash(Encoding.UTF8.GetBytes(HeaderCanon(obj)))); } /// /// Hash of any IRedbObject: header canon plus Props content. /// Returns null if there are no Props to hash (the callers fall back to /// ). /// public static Guid? ComputeFor(IRedbObject obj) { // Find Props property via reflection var propertiesProperty = obj.GetType().GetProperty("Props"); if (propertiesProperty != null) { var propertiesValue = propertiesProperty.GetValue(obj); if (propertiesValue != null) { return Combine(obj, ComputeForObject(propertiesValue)); } } // If no Props - return null return null; } public static Guid? ComputeFor(RedbObject obj) where TProps : class, new() { return Combine(obj, ComputeForProps(obj.Props)); } /// Header canon and the Props hash into one object hash; null Props hash stays null. private static Guid? Combine(IRedbObject obj, Guid? propsHash) { if (propsHash is null) return null; var payload = HeaderCanon(obj) + "||" + propsHash.Value.ToString("N"); return new Guid(RedbMd5.ComputeHash(Encoding.UTF8.GetBytes(payload))); } public static Guid? ComputeForProps(TProps props) where TProps : class, new() { return ComputeForObject(props); } /// /// Compute hash for arbitrary object via reflection. /// Returns null if object has no properties. /// private static Guid? ComputeForObject(object? obj) { // No object → no data to hash. The reflection-based ComputeFor(IRedbObject) // already returns null for a null Props (Props=null is a supported case — // see ComputeForBaseFields). This aligns the generic ComputeForProps path // with that contract instead of throwing NRE on obj.GetType(). if (obj is null) return null; // The objects on the way from the root to this one. Reached again on the same way, an object is a cycle: // the walk would never end and the stack overflow takes the process down. An object reached twice on // different ways (one instance shared by two properties) is no cycle and hashes as before, as two copies. var path = _walkPath ??= new HashSet(ReferenceEqualityComparer.Instance); if (!path.Add(obj)) throw new InvalidOperationException( $"The props of a redb object hold a reference cycle: an instance of '{obj.GetType().FullName}' is " + "reached again through its own properties. A nested class is stored as a tree of values and cannot " + "refer back to an object above it. Mark the back-reference [RedbIgnore], or link the objects as " + "RedbObject references, which are stored by id."); try { return ComputeForWalkedObject(obj); } finally { path.Remove(obj); } } /// The way of the current walk of ; the walk is synchronous. [ThreadStatic] private static HashSet? _walkPath; private static Guid? ComputeForWalkedObject(object obj) { // A collection passed as the root (collection base-row hashes above all): reflecting // over the collection type's OWN properties degenerates the canon - List exposed only // Capacity|Count, long[] only Length&Co, so same-sized collections with different // content hashed equal (found by the F2 short-circuit, pinned by // ArrayBaseHash_DependsOnElementContent). Format the collection through the same // canon branches a collection FIELD takes, and hash that string. if (obj is System.Collections.IDictionary rootDict) return new Guid(RedbMd5.ComputeHash(Encoding.UTF8.GetBytes(FormatDictionaryCanon(rootDict)))); if (obj is System.Collections.IEnumerable rootSeq && obj is not string) return new Guid(RedbMd5.ComputeHash(Encoding.UTF8.GetBytes(FormatEnumerableCanon(rootSeq)))); var properties = HashedProperties(obj.GetType()); // If no properties - no data for hashing if (properties.Length == 0) return null; var ordered = properties.Select(p => SafeGetValue(p, obj)); var payload = string.Join("|", ordered); var bytes = Encoding.UTF8.GetBytes(payload); var hash = RedbMd5.ComputeHash(bytes); return new Guid(hash); } /// The hashed properties of a type, in canon order; computed once per type. private static readonly System.Runtime.CompilerServices.ConditionalWeakTable HashedPropertiesByType = new(); /// /// The properties a type contributes to the hash, in canon order: by , then by the /// property name, both ordinal. A weak table, so a type of an unloadable module does not stay alive through it. /// An indexer is not a field (the scheme sync and the value writer skip it) and has no value without an index. /// private static PropertyInfo[] HashedProperties(Type type) => HashedPropertiesByType.GetValue(type, static t => t .GetProperties(BindingFlags.Public | BindingFlags.Instance) .Where(p => p.GetIndexParameters().Length == 0) .Where(p => !ShouldIgnoreForHash(p)) // Filter technical properties .OrderBy(HashSortKey, StringComparer.Ordinal) .ThenBy(p => p.Name, StringComparer.Ordinal) .ToArray()); /// /// The name a property sorts by in the hash canon: the name of its first /// (the first name of the property), the property name when it has none. A rename keeps the property where it /// sorted before, so the hashes stored before the rename stay valid after it; this is why the attribute stays /// on the property for good. A property without the attribute sorts by its name, exactly as before the /// attribute existed. The attributes are read in declaration order; the scheme sync checks the first one /// against the history the database keeps in _structures._renamed_from. /// internal static string HashSortKey(PropertyInfo property) => property.GetCustomAttributes(false).FirstOrDefault()?.OldName ?? property.Name; /// /// Checks if property should be ignored during hash calculation. /// private static bool ShouldIgnoreForHash(PropertyInfo property) { // Only RedbIgnore affects hash calculation. JsonIgnore is for JSON serialization. return property.GetCustomAttributes(typeof(RedbIgnoreAttribute), false).Length > 0; } /// /// The canon of one property value; recursively hashes nested objects and arrays. A getter's exception is not /// caught (owner decision 2026-09-15): an empty string standing in for it made the hash describe data the /// object does not have, and the save does not catch that getter either. /// private static string SafeGetValue(PropertyInfo property, object obj) { var value = property.GetValue(obj); if (value == null) return ""; var type = value.GetType(); // Primitives and simple types: the invariant canon (culture-free, milliseconds for temporal values) // A null property canonicalises to "" above, so an empty string takes a mark of its own. if (value is string { Length: 0 }) return EmptyTextMark; if (IsPrimitiveOrSimple(type)) return ScalarCanon(value, PropertySeparators); // V4 (L.2, LAZY plan §4.1): a nested RedbObject is a REFERENCE. The parent hashes // the reference's own persisted hash instead of walking its Props: walking would // (a) trigger lazy loading of the whole graph from inside a hash computation and // (b) make the eager and the lazy hash of the same parent differ (a stub carries // no Props). The hash field is present on stub and full object alike. if (value is IRedbObject nestedRef) return $"{nestedRef.Id}:{nestedRef.Hash?.ToString("N")}"; // id = identity, hash = content-at-write // O-1/B-3 (owner's verdict): _values stores the dictionary item IDENTIFIER, and the // hash canon is the id ONLY. ListItem content lives its own life (extension objects); // hashing the content would move the owner's hash whenever a value in _list_items // is renamed. if (value is IRedbListItem listItemRef) return listItemRef.Id.ToString(); // Dictionaries — hash by CONTENT, order-independent. A Dictionary is an UNORDERED set of // key/value pairs: {a:1,b:2} equals {b:2,a:1}, so equal maps must hash equally. .NET does // not guarantee enumeration order (and it changes after removals), and the same logical // map is rebuilt in a different order when materialized from _values than when first // created — hashing it in enumeration order desynchronizes _objects._hash vs the cache. // Canonicalize by sorting "key=valueHash" pairs before hashing. if (value is System.Collections.IDictionary dictionary) return FormatDictionaryCanon(dictionary); // Arrays and collections - hash each element (ORDER MATTERS here — lists/arrays are ordered) if (value is System.Collections.IEnumerable enumerable && type != typeof(string)) return FormatEnumerableCanon(enumerable); // Nested object (business class) - recursively hash! var nestedHash = ComputeForObject(value); return nestedHash?.ToString("N") ?? ""; } /// /// Canonical string of a dictionary - order-independent (sorted "key=valueCanon" pairs). /// A Dictionary is an UNORDERED set of key/value pairs: {a:1,b:2} equals {b:2,a:1}, so /// equal maps must hash equally regardless of enumeration order. /// private static string FormatDictionaryCanon(System.Collections.IDictionary dictionary) { var entries = new System.Collections.Generic.List(dictionary.Count); foreach (System.Collections.DictionaryEntry entry in dictionary) { // A key that is not a simple value (a tuple, a class) canonicalises through the serializer that writes // it into _array_index: culture-free, and distinct for distinct keys. Its ToString() was the canon // before: a class without its own ToString() gave the type name for every key, so a changed key kept // the hash, and a tuple of a double or a date followed the culture of the node. var keyStr = entry.Key == null ? "null" : IsPrimitiveOrSimple(entry.Key.GetType()) ? ScalarCanon(entry.Key, KeySeparators) : Escape(RedbKeySerializer.SerializeObject(entry.Key, entry.Key.GetType()), KeySeparators)!; string valStr; if (entry.Value == null) valStr = "null"; else if (entry.Value is "null") valStr = NullTextMark; // a null value canonicalises to "null" else if (IsPrimitiveOrSimple(entry.Value.GetType())) valStr = ScalarCanon(entry.Value, ElementSeparators); else if (entry.Value is IRedbObject dictRef) valStr = $"{dictRef.Id}:{dictRef.Hash?.ToString("N")}"; // V4 (L.2): reference by its hash else if (entry.Value is IRedbListItem dictListItem) valStr = dictListItem.Id.ToString(); // O-1: ListItem canon is the id only else valStr = ComputeForObject(entry.Value)?.ToString("N") ?? "null"; entries.Add($"{keyStr}={valStr}"); } entries.Sort(StringComparer.Ordinal); return $"{{{string.Join(",", entries)}}}"; } /// /// Canonical string of an ordered collection - element canons joined IN ORDER /// (lists/arrays are ordered, so reorder changes the canon). /// private static string FormatEnumerableCanon(System.Collections.IEnumerable enumerable) { var elementHashes = new System.Collections.Generic.List(); foreach (var item in enumerable) { if (item == null) { elementHashes.Add("null"); } else if (item is "null") { elementHashes.Add(NullTextMark); // a null element canonicalises to "null" } else if (item is string { Length: 0 }) { elementHashes.Add(EmptyTextMark); // "[]" is the canon of an empty collection } else if (IsPrimitiveOrSimple(item.GetType())) { elementHashes.Add(ScalarCanon(item, ElementSeparators)); } else if (item is IRedbObject itemRef) { elementHashes.Add($"{itemRef.Id}:{itemRef.Hash?.ToString("N")}"); // V4 (L.2) } else if (item is IRedbListItem itemListItem) { elementHashes.Add(itemListItem.Id.ToString()); // O-1: ListItem canon is the id only } else { // Recursively hash nested object var itemHash = ComputeForObject(item); elementHashes.Add(itemHash?.ToString("N") ?? "null"); } } return $"[{string.Join(",", elementHashes)}]"; } /// /// The canon of a primitive or simple value. Invariant: the process culture never takes part (a decimal /// separator or a date format of one node must not move the hash on another), and a temporal value is /// canonicalised in UTC at MILLISECOND precision - the precision every database keeps (SQLite stores an /// OLE date, truncated to milliseconds by .NET; PostgreSQL keeps microseconds; SQL Server 100 ns), so the /// hash the save stores is the hash the reloaded object recomputes. A change below one millisecond is /// not a change: the databases do not keep it. A DateTime hashes by its clock reading whatever its Kind, /// exactly as it is stored (DateTimeConverter.NormalizeForStorage stamps Kind=Utc without converting). /// Before this canon the values went through ToString(): sub-second digits were lost, so a save under /// ChangeTracking skipped a temporal property changed within the same second (BR-11, 2026-09-16). /// private static string ScalarCanon(object value, char[] separators) { var inv = CultureInfo.InvariantCulture; switch (value) { case string text: return Escape(text, separators)!; case char symbol: return Escape(symbol.ToString(), separators)!; case decimal d: // Strip trailing zeros (6450.000 == 6450.000000000000000000) return d.ToString("G29", inv); case double d: return d.ToString("R", inv); case float f: return f.ToString("R", inv); case DateTimeOffset dto: return TemporalCanon(dto.UtcTicks); case DateTime dt: return TemporalCanon(dt.Ticks); case DateOnly day: return day.ToString("yyyy-MM-dd", inv); case TimeOnly time: return new TimeOnly(time.Ticks - time.Ticks % TimeSpan.TicksPerMillisecond).ToString("HH:mm:ss.fff", inv); case TimeSpan span: return span.ToString("c", inv); case IFormattable formattable: return formattable.ToString(null, inv); default: return value.ToString() ?? ""; } } /// /// The escape character of the canon: inside a string it precedes a separator or itself. A control character /// (U+0001), not a backslash: a hash stored before the escaping was computed over the plain string, so a /// value that held the escaped form as text ("a\,b") would hash, with a backslash, like the new value it was /// changed to ("a,b"), and the change would be skipped. Business text does not hold U+0001, so the canon of /// an escaped string matches no canon stored before, and a string with a backslash keeps its canon. /// private const char EscapeChar = '\u0001'; /// /// The canon of an empty string where "" already stands for something else: a null class property /// canonicalises to "", and a collection of one empty string would read "[]" like an empty one. An escaped /// string never holds the escape character before anything but a separator or itself, so the mark is unique. /// private const string EmptyTextMark = "\u0001e"; /// /// The canon of the string "null" where "null" stands for a null value: an element of a collection and a /// dictionary value. Unique for the same reason as . /// private const string NullTextMark = "\u0001n"; /// Separators a string meets in the header canon: '|' joins the parts. private static readonly char[] HeaderSeparators = { EscapeChar, '|' }; /// Separators a string meets as a class property value: '|' joins the properties. private static readonly char[] PropertySeparators = { EscapeChar, '|' }; /// /// Separators a string meets as an element of a collection or a dictionary value: ',' joins the elements and /// the entries, '|' the properties of the class that holds the collection. /// private static readonly char[] ElementSeparators = { EscapeChar, '|', ',' }; /// Separators a dictionary key meets: those of an element and '=' between the key and its value. private static readonly char[] KeySeparators = { EscapeChar, '|', ',', '=' }; /// /// A string as it enters the canon: each separator of its place and the escape character itself get the escape /// character in front. The canon joins values with separators and does not quote them, so before the escaping /// "x|y" and "" hashed like "x" and "y|", and a ChangeTracking save of one over the other was skipped as /// unchanged. A string with no separator of its place and no escape character is returned as it is: its canon, /// and the hashes stored for it, stay what they were. Each place escapes only the separators that can split it, /// so a comma in a class property keeps its canon. /// private static string? Escape(string? text, char[] separators) { if (text is null || text.IndexOfAny(separators) < 0) return text; var escaped = new StringBuilder(text.Length + 8); foreach (var symbol in text) { if (Array.IndexOf(separators, symbol) >= 0) escaped.Append(EscapeChar); escaped.Append(symbol); } return escaped.ToString(); } private static string TemporalCanon(long ticks) => new DateTime(ticks - ticks % TimeSpan.TicksPerMillisecond, DateTimeKind.Unspecified) .ToString("yyyy-MM-ddTHH:mm:ss.fff", CultureInfo.InvariantCulture); /// /// Checks if type is primitive or simple (does not require recursion). /// private static bool IsPrimitiveOrSimple(Type type) { return type.IsPrimitive || type.IsEnum || type == typeof(string) || type == typeof(decimal) || type == typeof(DateTime) || type == typeof(DateTimeOffset) || type == typeof(TimeSpan) || type == typeof(DateOnly) || type == typeof(TimeOnly) || type == typeof(Guid) || Nullable.GetUnderlyingType(type) != null; } /// /// Combines multiple hashes into single hash. /// Used for computing array hash from its element hashes. /// public static Guid CombineHashes(System.Collections.Generic.List hashes) { if (hashes == null || !hashes.Any()) return Guid.Empty; // Combine all hashes into string and compute MD5 var payload = string.Join("|", hashes.Select(h => h.ToString("N"))); var bytes = Encoding.UTF8.GetBytes(payload); var hash = RedbMd5.ComputeHash(bytes); return new Guid(hash); } } } Path: redb/redb.Core/Utils/RedbKeySerializer.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/Utils/RedbKeySerializer.cs ---- using System; using System.Globalization; using System.Text; using System.Reflection; using System.Text.Json; using System.Text.Json.Serialization; namespace redb.Core.Utils; /// /// Serializes and deserializes Dictionary keys to/from _array_index (text) storage. /// Simple keys (string, int, Guid, etc.) are serialized directly. /// Complex keys (Tuple, custom classes) are serialized to Base64-encoded JSON. /// public static class RedbKeySerializer { /// /// Serialize key to _array_index text value /// /// Type of key /// Key to serialize /// String representation for _array_index column public static string Serialize(TKey key) { if (key == null) throw new ArgumentNullException(nameof(key), "Dictionary key cannot be null"); return SerializeObject(key, typeof(TKey)); } /// /// Serialize key to _array_index text value (non-generic version) /// /// Key to serialize /// Type of key /// String representation for _array_index column public static string SerializeObject(object key, Type keyType) { if (key == null) throw new ArgumentNullException(nameof(key), "Dictionary key cannot be null"); // String types - direct if (keyType == typeof(string)) return (string)key; if (keyType == typeof(char)) return ((char)key).ToString(); // Integer types - to string if (keyType == typeof(long)) return ((long)key).ToString(CultureInfo.InvariantCulture); if (keyType == typeof(int)) return ((int)key).ToString(CultureInfo.InvariantCulture); if (keyType == typeof(short)) return ((short)key).ToString(CultureInfo.InvariantCulture); if (keyType == typeof(byte)) return ((byte)key).ToString(CultureInfo.InvariantCulture); // Floating point - invariant culture if (keyType == typeof(double)) return ((double)key).ToString("G17", CultureInfo.InvariantCulture); if (keyType == typeof(float)) return ((float)key).ToString("G9", CultureInfo.InvariantCulture); if (keyType == typeof(decimal)) return ((decimal)key).ToString(CultureInfo.InvariantCulture); // Boolean if (keyType == typeof(bool)) return ((bool)key) ? "true" : "false"; // DateTime types - ISO 8601 if (keyType == typeof(DateTime)) return ((DateTime)key).ToString("O", CultureInfo.InvariantCulture); if (keyType == typeof(DateTimeOffset)) return ((DateTimeOffset)key).ToString("O", CultureInfo.InvariantCulture); if (keyType == typeof(DateOnly)) return ((DateOnly)key).ToString("O", CultureInfo.InvariantCulture); if (keyType == typeof(TimeOnly)) return ((TimeOnly)key).ToString("O", CultureInfo.InvariantCulture); if (keyType == typeof(TimeSpan)) return ((TimeSpan)key).ToString("c", CultureInfo.InvariantCulture); // Guid if (keyType == typeof(Guid)) return ((Guid)key).ToString(); // Byte array - Base64 if (keyType == typeof(byte[])) return Convert.ToBase64String((byte[])key); // Enum - as string name if (keyType.IsEnum) return key.ToString()!; // Complex keys (Tuple, custom classes) - Base64-encoded JSON // Base64 avoids escaping issues when key is used in JSON facet filters var json = JsonSerializer.Serialize(key, keyType, KeyJsonOptions); return Convert.ToBase64String(Encoding.UTF8.GetBytes(json)); } /// /// The options for the JSON of a complex key: the defaults plus . /// System.Text.Json writes no fields, and a ValueTuple has nothing but fields: without the converter a ValueTuple /// anywhere in a key (the key itself, a field of it, the Rest of a tuple of eight or more fields, an item of a /// Tuple<>, a property of a key class) was written as {}, and keys differing only there gave one /// text. A key with no ValueTuple in it gives the text it always gave. /// private static readonly JsonSerializerOptions KeyJsonOptions = new() { Converters = { new ValueTupleFieldsConverterFactory() } }; /// A ValueTuple of any arity, the one-field ValueTuple<T1> that ends a Rest chain included. private static bool IsValueTuple(Type type) => type.IsValueType && type.IsGenericType && type.FullName?.StartsWith("System.ValueTuple`", StringComparison.Ordinal) == true; /// /// Writes a ValueTuple as the object of its fields by name, each value by its runtime type, the way a /// Dictionary<string, object?> of the fields was written before, so a tuple of up to seven fields with no /// nested tuple keeps its text. Reads each field by its declared type; a field missing from the text, or a stored /// {}, reads as the field's default, as it did before. /// private sealed class ValueTupleFieldsConverterFactory : JsonConverterFactory { public override bool CanConvert(Type typeToConvert) => IsValueTuple(typeToConvert); public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options) => (JsonConverter)Activator.CreateInstance(typeof(ValueTupleFieldsConverter<>).MakeGenericType(typeToConvert))!; } private sealed class ValueTupleFieldsConverter : JsonConverter { private static readonly FieldInfo[] Fields = typeof(T).GetFields(); public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options) { writer.WriteStartObject(); foreach (var field in Fields) { writer.WritePropertyName(field.Name); var fieldValue = field.GetValue(value); if (fieldValue == null) writer.WriteNullValue(); else JsonSerializer.Serialize(writer, fieldValue, fieldValue.GetType(), options); } writer.WriteEndObject(); } public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { using var document = JsonDocument.ParseValue(ref reader); var root = document.RootElement; if (root.ValueKind != JsonValueKind.Object) throw new JsonException($"A {typeof(T)} key part must be a JSON object, got {root.ValueKind}."); var args = new object?[Fields.Length]; for (int i = 0; i < Fields.Length; i++) { if (root.TryGetProperty(Fields[i].Name, out var element)) args[i] = element.Deserialize(Fields[i].FieldType, options); } return (T)Activator.CreateInstance(typeof(T), args)!; } } /// /// Deserialize _array_index text value to key /// /// Type of key /// String from _array_index column /// Deserialized key public static TKey Deserialize(string arrayIndex) { if (arrayIndex == null) throw new ArgumentNullException(nameof(arrayIndex), "_array_index cannot be null for Dictionary element"); return (TKey)DeserializeObject(arrayIndex, typeof(TKey))!; } /// /// Deserialize _array_index text value to key (non-generic version) /// /// String from _array_index column /// Type of key /// Deserialized key public static object? DeserializeObject(string arrayIndex, Type keyType) { if (arrayIndex == null) throw new ArgumentNullException(nameof(arrayIndex), "_array_index cannot be null for Dictionary element"); // String types if (keyType == typeof(string)) return arrayIndex; if (keyType == typeof(char)) return arrayIndex.Length > 0 ? arrayIndex[0] : '\0'; // Integer types if (keyType == typeof(long)) return long.Parse(arrayIndex, CultureInfo.InvariantCulture); if (keyType == typeof(int)) return int.Parse(arrayIndex, CultureInfo.InvariantCulture); if (keyType == typeof(short)) return short.Parse(arrayIndex, CultureInfo.InvariantCulture); if (keyType == typeof(byte)) return byte.Parse(arrayIndex, CultureInfo.InvariantCulture); // Floating point if (keyType == typeof(double)) return double.Parse(arrayIndex, CultureInfo.InvariantCulture); if (keyType == typeof(float)) return float.Parse(arrayIndex, CultureInfo.InvariantCulture); if (keyType == typeof(decimal)) return decimal.Parse(arrayIndex, CultureInfo.InvariantCulture); // Boolean if (keyType == typeof(bool)) return arrayIndex.Equals("true", StringComparison.OrdinalIgnoreCase); // DateTime types if (keyType == typeof(DateTime)) return DateTime.Parse(arrayIndex, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind); if (keyType == typeof(DateTimeOffset)) return DateTimeOffset.Parse(arrayIndex, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind); if (keyType == typeof(DateOnly)) return DateOnly.Parse(arrayIndex, CultureInfo.InvariantCulture); if (keyType == typeof(TimeOnly)) return TimeOnly.Parse(arrayIndex, CultureInfo.InvariantCulture); if (keyType == typeof(TimeSpan)) return TimeSpan.Parse(arrayIndex, CultureInfo.InvariantCulture); // Guid if (keyType == typeof(Guid)) return Guid.Parse(arrayIndex); // Byte array - Base64 if (keyType == typeof(byte[])) return Convert.FromBase64String(arrayIndex); // Enum if (keyType.IsEnum) return Enum.Parse(keyType, arrayIndex); // Complex keys (Tuple, custom classes) - Base64-encoded JSON var json = Encoding.UTF8.GetString(Convert.FromBase64String(arrayIndex)); return JsonSerializer.Deserialize(json, keyType, KeyJsonOptions); } /// /// Check if key type is a complex type requiring JSON serialization /// /// Type to check /// True if type requires JSON serialization public static bool IsComplexKey(Type keyType) { // Simple types that don't need JSON if (keyType == typeof(string) || keyType == typeof(char)) return false; if (keyType == typeof(long) || keyType == typeof(int) || keyType == typeof(short) || keyType == typeof(byte)) return false; if (keyType == typeof(double) || keyType == typeof(float) || keyType == typeof(decimal)) return false; if (keyType == typeof(bool)) return false; if (keyType == typeof(DateTime) || keyType == typeof(DateTimeOffset) || keyType == typeof(DateOnly) || keyType == typeof(TimeOnly) || keyType == typeof(TimeSpan)) return false; if (keyType == typeof(Guid)) return false; if (keyType == typeof(byte[])) return false; if (keyType.IsEnum) return false; // Everything else is complex (Tuple, ValueTuple, custom classes, etc.) return true; } /// /// Get RedbTypeIds constant for key type /// /// C# key type /// Type ID for _structures._key_type column public static long GetKeyTypeId(Type keyType) { if (keyType == typeof(string)) return RedbTypeIds.String; if (keyType == typeof(char)) return RedbTypeIds.Char; if (keyType == typeof(long)) return RedbTypeIds.Long; if (keyType == typeof(int)) return RedbTypeIds.Int; if (keyType == typeof(short)) return RedbTypeIds.Short; if (keyType == typeof(byte)) return RedbTypeIds.Byte; if (keyType == typeof(double)) return RedbTypeIds.Double; if (keyType == typeof(float)) return RedbTypeIds.Float; if (keyType == typeof(decimal)) return RedbTypeIds.Decimal; if (keyType == typeof(bool)) return RedbTypeIds.Boolean; if (keyType == typeof(DateTime)) return RedbTypeIds.DateTime; if (keyType == typeof(DateTimeOffset)) return RedbTypeIds.DateTimeOffset; if (keyType == typeof(DateOnly)) return RedbTypeIds.DateOnly; if (keyType == typeof(TimeOnly)) return RedbTypeIds.TimeOnly; if (keyType == typeof(TimeSpan)) return RedbTypeIds.TimeSpan; if (keyType == typeof(Guid)) return RedbTypeIds.Guid; if (keyType == typeof(byte[])) return RedbTypeIds.ByteArray; if (keyType.IsEnum) return RedbTypeIds.Enum; // Complex keys (Tuple, custom classes) stored as Base64-encoded JSON // Using Class type to distinguish from simple String keys return RedbTypeIds.Class; } /// /// Check if C# type is valid as Dictionary key /// /// Type to check /// True if type can be used as Dictionary key public static bool CanBeKey(Type keyType) { // All serializable types can be keys // Only excluded: types that can't be serialized deterministically if (keyType == typeof(object)) return false; // Dynamic types are not supported if (keyType.FullName == "System.Object") return false; return true; } } Path: redb/redb.Core/Utils/RedbMd5.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/Utils/RedbMd5.cs ---- using System; using System.Security.Cryptography; namespace redb.Core.Utils { /// /// MD5 entry point for REDB hashing. /// /// /// REDB stores hashes as (exactly 16 bytes) in the database, so the algorithm /// itself cannot change without invalidating every existing database. It stays MD5 — this type only /// decides WHICH implementation computes it. /// /// /// /// On server platforms nothing changes: the call goes straight to , exactly /// as before. The managed fallback exists for browser-wasm (Blazor WebAssembly), where the /// runtime ships no MD5 provider and throws /// CryptographicException: Cryptography_UnknownHashAlgorithm, MD5 — which used to break /// SyncScheme and Save outright. /// /// /// /// The fallback is bit-for-bit identical to the system implementation (RFC 1321); this is asserted by /// unit tests comparing both over RFC test vectors, block boundaries and random buffers. Hashes /// written by a browser and by a server are therefore interchangeable. /// /// public static class RedbMd5 { /// /// Compute the MD5 digest of (16 bytes). /// Uses the platform implementation where it exists, the managed one where it does not. /// public static byte[] ComputeHash(byte[] data) { if (UseManagedImplementation) return ComputeHashManaged(data); using var md5 = MD5.Create(); return md5.ComputeHash(data); } /// /// True when the platform has no usable MD5 provider and the managed implementation must be used. /// Today that is browser-wasm only; every other target keeps the previous code path. /// public static bool UseManagedImplementation { get; } = OperatingSystem.IsBrowser(); // ===== Managed RFC 1321 implementation ===== // Public (not private) on purpose: tests must be able to compare it against the system // implementation on a normal desktop run, where UseManagedImplementation is false and the // fallback would otherwise never execute. /// /// Managed MD5 per RFC 1321. Produces the same 16 bytes as the platform implementation. /// Intended for platforms without an MD5 provider, and for tests asserting that equivalence. /// public static byte[] ComputeHashManaged(byte[] data) { if (data is null) throw new ArgumentNullException(nameof(data)); uint a0 = 0x67452301, b0 = 0xefcdab89, c0 = 0x98badcfe, d0 = 0x10325476; // Padded length: message + 0x80 + zero padding + 8-byte little-endian bit count, // rounded up to a whole number of 64-byte blocks. int paddedLength = ((data.Length + 8) / 64 + 1) * 64; var buffer = new byte[paddedLength]; Buffer.BlockCopy(data, 0, buffer, 0, data.Length); buffer[data.Length] = 0x80; ulong bitLength = (ulong)data.Length * 8; for (int i = 0; i < 8; i++) buffer[paddedLength - 8 + i] = (byte)(bitLength >> (8 * i)); var m = new uint[16]; for (int offset = 0; offset < paddedLength; offset += 64) { for (int j = 0; j < 16; j++) { int k = offset + j * 4; m[j] = (uint)(buffer[k] | (buffer[k + 1] << 8) | (buffer[k + 2] << 16) | (buffer[k + 3] << 24)); } uint a = a0, b = b0, c = c0, d = d0; for (int i = 0; i < 64; i++) { uint f; int g; if (i < 16) { f = (b & c) | (~b & d); g = i; } else if (i < 32) { f = (d & b) | (~d & c); g = (5 * i + 1) % 16; } else if (i < 48) { f = b ^ c ^ d; g = (3 * i + 5) % 16; } else { f = c ^ (b | ~d); g = (7 * i) % 16; } f = unchecked(f + a + K[i] + m[g]); a = d; d = c; c = b; b = unchecked(b + RotateLeft(f, S[i])); } a0 = unchecked(a0 + a); b0 = unchecked(b0 + b); c0 = unchecked(c0 + c); d0 = unchecked(d0 + d); } var digest = new byte[16]; WriteLittleEndian(digest, 0, a0); WriteLittleEndian(digest, 4, b0); WriteLittleEndian(digest, 8, c0); WriteLittleEndian(digest, 12, d0); return digest; } private static uint RotateLeft(uint value, int count) => (value << count) | (value >> (32 - count)); private static void WriteLittleEndian(byte[] target, int offset, uint value) { target[offset] = (byte)value; target[offset + 1] = (byte)(value >> 8); target[offset + 2] = (byte)(value >> 16); target[offset + 3] = (byte)(value >> 24); } /// Per-round left-rotation amounts (RFC 1321, section 3.4). private static readonly int[] S = { 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21 }; /// Sine-derived constants: K[i] = floor(2^32 * abs(sin(i + 1))). private static readonly uint[] K = { 0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501, 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821, 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8, 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a, 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05, 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665, 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1, 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391 }; } } Path: redb/redb.Core/Utils/RedbObjectTypes.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/Utils/RedbObjectTypes.cs ---- using System; using redb.Core.Models.Entities; namespace redb.Core.Utils { /// /// Type tests for the RedbObject family. A is a /// with tree navigation on top; a test for the exact generic type saw it as an object without Props, so a tree node /// was hashed by its header alone and never matched the hash its loaded twin recomputes - the props cache never /// served a node saved through CreateChildAsync (props cache review, 2026-09-16). /// public static class RedbObjectTypes { /// /// The closed RedbObject<TProps> type of - the type itself or one of its base /// types - or null for anything else (the non-generic , plain classes, null). /// public static Type? GenericOf(Type? type) { for (var t = type; t != null; t = t.BaseType) if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(RedbObject<>)) return t; return null; } } } Path: redb/redb.Core/Utils/RedbTemporalFormat.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/Utils/RedbTemporalFormat.cs ---- using System; using System.Globalization; namespace redb.Core.Utils { /// /// Invariant, round-trip text form for the zone-less temporal types /// (, , ). /// /// /// Both the JSON converters and the _values._String write path go through here, so the /// two can never disagree and neither depends on the ambient . /// /// /// /// Why this exists. Three distinct culture leaks, only the first of which is obvious: /// /// A bare DateOnly.ToString() / TimeOnly.ToString() uses the CURRENT /// culture's short date/time pattern: "23.08.2026" under ru-RU, "8/23/2026" under /// en-US, "2:30 PM" for a time. This is what the _values._String write path used /// to do, so a value written under one culture failed to parse, or silently mis-parsed with day /// and month swapped, under another. /// Parse / TryParse without an explicit reads /// back through the current culture, so the read side drifted with the write side. /// Even an explicit custom pattern is only partly safe: in a custom format string /// ':' resolves to the culture's TIME SEPARATOR ('-' and '.' are literals, /// only '/' is the date separator). Most cultures use ':', which is exactly why /// this one hid. /// /// The standard round-trip specifiers used here ("O" for the two date/time types, /// "c" for ) are culture-independent by definition. /// /// /// /// additionally used to be written as @"hh\:mm\:ss", which drops /// the day component and the sign: 3.02:00:00 came back as 02:00:00. "c" /// is the constant format [-][d'.']hh':'mm':'ss['.'fffffff] and keeps both. /// /// /// /// Parsing accepts the invariant form first and falls back to the current culture last, so rows /// written by an earlier build under a non-invariant culture keep loading on a host that still /// runs under that culture. /// /// public static class RedbTemporalFormat { /// Round-trip format: yyyy-MM-dd. public const string DateOnlyFormat = "O"; /// Round-trip format: HH:mm:ss.fffffff. public const string TimeOnlyFormat = "O"; /// Constant format: [-][d.]hh:mm:ss[.fffffff]. public const string TimeSpanFormat = "c"; public static string ToText(DateOnly value) => value.ToString(DateOnlyFormat, CultureInfo.InvariantCulture); public static string ToText(TimeOnly value) => value.ToString(TimeOnlyFormat, CultureInfo.InvariantCulture); public static string ToText(TimeSpan value) => value.ToString(TimeSpanFormat, CultureInfo.InvariantCulture); public static bool TryParseDateOnly(string? text, out DateOnly value) { value = default; if (string.IsNullOrWhiteSpace(text)) return false; // PostgreSQL sentinels. Npgsql maps DateTime.MinValue/MaxValue to -infinity/infinity, // so an unset DateOnly (0001-01-01, its default) comes back as the text "-infinity". // The DateTime converters have handled this for a long time; DateOnly did not, and // simply leaving a DateOnly property unassigned threw on load. if (text == "-infinity") { value = DateOnly.MinValue; return true; } if (text == "infinity") { value = DateOnly.MaxValue; return true; } if (DateOnly.TryParseExact(text, DateOnlyFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out value)) return true; if (DateOnly.TryParse(text, CultureInfo.InvariantCulture, DateTimeStyles.None, out value)) return true; // A full ISO timestamp also resolves to a date (the JSON side may carry one). if (DateTime.TryParse(text, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out var asDateTime)) { value = DateOnly.FromDateTime(asDateTime); return true; } // Legacy: written by an earlier build through the current culture. return DateOnly.TryParse(text, CultureInfo.CurrentCulture, DateTimeStyles.None, out value); } public static bool TryParseTimeOnly(string? text, out TimeOnly value) { value = default; if (string.IsNullOrWhiteSpace(text)) return false; if (TimeOnly.TryParseExact(text, TimeOnlyFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out value)) return true; if (TimeOnly.TryParse(text, CultureInfo.InvariantCulture, DateTimeStyles.None, out value)) return true; // Older rows carry a TimeSpan-shaped string ("14:30:00"). if (TryParseTimeSpan(text, out var asSpan) && asSpan >= TimeSpan.Zero && asSpan < TimeSpan.FromDays(1)) { value = TimeOnly.FromTimeSpan(asSpan); return true; } return TimeOnly.TryParse(text, CultureInfo.CurrentCulture, DateTimeStyles.None, out value); } public static bool TryParseTimeSpan(string? text, out TimeSpan value) { value = default; if (string.IsNullOrWhiteSpace(text)) return false; if (TimeSpan.TryParseExact(text, TimeSpanFormat, CultureInfo.InvariantCulture, out value)) return true; if (TimeSpan.TryParse(text, CultureInfo.InvariantCulture, out value)) return true; return TimeSpan.TryParse(text, CultureInfo.CurrentCulture, out value); } } } Path: redb/redb.Core/Utils/RedbTypeIds.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/Utils/RedbTypeIds.cs ---- namespace redb.Core.Utils; /// /// System type IDs for REDB. Matches _types table in database. /// Negative IDs are reserved for system types. /// public static class RedbTypeIds { // ═══════════════════════════════════════════════════════════════ // PRIMITIVE TYPES (basic C# types) // ═══════════════════════════════════════════════════════════════ /// String type - maps to _String column in _values public const long String = -9223372036854775700; /// Long type - maps to _Long column in _values public const long Long = -9223372036854775704; /// Guid type - maps to _Guid column in _values public const long Guid = -9223372036854775705; /// Double type - maps to _Double column in _values public const long Double = -9223372036854775707; /// Boolean type - maps to _Boolean column in _values public const long Boolean = -9223372036854775709; /// ByteArray type - maps to _ByteArray column in _values public const long ByteArray = -9223372036854775701; // ═══════════════════════════════════════════════════════════════ // EXTENDED TYPES // ═══════════════════════════════════════════════════════════════ /// DateTime type - maps to _DateTimeOffset (timestamptz) in database public const long DateTime = -9223372036854775708; /// DateTimeOffset type - maps to _DateTimeOffset (timestamptz) in database public const long DateTimeOffset = -9223372036854775673; /// Numeric type for precise decimal numbers - maps to _Numeric column public const long Numeric = -9223372036854775674; /// ListItem type - reference to _list_items table public const long ListItem = -9223372036854775706; /// Object type - reference to another _objects record (redbObject) public const long Object = -9223372036854775703; // ═══════════════════════════════════════════════════════════════ // ADDITIONAL PRIMITIVE TYPES (mapped to base types) // ═══════════════════════════════════════════════════════════════ /// Int type - maps to _Long column public const long Int = -9223372036854775699; /// Short type - maps to _Long column public const long Short = -9223372036854775698; /// Byte type - maps to _Long column public const long Byte = -9223372036854775697; /// Float type - maps to _Double column public const long Float = -9223372036854775696; /// Decimal type - maps to _Numeric column public const long Decimal = -9223372036854775695; /// Char type - maps to _String column public const long Char = -9223372036854775694; // ═══════════════════════════════════════════════════════════════ // NESTED CLASS TYPE // ═══════════════════════════════════════════════════════════════ /// /// Class type for nested objects (Address, Contact, etc.) /// Child fields stored in _values with _id_parent reference /// public const long Class = -9223372036854775675; // ═══════════════════════════════════════════════════════════════ // COLLECTION TYPES (NEW! For RedbObject and Dictionary) // ═══════════════════════════════════════════════════════════════ /// /// Array type for RedbObject<T[]> / RedbObject<List<T>>. /// Also used for _structures._collection_type to mark array fields. /// public const long Array = -9223372036854775668; /// /// Dictionary type for RedbObject<Dictionary<K,V>>. /// Also used for _structures._collection_type to mark dictionary fields. /// public const long Dictionary = -9223372036854775667; // ═══════════════════════════════════════════════════════════════ // DOCUMENT TYPES (hierarchy stored via _array_parent_id) // ═══════════════════════════════════════════════════════════════ /// /// JsonDocument type for RedbObject<JsonDocument>. /// Hierarchy stored via _values._array_parent_id. /// public const long JsonDocument = -9223372036854775666; /// /// XDocument type for RedbObject<XDocument>. /// Hierarchy stored via _values._array_parent_id. /// public const long XDocument = -9223372036854775665; // ═══════════════════════════════════════════════════════════════ // SPECIALIZED STRING TYPES // ═══════════════════════════════════════════════════════════════ /// Url type - validated string public const long Url = -9223372036854775693; /// Email type - validated string public const long Email = -9223372036854775692; /// Phone type - validated string public const long Phone = -9223372036854775691; /// Json type - JSON as string public const long Json = -9223372036854775690; /// Xml type - XML as string public const long Xml = -9223372036854775689; /// Base64 type - Base64 encoded string public const long Base64 = -9223372036854775688; /// Color type - color representation string public const long Color = -9223372036854775687; // ═══════════════════════════════════════════════════════════════ // TIME TYPES // ═══════════════════════════════════════════════════════════════ /// DateOnly type (.NET 6+) public const long DateOnly = -9223372036854775686; /// TimeOnly type (.NET 6+) - stored as Ticks in _Long public const long TimeOnly = -9223372036854775685; /// TimeSpan type - stored as Ticks in _Long public const long TimeSpan = -9223372036854775684; // ═══════════════════════════════════════════════════════════════ // ENUM TYPES // ═══════════════════════════════════════════════════════════════ /// Enum type - stored as string public const long Enum = -9223372036854775683; /// EnumInt type - stored as number public const long EnumInt = -9223372036854775682; // ═══════════════════════════════════════════════════════════════ // GEO TYPES // ═══════════════════════════════════════════════════════════════ /// Latitude type public const long Latitude = -9223372036854775681; /// Longitude type public const long Longitude = -9223372036854775680; /// GeoPoint type - JSON string public const long GeoPoint = -9223372036854775679; // ═══════════════════════════════════════════════════════════════ // FILE TYPES // ═══════════════════════════════════════════════════════════════ /// FilePath type public const long FilePath = -9223372036854775678; /// FileName type public const long FileName = -9223372036854775677; /// MimeType type public const long MimeType = -9223372036854775676; // ═══════════════════════════════════════════════════════════════ // SOFT DELETE SYSTEM (reserved IDs) // ═══════════════════════════════════════════════════════════════ /// /// Reserved scheme ID for deleted objects (@@__deleted). /// Objects marked for soft-deletion get this scheme ID. /// public const long DeletedScheme = -10; /// /// Reserved scheme name for deleted objects. /// Uses @@ prefix to bypass validation rules. /// public const string DeletedSchemeName = "@@__deleted"; } Path: redb/redb.Core/Utils/RedbTypeMapping.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/Utils/RedbTypeMapping.cs ---- using System; namespace redb.Core.Utils; /// /// Helper methods for REDB type mapping between C# types and database columns /// public static class RedbTypeMapping { /// /// Get _values column name for type ID /// /// Type ID from RedbTypeIds or _types table /// Column name in _values table (e.g., "_String", "_Long") public static string GetValueColumn(long typeId) { return typeId switch { RedbTypeIds.String => "_String", RedbTypeIds.Long => "_Long", RedbTypeIds.Int => "_Long", RedbTypeIds.Short => "_Long", RedbTypeIds.Byte => "_Long", RedbTypeIds.Guid => "_Guid", RedbTypeIds.Double => "_Double", RedbTypeIds.Float => "_Double", RedbTypeIds.DateTimeOffset => "_DateTimeOffset", RedbTypeIds.DateTime => "_DateTimeOffset", // DateOnly is seeded with _db_type 'DateTime' and resolves to _DateTimeOffset on the // SQL side (pvt_db_type_to_value_column); C# used to throw "Unknown type ID" here. RedbTypeIds.DateOnly => "_DateTimeOffset", RedbTypeIds.TimeOnly => "_Long", // Ticks RedbTypeIds.TimeSpan => "_Long", // Ticks RedbTypeIds.Boolean => "_Boolean", RedbTypeIds.ByteArray => "_ByteArray", RedbTypeIds.Numeric => "_Numeric", RedbTypeIds.Decimal => "_Numeric", RedbTypeIds.ListItem => "_ListItem", RedbTypeIds.Object => "_Object", _ => throw new ArgumentException($"Unknown type ID: {typeId}", nameof(typeId)) }; } /// /// Check if type can be used as Dictionary key /// /// Type ID to check /// True if type can be Dictionary key public static bool CanBeKey(long typeId) { return typeId switch { RedbTypeIds.String => true, RedbTypeIds.Long => true, RedbTypeIds.Int => true, RedbTypeIds.Short => true, RedbTypeIds.Byte => true, RedbTypeIds.Guid => true, _ => false }; } /// /// Check if type is a collection type (Array/Dictionary/JsonDocument/XDocument) /// These types are used for _schemes._type to indicate Props structure /// /// Type ID to check /// True if type is collection public static bool IsCollectionType(long typeId) { return typeId is RedbTypeIds.Array or RedbTypeIds.Dictionary or RedbTypeIds.JsonDocument or RedbTypeIds.XDocument; } /// /// Check if type requires _values records (vs direct storage in _objects._value_*) /// /// Type ID to check /// True if type needs _values records public static bool RequiresValuesRecords(long typeId) { // Only Class, Array, Dictionary, JsonDocument, XDocument require _values return typeId is RedbTypeIds.Class or RedbTypeIds.Array or RedbTypeIds.Dictionary or RedbTypeIds.JsonDocument or RedbTypeIds.XDocument; } /// /// Get _objects column name for RedbPrimitive value storage /// /// Type ID /// Column name in _objects table (e.g., "_value_long") public static string GetObjectValueColumn(long typeId) { return typeId switch { RedbTypeIds.String => "_value_string", RedbTypeIds.Long => "_value_long", RedbTypeIds.Int => "_value_long", RedbTypeIds.Short => "_value_long", RedbTypeIds.Byte => "_value_long", RedbTypeIds.Guid => "_value_guid", RedbTypeIds.Double => "_value_double", RedbTypeIds.Float => "_value_double", RedbTypeIds.DateTimeOffset => "_value_datetime", RedbTypeIds.DateTime => "_value_datetime", RedbTypeIds.DateOnly => "_value_datetime", RedbTypeIds.TimeOnly => "_value_long", RedbTypeIds.TimeSpan => "_value_long", RedbTypeIds.Boolean => "_value_bool", RedbTypeIds.ByteArray => "_value_bytes", RedbTypeIds.Numeric => "_value_numeric", RedbTypeIds.Decimal => "_value_numeric", _ => throw new ArgumentException($"Type {typeId} cannot be stored in _objects._value_* columns", nameof(typeId)) }; } } Path: redb/redb.Core/Utils/SchemeHashCalculator.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/Utils/SchemeHashCalculator.cs ---- using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; using System.Text; using redb.Core.Models.Entities; namespace redb.Core.Utils; /// /// Utility for computing MD5 hash of scheme structure. /// Used for change detection and cache invalidation. /// public static class SchemeHashCalculator { /// /// Computes MD5 hash of scheme from all its structures. /// Hash aggregates critical fields of all structures: Id, Name, IdType, IdParent, IsArray, AllowNotNull, StoreNull, Unique. /// /// List of scheme structures. /// MD5 hash as Guid. public static Guid ComputeSchemeStructureHash(List structures) { if (structures == null || !structures.Any()) return Guid.Empty; // Sort for stable hash (independent of load order) var sorted = structures .OrderBy(s => s.IdParent ?? 0) .ThenBy(s => s.Order ?? 0) .ThenBy(s => s.Id) .ToList(); var sb = new StringBuilder(); foreach (var s in sorted) { // Include only critical fields (that affect data) sb.Append($"{s.Id}|"); sb.Append($"{s.Name}|"); sb.Append($"{s.IdType}|"); sb.Append($"{s.IdParent}|"); sb.Append($"{s.CollectionType}|"); sb.Append($"{s.KeyType}|"); sb.Append($"{s.AllowNotNull}|"); sb.Append($"{s.StoreNull}|"); // V4 (Л2): virtual appearing/disappearing must change the hash (LAZY plan §6). sb.Append($"{s.Lazy}|"); // V4: a key appearing or disappearing must change the hash, or the metadata cache and the // structure tree keep answering from the old flag until restart. sb.Append($"{s.Unique};"); } // Compute MD5 and convert to Guid var hash = RedbMd5.ComputeHash(Encoding.UTF8.GetBytes(sb.ToString())); return new Guid(hash); } } Path: redb/redb.Core/Utils/TreeExtensions.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/Utils/TreeExtensions.cs ---- using System; using System.Collections.Generic; using System.Linq; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; namespace redb.Core.Utils { /// /// Extensions for working with tree structures. /// public static class TreeExtensions { /// /// Breadth-First Search tree traversal for polymorphic trees. /// /// Root node for traversal /// Node sequence in BFS order public static IEnumerable BreadthFirstTraversal(this ITreeRedbObject root) { var queue = new Queue(); queue.Enqueue(root); while (queue.Count > 0) { var current = queue.Dequeue(); yield return current; foreach (var child in current.Children) queue.Enqueue(child); } } /// /// Breadth-First Search tree traversal for typed trees. /// /// Object properties type /// Root node for traversal /// Node sequence in BFS order public static IEnumerable> BreadthFirstTraversal(this ITreeRedbObject root) where TProps : class, new() { var queue = new Queue>(); queue.Enqueue(root); while (queue.Count > 0) { var current = queue.Dequeue(); yield return current; // Children is untyped, cast to typed version foreach (var child in current.Children.OfType>()) queue.Enqueue(child); } } /// /// Depth-First Search tree traversal - pre-order for polymorphic trees. /// /// Root node for traversal /// Node sequence in DFS pre-order public static IEnumerable DepthFirstTraversal(this ITreeRedbObject root) { yield return root; foreach (var child in root.Children) { foreach (var descendant in child.DepthFirstTraversal()) yield return descendant; } } /// /// Depth-First Search tree traversal - pre-order for typed trees. /// /// Object properties type /// Root node for traversal /// Node sequence in DFS pre-order public static IEnumerable> DepthFirstTraversal(this ITreeRedbObject root) where TProps : class, new() { yield return root; // Children is untyped, cast to typed version foreach (var child in root.Children.OfType>()) { foreach (var descendant in child.DepthFirstTraversal()) yield return descendant; } } /// /// Depth-First Search tree traversal - post-order for polymorphic trees. /// /// Root node for traversal /// Node sequence in DFS post-order public static IEnumerable PostOrderTraversal(this ITreeRedbObject root) { foreach (var child in root.Children) { foreach (var descendant in child.PostOrderTraversal()) yield return descendant; } yield return root; } /// /// Depth-First Search tree traversal - post-order for typed trees. /// /// Object properties type /// Root node for traversal /// Node sequence in DFS post-order public static IEnumerable> PostOrderTraversal(this ITreeRedbObject root) where TProps : class, new() { // Children is untyped, cast to typed version foreach (var child in root.Children.OfType>()) { foreach (var descendant in child.PostOrderTraversal()) yield return descendant; } yield return root; } /// /// Find node by ID in polymorphic tree. /// /// Root node for search /// ID of target node /// Found node or null public static ITreeRedbObject? FindById(this ITreeRedbObject root, long id) { return root.DepthFirstTraversal().FirstOrDefault(node => node.Id == id); } /// /// Find node by ID in typed tree. /// /// Object properties type /// Root node for search /// ID of target node /// Found node or null public static ITreeRedbObject? FindById(this ITreeRedbObject root, long id) where TProps : class, new() { return root.DepthFirstTraversal().FirstOrDefault(node => node.Id == id); } /// /// Find nodes by predicate in polymorphic tree. /// /// Root node for search /// Search predicate /// Collection of found nodes public static IEnumerable FindNodes(this ITreeRedbObject root, Func predicate) { return root.DepthFirstTraversal().Where(predicate); } /// /// Find nodes by predicate in typed tree. /// /// Object properties type /// Root node for search /// Search predicate /// Collection of found nodes public static IEnumerable> FindNodes(this ITreeRedbObject root, Func, bool> predicate) where TProps : class, new() { return root.DepthFirstTraversal().Where(predicate); } /// /// Gets all leaf nodes of polymorphic tree. /// /// Root node /// Collection of leaf nodes public static IEnumerable GetLeaves(this ITreeRedbObject root) { return root.DepthFirstTraversal().Where(node => node.IsLeaf); } /// /// Gets all leaf nodes of typed tree. /// /// Object properties type /// Root node /// Collection of leaf nodes public static IEnumerable> GetLeaves(this ITreeRedbObject root) where TProps : class, new() { return root.DepthFirstTraversal().Where(node => node.IsLeaf); } /// /// Gets all nodes at specific level in polymorphic tree. /// /// Root node /// Level (0 for root) /// Collection of nodes at specified level public static IEnumerable GetNodesAtLevel(this ITreeRedbObject root, int level) { return root.DepthFirstTraversal().Where(node => node.Level == level); } /// /// Gets all nodes at specific level in typed tree. /// /// Object properties type /// Root node /// Level (0 for root) /// Collection of nodes at specified level public static IEnumerable> GetNodesAtLevel(this ITreeRedbObject root, int level) where TProps : class, new() { return root.DepthFirstTraversal().Where(node => node.Level == level); } /// /// Builds materialized path for polymorphic node. /// /// Node /// Path separator /// Materialized path like "/1/5/23" public static string GetMaterializedPath(this ITreeRedbObject node, string separator = "/") { var pathIds = node.GetPathIds(); return separator + string.Join(separator, pathIds); } /// /// Builds materialized path for typed node. /// /// Object properties type /// Node /// Path separator /// Materialized path like "/1/5/23" public static string GetMaterializedPath(this ITreeRedbObject node, string separator = "/") where TProps : class, new() { var pathIds = node.GetPathIds(); return separator + string.Join(separator, pathIds); } /// /// Flattens polymorphic tree to list with level indicators. /// /// Root node /// List of (node, level) pairs public static IEnumerable<(ITreeRedbObject Node, int Level)> FlattenWithLevels(this ITreeRedbObject root) { return root.DepthFirstTraversal().Select(node => (node, node.Level)); } /// /// Flattens typed tree to list with level indicators. /// /// Object properties type /// Root node /// List of (node, level) pairs public static IEnumerable<(ITreeRedbObject Node, int Level)> FlattenWithLevels(this ITreeRedbObject root) where TProps : class, new() { return root.DepthFirstTraversal().Select(node => (node, node.Level)); } /// /// Checks if polymorphic tree is balanced (subtree depth difference does not exceed 1). /// /// Root node /// true if tree is balanced public static bool IsBalanced(this ITreeRedbObject root) { return CheckBalance(root) != -1; } /// /// Checks if typed tree is balanced (subtree depth difference does not exceed 1). /// /// Object properties type /// Root node /// true if tree is balanced public static bool IsBalanced(this ITreeRedbObject root) where TProps : class, new() { return CheckBalance(root) != -1; } private static int CheckBalance(ITreeRedbObject node) { if (!node.Children.Any()) return 0; var childHeights = new List(); foreach (var child in node.Children) { var height = CheckBalance(child); if (height == -1) return -1; // Not balanced childHeights.Add(height); } var maxHeight = childHeights.Max(); var minHeight = childHeights.Min(); return Math.Abs(maxHeight - minHeight) <= 1 ? maxHeight + 1 : -1; } private static int CheckBalance(ITreeRedbObject node) where TProps : class, new() { if (!node.Children.Any()) return 0; var childHeights = new List(); foreach (var child in node.Children) { var height = CheckBalance(child); if (height == -1) return -1; // Not balanced childHeights.Add(height); } var maxHeight = childHeights.Max(); var minHeight = childHeights.Min(); return Math.Abs(maxHeight - minHeight) <= 1 ? maxHeight + 1 : -1; } } } Path: redb/redb.Core/Utils/TreeObjectConverter.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/Utils/TreeObjectConverter.cs ---- using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; namespace redb.Core.Utils; /// /// Utility class for converting between RedbObject and TreeRedbObject types. /// Provides static methods for type conversion and parent chain building. /// public static class TreeObjectConverter { /// /// Convert RedbObject to TreeRedbObject preserving all properties. /// /// Object properties type /// Source RedbObject /// New TreeRedbObject with same data public static TreeRedbObject ToTreeObject(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, name = source.name, note = source.note, hash = source.hash, Props = source.Props }; } /// /// Convert IRedbObject to TreeRedbObject (creates new instance with Props = new TProps if types don't match). /// /// Target properties type /// Source object /// New TreeRedbObject public static TreeRedbObject ToTreeObject(IRedbObject source) where TProps : class, new() { // If source is already RedbObject, use direct conversion if (source is RedbObject typedSource) { return ToTreeObject(typedSource); } // Otherwise copy base properties var result = new TreeRedbObject { id = source.Id, parent_id = source.ParentId, scheme_id = source.SchemeId, owner_id = source.OwnerId, who_change_id = source.WhoChangeId, date_create = source.DateCreate, date_modify = source.DateModify, date_begin = source.DateBegin, date_complete = source.DateComplete, key = source.Key, value_long = source.ValueLong, value_string = source.ValueString, value_guid = source.ValueGuid, value_bool = source.ValueBool, value_double = source.ValueDouble, value_numeric = source.ValueNumeric, value_datetime = source.ValueDatetime, value_bytes = source.ValueBytes, value_unique = source.ValueUnique, name = source.Name, note = source.Note, hash = source.Hash, // Try to get Props if types match Props = (source as IRedbObject)?.Props ?? new TProps() }; return result; } /// /// Convert IRedbObject to ITreeRedbObject dynamically preserving actual Props type. /// Uses reflection to create correct TreeRedbObject generic type. /// /// Source object /// ITreeRedbObject with correct generic type public static ITreeRedbObject ToTreeObjectDynamic(IRedbObject source) { var sourceType = source.GetType(); // If source is generic RedbObject if (sourceType.IsGenericType && sourceType.GetGenericTypeDefinition() == typeof(RedbObject<>)) { var propsType = sourceType.GetGenericArguments()[0]; var treeType = typeof(TreeRedbObject<>).MakeGenericType(propsType); var treeObj = Activator.CreateInstance(treeType) as ITreeRedbObject; // Copy base properties. TreeRedbObject derives from RedbObject, not from TreeRedbObject: // tested against TreeRedbObject, nothing was copied and every object came back with id 0, so // LoadWithParentsAsync failed on the second object with "same key" while linking parents. if (treeObj is RedbObject treeBase && source is RedbObject redbBase) { CopyBaseProperties(redbBase, treeBase); } // Copy Props via reflection var propsProperty = sourceType.GetProperty("Props"); var targetPropsProperty = treeType.GetProperty("Props"); if (propsProperty != null && targetPropsProperty != null) { targetPropsProperty.SetValue(treeObj, propsProperty.GetValue(source)); } return treeObj!; } // Fallback for non-generic RedbObject return new TreeRedbObjectWrapper(source); } /// /// Build Parent relationships for a collection of tree objects. /// Links each object's Parent property to its parent in the collection. /// Also populates Children collections. /// /// Object properties type /// Collection of tree objects public static void BuildParentRelationships(IEnumerable> objects) where TProps : class, new() { var dict = objects.ToDictionary(o => o.id, o => o); foreach (var obj in objects) { obj.Parent = null; obj.Children.Clear(); if (obj.parent_id.HasValue && dict.TryGetValue(obj.parent_id.Value, out var parent)) { obj.Parent = parent; parent.Children.Add(obj); } } } /// /// Build Parent relationships for a collection of polymorphic tree objects. /// Links each object's Parent property to its parent in the collection. /// Also populates Children collections. /// /// Collection of tree objects public static void BuildParentRelationships(IEnumerable objects) { var dict = objects.ToDictionary(o => o.Id, o => o); foreach (var obj in objects) { obj.Parent = null; obj.Children.Clear(); if (obj.ParentId.HasValue && dict.TryGetValue(obj.ParentId.Value, out var parent)) { obj.Parent = parent; parent.Children.Add(obj); } } } /// /// Copy base properties from RedbObject to TreeRedbObject. /// private static void CopyBaseProperties(RedbObject source, RedbObject target) { target.id = source.id; target.parent_id = source.parent_id; target.scheme_id = source.scheme_id; target.owner_id = source.owner_id; target.who_change_id = source.who_change_id; target.date_create = source.date_create; target.date_modify = source.date_modify; target.date_begin = source.date_begin; target.date_complete = source.date_complete; target.key = source.key; target.value_long = source.value_long; target.value_string = source.value_string; target.value_guid = source.value_guid; target.value_bool = source.value_bool; target.value_double = source.value_double; target.value_numeric = source.value_numeric; target.value_datetime = source.value_datetime; target.value_bytes = source.value_bytes; target.value_unique = source.value_unique; target.name = source.name; target.note = source.note; target.hash = source.hash; } /// /// Simple wrapper for non-generic IRedbObject to ITreeRedbObject. /// Used when source object type is unknown at compile time. /// private class TreeRedbObjectWrapper : TreeRedbObject, ITreeRedbObject { /// /// Original source object. /// public IRedbObject SourceObject { get; } public TreeRedbObjectWrapper(IRedbObject source) { SourceObject = source; id = source.Id; parent_id = source.ParentId; scheme_id = source.SchemeId; owner_id = source.OwnerId; who_change_id = source.WhoChangeId; date_create = source.DateCreate; date_modify = source.DateModify; date_begin = source.DateBegin; date_complete = source.DateComplete; key = source.Key; value_long = source.ValueLong; value_string = source.ValueString; value_guid = source.ValueGuid; value_bool = source.ValueBool; value_double = source.ValueDouble; value_numeric = source.ValueNumeric; value_datetime = source.ValueDatetime; value_bytes = source.ValueBytes; value_unique = source.ValueUnique; name = source.Name; note = source.Note; hash = source.Hash; } } } Path: redb/redb.Core/Utils/UniqueKeyEncoder.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/Utils/UniqueKeyEncoder.cs ---- using System; using System.Globalization; using System.Text; using redb.Core.Exceptions; using redb.Core.Models.Entities; namespace redb.Core.Utils { /// /// Turns the value of a [RedbUnique] field into the 128-bit key stored in /// _values._unique: the RedbMd5 hash of the value's canonical form. /// /// /// The requirement is strict and two-sided: one logical value must give exactly one form, and /// different logical values must not give the same one. A hash of an uncanonicalised value has the /// same hole, only quieter — 1.50m and 1.5m would be two keys, 12:00+03:00 /// and 09:00Z two keys, "é" as one code point and as two would be two keys. /// /// /// /// The input is the as it is about to be written — the typed column, not /// the CLR value. That is what makes a recomputation from the database /// (RecomputeUniqueAsync) produce the same key as the original save: both start from the /// same representation. Precision is therefore pinned to what every provider keeps: /// milliseconds for timestamps (SQLite stores a Julian REAL), 18 decimal places for /// decimal (the column scale on PostgreSQL and MSSQL). /// /// /// /// Rules, one per typed column; the column tag makes the form injective across columns: /// /// _String: Unicode NFC. No trimming, no case folding — the application owns the /// notion of its key (see ). /// _Long: invariant decimal digits, one form for every integer width. /// _Guid: canonical D form, lower case. /// _Double: round-trip R; -0 is 0; NaN and infinities are /// refused — they are not values that can be equal to themselves. /// _DateTimeOffset: UTC, truncated to milliseconds, yyyy-MM-ddTHH:mm:ss.fffZ. /// _Boolean: 1 / 0. /// _Numeric: rounded to 18 places, trailing zeros dropped (G29), one zero. /// _ByteArray: the bytes themselves; there is nothing to canonicalise. /// /// A value with no typed column set (a NULL) has no key: NULL never takes part in uniqueness. /// /// /// /// is stamped into _structures._unique_version when a structure's /// keys are computed. Any change to the rules above — a different scale, trimming, another /// algorithm — must bump it; scheme synchronisation then recomputes every key of a structure whose /// stamp is behind, so stored keys never silently disagree with the encoder that checks them. /// /// public static class UniqueKeyEncoder { /// Version of the canonical-form rules. Bump on any change to them. public const int Version = 1; /// /// The key for 's typed content, or null when every typed column /// is NULL. Throws for a value that cannot be a key /// (NaN, infinity). /// public static Guid? Compute(RedbValue value) { if (value.ByteArray != null) return Hash((byte)'y', value.ByteArray); var text = CanonicalText(value, out var tag); return text is null ? null : Hash(tag, Encoding.UTF8.GetBytes(text)); } /// /// The salted form for collection-scoped element keys (S3): the same canonical content, /// prefixed with the identity of the owning collection (_array_parent_id of the /// base row), so equal values in DIFFERENT collections get different keys and only true /// in-collection duplicates collide. The 'p' tag keeps salted and unsalted forms /// injective against each other; the inner tag and a '|' separator keep the salted /// space injective across columns (the salt is decimal digits, never a '|'). /// public static Guid? Compute(RedbValue value, long? collectionSalt) { if (collectionSalt is null) return Compute(value); var saltPrefix = collectionSalt.Value.ToString(CultureInfo.InvariantCulture); if (value.ByteArray != null) { var prefix = Encoding.UTF8.GetBytes(saltPrefix + "|y|"); var payload = new byte[prefix.Length + value.ByteArray.Length]; Buffer.BlockCopy(prefix, 0, payload, 0, prefix.Length); Buffer.BlockCopy(value.ByteArray, 0, payload, prefix.Length, value.ByteArray.Length); return Hash((byte)'p', payload); } var text = CanonicalText(value, out var tag); return text is null ? null : Hash((byte)'p', Encoding.UTF8.GetBytes(saltPrefix + "|" + (char)tag + "|" + text)); } /// /// The canonical text of a scalar column, with the column tag; null when no scalar /// column is set. Exposed for tests and diagnostics — the stored form is the hash. /// public static string? CanonicalText(RedbValue value, out byte tag) { // S3: reference elements canonicalise by the TARGET id - the stable identity of the // link. The persisted content hash in _Guid moves whenever the target's content // changes, which would silently migrate the key; the id never does. Checked before // every scalar column because a reference row may ALSO carry the target's hash in // _Guid (the dictionary path does). Additive: no previously keyed row ever carried // _Object or _ListItem, so existing keys keep their form - no Version bump. if (value.Object.HasValue) { tag = (byte)'o'; return value.Object.Value.ToString(CultureInfo.InvariantCulture); } if (value.ListItem.HasValue) { tag = (byte)'r'; return value.ListItem.Value.ToString(CultureInfo.InvariantCulture); } if (value.String != null) { tag = (byte)'s'; return value.String.IsNormalized(NormalizationForm.FormC) ? value.String : value.String.Normalize(NormalizationForm.FormC); } if (value.Long.HasValue) { tag = (byte)'l'; return value.Long.Value.ToString(CultureInfo.InvariantCulture); } if (value.Guid.HasValue) { tag = (byte)'g'; return value.Guid.Value.ToString("D"); } if (value.Double.HasValue) { tag = (byte)'d'; var d = value.Double.Value; if (double.IsNaN(d) || double.IsInfinity(d)) throw new RedbUniqueKeyValueException(value.IdStructure, $"{d} cannot be a unique key: it is not equal to itself or has no finite representation"); if (d == 0) d = 0; // -0.0 and 0.0 are one value return d.ToString("R", CultureInfo.InvariantCulture); } if (value.DateTimeOffset.HasValue) { tag = (byte)'t'; var utc = value.DateTimeOffset.Value.UtcDateTime; var ms = new DateTime(utc.Ticks - utc.Ticks % TimeSpan.TicksPerMillisecond, DateTimeKind.Utc); return ms.ToString("yyyy-MM-dd'T'HH:mm:ss.fff'Z'", CultureInfo.InvariantCulture); } if (value.Boolean.HasValue) { tag = (byte)'b'; return value.Boolean.Value ? "1" : "0"; } if (value.Numeric.HasValue) { tag = (byte)'n'; var n = decimal.Round(value.Numeric.Value, 18); if (n == 0m) n = 0m; // one zero: no "-0" return n.ToString("G29", CultureInfo.InvariantCulture); } tag = 0; return null; } private static Guid Hash(byte tag, byte[] payload) { var bytes = new byte[payload.Length + 1]; bytes[0] = tag; Buffer.BlockCopy(payload, 0, bytes, 1, payload.Length); // Same construction as every other redb hash (RedbHash, SchemeHashCalculator): the 16 MD5 // bytes through the Guid constructor, so the column holds one representation of one thing. return new Guid(RedbMd5.ComputeHash(bytes)); } } } Path: redb/redb.Core/Utils/ValuesTopologicalSort.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/Utils/ValuesTopologicalSort.cs ---- using System.Collections.Generic; using System.Linq; using redb.Core.Data; using redb.Core.Models.Entities; namespace redb.Core.Utils { /// /// Topological sorting of _values to maintain FK constraint on _array_parent_id. /// Parent records must be inserted BEFORE children in BulkInsert. /// public static class ValuesTopologicalSort { /// /// Sort values by ArrayParentId dependencies (single-threaded). /// BFS algorithm: first records without parent, then their children, etc. /// public static List SortByFkDependency(List values) { if (values.Count <= 1) return values; var valueIds = values.Select(v => v.Id).ToHashSet(); // BFS sorting var byParent = values .Where(v => v.ArrayParentId.HasValue) .ToLookup(v => v.ArrayParentId!.Value); var result = new List(values.Count); var added = new HashSet(); var queue = new Queue(); // Start with records WITHOUT parent OR with EXTERNAL parent (parent in DB, not in batch) foreach (var v in values.Where(v => !v.ArrayParentId.HasValue || !valueIds.Contains(v.ArrayParentId.Value))) { queue.Enqueue(v); added.Add(v.Id); } while (queue.Count > 0) { var current = queue.Dequeue(); result.Add(current); foreach (var child in byParent[current.Id]) { if (!added.Contains(child.Id)) { queue.Enqueue(child); added.Add(child.Id); } } } // If records remain (circular dependencies?), add to end if (result.Count < values.Count) { var remaining = values.Where(v => !added.Contains(v.Id)).ToList(); result.AddRange(remaining); } return result; } } } Path: redb/redb.Core/Utils/appExt.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/Utils/appExt.cs ---- using System.Collections; using System.Linq.Expressions; namespace redb.Core.Utils { public static class appExt { public static void forEach(this IEnumerable d, Action a) { foreach (object? i in d) { a((T)i); } } #pragma warning disable CS8600, CS8602, CS8603, CS8604 public static void forEach(this IDictionary source, Action action) => source.forEach(i=>action((K)i.Key,(V?)i.Value)); /// /// Filter IQueryable by property name dynamically. /// Uses expression trees instead of EF.Property. /// public static IQueryable Filter(this IQueryable query, string propertyName, object propertyValue) { var parameter = Expression.Parameter(typeof(T), "e"); var property = Expression.Property(parameter, propertyName); var value = Expression.Constant(propertyValue); var equals = Expression.Equal(property, Expression.Convert(value, property.Type)); var lambda = Expression.Lambda>(equals, parameter); return query.Where(lambda); } #pragma warning restore CS8600, CS8602, CS8603, CS8604 } } Path: redb/redb.Core/redb.Core.csproj 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/redb.Core.csproj ---- net10.0;net11.0 enable enable true $(NoWarn);CS1591 redb.Core REDB - Entity Database for .NET Core library for REDB - Entity Database for .NET. SQL speed, NoSQL flexibility. Define schemas in C#, forget migrations, query with LINQ. Built for complex domains where traditional ORMs fall short. https://github.com/redbase-app/redb database;orm;redb;redbase;linq;dotnet;typed-schema;typed-storage;soft-delete;tree;window-functions;no-migrations;flexible-schema README.md