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