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