Skip to content

Add PagingQueryableExtensions for Marten #8260

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 4 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions src/All.slnx
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,13 @@
<Project Path="GreenDonut/src/GreenDonut.Data.Primitives/GreenDonut.Data.Primitives.csproj" />
<Project Path="GreenDonut/src/GreenDonut.Data/GreenDonut.Data.csproj" />
<Project Path="GreenDonut/src/GreenDonut/GreenDonut.csproj" />
<Project Path="GreenDonut\src\GreenDonut.Data.Marten\GreenDonut.Data.Marten.csproj" Type="Classic C#" />
</Folder>
<Folder Name="/GreenDonut/test/">
<Project Path="GreenDonut/test/GreenDonut.Data.EntityFramework.Tests/GreenDonut.Data.EntityFramework.Tests.csproj" />
<Project Path="GreenDonut/test/GreenDonut.Data.Tests/GreenDonut.Data.Tests.csproj" />
<Project Path="GreenDonut/test/GreenDonut.Tests/GreenDonut.Tests.csproj" />
<Project Path="GreenDonut\test\GreenDonut.Data.Marten.Tests\GreenDonut.Data.Marten.Tests.csproj" Type="Classic C#" />
</Folder>
<Folder Name="/HotChocolate/" />
<Folder Name="/HotChocolate/ApolloFederation/" />
Expand Down Expand Up @@ -92,8 +94,8 @@
<Project Path="HotChocolate/Core/src/Subscriptions/HotChocolate.Subscriptions.csproj" />
<Project Path="HotChocolate/Core/src/Types.Abstractions/HotChocolate.Types.Abstractions.csproj" />
<Project Path="HotChocolate/Core/src/Types.Analyzers/HotChocolate.Types.Analyzers.csproj" />
<Project Path="HotChocolate/Core/src/Types.CursorPagination/HotChocolate.Types.CursorPagination.csproj" />
<Project Path="HotChocolate/Core/src/Types.CursorPagination.Extensions/HotChocolate.Types.CursorPagination.Extensions.csproj" />
<Project Path="HotChocolate/Core/src/Types.CursorPagination/HotChocolate.Types.CursorPagination.csproj" />
<Project Path="HotChocolate/Core/src/Types.Errors/HotChocolate.Types.Errors.csproj" />
<Project Path="HotChocolate/Core/src/Types.Json/HotChocolate.Types.Json.csproj" />
<Project Path="HotChocolate/Core/src/Types.Mutations/HotChocolate.Types.Mutations.csproj" />
Expand Down Expand Up @@ -318,4 +320,4 @@
<Folder Name="/StrawberryShake/Tooling/test/">
<Project Path="StrawberryShake/Tooling/test/Configuration.Tests/StrawberryShake.Tools.Configuration.Tests.csproj" />
</Folder>
</Solution>
</Solution>
2 changes: 1 addition & 1 deletion src/Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
<PackageVersion Include="Glob" Version="1.1.9" />
<PackageVersion Include="IdentityModel" Version="4.1.1" />
<PackageVersion Include="JsonPointer.Net" Version="5.0.0" />
<PackageVersion Include="Marten" Version="7.33.0" />
<PackageVersion Include="Marten" Version="7.40.0" />
<PackageVersion Include="McMaster.Extensions.CommandLineUtils" Version="4.0.1" />
<PackageVersion Include="Microsoft.Azure.Functions.Extensions" Version="1.1.0" />
<PackageVersion Include="Microsoft.Azure.Functions.Worker.Core" Version="1.4.0" />
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,185 @@
using System.Collections.Concurrent;
using System.Linq.Expressions;
using System.Reflection;
using GreenDonut.Data.Cursors;

namespace GreenDonut.Data.Expressions;

