Path: redb/redb.Core/Query/Base/TreeQueryProviderBase.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/TreeQueryProviderBase.cs ---- using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text.Encodings.Web; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using redb.Core.Data; using redb.Core.Models.Configuration; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using redb.Core.Providers; using redb.Core.Query.Aggregation; using redb.Core.Query.FacetFilters; using redb.Core.Query.Parsing; #pragma warning disable CS0618 // Type or member is obsolete (internal calls into legacy ExecuteTreeToListAsync remain until full migration) using redb.Core.Query.QueryExpressions; using redb.Core.Serialization; using redb.Core.Utils; using redb.Core.Caching; namespace redb.Core.Query.Base; /// /// Base tree query provider for executing hierarchical LINQ queries via search_tree_objects_with_facets. /// Database-specific implementations should inherit and provide ISqlDialect. /// public abstract class TreeQueryProviderBase : ITreeQueryProvider, Grouping.IListItemKeySource { // The list provider of the service: the groupings read their list item keys through it (ListItemGroupKeys). IListProvider? Grouping.IListItemKeySource.ListItems { get; set; } protected readonly IRedbContext _context; protected readonly IRedbObjectSerializer _serializer; protected readonly IFilterExpressionParser _filterParser; protected readonly IOrderingExpressionParser _orderingParser; protected readonly IFacetFilterBuilder _facetBuilder; protected readonly ILogger? _logger; protected readonly ILazyPropsLoader? _lazyPropsLoader; protected readonly RedbServiceConfiguration _configuration; protected readonly ISqlDialect _sql; protected readonly ISchemeSyncProvider? _schemeSync; /// /// Metadata cache for this provider (domain-isolated). /// public GlobalMetadataCache Cache { get; } protected TreeQueryProviderBase( IRedbContext context, IRedbObjectSerializer serializer, ISqlDialect dialect, string? cacheDomain = null, ILazyPropsLoader? lazyPropsLoader = null, RedbServiceConfiguration? configuration = null, ILogger? logger = null, ISchemeSyncProvider? schemeSync = null) { _context = context; _serializer = serializer; _sql = dialect; _lazyPropsLoader = lazyPropsLoader; _configuration = configuration ?? new RedbServiceConfiguration(); _logger = logger; _schemeSync = schemeSync; Cache = new GlobalMetadataCache(cacheDomain ?? _configuration.GetEffectiveCacheDomain()); _filterParser = CreateFilterParser(); _orderingParser = CreateOrderingParser(); _facetBuilder = CreateFacetBuilder(); } /// /// The scheme id of a CLR type, found as Query<T>() finds it: the metadata cache, then the database through the /// scheme provider (a process that does not sync a scheme another one owns, a Tsak worker, meets it there on first /// use). Null when neither has it. The tree filters (WhereHasAncestor / WhereHasDescendant) read their target here; /// they read the cache alone, and failed for a scheme that existed in the database. /// internal long? ResolveSchemeIdByType(Type type) { var cached = Cache.GetSchemeIdByClrType(type); if (cached is > 0) return cached; if (_schemeSync == null) return null; // Task.Run as QueryableProviderBase.GetSchemeSync: no SynchronizationContext deadlock in Blazor or ASP.NET. var scheme = Task.Run(() => _schemeSync.GetSchemeByTypeAsync(type)).GetAwaiter().GetResult(); return scheme?.Id; } /// /// Creates filter expression parser. Override for Pro features. /// protected virtual IFilterExpressionParser CreateFilterParser() => new FilterExpressionParser(); /// /// Creates ordering expression parser. /// protected virtual IOrderingExpressionParser CreateOrderingParser() => new OrderingExpressionParser(); /// /// Creates facet filter builder. /// protected virtual IFacetFilterBuilder CreateFacetBuilder() => new FacetFilterBuilder(_logger); /// /// Creates query provider for delegation. Override in derived classes. /// protected abstract IRedbQueryProvider CreateQueryProvider(); /// /// Creates tree queryable instance. Override in derived classes. /// protected abstract IRedbQueryable CreateTreeQueryable(TreeQueryContext context) where TProps : class, new(); /// /// Check for Pro-only Distinct features (DistinctBy, DistinctByRedb, DistinctRedb). /// Throws NotSupportedException in Free version. /// /// /// The p_distinct_on argument of pvt_build_query_sql for a tree query - the same JSON the flat /// query passes. The Free tree providers used to pass none, and DistinctBy / DistinctByRedb on a tree returned /// every node. /// protected static string? BuildPvtDistinctOnJson(QueryContext context) where TProps : class, new() => QueryProviderBase.BuildPvtDistinctOnJson(context); protected virtual void CheckProOnlyDistinctFeatures(QueryContext context) where TProps : class, new() { // No-op: DistinctRedb / DistinctBy are evaluated downstream by the SQL builder. } // ===== IRedbQueryProvider IMPLEMENTATION (BASE FUNCTIONALITY) ===== public IRedbQueryable CreateQuery(long schemeId, long? userId = null, bool checkPermissions = false) where TProps : class, new() { // For regular queries create standard RedbQueryable // It reads through the v2-pvt module of the flat query provider var baseProvider = CreateQueryProvider(); return baseProvider.CreateQuery(schemeId, userId, checkPermissions); } // ===== AGGREGATIONS IMPLEMENTATION (delegate to QueryProviderBase) ===== // virtual for override in Pro version public virtual async Task ExecuteAggregateAsync(long schemeId, string fieldPath, AggregateFunction function, string? filterJson = null, CancellationToken cancellationToken = default) { var baseProvider = CreateQueryProvider(); return await baseProvider.ExecuteAggregateAsync(schemeId, fieldPath, function, filterJson); } public virtual async Task ExecuteAggregateAsync(long schemeId, string fieldPath, AggregateFunction function, QueryExpressions.FilterExpression? filter, CancellationToken cancellationToken = default) { var baseProvider = CreateQueryProvider(); return await baseProvider.ExecuteAggregateAsync(schemeId, fieldPath, function, filter); } public virtual async Task ExecuteAggregateBatchAsync(long schemeId, IEnumerable requests, string? filterJson = null, CancellationToken cancellationToken = default) { var baseProvider = CreateQueryProvider(); return await baseProvider.ExecuteAggregateBatchAsync(schemeId, requests, filterJson); } public virtual async Task ExecuteAggregateBatchAsync(long schemeId, IEnumerable requests, QueryExpressions.FilterExpression? filter, CancellationToken cancellationToken = default) { var baseProvider = CreateQueryProvider(); return await baseProvider.ExecuteAggregateBatchAsync(schemeId, requests, filter); } /// /// Get scheme by ID (for projections) - delegate to base provider /// public virtual async Task GetSchemeAsync(long schemeId, CancellationToken cancellationToken = default) { var baseProvider = CreateQueryProvider(); return await baseProvider.GetSchemeAsync(schemeId); } // ===== GROUPBY (delegate to QueryProviderBase) ===== // virtual for override in Pro version public virtual async Task ExecuteGroupedAggregateAsync( long schemeId, IEnumerable groupFields, IEnumerable aggregations, string? filterJson = null, string? havingJson = null, CancellationToken cancellationToken = default) { var baseProvider = CreateQueryProvider(); return await baseProvider.ExecuteGroupedAggregateAsync(schemeId, groupFields, aggregations, filterJson, havingJson); } /// /// Execute GroupBy aggregation with FilterExpression (Pro version). /// Delegates to QueryProvider. /// public virtual async Task ExecuteGroupedAggregateAsync( long schemeId, IEnumerable groupFields, IEnumerable aggregations, QueryExpressions.FilterExpression? filter, string? havingJson = null, CancellationToken cancellationToken = default) { var baseProvider = CreateQueryProvider(); return await baseProvider.ExecuteGroupedAggregateAsync(schemeId, groupFields, aggregations, filter, havingJson); } /// /// Array grouping without a tree: the flat provider answers it. /// public virtual Task ExecuteArrayGroupQueryAsync( redb.Core.Query.Grouping.ArrayGroupQuery query, CancellationToken cancellationToken = default) => CreateQueryProvider().ExecuteArrayGroupQueryAsync(query, cancellationToken); /// /// SQL of . /// public virtual Task GetArrayGroupQuerySqlAsync( redb.Core.Query.Grouping.ArrayGroupQuery query, CancellationToken cancellationToken = default) => CreateQueryProvider().GetArrayGroupQuerySqlAsync(query, cancellationToken); // ===== WINDOW FUNCTIONS (delegate to QueryProviderBase) ===== // virtual for override in Pro version public virtual async Task ExecuteWindowQueryAsync( long schemeId, IEnumerable selectFields, IEnumerable windowFuncs, IEnumerable partitionBy, IEnumerable orderBy, string? filterJson = null, string? frameJson = null, int? take = null, int? skip = null, CancellationToken cancellationToken = default) { var baseProvider = CreateQueryProvider(); return await baseProvider.ExecuteWindowQueryAsync(schemeId, selectFields, windowFuncs, partitionBy, orderBy, filterJson, frameJson, take, skip); } public virtual async Task ExecuteWindowQueryAsync( long schemeId, IEnumerable selectFields, IEnumerable windowFuncs, IEnumerable partitionBy, IEnumerable orderBy, QueryExpressions.FilterExpression? filter, string? frameJson = null, int? take = null, int? skip = null, CancellationToken cancellationToken = default) { var baseProvider = CreateQueryProvider(); return await baseProvider.ExecuteWindowQueryAsync(schemeId, selectFields, windowFuncs, partitionBy, orderBy, filter, frameJson, take, skip); } public virtual async Task GetWindowSqlPreviewAsync( long schemeId, IEnumerable selectFields, IEnumerable windowFuncs, IEnumerable partitionBy, IEnumerable orderBy, string? filterJson = null, string? frameJson = null, int? take = null, int? skip = null, CancellationToken cancellationToken = default) { var baseProvider = CreateQueryProvider(); return await baseProvider.GetWindowSqlPreviewAsync(schemeId, selectFields, windowFuncs, partitionBy, orderBy, filterJson, frameJson, take, skip); } // ===== GROUPED WINDOW (delegated to base provider) ===== public virtual Task ExecuteGroupedWindowQueryAsync( long schemeId, IEnumerable groupFields, IEnumerable aggregations, IEnumerable windowFuncs, IEnumerable partitionBy, IEnumerable orderBy, string? filterJson = null, string? havingJson = null, CancellationToken cancellationToken = default) => CreateQueryProvider().ExecuteGroupedWindowQueryAsync( schemeId, groupFields, aggregations, windowFuncs, partitionBy, orderBy, filterJson, havingJson, cancellationToken); public virtual Task ExecuteGroupedWindowQueryAsync( long schemeId, IEnumerable groupFields, IEnumerable aggregations, IEnumerable windowFuncs, IEnumerable partitionBy, IEnumerable orderBy, QueryExpressions.FilterExpression? filter, string? havingJson = null, CancellationToken cancellationToken = default) => CreateQueryProvider().ExecuteGroupedWindowQueryAsync( schemeId, groupFields, aggregations, windowFuncs, partitionBy, orderBy, filter, havingJson, cancellationToken); public virtual Task GetGroupedWindowSqlPreviewAsync( long schemeId, IEnumerable groupFields, IEnumerable aggregations, IEnumerable windowFuncs, IEnumerable partitionBy, IEnumerable orderBy, string? filterJson = null, string? havingJson = null, CancellationToken cancellationToken = default) => CreateQueryProvider().GetGroupedWindowSqlPreviewAsync( schemeId, groupFields, aggregations, windowFuncs, partitionBy, orderBy, filterJson, havingJson, cancellationToken); public virtual Task GetGroupedWindowSqlPreviewAsync( long schemeId, IEnumerable groupFields, IEnumerable aggregations, IEnumerable windowFuncs, IEnumerable partitionBy, IEnumerable orderBy, QueryExpressions.FilterExpression? filter, string? havingJson = null, CancellationToken cancellationToken = default) => CreateQueryProvider().GetGroupedWindowSqlPreviewAsync( schemeId, groupFields, aggregations, windowFuncs, partitionBy, orderBy, filter, havingJson, cancellationToken); public virtual Task GetGroupBySqlPreviewAsync( long schemeId, IEnumerable groupFields, IEnumerable aggregations, string? filterJson, string? havingJson = null, CancellationToken cancellationToken = default) => CreateQueryProvider().GetGroupBySqlPreviewAsync(schemeId, groupFields, aggregations, filterJson, havingJson, cancellationToken); public virtual Task GetGroupBySqlPreviewAsync( long schemeId, IEnumerable groupFields, IEnumerable aggregations, QueryExpressions.FilterExpression? filter, string? havingJson = null, CancellationToken cancellationToken = default) => CreateQueryProvider().GetGroupBySqlPreviewAsync(schemeId, groupFields, aggregations, filter, havingJson, cancellationToken); // ===== ITreeQueryProvider IMPLEMENTATION (TREE FUNCTIONALITY) ===== public IRedbQueryable CreateTreeQuery( long schemeId, long? userId = null, bool checkPermissions = false, long? rootObjectId = null, int? maxDepth = null ) where TProps : class, new() { var context = new TreeQueryContext(schemeId, userId, checkPermissions, rootObjectId, maxDepth); return CreateTreeQueryable(context); } // ===== QUERY EXECUTION ===== public async Task ExecuteAsync(Expression expression, Type elementType, CancellationToken cancellationToken = default) { // Extract context from expression if (expression is ConstantExpression constantExpr && constantExpr.Value != null) { // Determine operation type by elementType if (elementType == typeof(int)) { return await ExecuteCountAsyncGeneric(constantExpr.Value, cancellationToken); } else if (elementType == typeof(bool)) { return await ExecuteAnyAsyncGeneric(constantExpr.Value, cancellationToken); } else if (elementType.IsGenericType) { var genericType = elementType.GetGenericTypeDefinition(); if (genericType == typeof(List<>)) { // Determine result type (RedbObject or TreeRedbObject) var itemType = elementType.GetGenericArguments()[0]; if (itemType.IsGenericType && itemType.GetGenericTypeDefinition() == typeof(TreeRedbObject<>)) { return await ExecuteTreeToListAsyncGeneric(constantExpr.Value, cancellationToken); } else { return await ExecuteToListAsyncGeneric(constantExpr.Value, cancellationToken); } } } } throw new NotSupportedException($"Tree query expression type {expression.GetType().Name} with element type {elementType.Name} is not supported"); } // ===== COUNT QUERY EXECUTION ===== private async Task ExecuteCountAsyncGeneric(object contextObj, CancellationToken cancellationToken) { // Use reflection to call typed method // this.GetType() - support override in Pro version var contextType = contextObj.GetType(); if (contextType.IsGenericType && contextType.GetGenericTypeDefinition() == typeof(TreeQueryContext<>)) { // Tree query var propsType = contextType.GetGenericArguments()[0]; var method = this.GetType().GetMethod(nameof(ExecuteTreeCountAsync), System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); var genericMethod = method!.MakeGenericMethod(propsType); var task = (Task)genericMethod.Invoke(this, new object[] { contextObj, cancellationToken })!; return await task; } else if (contextType.IsGenericType && contextType.GetGenericTypeDefinition() == typeof(QueryContext<>)) { // Regular query - delegate to base provider var baseProvider = CreateQueryProvider(); return await (Task)typeof(QueryProviderBase) .GetMethod("ExecuteCountAsyncGeneric", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)! .Invoke(baseProvider, new object[] { contextObj, cancellationToken })!; } throw new NotSupportedException($"Unsupported context type: {contextType.Name}"); } // ===== ANY QUERY EXECUTION ===== private async Task ExecuteAnyAsyncGeneric(object contextObj, CancellationToken cancellationToken) { var contextType = contextObj.GetType(); if (contextType.IsGenericType && contextType.GetGenericTypeDefinition() == typeof(TreeQueryContext<>)) { // this.GetType(): the Pro provider overrides the method var propsType = contextType.GetGenericArguments()[0]; var method = this.GetType().GetMethod(nameof(ExecuteTreeAnyAsync), System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); var genericMethod = method!.MakeGenericMethod(propsType); return await (Task)genericMethod.Invoke(this, new object[] { contextObj, cancellationToken })!; } throw new NotSupportedException($"Unsupported context type for Any: {contextType.Name}"); } /// /// Is there at least one node the query returns (no Take or Skip: the queryable answers a page by its count). /// The default is the count compared with zero; a provider that can stop at the first node overrides it. /// protected virtual async Task ExecuteTreeAnyAsync(TreeQueryContext context, CancellationToken cancellationToken = default) where TProps : class, new() { #pragma warning disable CS0618 // the count is the default answer until a provider overrides this return await ExecuteTreeCountAsync(context, cancellationToken) > 0; #pragma warning restore CS0618 } /// /// The query cut to its first node, for : Take 1, and neither the /// ordering nor the distinct, which change which nodes come back but not whether any does. /// protected static TreeQueryContext FirstNodeProbe(TreeQueryContext context) where TProps : class, new() { var probe = context.Clone(); probe.Orderings = []; probe.IsDistinct = false; probe.IsDistinctRedb = false; probe.DistinctByField = null; probe.DistinctByIsBaseField = false; probe.Limit = 1; probe.Offset = null; return probe; } // ===== TOLIST QUERY EXECUTION ===== private async Task ExecuteToListAsyncGeneric(object contextObj, CancellationToken cancellationToken) { var contextType = contextObj.GetType(); if (contextType.IsGenericType && contextType.GetGenericTypeDefinition() == typeof(QueryContext<>)) { // Regular query - delegate to base provider var baseProvider = CreateQueryProvider(); return await (Task)typeof(QueryProviderBase) .GetMethod("ExecuteToListAsyncGeneric", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)! .Invoke(baseProvider, new object[] { contextObj, cancellationToken })!; } else if (contextType.IsGenericType && contextType.GetGenericTypeDefinition() == typeof(TreeQueryContext<>)) { // Tree query - use our method // this.GetType() - support override in Pro version var propsType = contextType.GetGenericArguments()[0]; var method = this.GetType().GetMethod(nameof(ExecuteTreeToListAsync), System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); var genericMethod = method!.MakeGenericMethod(propsType); var lazyOverride = (bool?)contextType.GetProperty("LazyReferences")?.GetValue(contextObj); return await LazyReferencesQueryScope.RunAsync(_context, _sql, _configuration, _logger, lazyOverride, () => (Task)genericMethod.Invoke(this, new object[] { contextObj, cancellationToken })!); } throw new NotSupportedException($"Unsupported context type for ToList: {contextType.Name}"); } private async Task ExecuteTreeToListAsyncGeneric(object contextObj, CancellationToken cancellationToken) { var contextType = contextObj.GetType(); if (contextType.IsGenericType && contextType.GetGenericTypeDefinition() == typeof(TreeQueryContext<>)) { // Tree query // this.GetType() - support override in Pro version var propsType = contextType.GetGenericArguments()[0]; var method = this.GetType().GetMethod(nameof(ExecuteTreeToListAsync), System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); var genericMethod = method!.MakeGenericMethod(propsType); var lazyOverride = (bool?)contextType.GetProperty("LazyReferences")?.GetValue(contextObj); return await LazyReferencesQueryScope.RunAsync(_context, _sql, _configuration, _logger, lazyOverride, () => (Task)genericMethod.Invoke(this, new object[] { contextObj, cancellationToken })!); } throw new NotSupportedException($"Unsupported context type for TreeToList: {contextType.Name}"); } // ===== TREE EXECUTION METHODS ===== /// /// COUNT of a tree query. Every provider builds it through its v2-pvt module; the base read the legacy /// search_tree_objects_with_facets functions, which no shipped dialect has. /// protected abstract Task ExecuteTreeCountAsync(TreeQueryContext context, CancellationToken cancellationToken = default) where TProps : class, new(); /// /// ToList of a tree query. Every provider builds it through its v2-pvt module; the base read the legacy /// search_tree_objects_with_facets functions, which no shipped dialect has. /// protected abstract Task ExecuteTreeToListAsync(TreeQueryContext context, CancellationToken cancellationToken = default) where TProps : class, new(); /// The value of an EXISTS wrapper: a boolean on PostgreSQL, 1 or 0 on SQL Server and SQLite. protected static bool ExistsResult(object? value) => value is not null and not DBNull && Convert.ToBoolean(value, System.Globalization.CultureInfo.InvariantCulture); /// /// A WhereHasAncestor / WhereHasDescendant the provider could not turn into object ids: one without a target scheme. /// WhereHasAncestor<T>() and WhereHasDescendant<T>() always set it, or fail naming the type, so only a /// TreeFilter built by hand gets here. It used to fall to the legacy search functions, which no dialect has. /// protected static InvalidOperationException UnresolvedTreeFilter() => new( "A WhereHasAncestor or WhereHasDescendant filter without a target scheme reached the tree query provider. " + "Build it with WhereHasAncestor() or WhereHasDescendant(), which find the scheme of T."); // ===== FILTER BUILDING ===== /// /// Determines if WhereHasAncestor can be optimized through logic inversion /// protected TreeFilter? GetOptimizableHasAncestorFilter(TreeQueryContext context) where TProps : class, new() { // Find first WhereHasAncestor filter (optimize one by one) // TargetSchemeId can be 0 if type is not registered in AutomaticTypeRegistry var filter = context.TreeFilters?.FirstOrDefault(f => f.Operator == TreeFilterOperator.HasAncestor); // Check that TargetSchemeId exists and is not equal to 0 if (filter != null && (!filter.TargetSchemeId.HasValue || filter.TargetSchemeId.Value == 0)) { _logger?.LogWarning("WhereHasAncestor filter found, but TargetSchemeId not set (type not registered in AutomaticTypeRegistry). Optimization skipped."); return null; } return filter; } /// /// WhereHasAncestor with maxDepth 1 as the children of the matching ancestors: the query's own parents, read by the /// tree query in one statement (o._id_parent among them). The general form reads the descendants down to the depth /// limit and hands their ids back to the query as one array parameter; at maxDepth 1 those are exactly the /// children, read by one statement and sent back to the server by the next. Null when the query has a root, /// parents, a depth limit (counted from the real root of an unrooted query) or another tree filter of its own, /// which the parents would replace. The caller returns before this when no ancestor matched: an empty list of /// parents never reaches the query. /// protected static TreeQueryContext? AsChildrenOfAncestors( TreeQueryContext context, TreeFilter hasAncestor, IReadOnlyCollection ancestorIds) where TProps : class, new() { if (hasAncestor.MaxDepth != 1 || context.RootObjectId.HasValue || context.ParentIds is { Length: > 0 } || context.MaxDepth.HasValue || context.TreeFilters.Count != 1) return null; var rewritten = context.CloneWithMaxDepth(1); rewritten.TreeFilters = new List(); rewritten.ParentIds = ancestorIds.ToArray(); return rewritten; } /// /// WhereHasAncestor without maxDepth as the descendants of the matching ancestors at any depth: the query walks down /// from them as its parents, in the statement that reads the page, instead of a statement that lists the descendants /// and a query that takes their ids back as parameters. The same answer, since no depth limit counts from the returned /// object. Null under the same conditions as , and when the filter has a /// maxDepth. /// protected static TreeQueryContext? AsDescendantsOfAncestors( TreeQueryContext context, TreeFilter hasAncestor, IReadOnlyCollection ancestorIds) where TProps : class, new() { if (hasAncestor.MaxDepth.HasValue || context.RootObjectId.HasValue || context.ParentIds is { Length: > 0 } || context.MaxDepth.HasValue || context.TreeFilters.Count != 1) return null; var rewritten = context.Clone(); rewritten.TreeFilters = new List(); rewritten.ParentIds = ancestorIds.ToArray(); return rewritten; } /// /// WhereHasAncestor with a maxDepth above 1 as the descendants of the matching ancestors down to that depth: the query /// walks down from them as its parents with its own depth limit set to maxDepth, in the statement that reads the page, /// instead of a statement that lists the descendants and a query that takes their ids back. The same answer only where /// the walk from several parents visits each node once, at its smallest depth: an object lies at most maxDepth levels /// below a matching ancestor exactly when the nearest one is that close, and a node under two nested matching /// ancestors comes once. The caller confirms its walk does that. Null under the same conditions as /// , and when maxDepth is not above 1. /// protected static TreeQueryContext? AsDescendantsWithinDepthOfAncestors( TreeQueryContext context, TreeFilter hasAncestor, IReadOnlyCollection ancestorIds) where TProps : class, new() { if (hasAncestor.MaxDepth is not > 1 || context.RootObjectId.HasValue || context.ParentIds is { Length: > 0 } || context.MaxDepth.HasValue || context.TreeFilters.Count != 1) return null; var rewritten = context.CloneWithMaxDepth(hasAncestor.MaxDepth.Value); rewritten.TreeFilters = new List(); rewritten.ParentIds = ancestorIds.ToArray(); return rewritten; } /// /// Determines if WhereHasDescendant can be optimized through logic inversion /// protected TreeFilter? GetOptimizableHasDescendantFilter(TreeQueryContext context) where TProps : class, new() { return context.TreeFilters?.FirstOrDefault(f => f.Operator == TreeFilterOperator.HasDescendant && f.TargetSchemeId.HasValue); } /// /// Build JSON for sorting (similar to base provider) /// FIXED: Uses _facetBuilder.BuildOrderBy to support 0$: prefix for base fields /// private JsonDocument? BuildOrderByFilter(TreeQueryContext context) where TProps : class, new() { if (context.Orderings == null || !context.Orderings.Any()) return null; // Use _facetBuilder.BuildOrderBy which correctly handles IsBaseField var jsonString = _facetBuilder.BuildOrderBy(context.Orderings); return JsonDocument.Parse(jsonString); } // ConvertFilterToFacets() REMOVED! REPLACED WITH PostgresFacetFilterBuilder! // Now Tree uses THE SAME POWERFUL SYSTEM as regular LINQ - ALL 25+ operators! /// /// Deserialize JSON result to list of TreeRedbObject /// protected List> DeserializeTreeObjects(string? objectsJson) where TProps : class, new() { if (string.IsNullOrEmpty(objectsJson) || objectsJson == "null") return new List>(); try { // Handle both array format and object format {"objects":[...]} JsonElement[]? jsonArray; var trimmed = objectsJson.TrimStart(); if (trimmed.StartsWith("{")) { // MSSQL returns full object: {"objects":[...],"total_count":N,...} var doc = JsonDocument.Parse(objectsJson); if (doc.RootElement.TryGetProperty("objects", out var objectsElement)) { jsonArray = JsonSerializer.Deserialize(objectsElement.GetRawText()); } else { return new List>(); } } else { // PostgreSQL returns array directly: [{...},{...}] jsonArray = JsonSerializer.Deserialize(objectsJson); } var result = new List>(); if (jsonArray == null) return result; foreach (var jsonElement in jsonArray) { try { // Deserialize as regular RedbObject var redbObj = _serializer.Deserialize(jsonElement.GetRawText()); if (redbObj == null) continue; // Convert to TreeRedbObject var treeObj = ConvertToTreeObject(redbObj); // NOTE: Props are batch-loaded by ExecuteTreeToListAsync; boundary stubs get their // loader from LazyReferenceInstaller after that (V4). result.Add(treeObj); } catch (Exception ex) { _logger?.LogWarning(ex, "Error deserializing tree object from JSON"); // Continue processing other objects } } return result; } catch (Exception ex) { _logger?.LogError(ex, "Error deserializing JSON array of tree objects"); return new List>(); } } /// /// Convert RedbObject to TreeRedbObject /// FIXED: Props copied from source (fixed bug with empty Props) /// protected TreeRedbObject ConvertToTreeObject(RedbObject source) where TProps : class, new() { var treeObj = new TreeRedbObject { id = source.id, parent_id = source.parent_id, scheme_id = source.scheme_id, owner_id = source.owner_id, who_change_id = source.who_change_id, date_create = source.date_create, date_modify = source.date_modify, date_begin = source.date_begin, date_complete = source.date_complete, key = source.key, value_long = source.value_long, value_string = source.value_string, value_guid = source.value_guid, value_bool = source.value_bool, value_double = source.value_double, value_numeric = source.value_numeric, value_datetime = source.value_datetime, value_bytes = source.value_bytes, value_unique = source.value_unique, name = source.name, note = source.note, hash = source.hash }; // CRITICAL FIX: Copy Props directly // Use GetPropsDirectly() to NOT trigger lazy load in source // Props setter is safe - it just sets the value var sourceProps = source.GetPropsDirectly(); if (sourceProps != null) { treeObj.Props = sourceProps; // Setter will set _propsLoaded=true } else if (source._propsLoaded) { // Props was loaded but it's null - set flag treeObj._propsLoaded = true; } return treeObj; } // ===== METHODS FOR BUILDING HIERARCHICAL RELATIONSHIPS ===== /// /// Get IDs of all objects and their parents up to root through recursive CTE /// public async Task> GetIdsWithAncestorsAsync(List filteredIds, CancellationToken cancellationToken = default) where TProps : class, new() { if (filteredIds == null || !filteredIds.Any()) return new List(); try { return await _context.QueryScalarListAsync(_sql.Tree_SelectIdsWithAncestors(), new object[] { filteredIds.ToArray(), redb.Core.Providers.Base.TreeProviderBase.MaxAncestorDepth }, cancellationToken); } catch (Exception ex) { _logger?.LogError(ex, "Error getting IDs with parents"); throw; } } /// /// Load full objects by ID list via get_object_json function /// public async Task>> LoadObjectsByIdsAsync(List objectIds, int? propsDepth = null, CancellationToken cancellationToken = default) where TProps : class, new() { if (objectIds == null || !objectIds.Any()) return new List>(); // Pro path: materialize entirely in C# (PVT) — NEVER call the server-side // get_object_json function. Triggered when a Pro lazy loader is injected. if (_lazyPropsLoader != null) { var rows = await _context.QueryAsync( _sql.ObjectStorage_SelectObjectsByIds(), new object[] { objectIds.ToArray() }, cancellationToken); return await MaterializeTreeObjectsFromRowsAsync(rows, propsDepth); } try { // Use dialect-specific SQL for loading objects by IDs var idsString = string.Join(",", objectIds); var effectiveDepth = propsDepth ?? _configuration.DefaultMaxTreeDepth; var sql = _sql.Query_LoadObjectsByIdsSql(idsString, effectiveDepth); var objectsJsonList = await _context.ExecuteJsonListAsync(sql, System.Array.Empty(), cancellationToken); var result = new List>(); foreach (var objectJson in objectsJsonList) { try { var redbObj = _serializer.Deserialize(objectJson); if (redbObj != null) { var treeObj = ConvertToTreeObject(redbObj); result.Add(treeObj); } } catch (Exception ex) { _logger?.LogWarning(ex, "Error deserializing object from get_object_json"); } } return result; } catch (Exception ex) { _logger?.LogError(ex, "Error loading objects by ID"); throw; } } /// /// Load full polymorphic objects by ID list via get_object_json function. /// Used for polymorphic trees where objects can be of different types. /// Each object is deserialized to its real type based on scheme_id. /// public async Task> LoadObjectsByIdsAsync(List objectIds, int? propsDepth = null, CancellationToken cancellationToken = default) { if (objectIds == null || !objectIds.Any()) return new List(); // Pro path: materialize entirely in C# (PVT) — NEVER call the server-side // get_object_json function. Triggered when a Pro lazy loader is injected. if (_lazyPropsLoader != null) { var rows = await _context.QueryAsync( _sql.ObjectStorage_SelectObjectsByIds(), new object[] { objectIds.ToArray() }, cancellationToken); var proResult = new List(); foreach (var schemeGroup in rows.GroupBy(r => r.IdScheme)) { var propsType = Cache.GetClrType(schemeGroup.Key) ?? throw new InvalidOperationException( $"Type not found for scheme_id={schemeGroup.Key}. Register type in AutomaticTypeRegistry."); var method = typeof(TreeQueryProviderBase).GetMethod( nameof(MaterializeTreeObjectsFromRowsAsync), System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); var genericMethod = method!.MakeGenericMethod(propsType); var task = (Task)genericMethod.Invoke(this, new object[] { schemeGroup.ToList(), propsDepth! })!; await task.ConfigureAwait(false); var typed = (System.Collections.IEnumerable)task.GetType().GetProperty("Result")!.GetValue(task)!; foreach (var o in typed) { if (o is ITreeRedbObject treeObj) proResult.Add(treeObj); } } return proResult; } try { // Use dialect-specific SQL for loading objects by IDs var idsString = string.Join(",", objectIds); var effectiveDepth = propsDepth ?? _configuration.DefaultMaxTreeDepth; var sql = _sql.Query_LoadObjectsByIdsSql(idsString, effectiveDepth); var objectsJsonList = await _context.ExecuteJsonListAsync(sql, System.Array.Empty(), cancellationToken); var result = new List(); foreach (var objectJson in objectsJsonList) { // 1. Extract scheme_id from JSON for polymorphic deserialization using var jsonDoc = JsonDocument.Parse(objectJson); var schemeId = jsonDoc.RootElement.GetProperty("scheme_id").GetInt64(); // 2. Get real C# type via AutomaticTypeRegistry var propsType = Cache.GetClrType(schemeId) ?? throw new InvalidOperationException( $"Type not found for scheme_id={schemeId}. Register type in AutomaticTypeRegistry."); // 3. Polymorphic deserialization: first RedbObject, then TreeRedbObject var redbObj = _serializer.DeserializeRedbDynamic(objectJson, propsType); if (redbObj != null) { // Convert to TreeRedbObject via reflection (call ConvertToTreeObject) var method = typeof(TreeQueryProviderBase).GetMethod(nameof(ConvertToTreeObject), System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); if (method != null) { var genericMethod = method.MakeGenericMethod(propsType); var convertResult = genericMethod.Invoke(this, new[] { redbObj }); if (convertResult is ITreeRedbObject treeObj) { result.Add(treeObj); } } } } return result; } catch (Exception ex) { _logger?.LogError(ex, "Error loading polymorphic objects by ID"); throw; } } /// /// Pro materialization: builds TreeRedbObject<TProps> from base _objects rows and /// loads Props via the injected lazy loader (ProLazyPropsLoader → PVT, in C#). /// Used by the Pro branch of LoadObjectsByIdsAsync to avoid get_object_json. /// private async Task>> MaterializeTreeObjectsFromRowsAsync( List rows, int? propsDepth) where TProps : class, new() { var result = rows.Select(MapRowToTreeObject).ToList(); if (_lazyPropsLoader != null && result.Count > 0) { var baseObjects = result.Cast>().ToList(); await _lazyPropsLoader.LoadPropsForManyAsync(baseObjects, propsDepth); } return result; } /// /// Maps a base _objects row to a TreeRedbObject shell (Props loaded separately). /// protected static TreeRedbObject MapRowToTreeObject(RedbObjectRow row) where TProps : class, new() { return new TreeRedbObject { id = row.Id, name = row.Name, scheme_id = row.IdScheme, parent_id = row.IdParent, owner_id = row.IdOwner, who_change_id = row.IdWhoChange, date_create = row.DateCreate, date_modify = row.DateModify, date_begin = row.DateBegin, date_complete = row.DateComplete, key = row.Key, value_long = row.ValueLong, value_string = row.ValueString, value_guid = row.ValueGuid, value_bool = row.ValueBool, value_double = row.ValueDouble, value_numeric = row.ValueNumeric, value_datetime = row.ValueDatetime, value_bytes = row.ValueBytes, value_unique = row.ValueUnique, note = row.Note, hash = row.Hash }; } /// /// Returns SQL query for tree search that will be executed (for debugging) /// public virtual async Task GetSqlPreviewAsync(TreeQueryContext context, CancellationToken cancellationToken = default) where TProps : class, new() { var facetFilters = _facetBuilder.BuildFacetFilters(context.Filter); var parameters = _facetBuilder.BuildQueryParameters(context.Limit, context.Offset); var orderByDoc = BuildOrderByFilter(context); var orderByJson = orderByDoc?.RootElement.GetRawText(); // OPTIMIZATION: ALWAYS use _base preview function var functionName = _sql.Query_TreeSqlPreviewBaseFunction(); _logger?.LogDebug("Getting Tree SQL Preview: Function={FunctionName}, SchemeId={SchemeId}, RootObjectId={RootObjectId}, MaxDepth={MaxDepth}", functionName, context.SchemeId, context.RootObjectId, context.MaxDepth); // Build parent_ids array for the SQL function var parentIds = context.ParentIds ?? (context.RootObjectId.HasValue ? new[] { context.RootObjectId.Value } : Array.Empty()); var sqlQuery = _sql.Query_TreeSqlPreviewTemplate(functionName); var result = await _context.QueryFirstOrDefaultAsync( sqlQuery, new object[] { context.SchemeId, parentIds, facetFilters, parameters.Limit ?? int.MaxValue, parameters.Offset ?? 0, orderByJson ?? "null", context.MaxDepth ?? 100, context.MaxRecursionDepth ?? 10 }, cancellationToken); return result?.sql_preview ?? "-- Tree SQL preview not available"; } // ===== DELETE ===== /// /// Get SQL preview for standard QueryContext (for IRedbQueryProvider compatibility) /// public Task GetSqlPreviewAsync(QueryContext context, CancellationToken cancellationToken = default) where TProps : class, new() { // For Tree provider convert to TreeQueryContext if (context is TreeQueryContext treeContext) { return GetSqlPreviewAsync(treeContext); } // Create TreeQueryContext from regular QueryContext var newTreeContext = new TreeQueryContext( context.SchemeId, context.UserId, context.CheckPermissions, null, // rootObjectId context.MaxDepth) { Filter = context.Filter, Orderings = context.Orderings.ToList(), Limit = context.Limit, Offset = context.Offset, LazyReferences = context.LazyReferences, }; return GetSqlPreviewAsync(newTreeContext); } /// /// Returns the JSON filter that will be sent to SQL function (for diagnostics) /// public Task GetFilterJsonAsync(QueryContext context, CancellationToken cancellationToken = default) where TProps : class, new() { var facetFilters = _facetBuilder.BuildFacetFilters(context.Filter); return Task.FromResult(facetFilters); } /// /// Delete objects by FilterExpression. Delegates to base QueryProvider. /// Cascade delete in DB handles children automatically. /// public async Task ExecuteDeleteAsync(long schemeId, QueryExpressions.FilterExpression? filter, CancellationToken cancellationToken = default) { var baseProvider = CreateQueryProvider(); return await baseProvider.ExecuteDeleteAsync(schemeId, filter); } /// /// Delete objects by ID array (cascade with children). /// public async Task ExecuteTreeDeleteAsync(long[] objectIds, CancellationToken cancellationToken = default) { if (objectIds.Length == 0) return 0; // Use dialect's cascade delete (handles children automatically) // MSSQL context auto-converts long[] to comma-separated string var deletedCount = await redb.Core.Providers.Base.ObjectDeleteByIds.RunAsync(_context, _sql, objectIds, cancellationToken); _logger?.LogDebug("TreeDelete: Deleted {Count} objects (cascade)", deletedCount); return deletedCount; } /// /// Execute GROUP BY with tree context (CTE for tree traversal). /// Base implementation: gets tree object IDs first, then delegates to base GroupBy with filter. /// Override in Pro version for optimized CTE-based implementation. /// public virtual async Task ExecuteTreeGroupedAggregateAsync( TreeQueryContext context, IEnumerable groupFields, IEnumerable aggregations, string? havingJson = null, CancellationToken cancellationToken = default) where TProps : class, new() { // Base implementation: get tree object IDs first, then filter grouping var treeObjectIds = await GetTreeObjectIdsAsync(context, cancellationToken); if (treeObjectIds.Count == 0) return System.Text.Json.JsonDocument.Parse("[]"); // Build filter JSON with object IDs var filterJson = BuildObjectIdsFilterJson(treeObjectIds); // Delegate to base grouped aggregate with ID filter (PVT path honors having) var baseProvider = CreateQueryProvider(); return await baseProvider.ExecuteGroupedAggregateAsync( context.SchemeId, groupFields, aggregations, filterJson, havingJson); } /// /// Array grouping over the objects of a subtree. Base implementation: the ids of the subtree (roots, depth and /// Where of the context) become the object condition of the flat array grouping. Pro overrides it with a tree CTE. /// public virtual async Task ExecuteTreeArrayGroupQueryAsync( TreeQueryContext context, Grouping.ArrayGroupQuery query, CancellationToken cancellationToken = default) where TProps : class, new() { var treeObjectIds = await GetTreeObjectIdsForArrayGroupAsync(context, query, cancellationToken); if (treeObjectIds.Count == 0) return System.Text.Json.JsonDocument.Parse("[]"); // no object in the subtree, so no element and no group return await CreateQueryProvider().ExecuteArrayGroupQueryAsync( WithObjectIds(query, treeObjectIds), cancellationToken); } /// /// SQL of : the flat array grouping over the ids of the subtree. /// public virtual async Task GetTreeArrayGroupQuerySqlAsync( TreeQueryContext context, Grouping.ArrayGroupQuery query, CancellationToken cancellationToken = default) where TProps : class, new() { var treeObjectIds = await GetTreeObjectIdsForArrayGroupAsync(context, query, cancellationToken); if (treeObjectIds.Count == 0) return "-- the subtree has no objects: the grouping runs no SQL and returns no groups"; return await CreateQueryProvider().GetArrayGroupQuerySqlAsync( WithObjectIds(query, treeObjectIds), cancellationToken); } private async Task> GetTreeObjectIdsForArrayGroupAsync( TreeQueryContext context, Grouping.ArrayGroupQuery query, CancellationToken cancellationToken) where TProps : class, new() { if (query.Filter != null || !string.IsNullOrEmpty(query.FilterJson)) throw new ArgumentException( "A tree array grouping takes its object condition from the tree context; the request must not carry one.", nameof(query)); query.EnsureValid(); return await GetTreeObjectIdsAsync(context, cancellationToken); } private Grouping.ArrayGroupQuery WithObjectIds(Grouping.ArrayGroupQuery query, List objectIds) => new() { SchemeId = query.SchemeId, ArrayPath = query.ArrayPath, GroupFields = query.GroupFields, Aggregations = query.Aggregations, FilterJson = BuildObjectIdsFilterJson(objectIds), HavingJson = query.HavingJson, Window = query.Window }; /// /// Gets object IDs matching tree query context. /// private async Task> GetTreeObjectIdsAsync(TreeQueryContext context, CancellationToken cancellationToken) where TProps : class, new() { // Use existing tree query infrastructure to get matching IDs var treeQueryable = new TreeQueryableBase( this, context.Clone(), _filterParser, _orderingParser, _facetBuilder); var objects = await treeQueryable.ToListAsync(cancellationToken); return objects.Select(o => o.Id).ToList(); } /// /// Builds filter JSON with object ID constraint. /// Uses 0$: prefix for base fields - required for PostgreSQL. /// private string BuildObjectIdsFilterJson(List objectIds) { // Format: {"0$:id":{"$in":[1,2,3]}} - base fields require 0$: prefix! var idsJson = System.Text.Json.JsonSerializer.Serialize(objectIds); return $"{{\"0$:id\":{{\"$in\":{idsJson}}}}}"; } /// /// Execute Window Functions with tree context. /// Base implementation: get tree object IDs first, then execute window functions with ID filter. /// Override in Pro version for optimized CTE-based implementation. /// public virtual async Task ExecuteTreeWindowQueryAsync( TreeQueryContext context, IEnumerable selectFields, IEnumerable windowFuncs, IEnumerable partitionBy, IEnumerable orderBy, string? frameJson = null, CancellationToken cancellationToken = default) where TProps : class, new() { // Base implementation: get tree object IDs first, then filter window query var treeObjectIds = await GetTreeObjectIdsAsync(context, cancellationToken); if (treeObjectIds.Count == 0) { return System.Text.Json.JsonDocument.Parse("[]"); } // Build filter JSON with object IDs var filterJson = BuildObjectIdsFilterJson(treeObjectIds); // Delegate to base window query with ID filter var baseProvider = CreateQueryProvider(); return await baseProvider.ExecuteWindowQueryAsync( context.SchemeId, selectFields, windowFuncs, partitionBy, orderBy, filterJson, frameJson, context.Limit, context.Offset); } /// /// Get SQL preview for tree window query. /// Base implementation: returns placeholder, override in Pro for actual SQL. /// public virtual async Task GetTreeWindowSqlPreviewAsync( TreeQueryContext context, IEnumerable selectFields, IEnumerable windowFuncs, IEnumerable partitionBy, IEnumerable orderBy, string? frameJson = null, CancellationToken cancellationToken = default) where TProps : class, new() { // Mirror the runtime path: fetch tree object IDs, then delegate to // the non-tree window preview with a `0$:id $in [...]` filter. var treeObjectIds = await GetTreeObjectIdsAsync(context, cancellationToken); if (treeObjectIds.Count == 0) { return $"-- Tree Window: subtree is empty (no objects matched RootObjectId={context.RootObjectId})\n-- SchemeId: {context.SchemeId}"; } var filterJson = BuildObjectIdsFilterJson(treeObjectIds); var baseProvider = CreateQueryProvider(); var preview = await baseProvider.GetWindowSqlPreviewAsync( context.SchemeId, selectFields, windowFuncs, partitionBy, orderBy, filterJson, frameJson, context.Limit, context.Offset); return $"-- Tree Window: subtree resolved to {treeObjectIds.Count} object(s) (RootObjectId={context.RootObjectId})\n" + preview; } /// /// Get SQL preview for tree GROUP BY query. /// Base implementation: fetches tree object IDs and delegates to the /// non-tree GroupBy preview with an `0$:id $in [...]` filter. /// public virtual async Task GetTreeGroupBySqlPreviewAsync( TreeQueryContext context, IEnumerable groupFields, IEnumerable aggregations, string? havingJson = null, CancellationToken cancellationToken = default) where TProps : class, new() { var treeObjectIds = await GetTreeObjectIdsAsync(context, cancellationToken); if (treeObjectIds.Count == 0) { return $"-- Tree GroupBy: subtree is empty (no objects matched RootObjectId={context.RootObjectId})\n-- SchemeId: {context.SchemeId}"; } var filterJson = BuildObjectIdsFilterJson(treeObjectIds); var baseProvider = CreateQueryProvider(); var preview = await baseProvider.GetGroupBySqlPreviewAsync( context.SchemeId, groupFields, aggregations, filterJson, havingJson, cancellationToken); return $"-- Tree GroupBy: subtree resolved to {treeObjectIds.Count} object(s) (RootObjectId={context.RootObjectId})\n" + preview; } // ===== TREE GROUPED WINDOW ===== /// /// Execute GroupBy + Window with tree context. /// Base implementation: gets tree object IDs first, then delegates to base GroupBy + Window with filter. /// Override in Pro version for optimized CTE-based implementation. /// public virtual async Task ExecuteTreeGroupedWindowQueryAsync( TreeQueryContext context, IEnumerable groupFields, IEnumerable aggregations, IEnumerable windowFuncs, IEnumerable partitionBy, IEnumerable orderBy, string? havingJson = null, CancellationToken cancellationToken = default) where TProps : class, new() { // Base implementation: get tree object IDs first, then filter grouping + window var treeObjectIds = await GetTreeObjectIdsAsync(context, cancellationToken); if (treeObjectIds.Count == 0) return System.Text.Json.JsonDocument.Parse("[]"); // Build filter JSON with object IDs var filterJson = BuildObjectIdsFilterJson(treeObjectIds); // Delegate to base grouped window query with ID filter var baseProvider = CreateQueryProvider(); return await baseProvider.ExecuteGroupedWindowQueryAsync( context.SchemeId, groupFields, aggregations, windowFuncs, partitionBy, orderBy, filterJson, havingJson, cancellationToken); } /// /// Get SQL preview for tree GroupBy + Window. /// Base implementation: returns placeholder. /// public virtual async Task GetTreeGroupedWindowSqlPreviewAsync( TreeQueryContext context, IEnumerable groupFields, IEnumerable aggregations, IEnumerable windowFuncs, IEnumerable partitionBy, IEnumerable orderBy, string? havingJson = null, CancellationToken cancellationToken = default) where TProps : class, new() { var treeObjectIds = await GetTreeObjectIdsAsync(context, cancellationToken); if (treeObjectIds.Count == 0) { return $"-- Tree GroupBy + Window: subtree is empty (no objects matched RootObjectId={context.RootObjectId})\n-- SchemeId: {context.SchemeId}"; } var filterJson = BuildObjectIdsFilterJson(treeObjectIds); var baseProvider = CreateQueryProvider(); var preview = await baseProvider.GetGroupedWindowSqlPreviewAsync( context.SchemeId, groupFields, aggregations, windowFuncs, partitionBy, orderBy, filterJson, havingJson, cancellationToken); return $"-- Tree GroupBy + Window: subtree resolved to {treeObjectIds.Count} object(s) (RootObjectId={context.RootObjectId})\n" + preview; } } // ===== HELPER CLASSES ===== /// /// Tree query context - extends QueryContext with tree parameters support /// public class TreeQueryContext : QueryContext where TProps : class, new() { public long? RootObjectId { get; set; } // Limit search to subtree public List TreeFilters { get; set; } // Tree filters // FIX: MaxDepth now inherited from base QueryContext public TreeQueryContext(long schemeId, long? userId, bool checkPermissions, long? rootObjectId, int? maxDepth) : base(schemeId, userId, checkPermissions, null, maxDepth) // Pass maxDepth to base constructor { RootObjectId = rootObjectId; TreeFilters = new List(); } /// /// Create a copy of tree context /// public new TreeQueryContext Clone() => CloneWithMaxDepth(MaxDepth); /// /// A copy with another depth limit. MaxDepth is init-only, so this is the one place that copies every setting /// (TQB-10: WithMaxDepth used to copy by hand and dropped the props depth, lazy references, projection, distinct). /// internal TreeQueryContext CloneWithMaxDepth(int? maxDepth) { // FIX: MaxDepth now passed via base constructor var clone = new TreeQueryContext(SchemeId, UserId, CheckPermissions, RootObjectId, maxDepth) { ParentIds = ParentIds, // SYNC: copy batch array Filter = Filter, Orderings = new List(Orderings), Limit = Limit, Offset = Offset, IsDistinct = IsDistinct, IsDistinctRedb = IsDistinctRedb, DistinctByField = DistinctByField, DistinctByIsBaseField = DistinctByIsBaseField, MaxRecursionDepth = MaxRecursionDepth, IsEmpty = IsEmpty, // FIX: copy IsEmpty flag for TreeQueryContext LazyReferences = LazyReferences, ProjectedStructureIds = ProjectedStructureIds, ProjectedFieldPaths = ProjectedFieldPaths, SkipPropsLoading = SkipPropsLoading, ProjectionReadsNoProps = ProjectionReadsNoProps, PropsDepth = PropsDepth }; // Copy tree filters clone.TreeFilters = new List(TreeFilters); return clone; } } /// /// Tree filter - representation of hierarchical operator /// public class TreeFilter { public TreeFilterOperator Operator { get; set; } public object? Value { get; set; } public int? MaxDepth { get; set; } public long? TargetSchemeId { get; set; } // For polymorphic queries (WhereHasAncestor<TTarget>) public Dictionary? FilterConditions { get; set; } // For Open Source: JSON for SQL functions public FilterExpression? OriginalFilter { get; set; } // For Pro: original FilterExpression public TreeFilter(TreeFilterOperator op, object? value = null) { Operator = op; Value = value; FilterConditions = new Dictionary(); } } /// /// Tree operator types (correspond to SQL operators from search_tree_objects_with_facets) /// public enum TreeFilterOperator { HasAncestor, // $hasAncestor - find objects with ancestor matching condition HasDescendant, // $hasDescendant - find objects with descendant matching condition Level, // $level - filter by level in tree IsRoot, // $isRoot - only root objects IsLeaf, // $isLeaf - only leaves ChildrenOf, // $childrenOf - direct children of object DescendantsOf // $descendantsOf - all descendants of object }