Skip to content

Commit

Permalink
Query: Add support for custom aggregate operators
Browse files Browse the repository at this point in the history
Resolves #22957

- Introduce IAggregateMethodCallTranslator and family to translate aggregate methods
- Currently we assume that either method instance or first argument (for static method) will be the one which can be of type enumerable, rest of the arguments if any are scalar.
- Also refactor code in SqlTranslator.VisitMethodCall to avoid visiting grouping element source multiple times
  • Loading branch information
smitpatel committed May 24, 2022
1 parent 176f301 commit e89465f
Show file tree
Hide file tree
Showing 31 changed files with 1,102 additions and 605 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ public static readonly IDictionary<Type, ServiceCharacteristics> RelationalServi
{ typeof(IModificationCommandBatchFactory), new ServiceCharacteristics(ServiceLifetime.Scoped) },
{ typeof(IRelationalSqlTranslatingExpressionVisitorFactory), new ServiceCharacteristics(ServiceLifetime.Scoped) },
{ typeof(IMethodCallTranslatorProvider), new ServiceCharacteristics(ServiceLifetime.Scoped) },
{ typeof(IAggregateMethodCallTranslatorProvider), new ServiceCharacteristics(ServiceLifetime.Scoped) },
{ typeof(IMemberTranslatorProvider), new ServiceCharacteristics(ServiceLifetime.Scoped) },
{ typeof(ISqlExpressionFactory), new ServiceCharacteristics(ServiceLifetime.Scoped) },
{ typeof(IRelationalQueryStringFactory), new ServiceCharacteristics(ServiceLifetime.Scoped) },
Expand Down Expand Up @@ -171,6 +172,7 @@ public override EntityFrameworkServicesBuilder TryAddCoreServices()
TryAdd<IShapedQueryCompilingExpressionVisitorFactory, RelationalShapedQueryCompilingExpressionVisitorFactory>();
TryAdd<IQueryableMethodTranslatingExpressionVisitorFactory, RelationalQueryableMethodTranslatingExpressionVisitorFactory>();
TryAdd<IMethodCallTranslatorProvider, RelationalMethodCallTranslatorProvider>();
TryAdd<IAggregateMethodCallTranslatorProvider, RelationalAggregateMethodCallTranslatorProvider>();
TryAdd<IMemberTranslatorProvider, RelationalMemberTranslatorProvider>();
TryAdd<IQueryTranslationPostprocessorFactory, RelationalQueryTranslationPostprocessorFactory>();
TryAdd<IRelationalSqlTranslatingExpressionVisitorFactory, RelationalSqlTranslatingExpressionVisitorFactory>();
Expand Down Expand Up @@ -202,6 +204,7 @@ public override EntityFrameworkServicesBuilder TryAddCoreServices()
.AddDependencyScoped<HistoryRepositoryDependencies>()
.AddDependencyScoped<RelationalCompiledQueryCacheKeyGeneratorDependencies>()
.AddDependencyScoped<RelationalMethodCallTranslatorProviderDependencies>()
.AddDependencyScoped<RelationalAggregateMethodCallTranslatorProviderDependencies>()
.AddDependencyScoped<RelationalMemberTranslatorProviderDependencies>()
.AddDependencyScoped<SqlExpressionFactoryDependencies>()
.AddDependencyScoped<RelationalSqlTranslatingExpressionVisitorDependencies>()
Expand Down
32 changes: 32 additions & 0 deletions src/EFCore.Relational/Query/IAggregateMethodCallTranslator.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using Microsoft.EntityFrameworkCore.Query.SqlExpressions;

namespace Microsoft.EntityFrameworkCore.Query;

