-
Notifications
You must be signed in to change notification settings - Fork 3.2k
/
Copy pathRelationalShapedQueryCompilingExpressionVisitor.ShaperProcessingExpressionVisitor.cs
3254 lines (2822 loc) · 172 KB
/
RelationalShapedQueryCompilingExpressionVisitor.ShaperProcessingExpressionVisitor.cs
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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// 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 System.Text;
using System.Text.Encodings.Web;
using System.Text.Json;
using Microsoft.EntityFrameworkCore.ChangeTracking.Internal;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Microsoft.EntityFrameworkCore.Query.Internal;
using Microsoft.EntityFrameworkCore.Query.SqlExpressions;
using Microsoft.EntityFrameworkCore.Storage.Json;
using static System.Linq.Expressions.Expression;
namespace Microsoft.EntityFrameworkCore.Query;
public partial class RelationalShapedQueryCompilingExpressionVisitor
{
/// <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 sealed partial class ShaperProcessingExpressionVisitor : ExpressionVisitor
{
/// <summary>
/// Reading database values
/// </summary>
private static readonly MethodInfo IsDbNullMethod =
typeof(DbDataReader).GetRuntimeMethod(nameof(DbDataReader.IsDBNull), [typeof(int)])!;
/// <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 static readonly MethodInfo GetFieldValueMethod =
typeof(DbDataReader).GetRuntimeMethod(nameof(DbDataReader.GetFieldValue), [typeof(int)])!;
/// <summary>
/// Coordinating results
/// </summary>
private static readonly MemberInfo ResultContextValuesMemberInfo
= typeof(ResultContext).GetMember(nameof(ResultContext.Values))[0];
private static readonly MemberInfo SingleQueryResultCoordinatorResultReadyMemberInfo
= typeof(SingleQueryResultCoordinator).GetMember(nameof(SingleQueryResultCoordinator.ResultReady))[0];
private static readonly MethodInfo CollectionAccessorGetOrCreateMethodInfo
= typeof(IClrCollectionAccessor).GetTypeInfo().GetDeclaredMethod(nameof(IClrCollectionAccessor.GetOrCreate))!;
private static readonly MethodInfo CollectionAccessorAddMethodInfo
= typeof(IClrCollectionAccessor).GetTypeInfo().GetDeclaredMethod(nameof(IClrCollectionAccessor.Add))!;
private static readonly PropertyInfo ObjectArrayIndexerPropertyInfo
= typeof(object[]).GetProperty("Item")!;
private static readonly ConstructorInfo JsonReaderDataConstructor
= typeof(JsonReaderData).GetConstructor([typeof(Stream)])!;
private static readonly ConstructorInfo JsonReaderManagerConstructor
= typeof(Utf8JsonReaderManager).GetConstructor(
[typeof(JsonReaderData), typeof(IDiagnosticsLogger<DbLoggerCategory.Query>)])!;
private static readonly MethodInfo Utf8JsonReaderManagerMoveNextMethod
= typeof(Utf8JsonReaderManager).GetMethod(nameof(Utf8JsonReaderManager.MoveNext), [])!;
private static readonly MethodInfo Utf8JsonReaderManagerCaptureStateMethod
= typeof(Utf8JsonReaderManager).GetMethod(nameof(Utf8JsonReaderManager.CaptureState), [])!;
private static readonly FieldInfo Utf8JsonReaderManagerCurrentReaderField
= typeof(Utf8JsonReaderManager).GetField(nameof(Utf8JsonReaderManager.CurrentReader))!;
private static readonly MethodInfo Utf8JsonReaderManagerSkipMethod
= typeof(Utf8JsonReaderManager).GetMethod(nameof(Utf8JsonReaderManager.Skip), [])!;
private static readonly MethodInfo Utf8JsonReaderValueTextEqualsMethod
= typeof(Utf8JsonReader).GetMethod(nameof(Utf8JsonReader.ValueTextEquals), [typeof(ReadOnlySpan<byte>)])!;
private static readonly PropertyInfo EncodingUtf8Property
= typeof(Encoding).GetProperty(nameof(Encoding.UTF8))!;
private static readonly MethodInfo Utf8GetBytesMethod
= typeof(Encoding).GetMethod(nameof(Encoding.GetBytes), [typeof(string)])!;
private static readonly MethodInfo ByteArrayAsSpanMethod = typeof(MemoryExtensions).GetMethods()
.Where(x => x.Name == nameof(MemoryExtensions.AsSpan) && x.GetGenericArguments().Count() == 1)
.Select(x => new { x, prms = x.GetParameters() })
.Where(x => x.prms.Count() == 1 && x.prms[0].ParameterType.IsArray)
.Single().x.MakeGenericMethod(typeof(byte));
private static readonly PropertyInfo Utf8JsonReaderTokenTypeProperty
= typeof(Utf8JsonReader).GetProperty(nameof(Utf8JsonReader.TokenType))!;
private static readonly MethodInfo PropertyGetJsonValueReaderWriterMethod =
typeof(IReadOnlyProperty).GetMethod(nameof(IReadOnlyProperty.GetJsonValueReaderWriter), [])!;
private static readonly MethodInfo PropertyGetTypeMappingMethod =
typeof(IReadOnlyProperty).GetMethod(nameof(IReadOnlyProperty.GetTypeMapping), [])!;
private readonly RelationalShapedQueryCompilingExpressionVisitor _parentVisitor;
private readonly ISet<string>? _tags;
private readonly bool _isTracking;
private readonly bool _queryStateManager;
private readonly bool _isAsync;
private readonly bool _splitQuery;
private readonly bool _detailedErrorsEnabled;
private readonly bool _generateCommandResolver;
private readonly ParameterExpression _resultCoordinatorParameter;
private readonly ParameterExpression? _executionStrategyParameter;
private readonly IDiagnosticsLogger<DbLoggerCategory.Query> _queryLogger;
/// <summary>
/// States scoped to SelectExpression
/// </summary>
private readonly SelectExpression _selectExpression;
private readonly ParameterExpression _dataReaderParameter;
private readonly ParameterExpression _resultContextParameter;
private readonly ParameterExpression? _indexMapParameter;
private readonly ReaderColumn?[]? _readerColumns;
/// <summary>
/// States to materialize only once
/// </summary>
private readonly Dictionary<Expression, Expression> _variableShaperMapping = new(ReferenceEqualityComparer.Instance);
/// <summary>
/// There are always entity variables to avoid materializing same entity twice
/// </summary>
private readonly List<ParameterExpression> _variables = [];
private readonly List<Expression> _expressions = [];
/// <summary>
/// IncludeExpressions are added later in case they are using ValuesArray
/// </summary>
private readonly List<Expression> _includeExpressions = [];
/// <summary>
/// Json entities are added after includes so that we can utilize tracking (includes will track all json entities)
/// </summary>
private readonly List<Expression> _jsonEntityExpressions = [];
/// <summary>
/// If there is collection shaper then we need to construct ValuesArray to store values temporarily in ResultContext
/// </summary>
private List<Expression>? _collectionPopulatingExpressions;
private Expression? _valuesArrayExpression;
private List<Expression>? _valuesArrayInitializers;
private bool _containsCollectionMaterialization;
/// <summary>
/// Since identifiers for collection are not part of larger lambda they don't cannot use caching to materialize only once.
/// </summary>
private bool _inline;
private int _collectionId;
/// <summary>
/// States to convert code to data reader read
/// </summary>
private readonly Dictionary<ParameterExpression, IDictionary<IProperty, int>> _materializationContextBindings = new();
private readonly Dictionary<ParameterExpression, object> _entityTypeIdentifyingExpressionInfo = new();
private readonly Dictionary<ProjectionBindingExpression, string> _singleEntityTypeDiscriminatorValues = new();
private readonly Dictionary<ParameterExpression, (ParameterExpression, ParameterExpression)>
_jsonValueBufferToJsonReaderDataAndKeyValuesParameterMapping = new();
private readonly Dictionary<ParameterExpression, (ParameterExpression, ParameterExpression)>
_jsonMaterializationContextToJsonReaderDataAndKeyValuesParameterMapping = new();
private readonly Dictionary<ParameterExpression, ParameterExpression>
_jsonReaderDataToJsonReaderManagerParameterMapping = new();
/// <summary>
/// Map between index of the non-constant json array element access
/// and the variable we store it's value that we extract from the reader
/// </summary>
private readonly Dictionary<int, ParameterExpression> _jsonArrayNonConstantElementAccessMap = new();
/// <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 ShaperProcessingExpressionVisitor(
RelationalShapedQueryCompilingExpressionVisitor parentVisitor,
SelectExpression selectExpression,
ISet<string> tags,
bool splitQuery,
bool indexMap)
{
_parentVisitor = parentVisitor;
_queryLogger = parentVisitor.QueryCompilationContext.Logger;
_resultCoordinatorParameter = Parameter(
splitQuery ? typeof(SplitQueryResultCoordinator) : typeof(SingleQueryResultCoordinator), "resultCoordinator");
_executionStrategyParameter = splitQuery ? Parameter(typeof(IExecutionStrategy), "executionStrategy") : null;
_selectExpression = selectExpression;
_tags = tags;
_dataReaderParameter = Parameter(typeof(DbDataReader), "dataReader");
_resultContextParameter = Parameter(typeof(ResultContext), "resultContext");
_indexMapParameter = indexMap ? Parameter(typeof(int[]), "indexMap") : null;
if (parentVisitor.QueryCompilationContext.IsBuffering)
{
_readerColumns = new ReaderColumn?[_selectExpression.Projection.Count];
}
_generateCommandResolver = true;
_detailedErrorsEnabled = parentVisitor._detailedErrorsEnabled;
_isTracking = parentVisitor.QueryCompilationContext.QueryTrackingBehavior == QueryTrackingBehavior.TrackAll;
_queryStateManager = parentVisitor.QueryCompilationContext.QueryTrackingBehavior is QueryTrackingBehavior.TrackAll
or QueryTrackingBehavior.NoTrackingWithIdentityResolution;
_isAsync = parentVisitor.QueryCompilationContext.IsAsync;
_splitQuery = splitQuery;
_selectExpression.ApplyTags(_tags);
}
// For single query scenario
private ShaperProcessingExpressionVisitor(
RelationalShapedQueryCompilingExpressionVisitor parentVisitor,
ParameterExpression resultCoordinatorParameter,
SelectExpression selectExpression,
ParameterExpression dataReaderParameter,
ParameterExpression resultContextParameter,
ReaderColumn?[]? readerColumns)
{
_parentVisitor = parentVisitor;
_queryLogger = parentVisitor.QueryCompilationContext.Logger;
_resultCoordinatorParameter = resultCoordinatorParameter;
_selectExpression = selectExpression;
_dataReaderParameter = dataReaderParameter;
_resultContextParameter = resultContextParameter;
_readerColumns = readerColumns;
_generateCommandResolver = false;
_detailedErrorsEnabled = parentVisitor._detailedErrorsEnabled;
_isTracking = parentVisitor.QueryCompilationContext.QueryTrackingBehavior == QueryTrackingBehavior.TrackAll;
_queryStateManager = parentVisitor.QueryCompilationContext.QueryTrackingBehavior is QueryTrackingBehavior.TrackAll
or QueryTrackingBehavior.NoTrackingWithIdentityResolution;
_isAsync = parentVisitor.QueryCompilationContext.IsAsync;
_splitQuery = false;
}
// For split query scenario
private ShaperProcessingExpressionVisitor(
RelationalShapedQueryCompilingExpressionVisitor parentVisitor,
ParameterExpression resultCoordinatorParameter,
ParameterExpression executionStrategyParameter,
SelectExpression selectExpression,
ISet<string> tags)
{
_parentVisitor = parentVisitor;
_queryLogger = parentVisitor.QueryCompilationContext.Logger;
_resultCoordinatorParameter = resultCoordinatorParameter;
_executionStrategyParameter = executionStrategyParameter;
_selectExpression = selectExpression;
_tags = tags;
_dataReaderParameter = Parameter(typeof(DbDataReader), "dataReader");
_resultContextParameter = Parameter(typeof(ResultContext), "resultContext");
if (parentVisitor.QueryCompilationContext.IsBuffering)
{
_readerColumns = new ReaderColumn[_selectExpression.Projection.Count];
}
_generateCommandResolver = true;
_detailedErrorsEnabled = parentVisitor._detailedErrorsEnabled;
_isTracking = parentVisitor.QueryCompilationContext.QueryTrackingBehavior == QueryTrackingBehavior.TrackAll;
_queryStateManager = parentVisitor.QueryCompilationContext.QueryTrackingBehavior is QueryTrackingBehavior.TrackAll
or QueryTrackingBehavior.NoTrackingWithIdentityResolution;
_isAsync = parentVisitor.QueryCompilationContext.IsAsync;
_splitQuery = true;
_selectExpression.ApplyTags(_tags);
}
/// <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 LambdaExpression ProcessRelationalGroupingResult(
RelationalGroupByResultExpression relationalGroupByResultExpression,
out Expression relationalCommandResolver,
out IReadOnlyList<ReaderColumn?>? readerColumns,
out LambdaExpression keySelector,
out LambdaExpression keyIdentifier,
out LambdaExpression? relatedDataLoaders,
ref int collectionId)
{
_inline = true;
keySelector = Lambda(
Visit(relationalGroupByResultExpression.KeyShaper),
QueryCompilationContext.QueryContextParameter,
_dataReaderParameter);
keyIdentifier = Lambda(
Visit(relationalGroupByResultExpression.KeyIdentifier),
QueryCompilationContext.QueryContextParameter,
_dataReaderParameter);
_inline = false;
return ProcessShaper(
relationalGroupByResultExpression.ElementShaper,
out relationalCommandResolver!,
out readerColumns,
out relatedDataLoaders,
ref collectionId);
}
/// <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 LambdaExpression ProcessShaper(
Expression shaperExpression,
out Expression relationalCommandResolver,
out IReadOnlyList<ReaderColumn?>? readerColumns,
out LambdaExpression? relatedDataLoaders,
ref int collectionId)
{
relatedDataLoaders = null;
_collectionId = collectionId;
if (_indexMapParameter != null)
{
var result = Visit(shaperExpression);
_expressions.Add(result);
result = Block(_variables, _expressions);
relationalCommandResolver = _parentVisitor.CreateRelationalCommandResolverExpression(_selectExpression);
readerColumns = _readerColumns;
return Lambda(
result,
QueryCompilationContext.QueryContextParameter,
_dataReaderParameter,
_indexMapParameter);
}
_containsCollectionMaterialization = new CollectionShaperFindingExpressionVisitor()
.ContainsCollectionMaterialization(shaperExpression);
// for NoTrackingWithIdentityResolution we need to make sure we see JSON entities in the correct order
// specifically, if we project JSON collection, it needs to be projected before any individual element from that collection
// otherwise we store JSON entities in incorrect order in the Change Tracker, leading to possible data corruption
// we only need to do this once, on top level
// see issue #33073 for more context
if (_queryStateManager && !_isTracking && collectionId == 0)
{
var jsonCorrectOrderOfEntitiesForChangeTrackerValidator =
new JsonCorrectOrderOfEntitiesForChangeTrackerValidator(_selectExpression);
jsonCorrectOrderOfEntitiesForChangeTrackerValidator.Validate(shaperExpression);
}
if (!_containsCollectionMaterialization)
{
var result = Visit(shaperExpression);
_expressions.AddRange(_includeExpressions);
_expressions.AddRange(_jsonEntityExpressions);
_expressions.Add(result);
result = Block(_variables, _expressions);
relationalCommandResolver = _generateCommandResolver
? _parentVisitor.CreateRelationalCommandResolverExpression(_selectExpression)
: Constant(null, typeof(RelationalCommandResolver));
readerColumns = _readerColumns;
return Lambda(
result,
QueryCompilationContext.QueryContextParameter,
_dataReaderParameter,
_resultContextParameter,
_resultCoordinatorParameter);
}
else
{
_valuesArrayExpression = MakeMemberAccess(_resultContextParameter, ResultContextValuesMemberInfo);
_collectionPopulatingExpressions = [];
_valuesArrayInitializers = [];
var result = Visit(shaperExpression);
var valueArrayInitializationExpression = Assign(
_valuesArrayExpression, NewArrayInit(typeof(object), _valuesArrayInitializers));
_expressions.AddRange(_jsonEntityExpressions);
_expressions.Add(valueArrayInitializationExpression);
_expressions.AddRange(_includeExpressions);
if (_splitQuery)
{
_expressions.Add(Default(result.Type));
var initializationBlock = Block(_variables, _expressions);
result = Condition(
Equal(_valuesArrayExpression, Constant(null, typeof(object[]))),
initializationBlock,
result);
if (_isAsync)
{
var tasks = NewArrayInit(
typeof(Func<Task>), _collectionPopulatingExpressions.Select(
e => Lambda<Func<Task>>(e)));
relatedDataLoaders =
Lambda<Func<QueryContext, IExecutionStrategy, SplitQueryResultCoordinator, Task>>(
Call(TaskAwaiterMethodInfo, tasks),
QueryCompilationContext.QueryContextParameter,
_executionStrategyParameter!,
_resultCoordinatorParameter);
}
else
{
relatedDataLoaders =
Lambda<Action<QueryContext, IExecutionStrategy, SplitQueryResultCoordinator>>(
Block(_collectionPopulatingExpressions),
QueryCompilationContext.QueryContextParameter,
_executionStrategyParameter!,
_resultCoordinatorParameter);
}
}
else
{
var initializationBlock = Block(_variables, _expressions);
var conditionalMaterializationExpressions = new List<Expression>
{
IfThen(
Equal(_valuesArrayExpression, Constant(null, typeof(object[]))),
initializationBlock)
};
conditionalMaterializationExpressions.AddRange(_collectionPopulatingExpressions);
conditionalMaterializationExpressions.Add(
Condition(
IsTrue(
MakeMemberAccess(
_resultCoordinatorParameter, SingleQueryResultCoordinatorResultReadyMemberInfo)),
result,
Default(result.Type)));
result = Block(conditionalMaterializationExpressions);
}
relationalCommandResolver = _generateCommandResolver
? _parentVisitor.CreateRelationalCommandResolverExpression(_selectExpression)
: Constant(null, typeof(RelationalCommandCache));
;
readerColumns = _readerColumns;
collectionId = _collectionId;
return Lambda(
result,
QueryCompilationContext.QueryContextParameter,
_dataReaderParameter,
_resultContextParameter,
_resultCoordinatorParameter);
}
}
/// <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>
protected override Expression VisitBinary(BinaryExpression binaryExpression)
{
switch (binaryExpression)
{
case { NodeType: ExpressionType.Assign, Left: ParameterExpression parameterExpression }
when parameterExpression.Type == typeof(MaterializationContext):
{
var newExpression = (NewExpression)binaryExpression.Right;
if (newExpression.Arguments[0] is ProjectionBindingExpression projectionBindingExpression)
{
var projectionIndex = GetProjectionIndex(projectionBindingExpression);
var propertyMap = projectionIndex is IDictionary<IProperty, int>
? (IDictionary<IProperty, int>)projectionIndex
: ((QueryableJsonProjectionInfo)projectionIndex).PropertyIndexMap;
_materializationContextBindings[parameterExpression] = propertyMap;
_entityTypeIdentifyingExpressionInfo[parameterExpression] =
// If single entity type is being selected in hierarchy then we use the value directly else we store the offset
// to read discriminator value.
_singleEntityTypeDiscriminatorValues.TryGetValue(projectionBindingExpression, out var value)
? value
: propertyMap.Values.Max() + 1;
var updatedExpression = newExpression.Update(
[
_parentVisitor.Dependencies.LiftableConstantFactory.CreateLiftableConstant(
ValueBuffer.Empty,
static _ => ValueBuffer.Empty,
"emptyValueBuffer",
typeof(ValueBuffer)),
newExpression.Arguments[1]
]);
return Assign(binaryExpression.Left, updatedExpression);
}
if (newExpression.Arguments[0] is ParameterExpression valueBufferParameter
&& _jsonValueBufferToJsonReaderDataAndKeyValuesParameterMapping.TryGetValue(
valueBufferParameter, out var mappedParameter))
{
_jsonMaterializationContextToJsonReaderDataAndKeyValuesParameterMapping[parameterExpression] = mappedParameter;
var updatedExpression = newExpression.Update(
[
_parentVisitor.Dependencies.LiftableConstantFactory.CreateLiftableConstant(
ValueBuffer.Empty,
static _ => ValueBuffer.Empty,
"emptyValueBuffer",
typeof(ValueBuffer)),
newExpression.Arguments[1]
]);
return Assign(binaryExpression.Left, updatedExpression);
}
break;
}
case
{
NodeType: ExpressionType.Assign,
Left: MemberExpression { Member: FieldInfo { IsInitOnly: true } } memberExpression
}:
{
return memberExpression.Assign(Visit(binaryExpression.Right));
}
// we only have mapping between MaterializationContext and JsonReaderData, but we use JsonReaderManager to extract JSON
// values so we need to add mapping between JsonReaderData and JsonReaderManager parameter, so we know which parameter to
// use when generating actual Get* method
case { NodeType: ExpressionType.Assign, Left: ParameterExpression jsonReaderManagerParameter }
when jsonReaderManagerParameter.Type == typeof(Utf8JsonReaderManager):
{
var jsonReaderDataParameter = (ParameterExpression)((NewExpression)binaryExpression.Right).Arguments[0];
_jsonReaderDataToJsonReaderManagerParameterMapping[jsonReaderDataParameter] = jsonReaderManagerParameter;
break;
}
}
return base.VisitBinary(binaryExpression);
}
/// <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>
protected override Expression VisitExtension(Expression extensionExpression)
{
switch (extensionExpression)
{
case RelationalStructuralTypeShaperExpression
{
ValueBufferExpression: ProjectionBindingExpression projectionBindingExpression
} shaper
when !_inline:
{
// we can't cache ProjectionBindingExpression results for non-tracking queries
// JSON entities must be read and re-shaped every time (streaming)
// as part of the process we do fixup to the parents, so those JSON entities would be potentially fixed up multiple times
// it's ok for references (overwrite) but for collections they would be added multiple times if we were to cache the parent
// by creating every entity every time we guarantee this doesn't happen
if (!_isTracking || !_variableShaperMapping.TryGetValue(projectionBindingExpression, out var accessor))
{
if (GetProjectionIndex(projectionBindingExpression) is JsonProjectionInfo jsonProjectionInfo)
{
Check.DebugAssert(shaper.StructuralType is IEntityType, "JsonProjectionInfo over a complex type");
var entityType = (IEntityType)shaper.StructuralType;
if (_isTracking)
{
throw new InvalidOperationException(
RelationalStrings.JsonEntityOrCollectionProjectedAtRootLevelInTrackingQuery(
nameof(EntityFrameworkQueryableExtensions.AsNoTracking)));
}
// json entity at the root
var (jsonReaderDataVariable, keyValuesParameter) = JsonShapingPreProcess(
jsonProjectionInfo,
entityType,
isCollection: false);
var shaperResult = CreateJsonShapers(
entityType,
shaper.IsNullable,
jsonReaderDataVariable,
keyValuesParameter,
parentEntityExpression: null,
navigation: null);
var visitedShaperResult = Visit(shaperResult);
var visitedShaperResultParameter = Parameter(visitedShaperResult.Type);
_variables.Add(visitedShaperResultParameter);
_jsonEntityExpressions.Add(Assign(visitedShaperResultParameter, visitedShaperResult));
accessor = CompensateForCollectionMaterialization(
visitedShaperResultParameter,
shaper.Type);
}
else if (GetProjectionIndex(projectionBindingExpression) is QueryableJsonProjectionInfo
queryableJsonEntityProjectionInfo)
{
if (_isTracking)
{
throw new InvalidOperationException(
RelationalStrings.JsonEntityOrCollectionProjectedAtRootLevelInTrackingQuery(
nameof(EntityFrameworkQueryableExtensions.AsNoTracking)));
}
// json entity converted to query root and projected
var entityParameter = Parameter(shaper.Type);
_variables.Add(entityParameter);
var entityMaterializationExpression = (BlockExpression)_parentVisitor.InjectEntityMaterializers(shaper);
var mappedProperties = queryableJsonEntityProjectionInfo.PropertyIndexMap.Keys.ToList();
var rewrittenEntityMaterializationExpression = new QueryableJsonEntityMaterializerRewriter(mappedProperties)
.Rewrite(entityMaterializationExpression);
var visitedEntityMaterializationExpression = Visit(rewrittenEntityMaterializationExpression);
_expressions.Add(Assign(entityParameter, visitedEntityMaterializationExpression));
foreach (var childProjectionInfo in queryableJsonEntityProjectionInfo.ChildrenProjectionInfo)
{
var (jsonReaderDataVariable, keyValuesParameter) = JsonShapingPreProcess(
childProjectionInfo.JsonProjectionInfo,
childProjectionInfo.Navigation.TargetEntityType,
childProjectionInfo.Navigation.IsCollection);
var shaperResult = CreateJsonShapers(
childProjectionInfo.Navigation.TargetEntityType,
nullable: true,
jsonReaderDataVariable,
keyValuesParameter,
parentEntityExpression: entityParameter,
navigation: childProjectionInfo.Navigation);
var visitedShaperResult = Visit(shaperResult);
_includeExpressions.Add(visitedShaperResult);
}
accessor = CompensateForCollectionMaterialization(
entityParameter,
shaper.Type);
}
else
{
var entityParameter = Parameter(shaper.Type, "entity");
_variables.Add(entityParameter);
if (shaper.StructuralType is IEntityType entityType
&& entityType.GetMappingStrategy() == RelationalAnnotationNames.TpcMappingStrategy)
{
var concreteTypes = entityType.GetDerivedTypesInclusive().Where(e => !e.IsAbstract()).ToArray();
// Single concrete TPC entity type won't have discriminator column.
// We store the value here and inject it directly rather than reading from server.
if (concreteTypes.Length == 1)
{
_singleEntityTypeDiscriminatorValues[
projectionBindingExpression]
= concreteTypes[0].ShortName();
}
}
var entityMaterializationExpression = _parentVisitor.InjectEntityMaterializers(shaper);
entityMaterializationExpression = Visit(entityMaterializationExpression);
_expressions.Add(Assign(entityParameter, entityMaterializationExpression));
accessor = CompensateForCollectionMaterialization(
entityParameter,
shaper.Type);
}
if (_isTracking)
{
_variableShaperMapping[projectionBindingExpression] = accessor;
}
}
return accessor;
}
case RelationalStructuralTypeShaperExpression { ValueBufferExpression: ProjectionBindingExpression } shaper
when _inline:
{
if (shaper.StructuralType is IEntityType entityType
&& entityType.GetMappingStrategy() == RelationalAnnotationNames.TpcMappingStrategy)
{
var concreteTypes = entityType.GetDerivedTypesInclusive().Where(e => !e.IsAbstract()).ToArray();
// Single concrete TPC entity type won't have discriminator column.
// We store the value here and inject it directly rather than reading from server.
if (concreteTypes.Length == 1)
{
_singleEntityTypeDiscriminatorValues[
(ProjectionBindingExpression)shaper.ValueBufferExpression]
= concreteTypes[0].ShortName();
}
}
var entityMaterializationExpression = _parentVisitor.InjectEntityMaterializers(shaper);
entityMaterializationExpression = Visit(entityMaterializationExpression);
return entityMaterializationExpression;
}
case CollectionResultExpression { Navigation: INavigation navigation } collectionResultExpression
when GetProjectionIndex(collectionResultExpression.ProjectionBindingExpression)
is JsonProjectionInfo jsonProjectionInfo:
{
if (_isTracking)
{
throw new InvalidOperationException(
RelationalStrings.JsonEntityOrCollectionProjectedAtRootLevelInTrackingQuery(
nameof(EntityFrameworkQueryableExtensions.AsNoTracking)));
}
// json entity collection at the root
var (jsonReaderDataVariable, keyValuesParameter) = JsonShapingPreProcess(
jsonProjectionInfo,
navigation.TargetEntityType,
isCollection: true);
var shaperResult = CreateJsonShapers(
navigation.TargetEntityType,
nullable: true,
jsonReaderDataVariable,
keyValuesParameter,
parentEntityExpression: null,
navigation: navigation);
var visitedShaperResult = Visit(shaperResult);
var jsonCollectionParameter = Parameter(collectionResultExpression.Type);
_variables.Add(jsonCollectionParameter);
_jsonEntityExpressions.Add(Assign(jsonCollectionParameter, visitedShaperResult));
return CompensateForCollectionMaterialization(
jsonCollectionParameter,
collectionResultExpression.Type);
}
case ProjectionBindingExpression projectionBindingExpression
when _inline:
{
var projectionIndex = (int)GetProjectionIndex(projectionBindingExpression);
var projection = _selectExpression.Projection[projectionIndex];
return CreateGetValueExpression(
_dataReaderParameter,
projectionIndex,
IsNullableProjection(projection),
projection.Expression.TypeMapping!,
projectionBindingExpression.Type);
}
case ProjectionBindingExpression projectionBindingExpression
when !_inline:
{
if (_variableShaperMapping.TryGetValue(projectionBindingExpression, out var accessor))
{
return accessor;
}
var projectionIndex = (int)GetProjectionIndex(projectionBindingExpression);
var projection = _selectExpression.Projection[projectionIndex];
var nullable = IsNullableProjection(projection);
var valueParameter = Parameter(projectionBindingExpression.Type, "value" + (_variables.Count + 1));
_variables.Add(valueParameter);
_expressions.Add(
Assign(
valueParameter,
CreateGetValueExpression(
_dataReaderParameter,
projectionIndex,
nullable,
projection.Expression.TypeMapping!,
valueParameter.Type)));
if (_containsCollectionMaterialization)
{
var expressionToAdd = (Expression)valueParameter;
if (expressionToAdd.Type.IsValueType)
{
expressionToAdd = Convert(expressionToAdd, typeof(object));
}
_valuesArrayInitializers!.Add(expressionToAdd);
accessor = Convert(
ArrayIndex(
_valuesArrayExpression!,
Constant(_valuesArrayInitializers.Count - 1)),
projectionBindingExpression.Type);
}
else
{
accessor = valueParameter;
}
_variableShaperMapping[projectionBindingExpression] = accessor;
return accessor;
}
case IncludeExpression includeExpression:
{
var entity = Visit(includeExpression.EntityExpression);
if (includeExpression.NavigationExpression is RelationalCollectionShaperExpression
relationalCollectionShaperExpression)
{
var collectionIdConstant = Constant(_collectionId++);
var innerShaper = new ShaperProcessingExpressionVisitor(
_parentVisitor, _resultCoordinatorParameter, _selectExpression, _dataReaderParameter,
_resultContextParameter,
_readerColumns)
.ProcessShaper(relationalCollectionShaperExpression.InnerShaper, out _, out _, out _, ref _collectionId);
var entityClrType = entity.Type;
var navigation = includeExpression.Navigation;
var includingEntityClrType = navigation.DeclaringEntityType.ClrType;
if (includingEntityClrType != entityClrType
&& includingEntityClrType.IsAssignableFrom(entityClrType))
{
includingEntityClrType = entityClrType;
}
_inline = true;
var parentIdentifierLambda = Lambda(
Visit(relationalCollectionShaperExpression.ParentIdentifier),
QueryCompilationContext.QueryContextParameter,
_dataReaderParameter);
var outerIdentifierLambda = Lambda(
Visit(relationalCollectionShaperExpression.OuterIdentifier),
QueryCompilationContext.QueryContextParameter,
_dataReaderParameter);
var selfIdentifierLambda = Lambda(
Visit(relationalCollectionShaperExpression.SelfIdentifier),
QueryCompilationContext.QueryContextParameter,
_dataReaderParameter);
_inline = false;
_includeExpressions.Add(
Call(
InitializeIncludeCollectionMethodInfo.MakeGenericMethod(entityClrType, includingEntityClrType),
collectionIdConstant,
QueryCompilationContext.QueryContextParameter,
_dataReaderParameter,
_resultCoordinatorParameter,
entity,
parentIdentifierLambda,
outerIdentifierLambda,
_parentVisitor.Dependencies.LiftableConstantFactory.CreateLiftableConstant(
navigation,
LiftableConstantExpressionHelpers.BuildNavigationAccessLambda(navigation),
navigation.Name + "Navigation",
typeof(INavigationBase)),
navigation.IsShadowProperty()
? Constant(null, typeof(IClrCollectionAccessor))
: _parentVisitor.Dependencies.LiftableConstantFactory.CreateLiftableConstant(
navigation.GetCollectionAccessor(),
LiftableConstantExpressionHelpers.BuildClrCollectionAccessorLambda(navigation),
navigation.Name + "NavigationCollectionAccessor",
typeof(IClrCollectionAccessor)),
Constant(_isTracking),
#pragma warning disable EF1001 // Internal EF Core API usage.
Constant(includeExpression.SetLoaded)));
#pragma warning restore EF1001 // Internal EF Core API usage.
var relatedEntityClrType = innerShaper.ReturnType;
var inverseNavigation = navigation.Inverse;
_collectionPopulatingExpressions!.Add(
Call(
PopulateIncludeCollectionMethodInfo.MakeGenericMethod(includingEntityClrType, relatedEntityClrType),
collectionIdConstant,
QueryCompilationContext.QueryContextParameter,
_dataReaderParameter,
_resultCoordinatorParameter,
parentIdentifierLambda,
outerIdentifierLambda,
selfIdentifierLambda,
_parentVisitor.Dependencies.LiftableConstantFactory.CreateLiftableConstant(
relationalCollectionShaperExpression.ParentIdentifierValueComparers
.Select(x => (Func<object, object, bool>)x.Equals).ToArray(),
Lambda<Func<MaterializerLiftableConstantContext, object>>(
NewArrayInit(
typeof(Func<object, object, bool>),
relationalCollectionShaperExpression.ParentIdentifierValueComparers.Select(
vc => vc.ObjectEqualsExpression)),
Parameter(typeof(MaterializerLiftableConstantContext), "_")),
"parentIdentifierValueComparers",
typeof(Func<object, object, bool>[])),
_parentVisitor.Dependencies.LiftableConstantFactory.CreateLiftableConstant(
relationalCollectionShaperExpression.OuterIdentifierValueComparers
.Select(x => (Func<object, object, bool>)x.Equals).ToArray(),
Lambda<Func<MaterializerLiftableConstantContext, object>>(
NewArrayInit(
typeof(Func<object, object, bool>),
relationalCollectionShaperExpression.OuterIdentifierValueComparers.Select(
vc => vc.ObjectEqualsExpression)),
Parameter(typeof(MaterializerLiftableConstantContext), "_")),
"outerIdentifierValueComparers",
typeof(Func<object, object, bool>[])),
_parentVisitor.Dependencies.LiftableConstantFactory.CreateLiftableConstant(
relationalCollectionShaperExpression.SelfIdentifierValueComparers
.Select(x => (Func<object, object, bool>)x.Equals).ToArray(),
Lambda<Func<MaterializerLiftableConstantContext, object>>(
NewArrayInit(
typeof(Func<object, object, bool>),
relationalCollectionShaperExpression.SelfIdentifierValueComparers.Select(
vc => vc.ObjectEqualsExpression)),
Parameter(typeof(MaterializerLiftableConstantContext), "_")),
"selfIdentifierValueComparers",
typeof(Func<object, object, bool>[])),
innerShaper,
_parentVisitor.Dependencies.LiftableConstantFactory.CreateLiftableConstant(
inverseNavigation,
LiftableConstantExpressionHelpers.BuildNavigationAccessLambda(inverseNavigation),
(inverseNavigation?.Name ?? "null") + "InverseNavigation",
typeof(INavigationBase)),
GenerateFixup(includingEntityClrType, relatedEntityClrType, navigation, inverseNavigation),
Constant(_isTracking)));
}
else if (includeExpression.NavigationExpression is RelationalSplitCollectionShaperExpression
relationalSplitCollectionShaperExpression)
{
var collectionIdConstant = Constant(_collectionId++);
var innerProcessor = new ShaperProcessingExpressionVisitor(
_parentVisitor, _resultCoordinatorParameter,
_executionStrategyParameter!, relationalSplitCollectionShaperExpression.SelectExpression, _tags!);
var innerShaper = innerProcessor.ProcessShaper(
relationalSplitCollectionShaperExpression.InnerShaper,
out var relationalCommandResolver,
out var readerColumns,
out var relatedDataLoaders,
ref _collectionId);
var entityType = entity.Type;
var navigation = includeExpression.Navigation;
var includingEntityClrType = navigation.DeclaringEntityType.ClrType;
if (includingEntityClrType != entityType
&& includingEntityClrType.IsAssignableFrom(entityType))
{
includingEntityClrType = entityType;
}
_inline = true;
var parentIdentifierLambda = Lambda(
Visit(relationalSplitCollectionShaperExpression.ParentIdentifier),
QueryCompilationContext.QueryContextParameter,
_dataReaderParameter);
_inline = false;
innerProcessor._inline = true;
var childIdentifierLambda = Lambda(
innerProcessor.Visit(relationalSplitCollectionShaperExpression.ChildIdentifier),
QueryCompilationContext.QueryContextParameter,
innerProcessor._dataReaderParameter);
innerProcessor._inline = false;
_includeExpressions.Add(
Call(
InitializeSplitIncludeCollectionMethodInfo.MakeGenericMethod(entityType, includingEntityClrType),
collectionIdConstant,
QueryCompilationContext.QueryContextParameter,
_dataReaderParameter,
_resultCoordinatorParameter,