Path: redb/redb.SQLite/Query/SqliteQueryProvider.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.SQLite/Query/SqliteQueryProvider.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.SQLite.Query;
///
/// PVT-backed terminal aggregations for free SQLite. Generates the
/// aggregate SQL via the server-side compiler pvt_build_aggregate_sql
/// (free PVT v2 module) and executes the produced statement client-side,
/// wrapping the single result row with row_to_json to materialize
/// in a single round-trip after the build step.
///
/// Overrides the FilterExpression-typed virtual methods on the base provider.
/// Legacy facet-JSON overloads stay on the base type for dialects without
/// the PVT module (e.g. MSSql).
///
public partial class SqliteQueryProvider
{
///
/// 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)
};
}
///
/// Batch aggregate path: builds aggregations JSON, asks
/// pvt_build_aggregate_sql to compile the inner SQL, then executes
/// it through row_to_json 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 (RedbQueryable.AggregateAsync)
/// hit the v2-pvt module instead of the deprecated aggregate_batch
/// SQL function (now removed from PG 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();
var innerSql = await BuildAggregateSqlAsync(schemeId, list, filterJson, cancellationToken);
// SQLite has no row_to_json: execute the (fully-literal) inner SQL and
// serialize its single result row to a JSON object in C#.
var jsonRow = await FirstRowAsJsonAsync(innerSql);
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 pvt_build_aggregate_sql compiles for the
/// same requests and filter as the execution, which runs it as it is. 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 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);
object filterParam = string.IsNullOrEmpty(filterJson) || filterJson == "{}" || filterJson == "null"
? DBNull.Value
: (object)filterJson!;
// SQLite arg list mirrors PG positionally but without ::type casts (SQLite
// chokes on "::") and with 1/1 for the include_seed/polymorphic booleans.
var invocation = "SELECT pvt_build_aggregate_sql("
+ schemeId.ToString(CultureInfo.InvariantCulture)
+ ", $1, $2, 'flat', NULL, NULL, 1, 1) AS \"Value\"";
_logger?.LogDebug("PVT Aggregate Build: 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(
"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
/// pvt_build_aggregate_sql:
/// [{"alias":"x","$sum":{"$field":"Price"}}, {"alias":"y","$count":"*"}].
/// Count with empty FieldPath 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 pvt_build_aggregate_sql.")
};
var entry = new Dictionary { ["alias"] = alias };
// RedbQueryable / RedbGroupedQueryable encode COUNT(*) as FieldPath "*";
// PVT expects the literal star as the operand string, not as a field reference.
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()
};
}