Path: redb/redb.MSSql/Query/MssqlQueryProvider.Grouping.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.Grouping.cs ---- using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using redb.Core.Query.Aggregation; using redb.Core.Query.Grouping; using redb.Core.Query.QueryExpressions; namespace redb.MSSql.Query; /// /// PVT-backed GROUP BY for free MSSql. Generates the projection SQL via the /// server-side compiler dbo.pvt_build_groupby_sql and wraps it with /// FOR JSON PATH to materialize a JSON array of group rows in one /// round-trip after the build step. /// /// Mirrors PostgresQueryProvider.Grouping.cs — every grouping request /// is compiled by the SQL UDF so non-.NET callers can submit the same /// filter/group-by/aggregations JSON directly. /// public partial class MssqlQueryProvider { /// public override Task ExecuteGroupedAggregateAsync( long schemeId, IEnumerable groupFields, IEnumerable aggregations, string? filterJson = null, string? havingJson = null, CancellationToken cancellationToken = default) { return ExecuteGroupedAggregateInternalAsync(schemeId, groupFields, aggregations, filterJson, havingJson); } /// public override Task ExecuteGroupedAggregateAsync( long schemeId, IEnumerable groupFields, IEnumerable aggregations, FilterExpression? filter, string? havingJson = null, CancellationToken cancellationToken = default) { var filterJson = filter is null ? null : _facetBuilder.BuildFacetFilters(filter); return ExecuteGroupedAggregateInternalAsync(schemeId, groupFields, aggregations, filterJson, havingJson); } private async Task ExecuteGroupedAggregateInternalAsync( long schemeId, IEnumerable groupFields, IEnumerable aggregations, string? filterJson, string? havingJson = null, CancellationToken cancellationToken = default) { var groupList = groupFields?.ToList() ?? new List(); var aggList = aggregations?.ToList() ?? new List(); // Empty group-by => degenerate to a flat batch aggregate. if (groupList.Count == 0) { if (!string.IsNullOrEmpty(havingJson)) throw new NotSupportedException( "HAVING requires GROUP BY keys; cannot be combined with a flat aggregate batch."); if (aggList.Count == 0) return null; var aggResult = await ExecuteAggregateBatchInternalAsync(schemeId, aggList, filterJson); var rowJson = JsonSerializer.Serialize(new[] { aggResult.Values }); return JsonDocument.Parse(rowJson); } var innerSql = await BuildGroupByInnerSqlAsync(schemeId, groupList, aggList, filterJson, havingJson); // Wrap the inner SELECT with FOR JSON PATH to materialize a JSON array // of group rows. INCLUDE_NULL_VALUES preserves null group keys. var wrapped = "SELECT (SELECT * FROM (" + innerSql + ") _grp_rows FOR JSON PATH, INCLUDE_NULL_VALUES)"; var jsonArray = await _context.ExecuteScalarAsync(wrapped, System.Array.Empty(), cancellationToken); if (string.IsNullOrEmpty(jsonArray)) return JsonDocument.Parse("[]"); return JsonDocument.Parse(jsonArray); } /// /// Returns the inner SELECT compiled by dbo.pvt_build_groupby_sql for /// the requested grouping. Mirrors PostgreSQL's GetGroupBySqlPreviewAsync /// so ToSqlStringAsync on grouped queryables surfaces the actual SQL /// instead of a "preview not supported" placeholder. /// public override async Task GetGroupBySqlPreviewAsync( long schemeId, IEnumerable groupFields, IEnumerable aggregations, string? filterJson, string? havingJson = null, CancellationToken cancellationToken = default) { var groupList = groupFields?.ToList() ?? new List(); var aggList = aggregations?.ToList() ?? new List(); if (groupList.Count == 0) throw new ArgumentException("A GroupBy SQL preview needs at least one key.", nameof(groupFields)); return await BuildGroupByInnerSqlAsync(schemeId, groupList, aggList, filterJson, havingJson); } /// /// FilterExpression overload of /// . /// public override Task GetGroupBySqlPreviewAsync( long schemeId, IEnumerable groupFields, IEnumerable aggregations, FilterExpression? filter, string? havingJson = null, CancellationToken cancellationToken = default) { var filterJson = filter is null ? null : _facetBuilder.BuildFacetFilters(filter); return GetGroupBySqlPreviewAsync(schemeId, groupFields, aggregations, filterJson, havingJson); } private async Task BuildGroupByInnerSqlAsync( long schemeId, IList groupList, IList aggList, string? filterJson, string? havingJson = null, CancellationToken cancellationToken = default) { var groupByJson = BuildPvtGroupByJson(groupList); var aggregationsJson = aggList.Count == 0 ? null : BuildPvtAggregationsJson(aggList); object filterParam = string.IsNullOrEmpty(filterJson) || filterJson == "{}" || filterJson == "null" ? DBNull.Value : (object)filterJson!; object aggParam = aggregationsJson is null ? DBNull.Value : (object)aggregationsJson; // The HAVING used to be dropped here (NULL was passed), and GroupBy(...).Having(...) returned every group. object havingParam = string.IsNullOrEmpty(havingJson) ? DBNull.Value : (object)havingJson; // pvt_build_groupby_sql(@scheme_id, @filter, @group_by, @aggs, @having, @order, @limit, @offset, @source_mode) // $1 = filter, $2 = group_by, $3 = aggregations, $4 = having var invocation = "SELECT dbo.pvt_build_groupby_sql(" + schemeId.ToString(CultureInfo.InvariantCulture) + ", $1, $2, $3, $4, NULL, NULL, 0, N'flat')"; _logger?.LogDebug( "PVT GroupBy Build (MSSql): SchemeId={SchemeId}, GroupBy={GroupBy}, Aggs={Aggs}, Filter={Filter}, Having={Having}", schemeId, groupByJson, aggregationsJson ?? "null", filterJson ?? "null", havingJson ?? "null"); var innerSql = await _context.ExecuteScalarAsync(invocation, new object[] { filterParam, groupByJson, aggParam, havingParam }, cancellationToken); if (string.IsNullOrWhiteSpace(innerSql)) throw new InvalidOperationException( "dbo.pvt_build_groupby_sql could not compile this grouping for scheme " + schemeId + (havingJson is null ? "." : " - the HAVING " + havingJson + " has a shape it does not support.")); return innerSql!; } /// /// Serializes group fields to the JSON shape consumed by /// dbo.pvt_build_groupby_sql: [{"field":"Department","alias":"Dept"}]. /// Base fields get the 0$: prefix so PVT resolves them to the /// underlying _objects column. /// private static string BuildPvtGroupByJson(IList groupFields) { var entries = new List>(groupFields.Count); foreach (var g in groupFields) { var entry = new Dictionary { ["field"] = NormalizePvtFieldName(g.FieldPath, g.IsBaseField) }; if (!string.IsNullOrEmpty(g.Alias)) entry["alias"] = g.Alias!; entries.Add(entry); } return JsonSerializer.Serialize(entries); } /// /// Applies the 0$: base-field prefix when /// is and the path is not already prefixed. /// internal static string NormalizePvtFieldName(string? fieldPath, bool isBaseField) { var path = fieldPath ?? string.Empty; if (!isBaseField) return path; if (path.Length == 0 || path.StartsWith("0$:", StringComparison.Ordinal) || path[0] == '_') return path; return "0$:" + path; } /// /// GroupByArray on the free SQL Server provider: dbo.pvt_build_array_groupby_sql of the module builds the /// grouping (and its HAVING); a window over the groups is written around it by . /// The module function cannot raise, so it answers what it refuses with NULL, and this refuses in turn. /// public override async Task ExecuteArrayGroupQueryAsync(ArrayGroupQuery query, CancellationToken cancellationToken = default) { var sql = await BuildArrayGroupSqlAsync(query, cancellationToken); var wrapped = "SELECT (SELECT * FROM (" + sql + ") _grp_rows FOR JSON PATH, INCLUDE_NULL_VALUES)"; var json = await _context.ExecuteScalarAsync(wrapped, System.Array.Empty(), cancellationToken); // FOR JSON gives NULL for no rows. return JsonDocument.Parse(string.IsNullOrEmpty(json) ? "[]" : json); } /// public override Task GetArrayGroupQuerySqlAsync(ArrayGroupQuery query, CancellationToken cancellationToken = default) => BuildArrayGroupSqlAsync(query, cancellationToken); private async Task BuildArrayGroupSqlAsync(ArrayGroupQuery query, CancellationToken cancellationToken) { query.EnsureValid(); var filterJson = query.Filter != null ? _facetBuilder.BuildFacetFilters(query.Filter) : query.FilterJson; var shown = query.Aggregations.ToList(); var aggregations = query.Window == null ? shown : GroupedWindowSelect.WithHiddenAggregates(shown, query.Window.Functions, query.Window.PartitionBy, query.Window.OrderBy); // dbo.pvt_build_array_groupby_sql(@scheme_id, @array_path, @filter, @group_by, @aggregations, @having, @source_mode) var invocation = "SELECT dbo.pvt_build_array_groupby_sql(" + query.SchemeId.ToString(CultureInfo.InvariantCulture) + ", $1, $2, $3, $4, $5, N'flat')"; var innerSql = await _context.ExecuteScalarAsync(invocation, new object[] { query.ArrayPath, ArrayGroupModuleJson.Param(filterJson), ArrayGroupModuleJson.GroupBy(query.GroupFields), ArrayGroupModuleJson.Param(ArrayGroupModuleJson.Aggregations(aggregations)), ArrayGroupModuleJson.Param(query.HavingJson) }, cancellationToken); if (string.IsNullOrWhiteSpace(innerSql)) throw new InvalidOperationException( "dbo.pvt_build_array_groupby_sql refused the grouping of '" + query.ArrayPath + "' for scheme " + query.SchemeId + ": a key, an aggregate, a condition or the outer filter names something the elements or the scheme do not have."); if (innerSql.StartsWith("--error:", StringComparison.Ordinal)) throw new NotSupportedException("GroupByArray (MssqlQueryProvider): " + innerSql["--error:".Length..].Trim()); return query.Window == null ? innerSql : GroupedWindowSelect.Build(innerSql, query.GroupFields, aggregations, shown, query.Window.Functions, query.Window.PartitionBy, query.Window.OrderBy, QuoteGwndIdent, rankingNeedsOrder: true); } }