Path: redb/redb.Core/Query/RedbQueryable.cs
Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb
Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Core/Query/RedbQueryable.cs
----
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using redb.Core.Models.Entities;
using redb.Core.Models.Contracts;
using redb.Core.Query.QueryExpressions;
using redb.Core.Query.FacetFilters;
namespace redb.Core.Query;
///
/// Basic implementation of IRedbQueryable
///
public class RedbQueryable : IRedbQueryable, IOrderedRedbQueryable
where TProps : class, new()
{
protected readonly IRedbQueryProvider _provider;
internal IRedbQueryProvider QueryProvider => _provider;
protected readonly QueryContext _context;
protected readonly IFilterExpressionParser _filterParser;
protected readonly IOrderingExpressionParser _orderingParser;
protected readonly IFacetFilterBuilder? _facetBuilder;
public RedbQueryable(
IRedbQueryProvider provider,
QueryContext context,
IFilterExpressionParser filterParser,
IOrderingExpressionParser orderingParser,
IFacetFilterBuilder? facetBuilder = null)
{
_provider = provider;
_context = context;
_filterParser = filterParser;
_orderingParser = orderingParser;
_facetBuilder = facetBuilder;
}
public virtual IRedbQueryable Where(Expression> predicate)
{
var newContext = _context.Clone();
var filterExpression = _filterParser.ParseFilter(predicate);
// FIX: Check for empty filter (Where(x => false))
if (IsEmptyFilter(filterExpression))
{
newContext.IsEmpty = true;
}
// If filter already exists, combine via AND
if (newContext.Filter != null)
{
newContext.Filter = new LogicalExpression(
LogicalOperator.And,
new[] { newContext.Filter, filterExpression }
);
}
else
{
newContext.Filter = filterExpression;
}
return new RedbQueryable(_provider, newContext, _filterParser, _orderingParser, _facetBuilder);
}
public virtual IRedbQueryable WhereRedb(Expression> predicate)
{
if (predicate == null)
throw new ArgumentNullException(nameof(predicate));
var newContext = _context.Clone();
// Parse expression for base IRedbObject fields
var filterExpression = _filterParser.ParseRedbFilter(predicate);
// Check for empty filter
if (IsEmptyFilter(filterExpression))
{
newContext.IsEmpty = true;
}
// If filter already exists, combine via AND
if (newContext.Filter != null)
{
newContext.Filter = new LogicalExpression(
LogicalOperator.And,
new[] { newContext.Filter, filterExpression }
);
}
else
{
newContext.Filter = filterExpression;
}
return new RedbQueryable(_provider, newContext, _filterParser, _orderingParser, _facetBuilder);
}
public virtual IOrderedRedbQueryable OrderBy(Expression> keySelector)
{
var newContext = _context.Clone();
newContext.Orderings.Clear(); // OrderBy replaces previous sorting
var ordering = _orderingParser.ParseOrdering(keySelector, SortDirection.Ascending);
newContext.Orderings.Add(ordering);
// FIX: Preserve IsEmpty flag after OrderBy
// Even if ordering is added, query can remain empty (Where(x => false))
return new RedbQueryable(_provider, newContext, _filterParser, _orderingParser, _facetBuilder);
}
public virtual IOrderedRedbQueryable OrderByDescending(Expression> keySelector)
{
var newContext = _context.Clone();
newContext.Orderings.Clear(); // OrderByDescending replaces previous sorting
var ordering = _orderingParser.ParseOrdering(keySelector, SortDirection.Descending);
newContext.Orderings.Add(ordering);
// FIX: Preserve IsEmpty flag after OrderByDescending
// IsEmpty is already copied in Clone(), no additional actions required
return new RedbQueryable(_provider, newContext, _filterParser, _orderingParser, _facetBuilder);
}
public virtual IOrderedRedbQueryable ThenBy(Expression> keySelector)
{
var newContext = _context.Clone();
var ordering = _orderingParser.ParseOrdering(keySelector, SortDirection.Ascending);
newContext.Orderings.Add(ordering);
// FIX: Preserve IsEmpty flag after ThenBy
// IsEmpty is already copied in Clone(), no additional actions required
return new RedbQueryable(_provider, newContext, _filterParser, _orderingParser, _facetBuilder);
}
public virtual IOrderedRedbQueryable ThenByDescending(Expression> keySelector)
{
var newContext = _context.Clone();
var ordering = _orderingParser.ParseOrdering(keySelector, SortDirection.Descending);
newContext.Orderings.Add(ordering);
// FIX: Preserve IsEmpty flag after ThenByDescending
// IsEmpty is already copied in Clone(), no additional actions required
return new RedbQueryable(_provider, newContext, _filterParser, _orderingParser, _facetBuilder);
}
// ═══════════════════════════════════════════════════════════════════════════
// SORTING BY BASE RedbObject FIELDS (OrderByRedb, ThenByRedb)
// ═══════════════════════════════════════════════════════════════════════════
public virtual IOrderedRedbQueryable OrderByRedb(Expression> keySelector)
{
var newContext = _context.Clone();
newContext.Orderings.Clear(); // OrderByRedb replaces previous sorting
var ordering = _orderingParser.ParseRedbOrdering(keySelector, SortDirection.Ascending);
newContext.Orderings.Add(ordering);
return new RedbQueryable(_provider, newContext, _filterParser, _orderingParser, _facetBuilder);
}
public virtual IOrderedRedbQueryable OrderByDescendingRedb(Expression> keySelector)
{
var newContext = _context.Clone();
newContext.Orderings.Clear(); // OrderByDescendingRedb replaces previous sorting
var ordering = _orderingParser.ParseRedbOrdering(keySelector, SortDirection.Descending);
newContext.Orderings.Add(ordering);
return new RedbQueryable(_provider, newContext, _filterParser, _orderingParser, _facetBuilder);
}
public virtual IOrderedRedbQueryable ThenByRedb(Expression> keySelector)
{
var newContext = _context.Clone();
var ordering = _orderingParser.ParseRedbOrdering(keySelector, SortDirection.Ascending);
newContext.Orderings.Add(ordering); // ThenByRedb adds to existing sorting
return new RedbQueryable(_provider, newContext, _filterParser, _orderingParser, _facetBuilder);
}
public virtual IOrderedRedbQueryable ThenByDescendingRedb(Expression> keySelector)
{
var newContext = _context.Clone();
var ordering = _orderingParser.ParseRedbOrdering(keySelector, SortDirection.Descending);
newContext.Orderings.Add(ordering); // ThenByDescendingRedb adds to existing sorting
return new RedbQueryable(_provider, newContext, _filterParser, _orderingParser, _facetBuilder);
}
public virtual IRedbQueryable Take(int count)
{
if (count < 0)
throw new ArgumentException("Take count must be non-negative", nameof(count));
var newContext = _context.Clone();
newContext.Limit = count;
return new RedbQueryable(_provider, newContext, _filterParser, _orderingParser, _facetBuilder);
}
public virtual IRedbQueryable Skip(int count)
{
if (count < 0)
throw new ArgumentException("Skip count must be non-negative", nameof(count));
var newContext = _context.Clone();
newContext.Offset = count;
return new RedbQueryable(_provider, newContext, _filterParser, _orderingParser, _facetBuilder);
}
public virtual async Task>> ToListAsync(CancellationToken cancellationToken = default)
{
var result = await _provider.ExecuteAsync(BuildExpression(), typeof(List>), cancellationToken: cancellationToken);
return (List>)result;
}
///
/// Number of rows of the same query returns, Take and Skip included.
/// The providers count the filtered set and leave paging out, so Take(10).CountAsync()
/// used to answer with the size of the whole set. The set is counted without paging and the
/// page is cut from that number here, the same way for every provider.
///
public virtual async Task CountAsync(CancellationToken cancellationToken = default)
{
if (!IsPaged(_context))
return await CountWholeSetAsync(cancellationToken);
var unpaged = _context.Clone();
unpaged.Limit = null;
unpaged.Offset = null;
var total = await new RedbQueryable(_provider, unpaged, _filterParser, _orderingParser, _facetBuilder)
.CountWholeSetAsync(cancellationToken);
return PagedCount(total, _context.Offset, _context.Limit);
}
/// Count as the provider computes it: the filtered set, whatever Take and Skip say.
private protected async Task CountWholeSetAsync(CancellationToken cancellationToken)
{
var result = await _provider.ExecuteAsync(BuildCountExpression(), typeof(int), cancellationToken: cancellationToken);
return (int)result;
}
/// Is there an object in the whole set filtered by , Take and Skip aside.
private async Task AnyOfWholeSetAsync(FilterExpression? filter, CancellationToken cancellationToken)
{
if (_context.IsEmpty)
return false;
var whole = _context.Clone();
whole.Limit = null;
whole.Offset = null;
whole.Filter = filter;
var result = await _provider.ExecuteAsync(Expression.Constant(whole), typeof(bool), cancellationToken: cancellationToken);
return (bool)result;
}
///
/// The filter reads Props fields directly, nothing else: no field of the object itself, no computed value
/// (arithmetic, functions). The constant of Where(x => true / false) passes.
///
private static bool ReadsPropsFieldsOnly(FilterExpression filter) => filter switch
{
ComparisonExpression c => c.Property.Name == "__constant"
|| (c.LeftExpression == null && c.RightExpression == null && !c.Property.IsBaseField),
InExpression i => !i.Property.IsBaseField,
NullCheckExpression n => !n.Property.IsBaseField,
LogicalExpression l => l.Operator != LogicalOperator.NotTrue && l.Operands.All(ReadsPropsFieldsOnly),
_ => false
};
internal static bool IsPaged(QueryContext context)
=> context.Limit != null || (context.Offset ?? 0) > 0;
/// Rows left of after skipping and taking.
internal static int PagedCount(int total, int? offset, int? limit)
{
var afterSkip = Math.Max(0, total - (offset ?? 0));
return limit is { } take ? Math.Min(take, afterSkip) : afterSkip;
}
public virtual async Task?> FirstOrDefaultAsync(CancellationToken cancellationToken = default)
{
// For FirstOrDefault limit to 1 record
var limitedContext = _context.Clone();
limitedContext.Limit = 1;
var tempQueryable = new RedbQueryable(_provider, limitedContext, _filterParser, _orderingParser);
var result = await tempQueryable.ToListAsync(cancellationToken: cancellationToken);
return result.FirstOrDefault();
}
public virtual async Task?> FirstOrDefaultAsync(Expression> predicate, CancellationToken cancellationToken = default)
{
return await Where(predicate).FirstOrDefaultAsync(cancellationToken: cancellationToken);
}
public virtual async Task AnyAsync(CancellationToken cancellationToken = default)
{
// A paged query has rows only if the page has: Take(0) has none, Skip(n) only past the n-th.
if (IsPaged(_context))
return await CountAsync(cancellationToken) > 0;
// Asked of the provider as its own operation: one that can stop at the first match does
// not have to count the whole set. The provider default is still "count is above zero".
var result = await _provider.ExecuteAsync(BuildCountExpression(), typeof(bool), cancellationToken: cancellationToken);
return (bool)result;
}
public virtual async Task AnyAsync(Expression> predicate, CancellationToken cancellationToken = default)
{
// Create new query with additional filter
var filteredQuery = Where(predicate);
return await filteredQuery.AnyAsync(cancellationToken: cancellationToken);
}
public virtual IRedbQueryable WhereIn(Expression> selector, IEnumerable values)
{
if (selector == null)
throw new ArgumentNullException(nameof(selector));
if (values == null)
throw new ArgumentNullException(nameof(values));
var valuesList = values.ToList();
if (!valuesList.Any())
{
// If list is empty, return query that finds nothing
return Where(_ => false);
}
// Create expression: x => values.Contains(selector(x))
var parameter = selector.Parameters[0];
var selectorBody = selector.Body;
// Create constant with list of values
var valuesConstant = Expression.Constant(valuesList);
// Create Contains call
var containsMethod = typeof(List).GetMethod("Contains", new[] { typeof(TValue) });
var containsCall = Expression.Call(valuesConstant, containsMethod!, selectorBody);
// Create lambda expression
var lambda = Expression.Lambda>(containsCall, parameter);
return Where(lambda);
}
public virtual IRedbQueryable WhereInRedb(Expression> selector, IEnumerable values)
{
if (selector == null)
throw new ArgumentNullException(nameof(selector));
if (values == null)
throw new ArgumentNullException(nameof(values));
var valuesList = values.ToList();
if (!valuesList.Any())
{
// Empty list = finds nothing
return WhereRedb(_ => false);
}
// Create expression: x => values.Contains(selector(x))
var parameter = selector.Parameters[0];
var selectorBody = selector.Body;
// Create constant with list of values
var valuesConstant = Expression.Constant(valuesList);
// Create Contains call
var containsMethod = typeof(List).GetMethod("Contains", new[] { typeof(TValue) });
var containsCall = Expression.Call(valuesConstant, containsMethod!, selectorBody);
// Create lambda expression for IRedbObject
var lambda = Expression.Lambda>(containsCall, parameter);
return WhereRedb(lambda);
}
public virtual async Task AllAsync(Expression> predicate, CancellationToken cancellationToken = default)
{
if (predicate == null)
throw new ArgumentNullException(nameof(predicate));
// All() == true if all records satisfy the condition: no object of the whole filtered set (Take and Skip
// aside) is a counterexample, an object for which the predicate is not TRUE. A provider that compiles NotTrue
// answers that as one existence check, which stops at the first counterexample. The predicate must read Props
// fields only: a provider compiles the fields of the object and Props in separate parts of a statement, and
// NotTrue cannot be split across them.
var predicateFilter = _filterParser.ParseFilter(predicate);
// All(x => true), or a predicate that folds to it: true for any set. It must not reach NotTrue: a provider
// drops a true operand from a logical node, so "not true" would compile to "every object is a counterexample".
if (predicateFilter is ComparisonExpression { Property.Name: "__constant", Operator: ComparisonOperator.Equal, Value: true })
return true;
// A provider may answer All over the whole scheme in one statement of its own (QueryProviderBase.TryAllWithoutFilterAsync).
// Only for the plain set of the scheme: WhereRedb and WhereInRedb sit in the filter, the tree queryables have an
// AllAsync of their own, and Take and Skip are set aside here as by the counts below. A distinct set is not the
// set of objects: DistinctBy keeps one object per key, and the counts below compare keys.
if (_context.Filter == null && !_context.IsEmpty
&& _context.DistinctByField == null && !_context.IsDistinct && !_context.IsDistinctRedb
&& _provider is Base.QueryProviderBase provider
&& ReadsPropsFieldsOnly(predicateFilter) && !IsEmptyFilter(predicateFilter)
&& await provider.TryAllWithoutFilterAsync(_context, predicateFilter, cancellationToken) is bool all)
return all;
if (_provider is Base.QueryProviderBase { CompilesNotTrue: true } && ReadsPropsFieldsOnly(predicateFilter))
{
if (IsEmptyFilter(predicateFilter))
return !await AnyOfWholeSetAsync(_context.Filter, cancellationToken); // All(x => false): only an empty set
var notTrue = new LogicalExpression(LogicalOperator.NotTrue, new[] { predicateFilter });
var counterexamples = _context.Filter == null
? notTrue
: new LogicalExpression(LogicalOperator.And, new[] { _context.Filter, notTrue });
return !await AnyOfWholeSetAsync(counterexamples, cancellationToken);
}
// Otherwise both counts are of the whole filtered set: two counts cut to the same page size would
// come out equal whenever enough rows match, whether or not all of them do.
var totalCount = await CountWholeSetAsync(cancellationToken);
if (totalCount == 0)
return true; // All elements of empty set satisfy any condition
var matching = Where(predicate);
var matchingCount = matching is RedbQueryable flat
? await flat.CountWholeSetAsync(cancellationToken)
: await matching.CountAsync(cancellationToken: cancellationToken);
return totalCount == matchingCount;
}
public virtual IRedbProjectedQueryable Select(Expression, TResult>> selector)
{
if (selector == null)
throw new ArgumentNullException(nameof(selector));
return new RedbProjectedQueryable(this, selector, _provider, _context.SchemeId);
}
///
/// Internal method for optimized loading with structure_ids filter.
/// Virtual for overriding in PostgresTreeQueryable (List TreeRedbObject → List RedbObject).
/// Text paths are taken from context (_context.ProjectedFieldPaths).
///
///
/// Structure IDs extracted from projection expression. Used by Pro's ProLazyPropsLoader
/// to load only matching _values rows. Null = no projection filter.
///
///
/// When true, tells MaterializeResultsFromJson to skip ALL Props post-processing
/// (both eager LoadPropsForManyAsync and lazy loader setup). This is required for
/// projections because Props data already comes from the SQL projection function
/// (search_objects_with_projection_by_paths) embedded in the JSON "properties" field.
/// Re-loading would overwrite partial Props with full object data, wasting the projection.
///
/// Cancels the operation (OCE only; a rollback in flight always completes).
protected internal virtual async Task>> ToListWithProjectionAsync(
HashSet? projectedStructureIds,
bool skipPropsLoading = false,
CancellationToken cancellationToken = default)
{
// Set structure_ids in context for passing to provider
if (projectedStructureIds != null && projectedStructureIds.Count > 0)
{
_context.ProjectedStructureIds = projectedStructureIds;
}
// An empty set is an answer of its own: the selector reads base fields only.
_context.ProjectionReadsNoProps = projectedStructureIds is { Count: 0 };
if (skipPropsLoading)
{
// FIX: Skip BOTH Props loading AND lazy loader setup.
// Projection SQL already returns "properties" with only the needed fields.
// Deserializer maps them to Props via setter (_propsLoaded = true).
// Any post-processing (eager or lazy) would overwrite partial Props with full data.
_context.SkipPropsLoading = true;
}
// Delegate to provider using the same BuildExpression() as ToListAsync()
var result = await _provider.ExecuteAsync(BuildExpression(), typeof(List>), cancellationToken: cancellationToken);
return (List>)result;
}
///
/// A copy of this query for a projection to configure and run. The projection writes its
/// settings (fields to load, skipping of Props) into the context; written into the query itself
/// they stayed there, and the same query run again as ToListAsync returned objects with part
/// of their Props.
///
internal virtual RedbQueryable CloneForProjection()
=> new RedbQueryable(_provider, _context.Clone(), _filterParser, _orderingParser, _facetBuilder);
///
/// Scheme ID for access from projections
///
internal long SchemeId => _context.SchemeId;
///
/// Provider for access from projections
///
internal IRedbQueryProvider Provider => _provider;
///
/// Sets text paths for SQL function search_objects_with_projection_by_paths.
/// Called from RedbProjectedQueryable before ToListWithProjectionAsync.
///
internal void SetProjectedFieldPaths(List? paths)
{
if (paths != null && paths.Count > 0)
{
_context.ProjectedFieldPaths = paths;
}
}
public virtual IRedbQueryable Distinct()
{
var newContext = _context.Clone();
newContext.IsDistinct = true;
return new RedbQueryable(_provider, newContext, _filterParser, _orderingParser, _facetBuilder);
}
public virtual IRedbQueryable DistinctRedb()
{
var newContext = _context.Clone();
newContext.IsDistinctRedb = true;
return new RedbQueryable(_provider, newContext, _filterParser, _orderingParser, _facetBuilder);
}
public virtual IRedbQueryable DistinctBy(Expression> keySelector)
{
if (keySelector == null)
throw new ArgumentNullException(nameof(keySelector));
var newContext = _context.Clone();
var ordering = _orderingParser.ParseOrdering(keySelector, SortDirection.Ascending);
newContext.DistinctByField = ordering;
newContext.DistinctByIsBaseField = false;
// The ordering by the key goes first, once, in the direction the query gave it.
newContext.PutDistinctKeyFirst(ordering);
return new RedbQueryable(_provider, newContext, _filterParser, _orderingParser, _facetBuilder);
}
public virtual IRedbQueryable DistinctByRedb(Expression> keySelector)
{
if (keySelector == null)
throw new ArgumentNullException(nameof(keySelector));
var newContext = _context.Clone();
var ordering = _orderingParser.ParseRedbOrdering(keySelector, SortDirection.Ascending);
newContext.DistinctByField = ordering;
newContext.DistinctByIsBaseField = true;
// The ordering by the key goes first, once, in the direction the query gave it.
newContext.PutDistinctKeyFirst(ordering);
return new RedbQueryable(_provider, newContext, _filterParser, _orderingParser, _facetBuilder);
}
public virtual IRedbQueryable WithMaxRecursionDepth(int depth)
{
if (depth < 1)
throw new ArgumentException("Max recursion depth must be positive", nameof(depth));
var newContext = _context.Clone();
newContext.MaxRecursionDepth = depth;
return new RedbQueryable(_provider, newContext, _filterParser, _orderingParser, _facetBuilder);
}
public virtual IRedbQueryable WithLazyReferences(bool enabled = true)
{
var newContext = _context.Clone();
newContext.LazyReferences = enabled;
return new RedbQueryable(_provider, newContext, _filterParser, _orderingParser, _facetBuilder);
}
///
/// Builds expression for query execution
///
protected virtual Expression BuildExpression()
{
// Expression representing the entire query will be created here
// Return stub for now - concrete implementation will be in provider
return Expression.Constant(_context);
}
///
/// Builds expression for record count
///
protected virtual Expression BuildCountExpression()
{
// Similarly for Count
return Expression.Constant(_context);
}
///
/// NEW METHOD: Determines if filter is empty (Where(x => false))
///
private bool IsEmptyFilter(FilterExpression filter)
{
// Check for constant false filter (created for Where(x => false))
if (filter is ComparisonExpression comparison &&
comparison.Property.Name == "__constant" &&
comparison.Property.Type == typeof(bool) &&
comparison.Operator == ComparisonOperator.Equal &&
comparison.Value is bool boolValue &&
boolValue == false)
{
return true;
}
return false;
}
// ===== TREE METHODS =====
// For base RedbQueryable these methods throw NotSupportedException
// PostgresTreeQueryable overrides them with real implementation
public virtual IRedbQueryable WhereHasAncestor(
Expression> ancestorCondition,
int? maxDepth = null)
where TTarget : class
{
throw new NotSupportedException(
"Tree methods are not supported in non-tree queries. " +
"Use ITreeQueryProvider.CreateTreeQuery() to create queries with tree support.");
}
public virtual IRedbQueryable WhereHasDescendant(
Expression> descendantCondition,
int? maxDepth = null)
where TTarget : class
{
throw new NotSupportedException(
"Tree methods are not supported in non-tree queries. " +
"Use ITreeQueryProvider.CreateTreeQuery() to create queries with tree support.");
}
public virtual IRedbQueryable WhereLevel(int level)
{
throw new NotSupportedException(
"Tree methods are not supported in non-tree queries. " +
"Use ITreeQueryProvider.CreateTreeQuery() to create queries with tree support.");
}
public virtual IRedbQueryable WhereLevel(Expression> levelCondition)
{
throw new NotSupportedException(
"Tree methods are not supported in non-tree queries. " +
"Use ITreeQueryProvider.CreateTreeQuery() to create queries with tree support.");
}
public virtual IRedbQueryable WhereRoots()
{
throw new NotSupportedException(
"Tree methods are not supported in non-tree queries. " +
"Use ITreeQueryProvider.CreateTreeQuery() to create queries with tree support.");
}
public virtual IRedbQueryable WhereLeaves()
{
throw new NotSupportedException(
"Tree methods are not supported in non-tree queries. " +
"Use ITreeQueryProvider.CreateTreeQuery() to create queries with tree support.");
}
public virtual IRedbQueryable WhereChildrenOf(long parentId)
{
throw new NotSupportedException(
"Tree methods are not supported in non-tree queries. " +
"Use ITreeQueryProvider.CreateTreeQuery() to create queries with tree support.");
}
public virtual IRedbQueryable WhereChildrenOf(IRedbObject parentObject)
{
throw new NotSupportedException(
"Tree methods are not supported in non-tree queries. " +
"Use ITreeQueryProvider.CreateTreeQuery() to create queries with tree support.");
}
public virtual IRedbQueryable WhereDescendantsOf(long ancestorId, int? maxDepth = null)
{
throw new NotSupportedException(
"Tree methods are not supported in non-tree queries. " +
"Use ITreeQueryProvider.CreateTreeQuery() to create queries with tree support.");
}
public virtual IRedbQueryable WhereDescendantsOf(IRedbObject ancestorObject, int? maxDepth = null)
{
throw new NotSupportedException(
"Tree methods are not supported in non-tree queries. " +
"Use ITreeQueryProvider.CreateTreeQuery() to create queries with tree support.");
}
public virtual IRedbQueryable WithMaxDepth(int depth)
{
throw new NotSupportedException(
"Tree methods are not supported in non-tree queries. " +
"Use ITreeQueryProvider.CreateTreeQuery() to create queries with tree support.");
}
public virtual IRedbQueryable WithPropsDepth(int depth)
{
var newContext = _context.Clone();
newContext.PropsDepth = depth;
return new RedbQueryable(_provider, newContext, _filterParser, _orderingParser, _facetBuilder);
}
// ===== MATERIALIZATION METHODS =====
public virtual async Task>> ToTreeListAsync(CancellationToken cancellationToken = default)
{
throw new NotSupportedException(
"ToTreeListAsync is not supported in non-tree queries. " +
"Use ITreeQueryProvider.CreateTreeQuery() to create queries with tree support.");
}
public virtual async Task>> ToFlatListAsync(CancellationToken cancellationToken = default)
{
throw new NotSupportedException(
"ToFlatListAsync is not supported in non-tree queries. " +
"Use ITreeQueryProvider.CreateTreeQuery() to create queries with tree support.");
}
public virtual async Task> ToRootListAsync(CancellationToken cancellationToken = default)
{
throw new NotSupportedException(
"ToRootListAsync is not supported in non-tree queries. " +
"Use ITreeQueryProvider.CreateTreeQuery() to create queries with tree support.");
}
public virtual async Task DeleteAsync(CancellationToken cancellationToken = default)
{
// Pass FilterExpression directly (Pro uses it for PVT-based deletion, OpenSource falls back to facet-JSON)
return await _provider.ExecuteDeleteAsync(_context.SchemeId, _context.Filter, cancellationToken: cancellationToken);
}
// ===== AGGREGATIONS =====
// Every aggregate method below ends in one of these three provider calls. They are the seam a
// derived queryable overrides to aggregate over its own object set: a tree query has to range
// over its subtree, and the flat provider calls know nothing but the scheme.
/// One aggregate over a Props field of the objects this query selects.
protected virtual Task ExecuteAggregateCoreAsync(
string fieldPath, Aggregation.AggregateFunction function, CancellationToken cancellationToken)
=> _provider.ExecuteAggregateAsync(_context.SchemeId, fieldPath, function, _context.Filter, cancellationToken: cancellationToken);
/// Several aggregates in one statement over the objects this query selects.
protected virtual Task ExecuteAggregateBatchCoreAsync(
IEnumerable requests, CancellationToken cancellationToken)
=> _provider.ExecuteAggregateBatchAsync(_context.SchemeId, requests, _context.Filter, cancellationToken: cancellationToken);
/// Grouped aggregates; with no group fields, one row over the objects this query selects.
protected virtual Task ExecuteGroupedAggregateCoreAsync(
IEnumerable groupFields,
IEnumerable aggregations,
CancellationToken cancellationToken)
=> _provider.ExecuteGroupedAggregateAsync(_context.SchemeId, groupFields, aggregations, _context.Filter, cancellationToken: cancellationToken);
public virtual async Task SumAsync(Expression> selector, CancellationToken cancellationToken = default)
where TField : struct
{
var fieldPath = ExtractFieldPath(selector);
// Pass FilterExpression directly (Pro uses it, Free falls back to facet-JSON)
var result = await ExecuteAggregateCoreAsync(fieldPath, Aggregation.AggregateFunction.Sum, cancellationToken);
return result ?? 0m;
}
public virtual async Task AverageAsync(Expression> selector, CancellationToken cancellationToken = default)
where TField : struct
{
var fieldPath = ExtractFieldPath(selector);
// Pass FilterExpression directly (Pro uses it, Free falls back to facet-JSON)
var result = await ExecuteAggregateCoreAsync(fieldPath, Aggregation.AggregateFunction.Average, cancellationToken);
return result ?? 0m;
}
public virtual async Task MinAsync(Expression> selector, CancellationToken cancellationToken = default)
where TField : struct
{
var fieldPath = ExtractFieldPath(selector);
// Pass FilterExpression directly (Pro uses it, Free falls back to facet-JSON)
var result = await ExecuteAggregateCoreAsync(fieldPath, Aggregation.AggregateFunction.Min, cancellationToken);
if (result == null) return null;
return (TField)Utils.TemporalDecoder.ChangeType(result.Value, typeof(TField));
}
public virtual async Task MaxAsync(Expression> selector, CancellationToken cancellationToken = default)
where TField : struct
{
var fieldPath = ExtractFieldPath(selector);
// Pass FilterExpression directly (Pro uses it, Free falls back to facet-JSON)
var result = await ExecuteAggregateCoreAsync(fieldPath, Aggregation.AggregateFunction.Max, cancellationToken);
if (result == null) return null;
return (TField)Utils.TemporalDecoder.ChangeType(result.Value, typeof(TField));
}
// ===== AGGREGATIONS FOR BASE FIELDS =====
///
/// Sum of base IRedbObject field values (ValueLong, Key, etc.)
/// SQL: uses aggregate_grouped with empty grouping for base fields
///
public virtual async Task SumRedbAsync(Expression> selector, CancellationToken cancellationToken = default)
where TField : struct
{
var fieldPath = ExtractFieldPathRedb(selector);
// Use aggregate_grouped with empty group_fields
var groupFields = Array.Empty();
var aggregations = new[] { new Aggregation.AggregateRequest
{
FieldPath = $"0$:{fieldPath}",
Function = Aggregation.AggregateFunction.Sum,
Alias = "result"
}};
// Pass FilterExpression directly: Pro's filterJson grouped-overload drops the filter and
// aggregates the whole scheme (same defect fixed in AggregateAsync). Free converts it to facet-JSON.
var jsonResult = await ExecuteGroupedAggregateCoreAsync(groupFields, aggregations, cancellationToken);
if (jsonResult != null && jsonResult.RootElement.GetArrayLength() > 0)
{
var firstRow = jsonResult.RootElement[0];
// SUM over an EMPTY selection is NULL in SQL (an aggregate with no GROUP BY still returns one
// row). Now that the filter is honoured, WhereRedb(...) matching nothing produces exactly that.
// Read it as a number and it throws (JsonElement.GetDecimal requires a Number kind) — so treat
// NULL as 0m: an empty sum is 0 (Enumerable.Sum semantics; a ledger with no movements is 0).
if (firstRow.TryGetProperty("result", out var value) && value.ValueKind != JsonValueKind.Null)
{
return value.GetDecimal();
}
}
return 0m;
}
///
/// Average value of base IRedbObject field
/// SQL: uses aggregate_grouped with empty grouping
///
public virtual async Task AverageRedbAsync(Expression> selector, CancellationToken cancellationToken = default)
where TField : struct
{
var fieldPath = ExtractFieldPathRedb(selector);
var groupFields = Array.Empty();
var aggregations = new[] { new Aggregation.AggregateRequest
{
FieldPath = $"0$:{fieldPath}",
Function = Aggregation.AggregateFunction.Average,
Alias = "result"
}};
// Pass FilterExpression directly (Pro drops filterJson here — see SumRedbAsync).
var jsonResult = await ExecuteGroupedAggregateCoreAsync(groupFields, aggregations, cancellationToken);
if (jsonResult != null && jsonResult.RootElement.GetArrayLength() > 0)
{
var firstRow = jsonResult.RootElement[0];
// AVG over an empty selection is NULL (see SumRedbAsync) — guard against GetDecimal throwing.
if (firstRow.TryGetProperty("result", out var value) && value.ValueKind != JsonValueKind.Null)
return value.GetDecimal();
}
return 0m;
}
///
/// Minimum value of base IRedbObject field (ValueLong, Key, DateCreate, etc.)
/// SQL: uses aggregate_grouped with empty grouping
///
public virtual async Task MinRedbAsync(Expression> selector, CancellationToken cancellationToken = default)
where TField : struct
{
var fieldPath = ExtractFieldPathRedb(selector);
var groupFields = Array.Empty();
var aggregations = new[] { new Aggregation.AggregateRequest
{
FieldPath = $"0$:{fieldPath}",
Function = Aggregation.AggregateFunction.Min,
Alias = "result"
}};
// Pass FilterExpression directly (Pro drops filterJson here — see SumRedbAsync).
var jsonResult = await ExecuteGroupedAggregateCoreAsync(groupFields, aggregations, cancellationToken);
if (jsonResult != null && jsonResult.RootElement.GetArrayLength() > 0)
{
var firstRow = jsonResult.RootElement[0];
if (firstRow.TryGetProperty("result", out var value) && value.ValueKind != JsonValueKind.Null)
return (TField?)Utils.JsonValueConverter.Convert(value, typeof(TField));
}
return null;
}
///
/// Maximum value of base IRedbObject field (ValueLong, Key, DateCreate, etc.)
/// SQL: uses aggregate_grouped with empty grouping
///
public virtual async Task MaxRedbAsync(Expression> selector, CancellationToken cancellationToken = default)
where TField : struct
{
var fieldPath = ExtractFieldPathRedb(selector);
var groupFields = Array.Empty();
var aggregations = new[] { new Aggregation.AggregateRequest
{
FieldPath = $"0$:{fieldPath}",
Function = Aggregation.AggregateFunction.Max,
Alias = "result"
}};
// Pass FilterExpression directly (Pro drops filterJson here — see SumRedbAsync).
var jsonResult = await ExecuteGroupedAggregateCoreAsync(groupFields, aggregations, cancellationToken);
if (jsonResult != null && jsonResult.RootElement.GetArrayLength() > 0)
{
var firstRow = jsonResult.RootElement[0];
if (firstRow.TryGetProperty("result", out var value) && value.ValueKind != JsonValueKind.Null)
return (TField?)Utils.JsonValueConverter.Convert(value, typeof(TField));
}
return null;
}
///
/// Get field statistics (Sum, Avg, Min, Max, Count) in one call
/// Executed as ONE SQL query!
///
public virtual async Task> GetStatisticsAsync(
Expression> selector, CancellationToken cancellationToken = default) where TField : struct
{
var fieldPath = ExtractFieldPath(selector);
var schemeId = _context.SchemeId;
// ONE SQL query for all aggregations!
var requests = new[]
{
new Aggregation.AggregateRequest { FieldPath = fieldPath, Function = Aggregation.AggregateFunction.Sum, Alias = "Sum" },
new Aggregation.AggregateRequest { FieldPath = fieldPath, Function = Aggregation.AggregateFunction.Average, Alias = "Average" },
new Aggregation.AggregateRequest { FieldPath = fieldPath, Function = Aggregation.AggregateFunction.Min, Alias = "Min" },
new Aggregation.AggregateRequest { FieldPath = fieldPath, Function = Aggregation.AggregateFunction.Max, Alias = "Max" },
new Aggregation.AggregateRequest { FieldPath = fieldPath, Function = Aggregation.AggregateFunction.Count, Alias = "Count" }
};
// Pass FilterExpression directly: Pro's filterJson batch-overload drops the filter (whole-scheme
// stats). Same fix as AggregateAsync; Free converts to facet-JSON.
var batchResult = await ExecuteAggregateBatchCoreAsync(requests, cancellationToken);
return new Aggregation.FieldStatistics
{
Sum = batchResult.Get("Sum") ?? 0m,
Average = batchResult.Get("Average") ?? 0m,
Min = batchResult.Get("Min"),
Max = batchResult.Get("Max"),
Count = batchResult.Get("Count") ?? 0
};
}
///
/// Flexible aggregation - choose what to aggregate via Agg.Sum/Avg/Min/Max/Count
/// Executed as ONE SQL query (aggregate_batch)!
///
public virtual async Task AggregateAsync(Expression, TResult>> selector, CancellationToken cancellationToken = default)
{
var schemeId = _context.SchemeId;
// Every Agg.* call of the selector; the SQL preview of the aggregate reads the same requests.
var requests = Aggregation.AggregateSelectorParser.Parse(selector);
// BUG FIX: pass the FilterExpression directly so providers that only
// honour the typed overload (e.g. Pro) don't silently drop the outer Where.
var batchResult = await ExecuteAggregateBatchCoreAsync(requests, cancellationToken);
// Build result
return BuildAggregateResult(selector, batchResult.Values);
}
///
/// Flexible aggregation ONLY for base IRedbObject fields
/// Executed as ONE SQL query (aggregate_grouped without grouping)
///
public virtual async Task AggregateRedbAsync(Expression> selector, CancellationToken cancellationToken = default)
{
var schemeId = _context.SchemeId;
// Parse expression and find all Agg.* calls
var aggregations = ParseAggregateRedbExpression(selector);
// Use aggregate_grouped with EMPTY grouping
var groupFields = Array.Empty();
var requests = aggregations.Select(agg => new Aggregation.AggregateRequest
{
// COUNT(*) - don't add 0$: (field is empty or "*")
// For other base fields - add 0$:
FieldPath = (agg.Function == Aggregation.AggregateFunction.Count &&
(string.IsNullOrEmpty(agg.FieldPath) || agg.FieldPath == "*"))
? agg.FieldPath // COUNT(*) - leave as is
: $"0$:{agg.FieldPath}", // Base field - add prefix
Function = agg.Function,
Alias = agg.PropertyName
});
// Pass FilterExpression directly (Pro drops filterJson here — see SumRedbAsync).
var jsonResult = await ExecuteGroupedAggregateCoreAsync(groupFields, requests, cancellationToken);
// Parse result (first row, since no grouping)
if (jsonResult != null && jsonResult.RootElement.GetArrayLength() > 0)
{
var firstRow = jsonResult.RootElement[0];
return BuildAggregateRedbResultFromJson(selector, firstRow);
}
throw new InvalidOperationException("AggregateRedbAsync returned no results");
}
///
/// Parses AggregateRedbAsync expression for base IRedbObject fields
///
private List<(string PropertyName, string FieldPath, Aggregation.AggregateFunction Function)> ParseAggregateRedbExpression(
Expression> selector)
{
var result = new List<(string PropertyName, string FieldPath, Aggregation.AggregateFunction Function)>();
if (selector.Body is NewExpression newExpr)
{
for (int i = 0; i < newExpr.Arguments.Count; i++)
{
var propName = newExpr.Members?[i].Name ?? $"Item{i}";
var arg = newExpr.Arguments[i];
if (arg is MethodCallExpression methodCall && methodCall.Method.DeclaringType == typeof(Aggregation.Agg))
{
var funcName = methodCall.Method.Name;
var function = funcName switch
{
"Sum" => Aggregation.AggregateFunction.Sum,
"Average" => Aggregation.AggregateFunction.Average,
"Min" => Aggregation.AggregateFunction.Min,
"Max" => Aggregation.AggregateFunction.Max,
"Count" => Aggregation.AggregateFunction.Count,
_ => throw new NotSupportedException($"Unknown aggregation: {funcName}")
};
// Extract base field path (without Props!)
string fieldPath = "*"; // for Count()
if (methodCall.Arguments.Count > 0)
{
// For IRedbObject: extract property name directly
if (methodCall.Arguments[0] is MemberExpression member)
{
fieldPath = member.Member.Name; // Id, ValueLong, DateCreate, etc.
}
}
result.Add((propName, fieldPath, function));
}
}
}
return result;
}
///
/// Builds AggregateRedbAsync result from JSON element
///
private TResult BuildAggregateRedbResultFromJson(
Expression> selector,
JsonElement jsonRow)
{
if (selector.Body is NewExpression newExpr && newExpr.Constructor != null)
{
var args = new object?[newExpr.Arguments.Count];
for (int i = 0; i < newExpr.Arguments.Count; i++)
{
var propName = newExpr.Members?[i].Name ?? $"Item{i}";
var targetType = newExpr.Constructor.GetParameters()[i].ParameterType;
object? value = null;
if (jsonRow.TryGetProperty(propName, out var jsonValue))
{
value = Query.Utils.JsonValueConverter.Convert(jsonValue, targetType);
}
args[i] = ConvertAggregateValue(value, targetType);
}
return (TResult)newExpr.Constructor.Invoke(args);
}
throw new ArgumentException("AggregateRedbAsync requires anonymous type creation (new { ... })", nameof(selector));
}
///
/// Creates aggregation result from dictionary of values
///
private TResult BuildAggregateResult(
Expression, TResult>> selector,
Dictionary results)
{
if (selector.Body is NewExpression newExpr && newExpr.Constructor != null)
{
var args = new object?[newExpr.Arguments.Count];
for (int i = 0; i < newExpr.Arguments.Count; i++)
{
var propName = newExpr.Members?[i].Name ?? $"Item{i}";
var targetType = newExpr.Constructor.GetParameters()[i].ParameterType;
results.TryGetValue(propName, out var value);
args[i] = ConvertAggregateValue(value, targetType);
}
return (TResult)newExpr.Constructor.Invoke(args);
}
throw new NotSupportedException("AggregateAsync supports only anonymous types");
}
private object? ConvertAggregateValue(object? value, Type targetType)
{
if (value == null)
{
return targetType.IsValueType ? Activator.CreateInstance(targetType) : null;
}
var underlying = Nullable.GetUnderlyingType(targetType) ?? targetType;
return underlying switch
{
Type t when t == typeof(int) => Convert.ToInt32(value),
Type t when t == typeof(long) => Convert.ToInt64(value),
Type t when t == typeof(decimal) => redb.Core.Utils.RedbDecimal.From(value),
Type t when t == typeof(double) => Convert.ToDouble(value),
Type t when t == typeof(float) => Convert.ToSingle(value),
_ => Utils.TemporalDecoder.ChangeType(value, underlying)
};
}
///
/// The field path of a single aggregate's selector, read by the walker of AggregateAsync: an element, a dictionary
/// entry and the Value of a nullable are read as such, and a path that is not a chain of fields is refused.
///
protected string ExtractFieldPath(Expression> selector)
=> Aggregation.AggregateSelectorParser.ExtractFieldPath(selector.Body);
///
/// Extracts base field path from IRedbObject expression
/// Used for *RedbAsync methods (SumRedbAsync, GroupByRedb, etc.)
///
protected string ExtractFieldPathRedb(Expression> selector)
{
var body = selector.Body;
// Handle Convert (for nullable types)
if (body is UnaryExpression unary && unary.NodeType == ExpressionType.Convert)
{
body = unary.Operand;
}
if (body is MemberExpression member)
{
// For IRedbObject: just property name (Id, Name, ValueLong, etc.)
return member.Member.Name;
}
throw new ArgumentException("Cannot extract field path from IRedbObject selector", nameof(selector));
}
///
/// Builds JSON filter from current query context
///
protected virtual string? BuildFilterJson()
{
if (_context.Filter == null || _facetBuilder == null)
return null;
var json = _facetBuilder.BuildFacetFilters(_context.Filter);
return string.IsNullOrEmpty(json) || json == "{}" ? null : json;
}
// ===== GROUPBY =====
///
/// Grouping with aggregations.
/// Pro version receives FilterExpression directly for proper SQL compilation.
///
public virtual Grouping.IRedbGroupedQueryable GroupBy(
Expression> keySelector)
{
// Pass FilterExpression directly (Pro uses it, Free falls back to facet-JSON)
return new Grouping.RedbGroupedQueryable(
_provider, _context.SchemeId, _context.Filter, keySelector);
}
///
/// Grouping by base IRedbObject fields (id, scheme_id, parent_id, etc.)
/// Uses IRedbObject for compile-time safety - Props not visible!
/// Pro version receives FilterExpression directly for proper SQL compilation.
///
public virtual Grouping.IRedbGroupedQueryable GroupByRedb(
Expression> keySelector)
{
// Pass FilterExpression directly (Pro uses it, Free falls back to facet-JSON)
return new Grouping.RedbGroupedQueryable(
_provider, _context.SchemeId, _context.Filter, keySelector, isBaseFieldGrouping: true);
}
///
/// Grouping by array elements
///
public virtual Grouping.IRedbGroupedQueryable GroupByArray(
Expression>> arraySelector,
Expression> keySelector)
{
return new Grouping.RedbArrayGroupedQueryable(
_provider, _context.SchemeId, null, _context.Filter, arraySelector, keySelector);
}
// ===== WINDOW FUNCTIONS =====
///
/// Query with window functions.
/// Pro version receives FilterExpression directly for proper SQL compilation.
///
public virtual Window.IRedbWindowedQueryable WithWindow(
Action> windowConfig)
{
var windowSpec = new Window.WindowSpec();
windowConfig(windowSpec);
// Pass FilterExpression directly (Pro uses it, Free falls back to facet-JSON)
return new Window.RedbWindowedQueryable(
_provider, _context.SchemeId, _context.Filter, windowSpec, _context.Limit, _context.Offset);
}
// ===== SQL PREVIEW (like EF Core) =====
///
/// Get SQL representation of query (for debugging).
/// Analog of EF Core ToQueryString().
/// Pro version shows PVT SQL, Open Source - redb_json_objects.
/// Note: Uses Task.Run to avoid SynchronizationContext deadlock in Blazor/ASP.NET.
///
public virtual string ToSqlString()
{
// Use Task.Run to avoid Blazor SynchronizationContext deadlock
return Task.Run(() => _provider.GetSqlPreviewAsync(_context)).GetAwaiter().GetResult();
}
///
/// Async version of getting SQL (recommended)
///
public virtual Task ToSqlStringAsync(CancellationToken cancellationToken = default)
{
return _provider.GetSqlPreviewAsync(_context, cancellationToken: cancellationToken);
}
///
/// Get JSON filter that will be sent to SQL function (for diagnostics)
///
public virtual Task ToFilterJsonAsync(CancellationToken cancellationToken = default)
{
return _provider.GetFilterJsonAsync(_context, cancellationToken: cancellationToken);
}
private string BuildOrderByJson()
{
if (!_context.Orderings.Any())
return "[]";
var orders = _context.Orderings.Select(o => new {
field = o.Property.Name,
dir = o.Direction.ToString().ToUpper()
});
return System.Text.Json.JsonSerializer.Serialize(orders);
}
}