forked from ByteAether/QueryLink
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQueryableExtensions.cs
More file actions
258 lines (221 loc) · 8.58 KB
/
Copy pathQueryableExtensions.cs
File metadata and controls
258 lines (221 loc) · 8.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
using System.Linq.Expressions;
using System.Reflection;
using static ByteAether.QueryLink.Definitions;
namespace ByteAether.QueryLink;
/// <summary>
/// Provides extension methods for applying filter and order definitions to an IQueryable.
/// </summary>
public static class QueryableExtensions
{
/// <summary>
/// Applies the filter and order definitions to the source queryable.
/// </summary>
/// <typeparam name="T">The type of the elements in the source queryable.</typeparam>
/// <param name="source">The source queryable to apply the definitions to.</param>
/// <param name="definitions">The definitions containing filters and orders.</param>
/// <param name="overrides">Optional overrides for filters and orders.</param>
/// <returns>The modified queryable with filters and orders applied.</returns>
public static IQueryable<T> Apply<T>(
this IQueryable<T> source,
Definitions definitions,
Overrides<T>? overrides = null
) => source
.FilterByDefs(definitions.Filters, overrides?.Filter ?? [])
.OrderByDefs(definitions.Orders, overrides?.Order ?? []);
private static string GetFieldName(Expression expression)
{
expression = GetTrueExpression(expression);
return expression switch
{
MemberExpression memberExpression => GetMemberPath(memberExpression),
_ => throw new ArgumentException(
"Invalid expression type. Only MemberExpression is supported for overrides.",
nameof(expression)
)
};
}
private static string GetMemberPath(MemberExpression? expression)
{
var path = new List<string>();
while (expression != null)
{
path.Add(expression.Member.Name);
expression = expression.Expression as MemberExpression;
}
path.Reverse();
return string.Join(".", path);
}
private static Expression GetTrueExpression(Expression expression)
=> expression switch
{
UnaryExpression unaryExpression => GetTrueExpression(unaryExpression.Operand),
_ => expression
};
private static (Expression, ParameterExpression[]) BuildPropertyExpression<T>(
ParameterExpression param,
string propertyPath,
Dictionary<string, Overrides<T>.Override<object, object>> overridesByPath
)
{
if (overridesByPath.TryGetValue(propertyPath, out var or))
{
return (GetTrueExpression(or.ValueReplace.Body), [.. or.ValueReplace.Parameters]);
}
Expression body = param;
foreach (var part in propertyPath.Split('.'))
{
var prop = body.Type.GetProperty(part) ??
throw new ArgumentException($"Property {part} in path {propertyPath} not found on {body.Type.Name}");
body = Expression.Property(body, prop);
}
return (body, [param]);
}
#region Filtering
private static Expression GetFilterExpression(
Expression valueSelector,
ConstantExpression checkedValue,
FilterOperator operation
) => operation switch
{
FilterOperator.Eq => Expression.Equal(valueSelector, checkedValue),
FilterOperator.Neq => Expression.NotEqual(valueSelector, checkedValue),
FilterOperator.Gt => Expression.GreaterThan(valueSelector, checkedValue),
FilterOperator.Gte => Expression.GreaterThanOrEqual(valueSelector, checkedValue),
FilterOperator.Lt => Expression.LessThan(valueSelector, checkedValue),
FilterOperator.Lte => Expression.LessThanOrEqual(valueSelector, checkedValue),
FilterOperator.Has => ExpressionContains(valueSelector, checkedValue),
FilterOperator.Nhas => Expression.Not(ExpressionContains(valueSelector, checkedValue)),
FilterOperator.In => ExpressionContains(checkedValue, valueSelector),
FilterOperator.Nin => Expression.Not(ExpressionContains(checkedValue, valueSelector)),
FilterOperator.Sw => Expression.Call(valueSelector, typeof(string).GetMethod(nameof(string.StartsWith), [typeof(string)])!, checkedValue),
FilterOperator.Nsw => Expression.Not(Expression.Call(valueSelector, typeof(string).GetMethod(nameof(string.StartsWith), [typeof(string)])!, checkedValue)),
FilterOperator.Ew => Expression.Call(valueSelector, typeof(string).GetMethod(nameof(string.EndsWith), [typeof(string)])!, checkedValue),
FilterOperator.New => Expression.Not(Expression.Call(valueSelector, typeof(string).GetMethod(nameof(string.EndsWith), [typeof(string)])!, checkedValue)),
_ => throw new InvalidOperationException($"Operation {operation} is not supported!")
};
private static readonly MethodInfo _stringContains = typeof(string)
.GetMethod(nameof(string.Contains), [typeof(string)])!;
private static readonly MethodInfo _enumerableContains = typeof(Enumerable)
.GetMethods()
.Single(x => x.Name == nameof(Enumerable.Contains) && x.GetParameters().Length == 2);
private static MethodCallExpression ExpressionContains(Expression containerValue, Expression searchValue)
{
try
{
// Handle string.Contains first
if (containerValue.Type == typeof(string))
{
return Expression.Call(containerValue, _stringContains, searchValue);
}
// Fallback to Enumerable.Contains
var containsMethodGeneric = _enumerableContains.MakeGenericMethod(searchValue.Type);
return Expression.Call(null, containsMethodGeneric, containerValue, searchValue);
}
catch (Exception e)
{
throw new InvalidOperationException(
$"Type {containerValue.Type} does not support Contains for {searchValue.Type}",
e
);
}
}
private static IQueryable<T> FilterByDefs<T>(
this IQueryable<T> source,
IEnumerable<FilterDefinition<object?>> filterDefs,
IEnumerable<Overrides<T>.Override<object, object>> overrides
)
{
var param = Expression.Parameter(typeof(T), "x");
var overridesByPath = overrides.ToDictionary(x => GetFieldName(x.Selector.Body), x => x);
foreach (var def in filterDefs)
{
var (expBody, expParams) = BuildPropertyExpression(param, def.Name, overridesByPath);
// Get the actual type we need to use for comparison
var (targetType, value) = ResolveTargetTypeAndValue(expBody.Type, def.Value, def.Operation);
var checkedValue = Expression.Constant(value, targetType);
var conditionExpression = GetFilterExpression(expBody, checkedValue, def.Operation);
var conditionLambda = Expression.Lambda<Func<T, bool>>(conditionExpression, expParams);
source = source.Where(conditionLambda);
}
return source;
}
private static (Type TargetType, object? Value) ResolveTargetTypeAndValue(
Type propertyType,
object? value,
FilterOperator operation
)
{
// Handle enum conversion from string first
if (propertyType.IsEnum && value is string stringValue)
{
try
{
return (propertyType, Enum.Parse(propertyType, stringValue, ignoreCase: true));
}
catch
{
throw new InvalidOperationException(
$"Value '{stringValue}' is not valid for enum type {propertyType.Name}");
}
}
// Existing logic for IN/NIN operations
if (operation is FilterOperator.In or FilterOperator.Nin)
{
return (
value?.GetType() ?? typeof(object),
value
);
}
// Handle collection properties
if (propertyType.IsGenericType &&
propertyType.GetGenericTypeDefinition() == typeof(List<>))
{
var elementType = propertyType.GetGenericArguments()[0];
return (elementType, value);
}
if (propertyType.IsArray)
{
var elementType = propertyType.GetElementType();
return (elementType!, value);
}
// Default case
return (propertyType, value);
}
#endregion
#region Sorting
private static IQueryable<T> OrderByDefs<T>(
this IQueryable<T> source,
IEnumerable<OrderDefinition> orderDefs,
IEnumerable<Overrides<T>.Override<object, object>> overrides
)
{
var param = Expression.Parameter(typeof(T), "x");
var overridesByPath = overrides.ToDictionary(x => GetFieldName(x.Selector.Body), x => x);
// Check if source has existing orderings
var hasExistingOrder = source.Expression.Type == typeof(IOrderedQueryable<T>);
foreach (var def in orderDefs)
{
var (expBody, expParams) = BuildPropertyExpression(param, def.Name, overridesByPath);
var selector = Expression.Lambda<Func<T, object>>(
Expression.Convert(expBody, typeof(object)), expParams
);
if (hasExistingOrder)
{
// Append to existing order with ThenBy/ThenByDescending
source = def.IsReversed
? ((IOrderedQueryable<T>)source).ThenByDescending(selector)
: ((IOrderedQueryable<T>)source).ThenBy(selector);
}
else
{
// Apply first order with OrderBy/OrderByDescending
source = def.IsReversed
? Queryable.OrderByDescending(source, selector)
: Queryable.OrderBy(source, selector);
hasExistingOrder = true;
}
}
return source;
}
#endregion
}