/// <summary>
/// This class provides helper methods to build slicing where clauses.
/// </summary>
internal static class ExpressionHelpers
{
private static readonly MethodInfo _createAndConvert = typeof(ExpressionHelpers)
.GetMethod(nameof(CreateAndConvertParameter), BindingFlags.NonPublic | BindingFlags.Static)!;

private static readonly ConcurrentDictionary<Type, Func<object?, Expression>> _cachedConverters = new();

/// <summary>
/// Builds a where expression that can be used to slice a dataset.
/// </summary>
/// <param name="keys">
/// The key definitions that represent the cursor.
/// </param>
/// <param name="cursor">
/// The key values that represent the cursor.
/// </param>
/// <param name="forward">
/// Defines how the dataset is sorted.
/// </param>
/// <typeparam name="T">
/// The entity type.
/// </typeparam>
/// <returns>
/// Returns a where expression that can be used to slice a dataset.
/// </returns>
/// <exception cref="ArgumentNullException">
/// If <paramref name="keys"/> or <paramref name="cursor"/> is <c>null</c>.
/// </exception>
/// <exception cref="ArgumentException">
/// If the number of keys does not match the number of values.
/// </exception>
public static (Expression<Func<T, bool>> WhereExpression, int Offset) BuildWhereExpression<T>(
ReadOnlySpan<CursorKey> keys,
Cursor cursor,
bool forward)
{
if (keys.Length == 0)
{
throw new ArgumentException("At least one key must be specified.", nameof(keys));
}

if (keys.Length != cursor.Values.Length)
{
throw new ArgumentException("The number of keys must match the number of values.", nameof(cursor.Values));
}

var cursorExpr = new Expression[cursor.Values.Length];
for (var i = 0; i < cursor.Values.Length; i++)
{
cursorExpr[i] = CreateParameter(cursor.Values[i], keys[i].Expression.ReturnType);
}

var handled = new List<CursorKey>();
Expression? expression = null;

var parameter = Expression.Parameter(typeof(T), "t");

for (var i = 0; i < keys.Length; i++)
{
var key = keys[i];
Expression? current = null;
Expression keyExpr;

// Handle previously processed keys (AND conditions)
foreach (var handledKey in handled)
{
keyExpr = Expression.Equal(
ReplaceParameter(handledKey.Expression, parameter),
cursorExpr[handled.IndexOf(handledKey)]
);

current = current is null ? keyExpr : Expression.AndAlso(current, keyExpr);
}

// Determine the direction of the comparison (greater or less than)
var greaterThan = forward
? key.Direction == CursorKeyDirection.Ascending
: key.Direction == CursorKeyDirection.Descending;

keyExpr = key.Expression.ReturnType switch
{
{ } t when t == typeof(string) => BuildStringComparison(key, parameter, cursorExpr[i], greaterThan),
{ } t when t == typeof(bool) => BuildBooleanComparison(key, parameter, cursorExpr[i], greaterThan),
{ } t when t == typeof(DateTime) => throw new NotSupportedException(
"DateTime comparisons are not supported."),
{ } t when t == typeof(ulong) =>
throw new NotSupportedException("ulong comparisons are not supported."),
{ } t when t == typeof(ushort) => throw new NotSupportedException(
"ushort comparisons are not supported."),
_ => greaterThan
? Expression.GreaterThan(ReplaceParameter(key.Expression, parameter), cursorExpr[i])
: Expression.LessThan(ReplaceParameter(key.Expression, parameter), cursorExpr[i])
};

current = current is null ? keyExpr : Expression.AndAlso(current, keyExpr);
expression = expression is null ? current : Expression.OrElse(expression, current);

handled.Add(key);
}

return (Expression.Lambda<Func<T, bool>>(expression!, parameter), cursor.Offset ?? 0);
}

/// <summary>
/// Helper method to build string comparison using string.Compare
/// </summary>
/// <param name="key"></param>
/// <param name="parameter"></param>
/// <param name="cursorValue"></param>
/// <param name="greaterThan"></param>
/// <returns></returns>
private static Expression BuildStringComparison(CursorKey key, ParameterExpression parameter, Expression cursorValue, bool greaterThan)
{
var memberExpr = ReplaceParameter(key.Expression, parameter);
var compareMethod = typeof(string).GetMethod(nameof(string.Compare), [typeof(string), typeof(string)])!;

// Call string.Compare(memberExpr, cursorValue)
var compareCall = Expression.Call(null, compareMethod, memberExpr, cursorValue);

return greaterThan
? Expression.GreaterThan(compareCall, Expression.Constant(0))
: Expression.LessThan(compareCall, Expression.Constant(0));
}

/// <summary>
/// Helper method to build boolean comparison
/// </summary>
/// <param name="key"></param>
/// <param name="parameter"></param>
/// <param name="cursorValue"></param>
/// <param name="greaterThan"></param>
/// <returns></returns>
private static Expression BuildBooleanComparison(CursorKey key, ParameterExpression parameter, Expression cursorValue, bool greaterThan)
{
var memberExpr = ReplaceParameter(key.Expression, parameter);

return Expression.Equal(memberExpr, cursorValue);
}

private static Expression CreateParameter(object? value, Type type)
{
var converter = _cachedConverters.GetOrAdd(
type,
t =>
{
var method = _createAndConvert.MakeGenericMethod(t);
return v => (Expression)method.Invoke(null, [v])!;
});

return converter(value);
}

private static Expression CreateAndConvertParameter<T>(T value)
{
Expression<Func<T>> lambda = () => value;
return lambda.Body;
}

private static Expression ReplaceParameter(
LambdaExpression expression,
ParameterExpression replacement)
{
var visitor = new ReplaceParameterVisitor(expression.Parameters[0], replacement);
return visitor.Visit(expression.Body);
}

private class ReplaceParameterVisitor(ParameterExpression parameter, Expression replacement)
: ExpressionVisitor
{
protected override Expression VisitParameter(ParameterExpression node)
{
return node == parameter ? replacement : base.VisitParameter(node);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
using System.Linq.Expressions;

namespace GreenDonut.Data.Expressions;

internal sealed class ExtractOrderPropertiesVisitor : ExpressionVisitor
{
private const string _orderByMethod = "OrderBy";
private const string _thenByMethod = "ThenBy";
private const string _orderByDescendingMethod = "OrderByDescending";
private const string _thenByDescendingMethod = "ThenByDescending";
private bool _isOrderScope;

public List<MemberExpression> OrderProperties { get; } = [];

protected override Expression VisitMethodCall(MethodCallExpression node)
{
if (node.Method.Name == _orderByMethod ||
node.Method.Name == _thenByMethod ||
node.Method.Name == _orderByDescendingMethod ||
node.Method.Name == _thenByDescendingMethod)
{
_isOrderScope = true;

var lambda = StripQuotes(node.Arguments[1]);
Visit(lambda.Body);

_isOrderScope = false;
}

return base.VisitMethodCall(node);
}

protected override Expression VisitMember(MemberExpression node)
{
if (_isOrderScope)
{
// we only collect members that are within an order method.
OrderProperties.Add(node);
}

return base.VisitMember(node);
}

private static LambdaExpression StripQuotes(Expression expression)
{
while (expression.NodeType == ExpressionType.Quote)
{
expression = ((UnaryExpression)expression).Operand;
}

return (LambdaExpression)expression;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
using System.Linq.Expressions;

namespace GreenDonut.Data.Expressions;

internal sealed class ExtractSelectExpressionVisitor : ExpressionVisitor
{
private const string _selectMethod = "Select";

public LambdaExpression? Selector { get; private set; }

protected override Expression VisitMethodCall(MethodCallExpression node)
{
if (node.Method.Name == _selectMethod && node.Arguments.Count == 2)
{
var lambda = ConvertToLambda(node.Arguments[1]);
if (lambda.Type.IsGenericType
&& lambda.Type.GetGenericTypeDefinition() == typeof(Func<,>))
{
// we make sure that the selector is of type Expression<Func<T, T>>
// otherwise we are not interested in it.
var genericArgs = lambda.Type.GetGenericArguments();
if (genericArgs[0] == genericArgs[1])
{
Selector = lambda;
}
}
}

return base.VisitMethodCall(node);
}

private static LambdaExpression ConvertToLambda(Expression e)
{
while (e.NodeType == ExpressionType.Quote)
{
e = ((UnaryExpression)e).Operand;
}

if (e.NodeType != ExpressionType.MemberAccess)
{
return (LambdaExpression)e;
}

// Convert the property expression into a lambda expression
var typeArguments = e.Type.GetGenericArguments()[0].GetGenericArguments();
return Expression.Lambda(e, Expression.Parameter(typeArguments[0]));
}
}
Loading