Path: redb/redb.MSSql/Query/MssqlQueryProvider.Aggregation.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.MSSql/Query/MssqlQueryProvider.Aggregation.cs ---- using System; using System.Collections.Generic; using System.Globalization; 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.Models.Entities; using redb.Core.Query; using redb.Core.Query.Aggregation; using redb.Core.Query.QueryExpressions; namespace redb.MSSql.Query; /// /// PVT-backed terminal aggregations for free MSSql. Generates the /// aggregate SQL via the server-side compiler dbo.pvt_build_aggregate_sql /// (free PVT v2 module) and executes the produced statement client-side, /// wrapping the single result row with FOR JSON PATH, WITHOUT_ARRAY_WRAPPER /// to materialize in one round-trip after the /// build step. /// /// Mirrors PostgresQueryProvider.Aggregation.cs — the goal is to keep /// every aggregation request expressible as facet/aggregations JSON that /// non-.NET clients can submit directly (e.g. a Python service composing a /// facet AST and dispatching it through the SQL dialect's UDF). /// /// Overrides the FilterExpression-typed virtual methods on the base provider. /// Legacy facet-JSON overloads are also overridden because the MSSql /// dialect's Query_AggregateField/Batch functions throw — we route /// every aggregate path through the v2-pvt compiler instead. /// public partial class MssqlQueryProvider { /// /// Single-aggregate path. Delegates to /// with a one-element request list and extracts the scalar value. /// public override async Task ExecuteAggregateAsync( long schemeId, string fieldPath, AggregateFunction function, FilterExpression? filter, CancellationToken cancellationToken = default) { var request = new AggregateRequest { FieldPath = fieldPath ?? string.Empty, Function = function, Alias = "value" }; var batch = await ExecuteAggregateBatchAsync(schemeId, new[] { request }, filter); if (!batch.Values.TryGetValue("value", out var raw) || raw is null) return null; return raw switch { decimal d => d, double dbl => redb.Core.Utils.RedbDecimal.FromDouble(dbl), long l => l, int i => i, _ => Convert.ToDecimal(raw, CultureInfo.InvariantCulture) }; } /// /// Single-aggregate path for facet-JSON callers (legacy /// /// overload). Bypasses the throwing dialect SQL and routes through the /// v2-pvt aggregate compiler. /// public override 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 ExecuteAggregateBatchInternalAsync(schemeId, new[] { request }, filterJson); if (!batch.Values.TryGetValue("value", out var raw) || raw is null) return null; return raw switch { decimal d => d, double dbl => redb.Core.Utils.RedbDecimal.FromDouble(dbl), long l => l, int i => i, _ => Convert.ToDecimal(raw, CultureInfo.InvariantCulture) }; } /// /// Batch aggregate path: builds aggregations JSON, asks /// dbo.pvt_build_aggregate_sql to compile the inner SQL, then executes /// it through FOR JSON PATH, WITHOUT_ARRAY_WRAPPER to capture every /// alias in one row. /// public override Task ExecuteAggregateBatchAsync( long schemeId, IEnumerable requests, FilterExpression? filter, CancellationToken cancellationToken = default) { var facetFilters = filter is null ? null : _facetBuilder.BuildFacetFilters(filter); return ExecuteAggregateBatchInternalAsync(schemeId, requests, facetFilters); } /// /// Batch aggregate path with pre-built facet-JSON filter. Same PVT pipeline /// as the overload — overriding the base /// virtual ensures custom-projection callers /// () /// hit the v2-pvt module instead of the throwing legacy SQL function on the /// MSSql dialect. /// public override Task ExecuteAggregateBatchAsync( long schemeId, IEnumerable requests, string? filterJson = null, CancellationToken cancellationToken = default) { return ExecuteAggregateBatchInternalAsync(schemeId, requests, filterJson); } internal async Task ExecuteAggregateBatchInternalAsync( long schemeId, IEnumerable requests, string? filterJson, CancellationToken cancellationToken = default) { var list = requests?.ToList() ?? throw new ArgumentNullException(nameof(requests)); if (list.Count == 0) return new AggregateResult(); // Step 1: the server-side compiler builds the inner aggregate SELECT. var innerSql = await BuildAggregateSqlAsync(schemeId, list, filterJson, cancellationToken); // Step 2: wrap with FOR JSON to capture every alias in one row. // INCLUDE_NULL_VALUES preserves nulls so MIN/MAX over empty sets // round-trip as JSON null instead of being silently dropped. var wrapped = "SELECT (SELECT * FROM (" + innerSql + ") _agg_row FOR JSON PATH, WITHOUT_ARRAY_WRAPPER, INCLUDE_NULL_VALUES)"; var jsonRow = await _context.ExecuteScalarAsync(wrapped, System.Array.Empty(), cancellationToken); var result = new AggregateResult(); if (!string.IsNullOrEmpty(jsonRow)) { using var doc = JsonDocument.Parse(jsonRow); foreach (var prop in doc.RootElement.EnumerateObject()) { result.Values[prop.Name] = ConvertJsonValue(prop.Value); } } return result; } /// /// SQL preview of an AggregateAsync selector: the aggregate statement dbo.pvt_build_aggregate_sql compiles for /// the same requests and filter as the execution, which reads its one row through FOR JSON PATH. The base /// implementation asked for aggregate_batch_preview, a function of the removed legacy module. /// public override async Task GetAggregateSqlPreviewAsync( QueryContext context, Expression, TResult>> selector, CancellationToken cancellationToken = default) { var requests = ParseAggregateRequests(selector); if (requests.Count == 0) return "-- No aggregations specified"; var facetFilters = context.Filter is null ? null : _facetBuilder.BuildFacetFilters(context.Filter); return await BuildAggregateSqlAsync(context.SchemeId, requests, facetFilters, cancellationToken); } /// The aggregate statement dbo.pvt_build_aggregate_sql compiles for the requests; it binds no parameters. private async Task BuildAggregateSqlAsync( long schemeId, IList requests, string? filterJson, CancellationToken cancellationToken) { var aggregationsJson = BuildPvtAggregationsJson(requests); // pvt_build_aggregate_sql expects NULL for the empty / missing filter // (a literal "{}" or "null" string would defeat the IS NULL branch in // pvt_collect_fields and produce a missing-meta marker downstream). object filterParam = string.IsNullOrEmpty(filterJson) || filterJson == "{}" || filterJson == "null" ? DBNull.Value : (object)filterJson!; // $1 → @p0 = filter, $2 → @p1 = aggregations (mirrors PG ordering). var invocation = "SELECT dbo.pvt_build_aggregate_sql(" + schemeId.ToString(CultureInfo.InvariantCulture) + ", $1, $2, N'flat')"; _logger?.LogDebug("PVT Aggregate Build (MSSql): SchemeId={SchemeId}, Aggs={Aggs}, Filter={Filter}", schemeId, aggregationsJson, filterJson ?? "null"); var innerSql = await _context.ExecuteScalarAsync(invocation, new object[] { filterParam, aggregationsJson }, cancellationToken); if (string.IsNullOrWhiteSpace(innerSql)) throw new InvalidOperationException( "dbo.pvt_build_aggregate_sql returned an empty SQL string for scheme " + schemeId + "."); return innerSql; } /// /// Serializes an aggregate request list to the JSON shape consumed by /// dbo.pvt_build_aggregate_sql: /// [{"alias":"x","$sum":{"$field":"Price"}}, {"alias":"y","$count":"*"}]. /// Count with empty becomes /// $count: "*". /// private static string BuildPvtAggregationsJson(IList requests) { var auto = 0; var entries = new List>(requests.Count); foreach (var r in requests) { auto++; var alias = string.IsNullOrEmpty(r.Alias) ? "_agg_" + auto : r.Alias!; var opKey = r.Function switch { AggregateFunction.Sum => "$sum", AggregateFunction.Average => "$avg", AggregateFunction.Min => "$min", AggregateFunction.Max => "$max", AggregateFunction.Count => "$count", _ => throw new NotSupportedException( "Aggregation function " + r.Function + " is not supported by dbo.pvt_build_aggregate_sql.") }; var entry = new Dictionary { ["alias"] = alias }; var isCountStar = r.Function == AggregateFunction.Count && (string.IsNullOrEmpty(r.FieldPath) || r.FieldPath == "*"); if (isCountStar) { entry[opKey] = "*"; } else { FieldPathRefusal.EnsureModuleAggregateCanRead(r.FieldPath); entry[opKey] = new Dictionary { ["$field"] = NormalizePvtFieldName(r.FieldPath, r.IsBaseField) }; } // Agg.Count(g, x => condition): the module compiles it as a per-aggregate filter. if (r.ConditionJson != null) entry["filter"] = JsonDocument.Parse(r.ConditionJson).RootElement.Clone(); entries.Add(entry); } return JsonSerializer.Serialize(entries); } private static object? ConvertJsonValue(JsonElement el) => el.ValueKind switch { JsonValueKind.Number => el.TryGetDecimal(out var d) ? d : (object)el.GetDouble(), JsonValueKind.String => el.GetString(), JsonValueKind.True => true, JsonValueKind.False => false, JsonValueKind.Null => null, _ => el.GetRawText() }; }