forked from dotnet/efcore
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQueryCompilationContext.cs
More file actions
260 lines (220 loc) · 11.1 KB
/
Copy pathQueryCompilationContext.cs
File metadata and controls
260 lines (220 loc) · 11.1 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
259
260
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Utilities;
#nullable enable
namespace Microsoft.EntityFrameworkCore.Query
{
/// <summary>
/// <para>
/// The primary data structure representing the state/components used during query compilation.
/// </para>
/// <para>
/// This type is typically used by database providers (and other extensions). It is generally
/// not used in application code.
/// </para>
/// </summary>
public class QueryCompilationContext
{
/// <summary>
/// <para>
/// Prefix for all the query parameters generated during parameter extraction in query pipeline.
/// </para>
/// <para>
/// This property is typically used by database providers (and other extensions). It is generally
/// not used in application code.
/// </para>
/// </summary>
public const string QueryParameterPrefix = "__";
/// <summary>
/// <para>
/// ParameterExpression representing <see cref="QueryContext" /> parameter in query expression.
/// </para>
/// <para>
/// This property is typically used by database providers (and other extensions). It is generally
/// not used in application code.
/// </para>
/// </summary>
public static readonly ParameterExpression QueryContextParameter = Expression.Parameter(typeof(QueryContext), "queryContext");
/// <summary>
/// <para>
/// Expression representing a not translated expression in query tree during translation phase.
/// </para>
/// <para>
/// This property is typically used by database providers (and other extensions). It is generally
/// not used in application code.
/// </para>
/// </summary>
public static readonly Expression NotTranslatedExpression = new NotTranslatedExpressionType();
private readonly IQueryTranslationPreprocessorFactory _queryTranslationPreprocessorFactory;
private readonly IQueryableMethodTranslatingExpressionVisitorFactory _queryableMethodTranslatingExpressionVisitorFactory;
private readonly IQueryTranslationPostprocessorFactory _queryTranslationPostprocessorFactory;
private readonly IShapedQueryCompilingExpressionVisitorFactory _shapedQueryCompilingExpressionVisitorFactory;
private readonly ExpressionPrinter _expressionPrinter;
private Dictionary<string, LambdaExpression>? _runtimeParameters;
/// <summary>
/// Creates a new instance of the <see cref="QueryCompilationContext" /> class.
/// </summary>
/// <param name="dependencies"> Parameter object containing dependencies for this class. </param>
/// <param name="async"> A bool value indicating whether it is for async query. </param>
public QueryCompilationContext(
[NotNull] QueryCompilationContextDependencies dependencies,
bool async)
{
Check.NotNull(dependencies, nameof(dependencies));
Dependencies = dependencies;
IsAsync = async;
QueryTrackingBehavior = dependencies.QueryTrackingBehavior;
IsBuffering = dependencies.IsRetryingExecutionStrategy;
Model = dependencies.Model;
ContextOptions = dependencies.ContextOptions;
ContextType = dependencies.ContextType;
Logger = dependencies.Logger;
_queryTranslationPreprocessorFactory = dependencies.QueryTranslationPreprocessorFactory;
_queryableMethodTranslatingExpressionVisitorFactory = dependencies.QueryableMethodTranslatingExpressionVisitorFactory;
_queryTranslationPostprocessorFactory = dependencies.QueryTranslationPostprocessorFactory;
_shapedQueryCompilingExpressionVisitorFactory = dependencies.ShapedQueryCompilingExpressionVisitorFactory;
_expressionPrinter = new ExpressionPrinter();
}
/// <summary>
/// Parameter object containing dependencies for this service.
/// </summary>
protected virtual QueryCompilationContextDependencies Dependencies { get; }
/// <summary>
/// A value indicating whether it is async query.
/// </summary>
public virtual bool IsAsync { get; }
/// <summary>
/// The model to use during query compilation.
/// </summary>
public virtual IModel Model { get; }
/// <summary>
/// The ContextOptions to use during query compilation.
/// </summary>
public virtual IDbContextOptions ContextOptions { get; }
/// <summary>
/// A value indicating <see cref="EntityFrameworkCore.QueryTrackingBehavior" /> of the query.
/// </summary>
public virtual QueryTrackingBehavior QueryTrackingBehavior { get; internal set; }
/// <summary>
/// A value indicating whether it is tracking query.
/// </summary>
[Obsolete("Use " + nameof(QueryTrackingBehavior) + " instead.")]
public virtual bool IsTracking
=> QueryTrackingBehavior == QueryTrackingBehavior.TrackAll;
/// <summary>
/// A value indicating whether the underlying server query needs to pre-buffer all data.
/// </summary>
public virtual bool IsBuffering { get; }
/// <summary>
/// A value indicating whether query filters are ignored in this query.
/// </summary>
public virtual bool IgnoreQueryFilters { get; internal set; }
/// <summary>
/// A value indicating whether eager loaded navigations are ignored in this query.
/// </summary>
public virtual bool IgnoreAutoIncludes { get; internal set; }
/// <summary>
/// The set of tags applied to this query.
/// </summary>
public virtual ISet<string> Tags { get; } = new HashSet<string>();
/// <summary>
/// The query logger to use during query compilation.
/// </summary>
public virtual IDiagnosticsLogger<DbLoggerCategory.Query> Logger { get; }
/// <summary>
/// The CLR type of derived DbContext to use during query compilation.
/// </summary>
public virtual Type ContextType { get; }
/// <summary>
/// Adds a tag to <see cref="Tags" />.
/// </summary>
/// <param name="tag"> The tag to add. </param>
public virtual void AddTag([NotNull] string tag)
{
Check.NotEmpty(tag, nameof(tag));
Tags.Add(tag);
}
/// <summary>
/// Creates the query executor func which gives results for this query.
/// </summary>
/// <typeparam name="TResult"> The result type of this query. </typeparam>
/// <param name="query"> The query to generate executor for. </param>
/// <returns> Returns <see cref="Func{QueryContext, TResult}" /> which can be invoked to get results of this query. </returns>
public virtual Func<QueryContext, TResult> CreateQueryExecutor<TResult>([NotNull] Expression query)
{
Check.NotNull(query, nameof(query));
Logger.QueryCompilationStarting(_expressionPrinter, query);
query = _queryTranslationPreprocessorFactory.Create(this).Process(query);
// Convert EntityQueryable to ShapedQueryExpression
query = _queryableMethodTranslatingExpressionVisitorFactory.Create(this).Visit(query);
query = _queryTranslationPostprocessorFactory.Create(this).Process(query);
// Inject actual entity materializer
// Inject tracking
query = _shapedQueryCompilingExpressionVisitorFactory.Create(this).Visit(query);
// If any additional parameters were added during the compilation phase (e.g. entity equality ID expression),
// wrap the query with code adding those parameters to the query context
query = InsertRuntimeParameters(query);
var queryExecutorExpression = Expression.Lambda<Func<QueryContext, TResult>>(
query,
QueryContextParameter);
try
{
return queryExecutorExpression.Compile();
}
finally
{
Logger.QueryExecutionPlanned(_expressionPrinter, queryExecutorExpression);
}
}
/// <summary>
/// Registers a runtime parameter that is being added at some point during the compilation phase.
/// A lambda must be provided, which will extract the parameter's value from the QueryContext every time
/// the query is executed.
/// </summary>
public virtual ParameterExpression RegisterRuntimeParameter([NotNull] string name, [NotNull] LambdaExpression valueExtractor)
{
Check.NotEmpty(name, nameof(name));
Check.NotNull(valueExtractor, nameof(valueExtractor));
if (valueExtractor.Parameters.Count != 1
|| valueExtractor.Parameters[0] != QueryContextParameter)
{
throw new ArgumentException(CoreStrings.RuntimeParameterMissingParameter, nameof(valueExtractor));
}
if (_runtimeParameters == null)
{
_runtimeParameters = new Dictionary<string, LambdaExpression>();
}
_runtimeParameters[name] = valueExtractor;
return Expression.Parameter(valueExtractor.ReturnType, name);
}
private Expression InsertRuntimeParameters(Expression query)
=> _runtimeParameters == null
? query
: Expression.Block(
_runtimeParameters
.Select(
kv =>
Expression.Call(
QueryContextParameter,
_queryContextAddParameterMethodInfo,
Expression.Constant(kv.Key),
Expression.Convert(Expression.Invoke(kv.Value, QueryContextParameter), typeof(object))))
.Append(query));
private static readonly MethodInfo _queryContextAddParameterMethodInfo
= typeof(QueryContext).GetRequiredDeclaredMethod(nameof(QueryContext.AddParameter));
private sealed class NotTranslatedExpressionType : Expression
{
public override Type Type => typeof(object);
public override ExpressionType NodeType => ExpressionType.Extension;
}
}
}