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);
}