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