Path: redb/redb.Core/Query/Base/QueryProviderBase.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/QueryProviderBase.cs ---- using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using 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; using redb.Core.Query.QueryExpressions; using redb.Core.Serialization; namespace redb.Core.Query.Base; /// /// Base query provider for executing LINQ queries through the v2-pvt module of the dialect (pvt_build_query_sql). /// Database-specific implementations should inherit and provide ISqlDialect. /// public abstract partial class QueryProviderBase : IRedbQueryProvider, 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 ISchemeSyncProvider? _schemeSync; protected readonly ISqlDialect _sql; protected QueryProviderBase( IRedbContext context, IRedbObjectSerializer serializer, ISqlDialect dialect, 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; _filterParser = CreateFilterParser(); _orderingParser = CreateOrderingParser(); _facetBuilder = CreateFacetBuilder(); } /// /// 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); public IRedbQueryable CreateQuery(long schemeId, long? userId = null, bool checkPermissions = false) where TProps : class, new() { var context = new QueryContext(schemeId, userId, checkPermissions); return new RedbQueryable(this, context, _filterParser, _orderingParser, _facetBuilder); } /// /// Hook for Distinct-related feature checks. No-op in OSS — DistinctRedb / /// DistinctBy are evaluated by SQL builders directly and either work or /// surface a concrete error from the dialect. /// protected virtual void CheckProOnlyDistinctFeatures(QueryContext context) where TProps : class, new() { } /// /// Get scheme by ID (for projections) /// public async Task GetSchemeAsync(long schemeId, CancellationToken cancellationToken = default) { if (_schemeSync != null) { return await _schemeSync.GetSchemeByIdAsync(schemeId); } return null; } public async Task ExecuteAsync(Expression expression, Type elementType, CancellationToken cancellationToken = default) { // Extract QueryContext from the 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 && elementType.GetGenericTypeDefinition() == typeof(List<>)) { return await ExecuteToListAsyncGeneric(constantExpr.Value, cancellationToken); } } throw new NotSupportedException($"Expression type {expression.GetType().Name} with element type {elementType.Name} is not supported"); } private async Task ExecuteCountAsyncGeneric(object contextObj, CancellationToken cancellationToken) { // Use reflection to call the generic method var contextType = contextObj.GetType(); if (contextType.IsGenericType && contextType.GetGenericTypeDefinition() == typeof(QueryContext<>)) { var propsType = contextType.GetGenericArguments()[0]; // Look for the method in the ACTUAL type (to support inheritance in Pro) var method = GetType().GetMethod(nameof(ExecuteCountAsync), 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; } throw new NotSupportedException($"Unsupported context type: {contextType.Name}"); } private async Task ExecuteAnyAsyncGeneric(object contextObj, CancellationToken cancellationToken) { // Use reflection to call the generic method var contextType = contextObj.GetType(); if (contextType.IsGenericType && contextType.GetGenericTypeDefinition() == typeof(QueryContext<>)) { var propsType = contextType.GetGenericArguments()[0]; // Look for the method in the ACTUAL type (to support inheritance in Pro) var method = GetType().GetMethod(nameof(ExecuteAnyAsync), 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; } throw new NotSupportedException($"Unsupported context type: {contextType.Name}"); } /// /// Is there at least one object the query returns: the inner statement of the v2-pvt module (no order, no page, /// as a count reads it) under EXISTS, which stops at the first match. It used to count every match and compare /// the count with zero. The queryable answers a paged query by its count and never asks this. /// protected virtual async Task ExecuteAnyAsync(QueryContext context, CancellationToken cancellationToken = default) where TProps : class, new() { RequirePvtPipeline(context, "AnyAsync"); var inner = await BuildPvtInnerSqlAsync(context, forCount: true); var sql = _sql.Query_WrapPvtWithExists(inner) ?? throw new InvalidOperationException("Query_WrapPvtWithExists returned null for a PVT-enabled dialect."); return ExistsResult(await _context.ExecuteScalarAsync(sql, System.Array.Empty(), cancellationToken)); } /// 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); /// /// The provider compiles over a filter on Props fields. AllAsync then asks /// for the first counterexample (AnyAsync of the set filtered by NotTrue of the predicate) instead of counting the /// set twice. A provider that does not compile it keeps the two counts. /// protected internal virtual bool CompilesNotTrue => false; /// /// AllAsync of over every object of the scheme (the query has no filter of its own), /// answered by the provider in one statement, or null when it has no such form for this predicate; AllAsync then /// goes on as without it. The predicate reads Props fields only. /// protected internal virtual Task TryAllWithoutFilterAsync(QueryContext context, FilterExpression predicate, CancellationToken cancellationToken) where TProps : class, new() => Task.FromResult(null); /// /// An ordering by Props fields keeps the objects without a value for the key and places them as LINQ does (null /// first ascending), ThenBy included. A projection then sends an OrderBy or ThenBy written after Select to the /// source, so a later Take/Skip stays in SQL; otherwise it sorts the projected rows in memory. /// protected internal virtual bool SortsByPropsLikeLinq => false; private async Task ExecuteToListAsyncGeneric(object contextObj, CancellationToken cancellationToken) { // Use reflection to call the generic method var contextType = contextObj.GetType(); if (contextType.IsGenericType && contextType.GetGenericTypeDefinition() == typeof(QueryContext<>)) { var propsType = contextType.GetGenericArguments()[0]; // Look for the method in the ACTUAL type (to support inheritance in Pro) var method = GetType().GetMethod(nameof(ExecuteToListAsync), 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, propsType, cancellationToken })!); } throw new NotSupportedException($"Unsupported context type: {contextType.Name}"); } /// /// Executes COUNT query. Override in Pro for PVT-based count with computed expressions. /// protected virtual async Task ExecuteCountAsync(QueryContext context, CancellationToken cancellationToken = default) where TProps : class, new() { // The inner SQL comes from pvt_build_query_sql and is counted on the client side. RequirePvtPipeline(context, "A count"); _logger?.LogDebug("PVT Count Query: SchemeId={SchemeId}", context.SchemeId); return await ExecuteCountAsyncPvt(context, cancellationToken); } /// /// A list read and a count run through the v2-pvt module of the dialect. The legacy search functions they fell back /// to (search_objects_with_facets_base and the projection functions) are gone from every shipped dialect. /// private void RequirePvtPipeline(QueryContext context, string what) where TProps : class, new() { if (!CanUsePvtPipeline(context)) throw new NotSupportedException( $"{what} reads through the v2-pvt module, and the dialect {_sql.GetType().Name} has none " + "(Query_BuildPvtSqlFunction returns null)."); } protected virtual async Task ExecuteToListAsync(QueryContext context, Type propsType, CancellationToken cancellationToken = default) where TProps : class, new() { // Pro-only features check CheckProOnlyDistinctFeatures(context); var hasFieldPathsEarly = context.ProjectedFieldPaths != null && context.ProjectedFieldPaths.Count > 0; // v2-pvt native projection path: when there are projected field paths // AND the dialect ships pvt_build_projection_sql. The outer SELECT // yields the requested scalar columns, wrapped into a JSON-row shape // that flows through the standard materializer. if (hasFieldPathsEarly && CanUsePvtProjection(context)) { _logger?.LogDebug("PVT Projection ToList Query: SchemeId={SchemeId}, Paths={Paths}", context.SchemeId, string.Join(",", context.ProjectedFieldPaths!)); return await ExecuteToListAsyncPvtProjection(context, cancellationToken); } // The full-object read. A projection the module cannot build natively reads whole objects here, and the // compiled selector trims them on the client side. RequirePvtPipeline(context, "A list read"); _logger?.LogDebug("PVT ToList Query: SchemeId={SchemeId}", context.SchemeId); return await ExecuteToListAsyncPvt(context, propsType, cancellationToken); } private async Task>> MaterializeResultsFromJson(System.Text.Json.JsonElement[] objects, QueryContext context, CancellationToken cancellationToken = default) where TProps : class, new() { _logger?.LogDebug("MATERIALIZATION: Received {Count} JSON objects for deserialization", objects?.Length ?? 0); // ⏱MEASURING MATERIALIZATION TIME var materializationTimer = System.Diagnostics.Stopwatch.StartNew(); var materializedResults = new List>(); var successCount = 0; var errorCount = 0; if (objects == null || objects.Length == 0) { _logger?.LogDebug("MATERIALIZATION: JSON array is empty or null"); return materializedResults; } foreach (var objElement in objects) { try { // Objects are already in JSON format from get_object_json var objectJson = objElement.GetRawText(); // Filter by access rights if necessary if (context.CheckPermissions && context.UserId.HasValue) { // Extract object ID for rights check if (objElement.TryGetProperty("id", out var idElement)) { var objectId = idElement.GetInt64(); var hasPermission = await CheckUserPermission(objectId, context.UserId.Value, cancellationToken); if (!hasPermission) { continue; // Skip object without access rights } } } // Deserialize object JSON data var redbObject = _serializer.Deserialize(objectJson); materializedResults.Add(redbObject); successCount++; } catch (Exception ex) { // Fail fast on deserialization error - indicates schema/data mismatch var innerMsg = ex.InnerException?.Message ?? ""; var jsonPreview = objElement.GetRawText(); if (jsonPreview.Length > 500) jsonPreview = jsonPreview[..500] + "..."; throw new InvalidOperationException( $"Deserialization failed: {ex.Message} | Inner: {innerMsg} | JSON: {jsonPreview}", ex); } } materializationTimer.Stop(); _logger?.LogDebug("MATERIALIZATION COMPLETED: Success={Success}, Errors={Errors}, Total objects={Total}", successCount, errorCount, materializedResults.Count); _logger?.LogDebug("Materialization JSON → C# objects completed in {ElapsedMs} ms", materializationTimer.ElapsedMilliseconds); // PROJECTION: If SkipPropsLoading = true — skip Props loading completely if (context.SkipPropsLoading) { return materializedResults; } // OPTIMIZATION: Two-phase loading strategy // Phase 1: the objects without their Props (already done above) // Phase 2: Load Props via LoadPropsForManyAsync (with cache check) // if (materializedResults.Count > 0 && _lazyPropsLoader != null) { // BULK load Props via LoadPropsForManyAsync (two-phase loading) // This method checks cache first, then loads only missing objects via get_object_json batch var projectedIds = context.ProjectedStructureIds; var propsLoadTimer = System.Diagnostics.Stopwatch.StartNew(); if (projectedIds != null && projectedIds.Count > 0) { await _lazyPropsLoader.LoadPropsForManyAsync(materializedResults, projectedIds, context.PropsDepth); } else { await _lazyPropsLoader.LoadPropsForManyAsync(materializedResults, context.PropsDepth); } propsLoadTimer.Stop(); _logger?.LogDebug("Props loaded via batch (with cache check) in {ElapsedMs} ms", propsLoadTimer.ElapsedMilliseconds); } // DISTINCT is performed by the SQL statement // No need to filter in memory! return materializedResults; } private async Task CheckUserPermission(long objectId, long userId, CancellationToken cancellationToken) { var sql = _sql.Query_CheckPermissionSql(); var result = await _context.QueryFirstOrDefaultAsync(sql, new object[] { objectId, userId }, cancellationToken); return result?.HasPermission ?? false; } /// /// Forms JSON for the order_by parameter based on sortings from the context /// FIXED: Uses _facetBuilder.BuildOrderBy to support 0$: prefix for base fields /// private string? BuildOrderByJson(QueryContext context) where TProps : class, new() { if (!context.Orderings.Any()) return null; // Using _facetBuilder.BuildOrderBy which correctly handles IsBaseField return _facetBuilder.BuildOrderBy(context.Orderings); } // ============================================================ // === v2-pvt PIPELINE === // Two-step search: ask the DB to BUILD the inner _id-list SQL via // pvt_build_query_sql(), then wrap on the client side. A dialect without // the module (Query_BuildPvtSqlFunction() == null) cannot list or count. // ============================================================ /// /// Returns true when the active dialect exposes the v2-pvt module. /// Projection is applied client-side (see RedbProjectedQueryable.ToListAsync), /// so the PVT pipeline serves projection queries by returning full objects via /// get_object_json — the compiled selector then extracts the requested fields. /// protected virtual bool CanUsePvtPipeline(QueryContext context) where TProps : class, new() { return _sql.Query_BuildPvtSqlFunction() is not null; } /// /// Phase 1: ask the database to build the inner _id-list SQL string. /// When is true the call passes p_limit=NULL, p_offset=0 and no order (used for the /// COUNT/EXISTS wrappers): a count needs no order, and the SQL Server module keeps an order without paging with /// OFFSET 0 ROWS, which would sort the rows only to count them. /// protected async Task BuildPvtInnerSqlAsync( QueryContext context, bool forCount, CancellationToken cancellationToken = default) where TProps : class, new() { var facetFilters = _facetBuilder.BuildFacetFilters(context.Filter); var orderByJson = BuildOrderByJson(context); var parameters = _facetBuilder.BuildQueryParameters(context.Limit, context.Offset); var limit = forCount ? (int?)null : parameters.Limit; var offset = forCount ? 0 : (parameters.Offset ?? 0); // DistinctBy → p_distinct_on jsonb array (PVT engine handles SELECT DISTINCT ON parity) var distinctOnJson = BuildPvtDistinctOnJson(context); var invocation = _sql.Query_BuildPvtSqlInvocation( schemeId : context.SchemeId, limit : limit, offset : offset, maxDepth : context.MaxRecursionDepth ?? 10, distinct : context.IsDistinct, sourceMode : "flat", treeIds : null, hasDistinctOn: distinctOnJson != null); if (invocation is null) throw new InvalidOperationException( "v2-pvt is enabled by dialect but Query_BuildPvtSqlInvocation returned null."); object filterParam = string.IsNullOrEmpty(facetFilters) || facetFilters == "{}" ? (object)DBNull.Value : facetFilters; object orderParam = forCount || string.IsNullOrEmpty(orderByJson) || orderByJson == "null" || orderByJson == "[]" ? (object)DBNull.Value : orderByJson; string? inner; if (distinctOnJson != null) inner = await _context.ExecuteScalarAsync(invocation, new object[] { filterParam, orderParam, distinctOnJson }, cancellationToken); else inner = await _context.ExecuteScalarAsync(invocation, new object[] { filterParam, orderParam }, cancellationToken); if (string.IsNullOrWhiteSpace(inner)) throw new InvalidOperationException( "pvt_build_query_sql returned an empty SQL string for scheme " + context.SchemeId + "."); return inner; } /// Base fields of a DistinctRedb key, by the names the PVT module maps (01_pvt_field_path). private static readonly string[] DistinctRedbFields = ["Name", "ValueLong", "ValueString", "ValueGuid", "ValueBool", "ParentId", "SchemeId", "Note", "Key"]; /// /// The p_distinct_on argument of pvt_build_query_sql for DistinctBy / DistinctByRedb, or null /// when the query has no distinct key. Shared by the flat query and the tree query of the Free providers. /// internal static string? BuildPvtDistinctOnJson(QueryContext context) where TProps : class, new() { // DistinctRedb: one object per value of the object's own columns except the id, the columns the Pro providers // partition by. The flag was set and never read here, so DistinctRedb() returned every object. if (context.IsDistinctRedb && context.DistinctByField == null) return "[" + string.Join(",", DistinctRedbFields.Select(f => "{\"field\":\"0$:" + f + "\"}")) + "]"; if (context.DistinctByField == null) return null; var name = context.DistinctByField.Property.Name; return context.DistinctByIsBaseField ? "[{\"field\":\"0$:" + name + "\"}]" : "[{\"field\":\"" + name + "\"}]"; } /// v2-pvt Count path: COUNT(*) wrapper over the inner _id-list SQL. protected virtual async Task ExecuteCountAsyncPvt(QueryContext context, CancellationToken cancellationToken = default) where TProps : class, new() { var inner = await BuildPvtInnerSqlAsync(context, forCount: true); var wrapped = _sql.Query_WrapPvtWithCount(inner) ?? throw new InvalidOperationException("Query_WrapPvtWithCount returned null for a PVT-enabled dialect."); var count = await _context.ExecuteScalarAsync(wrapped, System.Array.Empty(), cancellationToken); return checked((int)count); } /// v2-pvt SQL preview path: returns the inner _id-list SQL as-is. protected virtual Task GetSqlPreviewAsyncPvt(QueryContext context, CancellationToken cancellationToken = default) where TProps : class, new() => BuildPvtInnerSqlAsync(context, forCount: false); /// /// v2-pvt ToList path: the inner SQL picks the ids, the wrapper reads their _objects rows in that /// order, and the lazy loader reads the Props once, from the Props cache where it holds them. The JSON of an /// object is built once per read, by the loader; the wrapper used to build it too, and the loader built it again. /// protected virtual async Task ExecuteToListAsyncPvt(QueryContext context, Type propsType, CancellationToken cancellationToken = default) where TProps : class, new() { var loader = _lazyPropsLoader ?? throw new InvalidOperationException("The v2-pvt list read needs the lazy Props loader of the provider."); var inner = await BuildPvtInnerSqlAsync(context, forCount: false); var wrapped = _sql.Query_WrapPvtWithObjectRows(inner) ?? throw new InvalidOperationException("Query_WrapPvtWithObjectRows returned null for a PVT-enabled dialect."); var sqlTimer = System.Diagnostics.Stopwatch.StartNew(); var rows = await _context.QueryAsync(wrapped, System.Array.Empty(), cancellationToken); sqlTimer.Stop(); _logger?.LogDebug("PVT SQL (object rows) executed in {ElapsedMs} ms", sqlTimer.ElapsedMilliseconds); var objects = new List>(rows.Count); foreach (var row in rows) { if (context.CheckPermissions && context.UserId.HasValue && !await CheckUserPermission(row.Id, context.UserId.Value, cancellationToken)) continue; objects.Add(row.ToRedbObject()); } if (objects.Count == 0) return objects; // The rows carry no Props, so they are loaded whatever SkipPropsLoading says: that flag keeps the partial // Props of a projection statement, and this statement reads none. var propsLoadTimer = System.Diagnostics.Stopwatch.StartNew(); await loader.LoadPropsForManyAsync(objects, context.ProjectedStructureIds, context.PropsDepth, cancellationToken); propsLoadTimer.Stop(); _logger?.LogDebug("Props loaded via batch (with cache check) in {ElapsedMs} ms", propsLoadTimer.ElapsedMilliseconds); return objects; } /// /// Returns true when the active dialect exposes native PVT projection /// (pvt_build_projection_sql) AND the context has only safe constructs. /// Currently we exclude DistinctByField (uses p_distinct_on path that /// needs separate wiring) and ProjectedStructureIds (legacy by-ids path). /// protected virtual bool CanUsePvtProjection(QueryContext context) where TProps : class, new() { if (_sql.Query_BuildPvtProjectionSqlFunction() is null) return false; if (context.ProjectedFieldPaths is null || context.ProjectedFieldPaths.Count == 0) return false; if (context.DistinctByField != null) return false; if (context.ProjectedStructureIds != null && context.ProjectedStructureIds.Count > 0) return false; return true; } /// /// v2-pvt native projection path. Builds a projection JSON from /// context.ProjectedFieldPaths, asks pvt_build_projection_sql for the /// inner SELECT yielding the requested scalar columns, wraps it into a /// JSON-row shape compatible with the standard materializer, and runs /// it through ConvertFlatPropertiesToHierarchy + MaterializeResultsFromJson. /// The compiled selector (RedbProjectedQueryable) then trims the resulting /// RedbObject<TProps> instances client-side. /// protected virtual async Task ExecuteToListAsyncPvtProjection(QueryContext context, CancellationToken cancellationToken = default) where TProps : class, new() { var facetFilters = _facetBuilder.BuildFacetFilters(context.Filter); var orderByJson = BuildOrderByJson(context); var parameters = _facetBuilder.BuildQueryParameters(context.Limit, context.Offset); // Build projection JSON: one {"field":""} entry per ProjectedFieldPath. // The default alias inside pvt_build_projection equals the field text, so the // resulting inner-SQL columns are named exactly "FirstName", "Address.City", etc. // When IsDistinct is false we add an extra "_id" entry so we can attach the // object id to each materialized RedbObject. Under DISTINCT we drop // "_id" to avoid making every row trivially unique. var includeId = !context.IsDistinct; var projectionJson = BuildPvtProjectionJson(context.ProjectedFieldPaths!, includeId); var invocation = _sql.Query_BuildPvtProjectionSqlInvocation( schemeId : context.SchemeId, limit : parameters.Limit, offset : parameters.Offset ?? 0, maxDepth : context.MaxRecursionDepth ?? 10, distinct : context.IsDistinct, sourceMode : "flat", treeIds : null, hasDistinctOn: false); if (invocation is null) throw new InvalidOperationException( "Query_BuildPvtProjectionSqlInvocation returned null for a projection-PVT-enabled dialect."); object filterParam = string.IsNullOrEmpty(facetFilters) || facetFilters == "{}" ? (object)DBNull.Value : facetFilters; object orderParam = string.IsNullOrEmpty(orderByJson) || orderByJson == "null" || orderByJson == "[]" ? (object)DBNull.Value : orderByJson; var inner = await _context.ExecuteScalarAsync(invocation, new object[] { projectionJson, filterParam, orderParam }, cancellationToken); if (string.IsNullOrWhiteSpace(inner)) throw new InvalidOperationException( "pvt_build_projection_sql returned an empty SQL string for scheme " + context.SchemeId + "."); var wrapped = _sql.Query_WrapPvtProjectionRowsAsJson(inner, includeId) ?? throw new InvalidOperationException("Query_WrapPvtProjectionRowsAsJson returned null for a projection-PVT-enabled dialect."); var sqlTimer = System.Diagnostics.Stopwatch.StartNew(); var rows = await _context.QueryAsync(wrapped, System.Array.Empty(), cancellationToken); sqlTimer.Stop(); _logger?.LogDebug("PVT projection SQL executed in {ElapsedMs} ms ({RowCount} rows)", sqlTimer.ElapsedMilliseconds, rows?.Count ?? 0); if (rows is null || rows.Count == 0) return new List>(); var objects = new System.Text.Json.JsonElement[rows.Count]; for (var i = 0; i < rows.Count; i++) { var json = rows[i].Value; if (string.IsNullOrWhiteSpace(json)) continue; objects[i] = System.Text.Json.JsonDocument.Parse(json).RootElement.Clone(); } // Convert dotted-key properties ("Address.City") into nested objects so // the typed Props deserializer can map them. Then go through the standard // materializer with SkipPropsLoading=true (we already have the Props subset). var hierarchical = ConvertFlatPropertiesToHierarchy(objects); var prevSkip = context.SkipPropsLoading; context.SkipPropsLoading = true; try { return await MaterializeResultsFromJson(hierarchical, context, cancellationToken); } finally { context.SkipPropsLoading = prevSkip; } } /// /// Serializes the projected field paths into the JSON shape expected by /// pvt_build_projection_sql: [{"field":"FirstName"},{"field":"Address.City"}, ...]. /// Adds a trailing {"field":"_id"} entry when is true. /// private static string BuildPvtProjectionJson(List fieldPaths, bool includeId) { var sb = new System.Text.StringBuilder(); sb.Append('['); for (var i = 0; i < fieldPaths.Count; i++) { if (i > 0) sb.Append(','); sb.Append("{\"field\":"); sb.Append(System.Text.Json.JsonSerializer.Serialize(fieldPaths[i])); sb.Append('}'); } if (includeId) { if (fieldPaths.Count > 0) sb.Append(','); sb.Append("{\"field\":\"_id\"}"); } sb.Append(']'); return sb.ToString(); } /// /// Trivial DTO for one-column string result-sets (e.g. get_object_json output). /// private sealed class StringValue { public string Value { get; set; } = string.Empty; } /// /// PROJECTION: Converts flat paths ("Address.City") to hierarchical JSON /// private System.Text.Json.JsonElement[] ConvertFlatPropertiesToHierarchy(System.Text.Json.JsonElement[] objects) { var result = new List(); foreach (var obj in objects) { try { var dict = new Dictionary(); // Copy all properties except properties foreach (var prop in obj.EnumerateObject()) { if (prop.Name == "properties") { // Convert flat properties to hierarchy var hierarchicalProps = ConvertFlatToHierarchy(prop.Value); dict["properties"] = hierarchicalProps; } else { dict[prop.Name] = JsonElementToObject(prop.Value); } } // Serialize back to JsonElement (without Unicode escaping) var jsonOptions = new System.Text.Json.JsonSerializerOptions { Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping }; var json = System.Text.Json.JsonSerializer.Serialize(dict, jsonOptions); var newElement = System.Text.Json.JsonDocument.Parse(json).RootElement.Clone(); result.Add(newElement); } catch (Exception ex) { _logger?.LogWarning(ex, "Error converting flat properties to hierarchy"); result.Add(obj); // Return original on error } } return result.ToArray(); } /// /// Converts flat paths to a hierarchical dictionary /// "Address.City": "Moscow" → {"Address": {"City": "Moscow"}} /// private Dictionary ConvertFlatToHierarchy(System.Text.Json.JsonElement flatProperties) { var result = new Dictionary(); // STEP 1: Collect all paths that are "classes" (have nested fields) // If there is "Address1.Details.Floor", then "Address1" and "Address1.Details" are classes var classPathPrefixes = new HashSet(); foreach (var prop in flatProperties.EnumerateObject()) { var path = prop.Name; var dotIndex = path.LastIndexOf('.'); while (dotIndex > 0) { var prefix = path.Substring(0, dotIndex); classPathPrefixes.Add(prefix); dotIndex = prefix.LastIndexOf('.'); } } // STEP 2: Sort - first nested paths (with dots), then simple ones var props = flatProperties.EnumerateObject() .OrderByDescending(p => p.Name.Contains('.') || p.Name.Contains('[')) .ThenBy(p => p.Name) .ToList(); foreach (var prop in props) { var path = prop.Name; // Skip class GUIDs at ANY nesting level // If the path is in classPathPrefixes — it's a class GUID, skip it if (classPathPrefixes.Contains(path)) { continue; // "Address1", "Address1.Details" are class GUIDs } var value = JsonElementToObject(prop.Value); var segments = ParsePathSegments(path); SetNestedValue(result, segments, value); } return result; } /// /// Parses path into segments taking arrays into account /// "Address.City" → ["Address", "City"] /// "Items[0].Price" → ["Items", "[0]", "Price"] /// private List ParsePathSegments(string path) { var segments = new List(); var current = new System.Text.StringBuilder(); for (int i = 0; i < path.Length; i++) { char c = path[i]; if (c == '.') { if (current.Length > 0) { segments.Add(current.ToString()); current.Clear(); } } else if (c == '[') { if (current.Length > 0) { segments.Add(current.ToString()); current.Clear(); } // Look for closing bracket int closeIndex = path.IndexOf(']', i); if (closeIndex > i) { segments.Add(path.Substring(i, closeIndex - i + 1)); // "[0]" i = closeIndex; } } else { current.Append(c); } } if (current.Length > 0) { segments.Add(current.ToString()); } return segments; } /// /// Sets value by nested path /// private void SetNestedValue(Dictionary root, List segments, object? value) { if (segments.Count == 0) return; var current = root; for (int i = 0; i < segments.Count - 1; i++) { var segment = segments[i]; var nextSegment = segments[i + 1]; // Check if next segment is an array index? bool nextIsArrayIndex = nextSegment.StartsWith("[") && nextSegment.EndsWith("]"); if (segment.StartsWith("[") && segment.EndsWith("]")) { // Current segment is an array index, skip (processed at previous step) continue; } if (!current.ContainsKey(segment)) { // If next segment is an array index, create a list if (nextIsArrayIndex) { current[segment] = new List(); } else { current[segment] = new Dictionary(); } } var next = current[segment]; if (nextIsArrayIndex) { // Extract index/key: "[0]" → "0", "[home]" → "home" var indexStr = nextSegment.Substring(1, nextSegment.Length - 2); if (int.TryParse(indexStr, out int index)) { // ARRAY: numeric index if (next is not List list) { list = new List(); current[segment] = list; } // Expand list if necessary while (list.Count <= index) { list.Add(new Dictionary()); } // Next element after index if (i + 2 < segments.Count) { if (list[index] is Dictionary itemDict) { current = itemDict; } else { var newDict = new Dictionary(); list[index] = newDict; current = newDict; } } else { // Last segment - just a value in the array list[index] = value; return; } } else { // DICTIONARY: string key (e.g. "home") if (next is not Dictionary dict) { dict = new Dictionary(); current[segment] = dict; } // Next element after key if (i + 2 < segments.Count) { if (!dict.ContainsKey(indexStr)) { dict[indexStr] = new Dictionary(); } if (dict[indexStr] is Dictionary keyDict) { current = keyDict; } else { var newDict = new Dictionary(); dict[indexStr] = newDict; current = newDict; } } else { // Last segment - just a value in the dictionary dict[indexStr] = value; return; } } i++; // Skip index segment } else if (next is Dictionary dict) { current = dict; } } // Set final value var lastSegment = segments[segments.Count - 1]; if (!lastSegment.StartsWith("[")) { current[lastSegment] = value; } } /// /// Converts JsonElement to object /// private object? JsonElementToObject(System.Text.Json.JsonElement element) { return element.ValueKind switch { System.Text.Json.JsonValueKind.Null => null, System.Text.Json.JsonValueKind.True => true, System.Text.Json.JsonValueKind.False => false, System.Text.Json.JsonValueKind.Number => element.TryGetInt64(out var l) ? l : element.GetDouble(), System.Text.Json.JsonValueKind.String => element.GetString(), System.Text.Json.JsonValueKind.Array => element.EnumerateArray().Select(JsonElementToObject).ToList(), System.Text.Json.JsonValueKind.Object => element.EnumerateObject() .ToDictionary(p => p.Name, p => JsonElementToObject(p.Value)), _ => element.GetRawText() }; } /// /// Returns the SQL query that will be executed (for debugging) /// public virtual async Task GetSqlPreviewAsync(QueryContext context, CancellationToken cancellationToken = default) where TProps : class, new() { // v2-pvt path: return the inner _id-list SQL produced by pvt_build_query_sql. // The caller can run it directly or wrap with COUNT/EXISTS/get_object_json on the client side. if (CanUsePvtPipeline(context)) { _logger?.LogDebug("PVT SQL Preview: SchemeId={SchemeId}", context.SchemeId); return await GetSqlPreviewAsyncPvt(context, cancellationToken); } var facetFilters = _facetBuilder.BuildFacetFilters(context.Filter); var parameters = _facetBuilder.BuildQueryParameters(context.Limit, context.Offset); var orderByJson = BuildOrderByJson(context); // The preview function of the dialect (one since the Props-level lazy switch was removed, V4) var functionName = _sql.Query_SqlPreviewFunction(); _logger?.LogDebug("Getting SQL Preview: Function={FunctionName}, SchemeId={SchemeId}, Distinct={Distinct}", functionName, context.SchemeId, context.IsDistinct); var sqlQuery = string.Format(_sql.Query_SqlPreviewTemplate(), functionName); var result = await _context.QueryFirstOrDefaultAsync(sqlQuery, new object[] { context.SchemeId, facetFilters, parameters.Limit ?? int.MaxValue, parameters.Offset ?? 0, orderByJson ?? "null", context.MaxRecursionDepth ?? 10, context.IsDistinct }, cancellationToken); // DISTINCT ON (_hash) in preview return result?.sql_preview ?? "-- SQL preview not available"; } /// /// Returns the JSON filter that will be sent to SQL function (for diagnostics) /// public virtual Task GetFilterJsonAsync(QueryContext context, CancellationToken cancellationToken = default) where TProps : class, new() { var facetFilters = _facetBuilder.BuildFacetFilters(context.Filter); return Task.FromResult(facetFilters); } /// /// SQL preview of an AggregateAsync selector (ToAggregateSqlStringAsync): the statement the provider runs for it. /// Every provider builds it from , the requests the execution reads. /// public abstract Task GetAggregateSqlPreviewAsync( QueryContext context, System.Linq.Expressions.Expression, TResult>> selector, CancellationToken cancellationToken = default) where TProps : class, new(); /// /// The aggregate requests of an AggregateAsync selector, read as the execution reads them /// (): a preview built from them shows the statement that runs. /// protected static List ParseAggregateRequests(System.Linq.Expressions.LambdaExpression selector) => AggregateSelectorParser.Parse(selector); /// /// Access rights check result /// private class PermissionCheckResult { public bool HasPermission { get; set; } } // ===== AGGREGATIONS ===== /// /// One aggregate over a redb field: the batch aggregate with one request, as MSSQL Free runs it. It asked the legacy /// aggregate_field function, which no shipped dialect has, and threw on PostgreSQL and SQLite Free. /// public virtual async Task ExecuteAggregateAsync( long schemeId, string fieldPath, AggregateFunction function, string? filterJson = null, CancellationToken cancellationToken = default) { var request = new AggregateRequest { FieldPath = fieldPath ?? string.Empty, Function = function, Alias = "value" }; var batch = await ExecuteAggregateBatchAsync(schemeId, new[] { request }, filterJson, cancellationToken); return batch.Values.TryGetValue("value", out var raw) && raw is not null ? Convert.ToDecimal(raw, System.Globalization.CultureInfo.InvariantCulture) : null; } /// /// Batch aggregation with a facet-JSON filter: one statement for all requests, built by the provider. /// public abstract Task ExecuteAggregateBatchAsync( long schemeId, IEnumerable requests, string? filterJson = null, CancellationToken cancellationToken = default); /// /// Execute single-field aggregation with FilterExpression (Pro version). /// Free fallback: converts FilterExpression to facet-JSON. /// public virtual async Task ExecuteAggregateAsync( long schemeId, string fieldPath, AggregateFunction function, QueryExpressions.FilterExpression? filter, CancellationToken cancellationToken = default) { var filterJson = filter != null ? _facetBuilder.BuildFacetFilters(filter) : null; return await ExecuteAggregateAsync(schemeId, fieldPath, function, filterJson); } /// /// Execute batch aggregation with FilterExpression (Pro version). /// Free fallback: converts FilterExpression to facet-JSON. /// public virtual async Task ExecuteAggregateBatchAsync( long schemeId, IEnumerable requests, QueryExpressions.FilterExpression? filter, CancellationToken cancellationToken = default) { var filterJson = filter != null ? _facetBuilder.BuildFacetFilters(filter) : null; return await ExecuteAggregateBatchAsync(schemeId, requests, filterJson); } // ===== DELETE ===== /// /// Delete objects by FilterExpression. Pro builds its own DELETE; Free reads the ids through the v2-pvt module, as /// a list read does, and deletes them by ids, counting every one it deleted. Free used to ask the removed /// search_objects_simple function for the ids, and a query delete threw NotSupportedException. /// public virtual async Task ExecuteDeleteAsync(long schemeId, QueryExpressions.FilterExpression? filter, CancellationToken cancellationToken = default) { if (_sql.Query_BuildPvtSqlFunction() is null) throw new NotSupportedException( $"A query delete reads the ids through the v2-pvt module, and the dialect {_sql.GetType().Name} has none " + "(Query_BuildPvtSqlFunction returns null)."); var facetFilters = filter != null ? _facetBuilder.BuildFacetFilters(filter) : null; // The objects of the scheme the filter selects: no page, no order, as a count reads them. var invocation = _sql.Query_BuildPvtSqlInvocation( schemeId: schemeId, limit: null, offset: 0, maxDepth: 10, distinct: false, sourceMode: "flat", treeIds: null, hasDistinctOn: false) ?? throw new InvalidOperationException("v2-pvt is enabled by dialect but Query_BuildPvtSqlInvocation returned null."); object filterParam = string.IsNullOrEmpty(facetFilters) || facetFilters == "{}" ? DBNull.Value : facetFilters; var inner = await _context.ExecuteScalarAsync(invocation, new object[] { filterParam, DBNull.Value }, cancellationToken); if (string.IsNullOrWhiteSpace(inner)) throw new InvalidOperationException("pvt_build_query_sql returned an empty SQL string for scheme " + schemeId + "."); var idsSql = _sql.Query_WrapPvtWithIds(inner) ?? throw new InvalidOperationException("Query_WrapPvtWithIds returned null for a PVT-enabled dialect."); var ids = await _context.QueryScalarListAsync(idsSql, System.Array.Empty(), cancellationToken); if (ids.Count == 0) return 0; var deletedCount = await redb.Core.Providers.Base.ObjectDeleteByIds.RunAsync(_context, _sql, ids.ToArray(), cancellationToken); _logger?.LogDebug("DELETE: Deleted {Count} objects by filter", deletedCount); return deletedCount; } }