Path: redb/redb.Core/Query/Base/TreeQueryableBase.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Core/Query/Base/TreeQueryableBase.cs ---- using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using redb.Core.Models.Entities; using redb.Core.Models.Contracts; using redb.Core.Query.QueryExpressions; using redb.Core.Query.FacetFilters; using redb.Core.Caching; namespace redb.Core.Query.Base; /// /// Base tree queryable for hierarchical LINQ queries. /// Extends RedbQueryable with tree operation support. /// public class TreeQueryableBase : RedbQueryable where TProps : class, new() { protected readonly ITreeQueryProvider _treeProvider; internal ITreeQueryProvider TreeProvider => _treeProvider; protected readonly TreeQueryContext _treeContext; private readonly IFacetFilterBuilder _facetBuilder; public TreeQueryableBase( ITreeQueryProvider provider, TreeQueryContext context, IFilterExpressionParser filterParser, IOrderingExpressionParser orderingParser, IFacetFilterBuilder? facetBuilder = null) : base(provider, context, filterParser, orderingParser) { _treeProvider = provider; _treeContext = context; _facetBuilder = facetBuilder ?? new FacetFilterBuilder(); } /// /// Creates a new instance with the specified context. Override in derived classes. /// protected virtual TreeQueryableBase CreateInstance(TreeQueryContext context) { return new TreeQueryableBase(_treeProvider, context, _filterParser, _orderingParser, _facetBuilder); } // ===== TREE BASE METHODS OVERRIDE ===== public override IRedbQueryable Where(Expression> predicate) { var newContext = _treeContext.Clone(); var filterExpression = _filterParser.ParseFilter(predicate); // FIX: Check for empty filter (Where(x => false)) if (IsEmptyFilter(filterExpression)) { newContext.IsEmpty = true; } // If there's already a filter, combine with AND if (newContext.Filter != null) { newContext.Filter = new LogicalExpression( LogicalOperator.And, new[] { newContext.Filter, filterExpression } ); } else { newContext.Filter = filterExpression; } // FIX: Return PostgresTreeQueryable, not base RedbQueryable return CreateInstance(newContext); } public override IRedbQueryable WhereRedb(Expression> predicate) { if (predicate == null) throw new ArgumentNullException(nameof(predicate)); var newContext = _treeContext.Clone(); var filterExpression = _filterParser.ParseRedbFilter(predicate); // Check for empty filter if (IsEmptyFilter(filterExpression)) { newContext.IsEmpty = true; } // If there's already a filter, combine with AND if (newContext.Filter != null) { newContext.Filter = new LogicalExpression( LogicalOperator.And, new[] { newContext.Filter, filterExpression } ); } else { newContext.Filter = filterExpression; } return CreateInstance(newContext); } // ===== OVERRIDE SORTING METHODS TO PRESERVE TREE CONTEXT ===== /// /// FIX ISSUE #4: Override OrderBy to preserve Tree context /// Base OrderBy returns RedbQueryable and loses Tree context! /// RETURNS: IOrderedTreeQueryable (inherits from IOrderedRedbQueryable + preserves Tree methods) /// public override IOrderedRedbQueryable OrderBy(Expression> keySelector) { var newContext = _treeContext.Clone(); newContext.Orderings.Clear(); // OrderBy replaces previous sorting var ordering = _orderingParser.ParseOrdering(keySelector, SortDirection.Ascending); newContext.Orderings.Add(ordering); // CORRECT: PostgresTreeQueryable implements IOrderedTreeQueryable : IOrderedRedbQueryable // Return as IOrderedRedbQueryable, but actually it's PostgresTreeQueryable! return CreateInstance(newContext); } /// /// FIX ISSUE #4: Override OrderByDescending for Tree context /// public override IOrderedRedbQueryable OrderByDescending(Expression> keySelector) { var newContext = _treeContext.Clone(); newContext.Orderings.Clear(); // OrderByDescending replaces previous sorting var ordering = _orderingParser.ParseOrdering(keySelector, SortDirection.Descending); newContext.Orderings.Add(ordering); // FIX: Return PostgresTreeQueryable, preserving Tree context! return CreateInstance(newContext); } /// /// FIX ISSUE #4: Override ThenBy for Tree context /// public override IOrderedRedbQueryable ThenBy(Expression> keySelector) { var newContext = _treeContext.Clone(); var ordering = _orderingParser.ParseOrdering(keySelector, SortDirection.Ascending); newContext.Orderings.Add(ordering); // ThenBy adds to existing sorting // FIX: Return PostgresTreeQueryable, preserving Tree context! return CreateInstance(newContext); } /// /// FIX ISSUE #4: Override ThenByDescending for Tree context /// public override IOrderedRedbQueryable ThenByDescending(Expression> keySelector) { var newContext = _treeContext.Clone(); var ordering = _orderingParser.ParseOrdering(keySelector, SortDirection.Descending); newContext.Orderings.Add(ordering); // ThenByDescending adds to existing sorting // FIX: Return PostgresTreeQueryable, preserving Tree context! return CreateInstance(newContext); } // ═══════════════════════════════════════════════════════════════════════════ // SORTING BY BASE RedbObject FIELDS FOR TREE CONTEXT // ═══════════════════════════════════════════════════════════════════════════ public override IOrderedRedbQueryable OrderByRedb(Expression> keySelector) { var newContext = _treeContext.Clone(); newContext.Orderings.Clear(); var ordering = _orderingParser.ParseRedbOrdering(keySelector, SortDirection.Ascending); newContext.Orderings.Add(ordering); return CreateInstance(newContext); } public override IOrderedRedbQueryable OrderByDescendingRedb(Expression> keySelector) { var newContext = _treeContext.Clone(); newContext.Orderings.Clear(); var ordering = _orderingParser.ParseRedbOrdering(keySelector, SortDirection.Descending); newContext.Orderings.Add(ordering); return CreateInstance(newContext); } public override IOrderedRedbQueryable ThenByRedb(Expression> keySelector) { var newContext = _treeContext.Clone(); var ordering = _orderingParser.ParseRedbOrdering(keySelector, SortDirection.Ascending); newContext.Orderings.Add(ordering); return CreateInstance(newContext); } public override IOrderedRedbQueryable ThenByDescendingRedb(Expression> keySelector) { var newContext = _treeContext.Clone(); var ordering = _orderingParser.ParseRedbOrdering(keySelector, SortDirection.Descending); newContext.Orderings.Add(ordering); return CreateInstance(newContext); } /// V4 (LAZY Л2): preserve the tree context (the base method would drop it). public override IRedbQueryable WithLazyReferences(bool enabled = true) { var newContext = _treeContext.Clone(); newContext.LazyReferences = enabled; return CreateInstance(newContext); } // ===== TREE FILTERS ===== /// /// The scheme of the target type of WhereHasAncestor / WhereHasDescendant, found as Query<T>() finds it: the /// metadata cache, then the database. A type the database has no scheme for fails here, as Query<T>() fails for /// it: Pro dropped the filter and returned every node, Free ran into a removed legacy path. /// private long RequireTargetSchemeId(string filterName) { var schemeId = _treeProvider is TreeQueryProviderBase provider ? provider.ResolveSchemeIdByType(typeof(TTarget)) : _treeProvider.Cache.GetSchemeIdByClrType(typeof(TTarget)); if (schemeId is null or 0) throw new InvalidOperationException( $"{filterName}<{typeof(TTarget).Name}>: scheme for type '{typeof(TTarget).Name}' not found. " + "Ensure the type is a [RedbScheme] class and InitializeAsync() was called at startup."); return schemeId.Value; } /// /// Filter by ancestors with polymorphic query support /// public override IRedbQueryable WhereHasAncestor( Expression> ancestorCondition, int? maxDepth = null) { if (ancestorCondition == null) throw new ArgumentNullException(nameof(ancestorCondition)); if (maxDepth.HasValue && maxDepth.Value < 1) throw new ArgumentException("maxDepth must be >= 1", nameof(maxDepth)); var newContext = _treeContext.Clone(); var targetSchemeId = RequireTargetSchemeId(nameof(WhereHasAncestor)); // Parse ancestor condition and add tree filter var filterExpression = _filterParser.ParseFilter(ancestorCondition); var ancestorFilter = new TreeFilter(TreeFilterOperator.HasAncestor) { FilterConditions = ConvertFilterToJson(filterExpression), OriginalFilter = filterExpression, // Pro: for ProSqlBuilder MaxDepth = maxDepth, TargetSchemeId = targetSchemeId }; newContext.TreeFilters.Add(ancestorFilter); return CreateInstance(newContext); } /// /// Filter by descendants with polymorphic query support /// public override IRedbQueryable WhereHasDescendant( Expression> descendantCondition, int? maxDepth = null) { if (descendantCondition == null) throw new ArgumentNullException(nameof(descendantCondition)); if (maxDepth.HasValue && maxDepth.Value < 1) throw new ArgumentException("maxDepth must be >= 1", nameof(maxDepth)); var newContext = _treeContext.Clone(); var targetSchemeId = RequireTargetSchemeId(nameof(WhereHasDescendant)); // Parse descendant condition and add tree filter var filterExpression = _filterParser.ParseFilter(descendantCondition); var descendantFilter = new TreeFilter(TreeFilterOperator.HasDescendant) { FilterConditions = ConvertFilterToJson(filterExpression), OriginalFilter = filterExpression, // Pro: for ProSqlBuilder MaxDepth = maxDepth, TargetSchemeId = targetSchemeId }; newContext.TreeFilters.Add(descendantFilter); return CreateInstance(newContext); } public override IRedbQueryable WhereLevel(int level) { var newContext = _treeContext.Clone(); var levelFilter = new TreeFilter(TreeFilterOperator.Level, level); newContext.TreeFilters.Add(levelFilter); return CreateInstance(newContext); } public override IRedbQueryable WhereLevel(Expression> levelCondition) { if (levelCondition == null) throw new ArgumentNullException(nameof(levelCondition)); var newContext = _treeContext.Clone(); var levelFilter = new TreeFilter(TreeFilterOperator.Level); // Analyze level condition (e.g.: level => level > 2) levelFilter.FilterConditions = ParseLevelCondition(levelCondition); newContext.TreeFilters.Add(levelFilter); return CreateInstance(newContext); } public override IRedbQueryable WhereRoots() { var newContext = _treeContext.Clone(); var rootFilter = new TreeFilter(TreeFilterOperator.IsRoot); newContext.TreeFilters.Add(rootFilter); return CreateInstance(newContext); } public override IRedbQueryable WhereLeaves() { var newContext = _treeContext.Clone(); var leafFilter = new TreeFilter(TreeFilterOperator.IsLeaf); newContext.TreeFilters.Add(leafFilter); return CreateInstance(newContext); } public override IRedbQueryable WhereChildrenOf(long parentId) { var newContext = _treeContext.Clone(); var childrenFilter = new TreeFilter(TreeFilterOperator.ChildrenOf, parentId); newContext.TreeFilters.Add(childrenFilter); return CreateInstance(newContext); } public override IRedbQueryable WhereChildrenOf(IRedbObject parentObject) { if (parentObject == null) throw new ArgumentNullException(nameof(parentObject)); return WhereChildrenOf(parentObject.Id); } public override IRedbQueryable WhereDescendantsOf(long ancestorId, int? maxDepth = null) { var newContext = _treeContext.Clone(); var descendantsFilter = new TreeFilter(TreeFilterOperator.DescendantsOf, ancestorId) { MaxDepth = maxDepth }; newContext.TreeFilters.Add(descendantsFilter); return CreateInstance(newContext); } public override IRedbQueryable WhereDescendantsOf(IRedbObject ancestorObject, int? maxDepth = null) { if (ancestorObject == null) throw new ArgumentNullException(nameof(ancestorObject)); return WhereDescendantsOf(ancestorObject.Id, maxDepth); } // ===== MATERIALIZATION METHODS ===== /// /// Execute query and get list of objects (base RedbObject) /// TreeRedbObject inherits from RedbObject, so direct casting works /// public override async Task>> ToListAsync(CancellationToken cancellationToken = default) { // Get TreeRedbObject and cast to RedbObject (they are compatible) var treeObjects = await ToFlatListAsync(cancellationToken: cancellationToken); return treeObjects.Cast>().ToList(); } internal override RedbQueryable CloneForProjection() => CreateInstance(_treeContext.Clone()); /// /// Override ToListWithProjectionAsync for correct type conversion. /// Tree provider returns List<TreeRedbObject>, need Cast to List<RedbObject>. /// protected internal override async Task>> ToListWithProjectionAsync( HashSet? projectedStructureIds, bool skipPropsLoading = false, CancellationToken cancellationToken = default) { // Set structure_ids in context for provider if (projectedStructureIds != null && projectedStructureIds.Count > 0) { _treeContext.ProjectedStructureIds = projectedStructureIds; } _treeContext.ProjectionReadsNoProps = projectedStructureIds is { Count: 0 }; if (skipPropsLoading) { // FIX: Same logic as RedbQueryable.ToListWithProjectionAsync. // Skip Props re-loading and disable lazy loader — projection SQL already // returned partial Props in the JSON, deserialized via Props setter. _treeContext.SkipPropsLoading = true; } // Get TreeRedbObject and cast to RedbObject via Cast var treeObjects = await ToFlatListAsync(cancellationToken: cancellationToken); return treeObjects.Cast>().ToList(); } public override async Task?> FirstOrDefaultAsync(CancellationToken cancellationToken = default) { // Limit to 1 record var limitedQuery = Take(1); var results = await limitedQuery.ToListAsync(cancellationToken: cancellationToken); return results.FirstOrDefault(); } public override IRedbQueryable Take(int count) { if (count < 0) throw new ArgumentException("Take count must be non-negative", nameof(count)); var newContext = _treeContext.Clone(); newContext.Limit = count; // FIX: Return PostgresTreeQueryable, preserving Tree context! return CreateInstance(newContext); } public override IRedbQueryable Skip(int count) { if (count < 0) throw new ArgumentException("Skip count must be non-negative", nameof(count)); var newContext = _treeContext.Clone(); newContext.Offset = count; // FIX: Return PostgresTreeQueryable, preserving Tree context! return CreateInstance(newContext); } public override IRedbQueryable WhereIn(Expression> selector, IEnumerable values) { if (selector == null) throw new ArgumentNullException(nameof(selector)); if (values == null) throw new ArgumentNullException(nameof(values)); var valuesList = values.ToList(); if (!valuesList.Any()) { // If list is empty, return query that finds nothing return Where(_ => false); } // Create expression: x => values.Contains(selector(x)) var parameter = selector.Parameters[0]; var selectorBody = selector.Body; // Create constant with list of values var valuesConstant = Expression.Constant(valuesList); // Create Contains call var containsMethod = typeof(List).GetMethod("Contains", new[] { typeof(TValue) }); var containsCall = Expression.Call(valuesConstant, containsMethod!, selectorBody); // Create lambda expression var lambda = Expression.Lambda>(containsCall, parameter); return Where(lambda); } public override IRedbQueryable WhereInRedb(Expression> selector, IEnumerable values) { if (selector == null) throw new ArgumentNullException(nameof(selector)); if (values == null) throw new ArgumentNullException(nameof(values)); var valuesList = values.ToList(); if (!valuesList.Any()) { // Empty list = finds nothing return WhereRedb(_ => false); } // Create expression: x => values.Contains(selector(x)) var parameter = selector.Parameters[0]; var selectorBody = selector.Body; // Create constant with list of values var valuesConstant = Expression.Constant(valuesList); // Create Contains call var containsMethod = typeof(List).GetMethod("Contains", new[] { typeof(TValue) }); var containsCall = Expression.Call(valuesConstant, containsMethod!, selectorBody); // Create lambda expression for IRedbObject var lambda = Expression.Lambda>(containsCall, parameter); return WhereRedb(lambda); } public override IRedbQueryable Distinct() { var newContext = _treeContext.Clone(); newContext.IsDistinct = true; // FIX: Return PostgresTreeQueryable, preserving Tree context! return CreateInstance(newContext); } public override IRedbQueryable DistinctRedb() { var newContext = _treeContext.Clone(); newContext.IsDistinctRedb = true; return CreateInstance(newContext); } public override IRedbQueryable DistinctBy(Expression> keySelector) { if (keySelector == null) throw new ArgumentNullException(nameof(keySelector)); var newContext = _treeContext.Clone(); var ordering = _orderingParser.ParseOrdering(keySelector, SortDirection.Ascending); newContext.DistinctByField = ordering; newContext.DistinctByIsBaseField = false; // The ordering by the key goes first, once, in the direction the query gave it. newContext.PutDistinctKeyFirst(ordering); return CreateInstance(newContext); } public override IRedbQueryable DistinctByRedb(Expression> keySelector) { if (keySelector == null) throw new ArgumentNullException(nameof(keySelector)); var newContext = _treeContext.Clone(); var ordering = _orderingParser.ParseRedbOrdering(keySelector, SortDirection.Ascending); newContext.DistinctByField = ordering; newContext.DistinctByIsBaseField = true; // The ordering by the key goes first, once, in the direction the query gave it. newContext.PutDistinctKeyFirst(ordering); return CreateInstance(newContext); } public override IRedbQueryable WithMaxRecursionDepth(int depth) { if (depth < 1) throw new ArgumentException("Max recursion depth must be positive", nameof(depth)); var newContext = _treeContext.Clone(); newContext.MaxRecursionDepth = depth; // FIX: Return PostgresTreeQueryable, preserving Tree context! return CreateInstance(newContext); } /// Same contract as the flat query: the rows ToListAsync returns, Take and Skip included. public override async Task CountAsync(CancellationToken cancellationToken = default) { if (!IsPaged(_treeContext)) return await CountWholeTreeSetAsync(cancellationToken); var unpaged = _treeContext.Clone(); unpaged.Limit = null; unpaged.Offset = null; var total = await CreateInstance(unpaged).CountWholeTreeSetAsync(cancellationToken); return PagedCount(total, _treeContext.Offset, _treeContext.Limit); } private async Task CountWholeTreeSetAsync(CancellationToken cancellationToken) { var result = await _treeProvider.ExecuteAsync(BuildCountExpression(), typeof(int), cancellationToken: cancellationToken); return (int)result; } public override async Task AnyAsync(CancellationToken cancellationToken = default) { // A paged query has rows only if the page has: Take(0) has none, Skip(n) only past the n-th. if (IsPaged(_treeContext)) return await CountAsync(cancellationToken: cancellationToken) > 0; // Asked of the provider as its own operation, as in the flat query: one that can stop at the first node does // not count the whole subtree. var result = await _treeProvider.ExecuteAsync(BuildCountExpression(), typeof(bool), cancellationToken: cancellationToken); return (bool)result; } public override async Task AnyAsync(Expression> predicate, CancellationToken cancellationToken = default) { // Create new query with additional filter var filteredQuery = Where(predicate); return await filteredQuery.AnyAsync(cancellationToken: cancellationToken); } public override async Task AllAsync(Expression> predicate, CancellationToken cancellationToken = default) { if (predicate == null) throw new ArgumentNullException(nameof(predicate)); // All() == true if all records satisfy condition. Counts of the whole set, as in the flat query. var totalCount = await CountWholeTreeSetAsync(cancellationToken); if (totalCount == 0) return true; // All elements of empty set satisfy any condition var matching = Where(predicate); var matchingCount = matching is TreeQueryableBase tree ? await tree.CountWholeTreeSetAsync(cancellationToken) : await matching.CountAsync(cancellationToken: cancellationToken); return totalCount == matchingCount; } // ===== TREE-SPECIFIC METHODS ===== /// /// Execute query and return filtered objects with populated Parent/Children chains /// Loads objects + all parents to root and establishes links /// Children contain only objects from the loaded chain /// public override async Task>> ToTreeListAsync(CancellationToken cancellationToken = default) { // 1. Get filtered objects (with Props via lazy loading) var filteredObjects = await ToFlatListAsync(cancellationToken: cancellationToken); if (!filteredObjects.Any()) return new List>(); var filteredIds = filteredObjects.Select(o => o.id).ToList(); // 2. Get IDs of all parents to root var allIds = await _treeProvider.GetIdsWithAncestorsAsync(filteredIds, cancellationToken); // 3. FIX: Calculate IDs of ONLY parents (that aren't already loaded) var parentIds = allIds.Except(filteredIds).ToList(); List allObjectsUntyped; if (parentIds.Any()) { // 4. Load ONLY parents (don't reload children!) var parents = await _treeProvider.LoadObjectsByIdsAsync(parentIds, _treeContext.PropsDepth, cancellationToken: cancellationToken); // 5. Combine parents with already loaded children allObjectsUntyped = parents .Concat(filteredObjects.Cast()) .ToList(); } else { // No parents (all objects are root) - use only filteredObjects allObjectsUntyped = filteredObjects.Cast().ToList(); } // 6. Establish Parent/Children relationships BuildRelationshipsUntyped(allObjectsUntyped); // 7. Return only filtered objects (filter by TProps type). A set: Contains on the list was a scan per object, // quadratic over a large subtree. var filteredIdSet = filteredIds.ToHashSet(); var matchingByIdAndType = allObjectsUntyped .Where(o => filteredIdSet.Contains(o.Id) && o is TreeRedbObject) .Cast>() .ToList(); return matchingByIdAndType; } /// /// Execute query and get list of tree root nodes /// Loads objects + all parents to root, establishes links and returns roots /// Children contain only objects from the loaded chain /// public override async Task> ToRootListAsync(CancellationToken cancellationToken = default) { // 1. Get filtered objects (with Props via lazy loading) var filteredObjects = await ToFlatListAsync(cancellationToken: cancellationToken); if (!filteredObjects.Any()) return new List(); var filteredIds = filteredObjects.Select(o => o.id).ToList(); // 2. Get IDs of all parents to root var allIds = await _treeProvider.GetIdsWithAncestorsAsync(filteredIds, cancellationToken); // 3. FIX: Calculate IDs of ONLY parents (that aren't already loaded) var parentIds = allIds.Except(filteredIds).ToList(); List allObjects; if (parentIds.Any()) { // 4. Load ONLY parents var parents = await _treeProvider.LoadObjectsByIdsAsync(parentIds, _treeContext.PropsDepth, cancellationToken: cancellationToken); // 5. Combine parents with already loaded children allObjects = parents .Concat(filteredObjects.Cast()) .ToList(); } else { // No parents - use only filteredObjects allObjects = filteredObjects.Cast().ToList(); } // 6. Establish Parent/Children relationships BuildRelationshipsUntyped(allObjects); // 7. Return roots (ParentId == null) return allObjects.Where(o => o.ParentId == null).ToList(); } /// /// Execute query and get flat list of tree objects /// public override async Task>> ToFlatListAsync(CancellationToken cancellationToken = default) { // Execute query through provider var expression = BuildTreeExpression(); var result = await _treeProvider.ExecuteAsync(expression, typeof(List>), cancellationToken: cancellationToken); var list = (List>)result; return list; } /// /// NEW METHOD: Determines if filter is empty (Where(x => false)) /// private bool IsEmptyFilter(FilterExpression filter) { // Check for constant false filter (created for Where(x => false)) if (filter is ComparisonExpression comparison && comparison.Property.Name == "__constant" && comparison.Property.Type == typeof(bool) && comparison.Operator == ComparisonOperator.Equal && comparison.Value is bool boolValue && boolValue == false) { return true; } return false; } // ===== LINQ METHODS ARE INHERITED FROM BASE CLASS ===== // REMOVED all duplicated Where/OrderBy/Take/Skip/Distinct methods! // Using logic from RedbQueryable - WITHOUT DUPLICATION! /// /// Configure maximum search depth in tree /// public override IRedbQueryable WithMaxDepth(int depth) { if (depth < 1) throw new ArgumentException("Max depth must be positive", nameof(depth)); return CreateInstance(_treeContext.CloneWithMaxDepth(depth)); } /// /// Configure maximum depth for loading nested RedbObject in Props /// public override IRedbQueryable WithPropsDepth(int depth) { if (depth < 1) throw new ArgumentException("Props depth must be positive", nameof(depth)); var newContext = _treeContext.Clone(); newContext.PropsDepth = depth; return CreateInstance(newContext); } public IRedbProjectedQueryable Select(Expression, TResult>> selector) { return new TreeProjectedQueryable(this, selector); } // ===== HELPER METHODS ===== /// /// Build expression for tree query /// protected virtual Expression BuildTreeExpression() { return Expression.Constant(_treeContext); } /// /// Converts FilterExpression to JSON dictionary. /// Uses FacetFilterBuilder for full operator support. /// private Dictionary ConvertFilterToJson(FilterExpression filter) { // Uses FacetFilterBuilder for full operator support var facetFiltersJson = _facetBuilder.BuildFacetFilters(filter); if (facetFiltersJson == "{}") return new Dictionary(); // Parse JSON back to Dictionary var result = System.Text.Json.JsonSerializer.Deserialize>(facetFiltersJson); return result ?? new Dictionary(); } /// /// Parse level condition (e.g.: level => level > 2) /// private Dictionary ParseLevelCondition(Expression> levelCondition) { // Simplified parsing - analyze lambda body if (levelCondition.Body is BinaryExpression binary) { switch (binary.NodeType) { case ExpressionType.GreaterThan: if (binary.Right is ConstantExpression gtConstant) return new Dictionary { ["$gt"] = gtConstant.Value! }; break; case ExpressionType.LessThan: if (binary.Right is ConstantExpression ltConstant) return new Dictionary { ["$lt"] = ltConstant.Value! }; break; case ExpressionType.GreaterThanOrEqual: if (binary.Right is ConstantExpression gteConstant) return new Dictionary { ["$gte"] = gteConstant.Value! }; break; case ExpressionType.LessThanOrEqual: if (binary.Right is ConstantExpression lteConstant) return new Dictionary { ["$lte"] = lteConstant.Value! }; break; case ExpressionType.Equal: if (binary.Right is ConstantExpression eqConstant) return new Dictionary { ["$eq"] = eqConstant.Value! }; break; } } // Fallback - return equality 0 (root level) return new Dictionary { ["$eq"] = 0 }; } /// /// Establish Parent/Children relationships between loaded objects /// Does not filter objects - only establishes bidirectional links /// private void BuildRelationships(List> objects) { if (!objects.Any()) return; // Create dictionary for fast lookup by ID var objectDict = objects.ToDictionary(obj => obj.id, obj => obj); // Establish relationships for all objects foreach (var obj in objects) { // Clear Children in case of repeated call obj.Children.Clear(); obj.Parent = null; // If parent exists and is in list - establish relationship if (obj.parent_id.HasValue && objectDict.TryGetValue(obj.parent_id.Value, out var parent)) { obj.Parent = parent; parent.Children.Add(obj); } } } /// /// Build Parent/Children relationships for untyped objects /// Used for polymorphic trees in ToRootListAsync /// private void BuildRelationshipsUntyped(List objects) { if (!objects.Any()) return; // Create dictionary for fast lookup by ID var objectDict = objects.ToDictionary(obj => obj.Id, obj => obj); // Establish relationships for all objects foreach (var obj in objects) { // Clear Children in case of repeated call obj.Children.Clear(); obj.Parent = null; // If parent exists and is in list - establish relationship if (obj.ParentId.HasValue && objectDict.TryGetValue(obj.ParentId.Value, out var parent)) { obj.Parent = parent; parent.Children.Add(obj); } } } /// /// Delete objects without loading data /// Executes DELETE with filters from query /// public override async Task DeleteAsync(CancellationToken cancellationToken = default) { // 1. Get list of objects by filter var objects = await ToListAsync(cancellationToken: cancellationToken); if (objects.Count == 0) return 0; // 2. Extract object IDs var objectIds = objects.Select(o => o.Id).ToArray(); // 3. Delete through provider return await _treeProvider.ExecuteTreeDeleteAsync(objectIds, cancellationToken: cancellationToken); } /// /// Override GroupBy to respect tree context (rootObjectId, maxDepth, ParentIds). /// Returns TreeGroupedQueryable that uses tree-aware execution. /// public override Grouping.IRedbGroupedQueryable GroupBy( Expression> keySelector) { // Return tree-aware grouped queryable that has access to TreeQueryContext return new Grouping.TreeGroupedQueryable( _treeProvider, _treeContext, keySelector, BuildFilterJson()); } /// /// Override GroupByRedb to respect tree context. /// public override Grouping.IRedbGroupedQueryable GroupByRedb( Expression> keySelector) { return new Grouping.TreeGroupedQueryable( _treeProvider, _treeContext, keySelector, BuildFilterJson(), isBaseFieldGrouping: true); } /// /// Override GroupByArray to respect tree context: only the elements of the objects of the subtree are grouped. /// public override Grouping.IRedbGroupedQueryable GroupByArray( Expression>> arraySelector, Expression> keySelector) { return new Grouping.RedbArrayGroupedQueryable( new Grouping.TreeArrayGroupRunner(_treeProvider, _treeContext.Clone()), _treeContext.SchemeId, filter: null, arraySelector, keySelector); } /// /// Override WithWindow to use tree-aware execution. /// Returns TreeWindowedQueryable that uses tree-aware execution with CTE. /// public override Window.IRedbWindowedQueryable WithWindow( Action> windowConfig) { var filterJson = BuildFilterJson(); var windowSpec = new Window.WindowSpec(); windowConfig(windowSpec); return new Window.TreeWindowedQueryable( _treeProvider, _treeContext, filterJson, windowSpec); } // ===== AGGREGATIONS ===== // // SumAsync, AverageAsync, MinAsync, MaxAsync, GetStatisticsAsync, AggregateAsync and their // *RedbAsync counterparts all end in the three calls below. Left to the flat provider they // aggregated the whole scheme: the root, the depth limit and the tree filters of this query // never reached it. A tree aggregate is a tree GROUP BY with no group fields, so all three go // through the same call GroupBy already uses, and return its single row. /// protected override async Task ExecuteGroupedAggregateCoreAsync( IEnumerable groupFields, IEnumerable aggregations, CancellationToken cancellationToken) => await _treeProvider.ExecuteTreeGroupedAggregateAsync( _treeContext, groupFields, aggregations, havingJson: null, cancellationToken: cancellationToken); /// protected override async Task ExecuteAggregateBatchCoreAsync( IEnumerable requests, CancellationToken cancellationToken) { var requestList = requests.ToList(); var result = new Aggregation.AggregateResult(); using var json = await _treeProvider.ExecuteTreeGroupedAggregateAsync( _treeContext, Array.Empty(), requestList, havingJson: null, cancellationToken: cancellationToken); var row = json != null && json.RootElement.GetArrayLength() > 0 ? json.RootElement[0] : (System.Text.Json.JsonElement?)null; foreach (var request in requestList) { object? value = null; if (row.HasValue && row.Value.TryGetProperty(request.Alias, out var element)) { value = element.ValueKind switch { System.Text.Json.JsonValueKind.Number => element.GetDecimal(), System.Text.Json.JsonValueKind.String => element.GetString(), System.Text.Json.JsonValueKind.True => true, System.Text.Json.JsonValueKind.False => false, _ => null }; } result.Values[request.Alias] = value; } return result; } /// protected override async Task ExecuteAggregateCoreAsync( string fieldPath, Aggregation.AggregateFunction function, CancellationToken cancellationToken) { const string alias = "result"; var batch = await ExecuteAggregateBatchCoreAsync( [new Aggregation.AggregateRequest { FieldPath = fieldPath, Function = function, Alias = alias }], cancellationToken); return batch.Values.TryGetValue(alias, out var value) && value != null ? redb.Core.Utils.RedbDecimal.From(value) : null; } }