Skip to content

Commit

Permalink
Implement average aggregation for decimal in SQLite
Browse files Browse the repository at this point in the history
Contributes to dotnet#19635
  • Loading branch information
ranma42 committed May 15, 2024
1 parent 5ffdda0 commit 50b76b6
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -53,9 +53,14 @@ public SqliteQueryableAggregateMethodTranslator(ISqlExpressionFactory sqlExpress
var averageArgumentType = GetProviderType(averageSqlExpression);
if (averageArgumentType == typeof(decimal))
{
throw new NotSupportedException(
SqliteStrings.AggregateOperationNotSupported(
nameof(Queryable.Average), averageArgumentType.ShortDisplayName()));
averageSqlExpression = CombineTerms(source, averageSqlExpression);
return _sqlExpressionFactory.Function(
"ef_avg",
[averageSqlExpression],
nullable: true,
argumentsPropagateNullability: [false],
averageSqlExpression.Type,
averageSqlExpression.TypeMapping);
}

break;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,17 @@ private void InitializeDbConnection(DbConnection connection)
name: "ef_negate",
(decimal? m) => -m,
isDeterministic: true);

sqliteConnection.CreateAggregate(
"ef_avg",
seed: (0m, 0ul),
((decimal sum, ulong count) acc, decimal? value) => value is null
? acc
: (acc.sum + value.Value, acc.count + 1),
((decimal sum, ulong count) acc) => acc.count == 0
? default(decimal?)
: acc.sum / acc.count,
isDeterministic: true);
}
else
{
Expand Down

0 comments on commit 50b76b6

Please sign in to comment.