Path: redb/redb.Core/Query/Grouping/ArrayGroupModuleJson.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/Grouping/ArrayGroupModuleJson.cs
----
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using redb.Core.Query.Aggregation;
namespace redb.Core.Query.Grouping;
///
/// The JSON arguments of the free providers' pvt_build_array_groupby_sql (PostgreSQL and SQL Server modules,
/// SQLite extension): keys [{field, alias}] and aggregates [{field, func, alias, filter?}], where
/// field may be and filter is the condition of a conditional
/// count in the HAVING language. One writer for the three providers.
///
public static class ArrayGroupModuleJson
{
public static string GroupBy(IEnumerable groupFields)
=> JsonSerializer.Serialize(groupFields.Select(g => new Dictionary
{
["field"] = g.FieldPath,
["alias"] = g.Alias
}));
public static string? Aggregations(IReadOnlyList aggregations)
{
if (aggregations.Count == 0) return null;
return JsonSerializer.Serialize(aggregations.Select(a =>
{
var entry = new Dictionary
{
["field"] = string.IsNullOrEmpty(a.FieldPath) ? "*" : a.FieldPath,
["func"] = a.Function switch
{
AggregateFunction.Average => "AVG",
AggregateFunction.Sum => "SUM",
AggregateFunction.Min => "MIN",
AggregateFunction.Max => "MAX",
AggregateFunction.Count => "COUNT",
_ => throw new NotSupportedException($"Aggregation function {a.Function} is not supported for GroupByArray.")
},
["alias"] = a.Alias ?? a.Function.ToString()
};
if (a.ConditionJson != null)
entry["filter"] = JsonDocument.Parse(a.ConditionJson).RootElement.Clone();
return entry;
}));
}
/// A JSON argument or DBNull for an empty one.
public static object Param(string? json)
=> string.IsNullOrEmpty(json) || json == "{}" || json == "null" ? DBNull.Value : json;
}