/// <summary>
/// <para>
/// A SQL translator for LINQ <see cref="MethodCallExpression" /> expression represending an aggregate function.
/// </para>
/// <para>
/// This interface is typically used by database providers (and other extensions). It is generally
/// not used in application code.
/// </para>
/// </summary>
public interface IAggregateMethodCallTranslator
{
/// <summary>
/// Translates a LINQ <see cref="MethodCallExpression" /> to a SQL equivalent.
/// </summary>
/// <param name="method">The method info from <see cref="MethodCallExpression.Method" />.</param>
/// <param name="source">The source on which the aggregate method is applied.</param>
/// <param name="arguments">SQL representations of scalar <see cref="MethodCallExpression.Arguments" />.</param>
/// <param name="logger">The query logger to use.</param>
/// <returns>A SQL translation of the <see cref="MethodCallExpression" />.</returns>
SqlExpression? Translate(
MethodInfo method,
EnumerableExpression source,
IReadOnlyList<SqlExpression> arguments,
IDiagnosticsLogger<DbLoggerCategory.Query> logger);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

namespace Microsoft.EntityFrameworkCore.Query;

/// <summary>
/// Represents plugin for <see cref="IAggregateMethodCallTranslator" />.
/// </summary>
/// <remarks>
/// The service lifetime is <see cref="ServiceLifetime.Scoped" /> and multiple registrations
/// are allowed. This means that each <see cref="DbContext" /> instance will use its own
/// set of instances of this service.
/// The implementations may depend on other services registered with any lifetime.
/// The implementations do not need to be thread-safe.
/// </remarks>
public interface IAggregateMethodCallTranslatorPlugin
{
/// <summary>
/// Gets the method call translators.
/// </summary>
IEnumerable<IAggregateMethodCallTranslator> Translators { get; }
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using Microsoft.EntityFrameworkCore.Query.SqlExpressions;

namespace Microsoft.EntityFrameworkCore.Query;

/// <summary>
/// Provides translations for LINQ <see cref="MethodCallExpression" /> expressions which represents aggregate methods.
/// </summary>
/// <remarks>
/// The service lifetime is <see cref="ServiceLifetime.Scoped" /> and multiple registrations
/// are allowed. This means that each <see cref="DbContext" /> instance will use its own
/// set of instances of this service.
/// The implementations may depend on other services registered with any lifetime.
/// The implementations do not need to be thread-safe.
/// </remarks>
public interface IAggregateMethodCallTranslatorProvider
{
/// <summary>
/// Translates a LINQ aggregate <see cref="MethodCallExpression" /> to a SQL equivalent.
/// </summary>
/// <param name="model">A model to use for translation.</param>
/// <param name="method">The method info from <see cref="MethodCallExpression.Method" />.</param>
/// <param name="source">The source on which the aggregate method is applied.</param>
/// <param name="arguments">SQL representations of scalar <see cref="MethodCallExpression.Arguments" />.</param>
/// <param name="logger">The query logger to use.</param>
/// <returns>A SQL translation of the <see cref="MethodCallExpression" />.</returns>
SqlExpression? Translate(
IModel model,
MethodInfo method,
EnumerableExpression source,
IReadOnlyList<SqlExpression> arguments,
IDiagnosticsLogger<DbLoggerCategory.Query> logger);
}
1 change: 0 additions & 1 deletion src/EFCore.Relational/Query/IMethodCallTranslator.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Diagnostics.CodeAnalysis;
using Microsoft.EntityFrameworkCore.Query.SqlExpressions;

namespace Microsoft.EntityFrameworkCore.Query;
Expand Down
10 changes: 6 additions & 4 deletions src/EFCore.Relational/Query/IMethodCallTranslatorProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,14 @@
namespace Microsoft.EntityFrameworkCore.Query;

/// <summary>
/// Provides translations for LINQ <see cref="MethodCallExpression" /> expressions.
/// Provides translations for LINQ <see cref="MethodCallExpression" /> expressions which represents scalar methods.
/// </summary>
/// <remarks>
/// The service lifetime is <see cref="ServiceLifetime.Singleton" />. This means a single instance
/// is used by many <see cref="DbContext" /> instances. The implementation must be thread-safe.
/// This service cannot depend on services registered as <see cref="ServiceLifetime.Scoped" />.
/// The service lifetime is <see cref="ServiceLifetime.Scoped" /> and multiple registrations
/// are allowed. This means that each <see cref="DbContext" /> instance will use its own
/// set of instances of this service.
/// The implementations may depend on other services registered with any lifetime.
/// The implementations do not need to be thread-safe.
/// </remarks>
public interface IMethodCallTranslatorProvider
{
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,180 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using Microsoft.EntityFrameworkCore.Query.SqlExpressions;

namespace Microsoft.EntityFrameworkCore.Query.Internal;

/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public class QueryableAggregateMethodTranslator : IAggregateMethodCallTranslator
{
private readonly ISqlExpressionFactory _sqlExpressionFactory;

/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public QueryableAggregateMethodTranslator(ISqlExpressionFactory sqlExpressionFactory)
{
_sqlExpressionFactory = sqlExpressionFactory;
}

/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public virtual SqlExpression? Translate(
MethodInfo method, EnumerableExpression source, IReadOnlyList<SqlExpression> arguments,
IDiagnosticsLogger<DbLoggerCategory.Query> logger)
{
if (method.DeclaringType == typeof(Queryable))
{
var methodInfo = method.IsGenericMethod
? method.GetGenericMethodDefinition()
: method;
switch (methodInfo.Name)
{
case nameof(Queryable.Average)
when (QueryableMethods.IsAverageWithoutSelector(methodInfo)
|| QueryableMethods.IsAverageWithSelector(methodInfo))
&& source.Selector is SqlExpression averageSqlExpression:
var averageInputType = averageSqlExpression.Type;
if (averageInputType == typeof(int)
|| averageInputType == typeof(long))
{
averageSqlExpression = _sqlExpressionFactory.ApplyDefaultTypeMapping(
_sqlExpressionFactory.Convert(averageSqlExpression, typeof(double)));
}

averageSqlExpression = CombineTerms(source, averageSqlExpression);
return averageInputType == typeof(float)
? _sqlExpressionFactory.Convert(
_sqlExpressionFactory.Function(
"AVG",
new[] { averageSqlExpression },
nullable: true,
argumentsPropagateNullability: new[] { false },
typeof(double)),
averageSqlExpression.Type,
averageSqlExpression.TypeMapping)
: _sqlExpressionFactory.Function(
"AVG",
new[] { averageSqlExpression },
nullable: true,
argumentsPropagateNullability: new[] { false },
averageSqlExpression.Type,
averageSqlExpression.TypeMapping);

case nameof(Queryable.Count)
when methodInfo == QueryableMethods.CountWithoutPredicate
|| methodInfo == QueryableMethods.CountWithPredicate:
var countSqlExpression = (source.Selector as SqlExpression) ?? _sqlExpressionFactory.Fragment("*");
countSqlExpression = CombineTerms(source, countSqlExpression);
return _sqlExpressionFactory.ApplyDefaultTypeMapping(
_sqlExpressionFactory.Function(
"COUNT",
new[] { countSqlExpression },
nullable: false,
argumentsPropagateNullability: new[] { false },
typeof(int)));

case nameof(Queryable.LongCount)
when methodInfo == QueryableMethods.LongCountWithoutPredicate
|| methodInfo == QueryableMethods.LongCountWithPredicate:
var longCountSqlExpression = (source.Selector as SqlExpression) ?? _sqlExpressionFactory.Fragment("*");
longCountSqlExpression = CombineTerms(source, longCountSqlExpression);

return _sqlExpressionFactory.ApplyDefaultTypeMapping(
_sqlExpressionFactory.Function(
"COUNT",
new[] { longCountSqlExpression },
nullable: false,
argumentsPropagateNullability: new[] { false },
typeof(long)));

case nameof(Queryable.Max)
when (methodInfo == QueryableMethods.MaxWithoutSelector
|| methodInfo == QueryableMethods.MaxWithSelector)
&& source.Selector is SqlExpression maxSqlExpression:
maxSqlExpression = CombineTerms(source, maxSqlExpression);
return _sqlExpressionFactory.Function(
"MAX",
new[] { maxSqlExpression },
nullable: true,
argumentsPropagateNullability: new[] { false },
maxSqlExpression.Type,
maxSqlExpression.TypeMapping);

case nameof(Queryable.Min)
when (methodInfo == QueryableMethods.MinWithoutSelector
|| methodInfo == QueryableMethods.MinWithSelector)
&& source.Selector is SqlExpression minSqlExpression:
minSqlExpression = CombineTerms(source, minSqlExpression);
return _sqlExpressionFactory.Function(
"MIN",
new[] { minSqlExpression },
nullable: true,
argumentsPropagateNullability: new[] { false },
minSqlExpression.Type,
minSqlExpression.TypeMapping);

case nameof(Queryable.Sum)
when (QueryableMethods.IsSumWithoutSelector(methodInfo)
|| QueryableMethods.IsSumWithSelector(methodInfo))
&& source.Selector is SqlExpression sumSqlExpression:
sumSqlExpression = CombineTerms(source, sumSqlExpression);
var sumInputType = sumSqlExpression.Type;
return sumInputType == typeof(float)
? _sqlExpressionFactory.Convert(
_sqlExpressionFactory.Function(
"SUM",
new[] { sumSqlExpression },
nullable: true,
argumentsPropagateNullability: new[] { false },
typeof(double)),
sumInputType,
sumSqlExpression.TypeMapping)
: _sqlExpressionFactory.Function(
"SUM",
new[] { sumSqlExpression },
nullable: true,
argumentsPropagateNullability: new[] { false },
sumInputType,
sumSqlExpression.TypeMapping);
}
}

return null;
}

private SqlExpression CombineTerms(EnumerableExpression enumerableExpression, SqlExpression sqlExpression)
{
if (enumerableExpression.Predicate != null)
{
if (sqlExpression is SqlFragmentExpression)
{
sqlExpression = _sqlExpressionFactory.Constant(1);
}

sqlExpression = _sqlExpressionFactory.Case(
new List<CaseWhenClause> { new(enumerableExpression.Predicate, sqlExpression) },
elseResult: null);
}

if (enumerableExpression.IsDistinct)
{
sqlExpression = new DistinctExpression(sqlExpression);
}

return sqlExpression;
}
}
Loading

0 comments on commit e89465f

Please sign in to comment.