forked from dotnet/efcore
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CosmosSqlTranslatingExpressionVisitor.cs
1040 lines (891 loc) · 48.6 KB
/
CosmosSqlTranslatingExpressionVisitor.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
// 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;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using Microsoft.EntityFrameworkCore.Cosmos.Internal;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Query;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.EntityFrameworkCore.Utilities;
#nullable disable
namespace Microsoft.EntityFrameworkCore.Cosmos.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 CosmosSqlTranslatingExpressionVisitor : ExpressionVisitor
{
private const string _runtimeParameterPrefix = QueryCompilationContext.QueryParameterPrefix + "entity_equality_";
private static readonly MethodInfo _parameterValueExtractor =
typeof(CosmosSqlTranslatingExpressionVisitor).GetTypeInfo().GetDeclaredMethod(nameof(ParameterValueExtractor));
private static readonly MethodInfo _parameterListValueExtractor =
typeof(CosmosSqlTranslatingExpressionVisitor).GetTypeInfo().GetDeclaredMethod(nameof(ParameterListValueExtractor));
private static readonly MethodInfo _concatMethodInfo
= typeof(string).GetRuntimeMethod(nameof(string.Concat), new[] { typeof(object), typeof(object) });
private static readonly MethodInfo _stringEqualsWithStringComparison
= typeof(string).GetRuntimeMethod(nameof(string.Equals), new[] { typeof(string), typeof(StringComparison) });
private static readonly MethodInfo _stringEqualsWithStringComparisonStatic
= typeof(string).GetRuntimeMethod(nameof(string.Equals), new[] { typeof(string), typeof(string), typeof(StringComparison) });
private readonly QueryCompilationContext _queryCompilationContext;
private readonly IModel _model;
private readonly ISqlExpressionFactory _sqlExpressionFactory;
private readonly IMemberTranslatorProvider _memberTranslatorProvider;
private readonly SqlTypeMappingVerifyingExpressionVisitor _sqlVerifyingExpressionVisitor;
private readonly IMethodCallTranslatorProvider _methodCallTranslatorProvider;
/// <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 CosmosSqlTranslatingExpressionVisitor(
QueryCompilationContext queryCompilationContext,
ISqlExpressionFactory sqlExpressionFactory,
IMemberTranslatorProvider memberTranslatorProvider,
IMethodCallTranslatorProvider methodCallTranslatorProvider)
{
_queryCompilationContext = queryCompilationContext;
_model = queryCompilationContext.Model;
_sqlExpressionFactory = sqlExpressionFactory;
_memberTranslatorProvider = memberTranslatorProvider;
_methodCallTranslatorProvider = methodCallTranslatorProvider;
_sqlVerifyingExpressionVisitor = new SqlTypeMappingVerifyingExpressionVisitor();
}
/// <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 string TranslationErrorDetails { get; private set; }
/// <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 virtual void AddTranslationErrorDetails(string details)
{
Check.NotNull(details, nameof(details));
if (TranslationErrorDetails == null)
{
TranslationErrorDetails = details;
}
else
{
TranslationErrorDetails += Environment.NewLine + details;
}
}
/// <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(Expression expression)
{
Check.NotNull(expression, nameof(expression));
TranslationErrorDetails = null;
return TranslateInternal(expression);
}
private SqlExpression TranslateInternal(Expression expression)
{
var result = Visit(expression);
if (result is SqlExpression translation)
{
translation = _sqlExpressionFactory.ApplyDefaultTypeMapping(translation);
if (translation.TypeMapping == null)
{
// The return type is not-mappable hence return null
return null;
}
_sqlVerifyingExpressionVisitor.Visit(translation);
return translation;
}
return null;
}
/// <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)
{
Check.NotNull(binaryExpression, nameof(binaryExpression));
if (binaryExpression.NodeType == ExpressionType.Coalesce)
{
var ifTrue = binaryExpression.Left;
var ifFalse = binaryExpression.Right;
if (ifTrue.Type != ifFalse.Type)
{
ifFalse = Expression.Convert(ifFalse, ifTrue.Type);
}
return Visit(
Expression.Condition(
Expression.NotEqual(ifTrue, Expression.Constant(null, ifTrue.Type)),
ifTrue,
ifFalse));
}
var left = TryRemoveImplicitConvert(binaryExpression.Left);
var right = TryRemoveImplicitConvert(binaryExpression.Right);
// Remove convert-to-object nodes if both sides have them, or if the other side is null constant
var isLeftConvertToObject = TryUnwrapConvertToObject(left, out var leftOperand);
var isRightConvertToObject = TryUnwrapConvertToObject(right, out var rightOperand);
if (isLeftConvertToObject && isRightConvertToObject)
{
left = leftOperand;
right = rightOperand;
}
else if (isLeftConvertToObject && right.IsNullConstantExpression())
{
left = leftOperand;
}
else if (isRightConvertToObject && left.IsNullConstantExpression())
{
right = rightOperand;
}
var visitedLeft = Visit(left);
var visitedRight = Visit(right);
if ((binaryExpression.NodeType == ExpressionType.Equal
|| binaryExpression.NodeType == ExpressionType.NotEqual)
// Visited expression could be null, We need to pass MemberInitExpression
&& TryRewriteEntityEquality(
binaryExpression.NodeType, visitedLeft ?? left, visitedRight ?? right, equalsMethod: false, out var result))
{
return result;
}
if (binaryExpression.Method == _concatMethodInfo)
{
return null;
}
var uncheckedNodeTypeVariant = binaryExpression.NodeType switch
{
ExpressionType.AddChecked => ExpressionType.Add,
ExpressionType.SubtractChecked => ExpressionType.Subtract,
ExpressionType.MultiplyChecked => ExpressionType.Multiply,
_ => binaryExpression.NodeType
};
return TranslationFailed(binaryExpression.Left, visitedLeft, out var sqlLeft)
|| TranslationFailed(binaryExpression.Right, visitedRight, out var sqlRight)
? null
: _sqlExpressionFactory.MakeBinary(
uncheckedNodeTypeVariant,
sqlLeft,
sqlRight,
null);
static bool TryUnwrapConvertToObject(Expression expression, out Expression operand)
{
if (expression is UnaryExpression convertExpression
&& (convertExpression.NodeType == ExpressionType.Convert
|| convertExpression.NodeType == ExpressionType.ConvertChecked)
&& expression.Type == typeof(object))
{
operand = convertExpression.Operand;
return true;
}
operand = null;
return false;
}
}
/// <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 VisitConditional(ConditionalExpression conditionalExpression)
{
Check.NotNull(conditionalExpression, nameof(conditionalExpression));
var test = Visit(conditionalExpression.Test);
var ifTrue = Visit(conditionalExpression.IfTrue);
var ifFalse = Visit(conditionalExpression.IfFalse);
return TranslationFailed(conditionalExpression.Test, test, out var sqlTest)
|| TranslationFailed(conditionalExpression.IfTrue, ifTrue, out var sqlIfTrue)
|| TranslationFailed(conditionalExpression.IfFalse, ifFalse, out var sqlIfFalse)
? null
: _sqlExpressionFactory.Condition(sqlTest, sqlIfTrue, sqlIfFalse);
}
/// <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 VisitConstant(ConstantExpression constantExpression)
=> new SqlConstantExpression(Check.NotNull(constantExpression, nameof(constantExpression)), null);
/// <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)
{
Check.NotNull(extensionExpression, nameof(extensionExpression));
switch (extensionExpression)
{
case EntityProjectionExpression _:
case EntityReferenceExpression _:
case SqlExpression _:
return extensionExpression;
case EntityShaperExpression entityShaperExpression:
var result = Visit(entityShaperExpression.ValueBufferExpression);
if (result.NodeType == ExpressionType.Convert
&& result.Type == typeof(ValueBuffer)
&& result is UnaryExpression outerUnary
&& outerUnary.Operand.NodeType == ExpressionType.Convert
&& outerUnary.Operand.Type == typeof(object))
{
result = ((UnaryExpression)outerUnary.Operand).Operand;
}
if (result is EntityProjectionExpression entityProjectionExpression)
{
return new EntityReferenceExpression(entityProjectionExpression);
}
return null;
case ProjectionBindingExpression projectionBindingExpression:
return projectionBindingExpression.ProjectionMember != null
? ((SelectExpression)projectionBindingExpression.QueryExpression)
.GetMappedProjection(projectionBindingExpression.ProjectionMember)
: null;
default:
return null;
}
}
/// <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 VisitInvocation(InvocationExpression invocationExpression)
=> null;
/// <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 VisitLambda<T>(Expression<T> lambdaExpression)
=> throw new InvalidOperationException(CoreStrings.TranslationFailed(lambdaExpression.Print()));
/// <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 VisitListInit(ListInitExpression listInitExpression)
=> null;
/// <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 VisitMember(MemberExpression memberExpression)
{
Check.NotNull(memberExpression, nameof(memberExpression));
var innerExpression = Visit(memberExpression.Expression);
return TryBindMember(innerExpression, MemberIdentity.Create(memberExpression.Member))
?? (TranslationFailed(memberExpression.Expression, innerExpression, out var sqlInnerExpression)
? null
: _memberTranslatorProvider.Translate(
sqlInnerExpression, memberExpression.Member, memberExpression.Type, _queryCompilationContext.Logger));
}
/// <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 VisitMemberInit(MemberInitExpression memberInitExpression)
=> GetConstantOrNull(Check.NotNull(memberInitExpression, nameof(memberInitExpression)));
/// <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 VisitMethodCall(MethodCallExpression methodCallExpression)
{
Check.NotNull(methodCallExpression, nameof(methodCallExpression));
if (methodCallExpression.TryGetEFPropertyArguments(out var source, out var propertyName)
|| methodCallExpression.TryGetIndexerArguments(_model, out source, out propertyName))
{
return TryBindMember(Visit(source), MemberIdentity.Create(propertyName));
}
SqlExpression sqlObject = null;
SqlExpression[] arguments;
var method = methodCallExpression.Method;
if (method.Name == nameof(object.Equals)
&& methodCallExpression.Object != null
&& methodCallExpression.Arguments.Count == 1)
{
var left = Visit(methodCallExpression.Object);
var right = Visit(RemoveObjectConvert(methodCallExpression.Arguments[0]));
if (TryRewriteEntityEquality(
ExpressionType.Equal,
left ?? methodCallExpression.Object,
right ?? methodCallExpression.Arguments[0],
equalsMethod: true,
out var result))
{
return result;
}
if (left is SqlExpression leftSql
&& right is SqlExpression rightSql)
{
sqlObject = leftSql;
arguments = new SqlExpression[1] { rightSql };
}
else
{
return null;
}
}
else if (method.Name == nameof(object.Equals)
&& methodCallExpression.Object == null
&& methodCallExpression.Arguments.Count == 2)
{
var left = Visit(RemoveObjectConvert(methodCallExpression.Arguments[0]));
var right = Visit(RemoveObjectConvert(methodCallExpression.Arguments[1]));
if (TryRewriteEntityEquality(
ExpressionType.Equal,
left ?? methodCallExpression.Arguments[0],
right ?? methodCallExpression.Arguments[1],
equalsMethod: true,
out var result))
{
return result;
}
if (left is SqlExpression leftSql
&& right is SqlExpression rightSql)
{
arguments = new SqlExpression[2] { leftSql, rightSql };
}
else
{
return null;
}
}
else if (method.IsGenericMethod
&& method.GetGenericMethodDefinition().Equals(EnumerableMethods.Contains))
{
var enumerable = Visit(methodCallExpression.Arguments[0]);
var item = Visit(methodCallExpression.Arguments[1]);
if (TryRewriteContainsEntity(enumerable, item ?? methodCallExpression.Arguments[1], out var result))
{
return result;
}
if (enumerable is SqlExpression sqlEnumerable
&& item is SqlExpression sqlItem)
{
arguments = new SqlExpression[2] { sqlEnumerable, sqlItem };
}
else
{
return null;
}
}
else if (methodCallExpression.Arguments.Count == 1
&& method.IsContainsMethod())
{
var enumerable = Visit(methodCallExpression.Object);
var item = Visit(methodCallExpression.Arguments[0]);
if (TryRewriteContainsEntity(enumerable, item ?? methodCallExpression.Arguments[0], out var result))
{
return result;
}
if (enumerable is SqlExpression sqlEnumerable
&& item is SqlExpression sqlItem)
{
sqlObject = sqlEnumerable;
arguments = new SqlExpression[1] { sqlItem };
}
else
{
return null;
}
}
else
{
if (TranslationFailed(methodCallExpression.Object, Visit(methodCallExpression.Object), out sqlObject))
{
return null;
}
arguments = new SqlExpression[methodCallExpression.Arguments.Count];
for (var i = 0; i < arguments.Length; i++)
{
var argument = methodCallExpression.Arguments[i];
if (TranslationFailed(argument, Visit(argument), out var sqlArgument))
{
return null;
}
arguments[i] = sqlArgument;
}
}
var translation = _methodCallTranslatorProvider.Translate(
_model, sqlObject, methodCallExpression.Method, arguments, _queryCompilationContext.Logger);
if (translation == null)
{
if (methodCallExpression.Method == _stringEqualsWithStringComparison
|| methodCallExpression.Method == _stringEqualsWithStringComparisonStatic)
{
AddTranslationErrorDetails(CoreStrings.QueryUnableToTranslateStringEqualsWithStringComparison);
}
else
{
AddTranslationErrorDetails(
CoreStrings.QueryUnableToTranslateMethod(
methodCallExpression.Method.DeclaringType?.DisplayName(),
methodCallExpression.Method.Name));
}
}
return translation;
static Expression RemoveObjectConvert(Expression expression)
=> expression is UnaryExpression unaryExpression
&& (unaryExpression.NodeType == ExpressionType.Convert || unaryExpression.NodeType == ExpressionType.ConvertChecked)
&& unaryExpression.Type == typeof(object)
? unaryExpression.Operand
: expression;
}
/// <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 VisitNew(NewExpression newExpression)
=> GetConstantOrNull(Check.NotNull(newExpression, nameof(newExpression)));
/// <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 VisitNewArray(NewArrayExpression newArrayExpression)
=> null;
/// <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 VisitParameter(ParameterExpression parameterExpression)
=> parameterExpression.Name?.StartsWith(QueryCompilationContext.QueryParameterPrefix, StringComparison.Ordinal) == true
? new SqlParameterExpression(Check.NotNull(parameterExpression, nameof(parameterExpression)), null)
: null;
/// <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 VisitUnary(UnaryExpression unaryExpression)
{
Check.NotNull(unaryExpression, nameof(unaryExpression));
var operand = Visit(unaryExpression.Operand);
if (operand is EntityReferenceExpression entityReferenceExpression
&& (unaryExpression.NodeType == ExpressionType.Convert
|| unaryExpression.NodeType == ExpressionType.ConvertChecked
|| unaryExpression.NodeType == ExpressionType.TypeAs))
{
return entityReferenceExpression.Convert(unaryExpression.Type);
}
if (TranslationFailed(unaryExpression.Operand, operand, out var sqlOperand))
{
return null;
}
switch (unaryExpression.NodeType)
{
case ExpressionType.Not:
return _sqlExpressionFactory.Not(sqlOperand);
case ExpressionType.Negate:
case ExpressionType.NegateChecked:
return _sqlExpressionFactory.Negate(sqlOperand);
case ExpressionType.Convert:
case ExpressionType.ConvertChecked:
if (operand.Type.IsInterface
&& unaryExpression.Type.GetInterfaces().Any(e => e == operand.Type)
|| unaryExpression.Type.UnwrapNullableType() == operand.Type
|| unaryExpression.Type.UnwrapNullableType() == typeof(Enum)
// Object convert needs to be converted to explicit cast when mismatching types
// But we let is pass here since we don't have explicit cast mechanism here and in some cases object convert is due to value types
|| unaryExpression.Type == typeof(object))
{
return sqlOperand;
}
break;
}
return null;
}
/// <inheritdoc />
protected override Expression VisitTypeBinary(TypeBinaryExpression typeBinaryExpression)
{
Check.NotNull(typeBinaryExpression, nameof(typeBinaryExpression));
var innerExpression = Visit(typeBinaryExpression.Expression);
if (typeBinaryExpression.NodeType == ExpressionType.TypeIs
&& innerExpression is EntityReferenceExpression entityReferenceExpression)
{
var entityType = entityReferenceExpression.EntityType;
if (entityType.GetAllBaseTypesInclusive().Any(et => et.ClrType == typeBinaryExpression.TypeOperand))
{
return _sqlExpressionFactory.Constant(true);
}
var derivedType = entityType.GetDerivedTypes().SingleOrDefault(et => et.ClrType == typeBinaryExpression.TypeOperand);
if (derivedType != null
&& TryBindMember(
entityReferenceExpression,
MemberIdentity.Create(entityType.GetDiscriminatorPropertyName())) is SqlExpression discriminatorColumn)
{
var concreteEntityTypes = derivedType.GetConcreteDerivedTypesInclusive().ToList();
return concreteEntityTypes.Count == 1
? _sqlExpressionFactory.Equal(
discriminatorColumn,
_sqlExpressionFactory.Constant(concreteEntityTypes[0].GetDiscriminatorValue()))
: (SqlExpression)_sqlExpressionFactory.In(
discriminatorColumn,
_sqlExpressionFactory.Constant(concreteEntityTypes.Select(et => et.GetDiscriminatorValue()).ToList()),
negated: false);
}
}
return null;
}
private Expression TryBindMember(Expression source, MemberIdentity member)
{
if (!(source is EntityReferenceExpression entityReferenceExpression))
{
return null;
}
var result = member.MemberInfo != null
? entityReferenceExpression.ParameterEntity.BindMember(
member.MemberInfo, entityReferenceExpression.Type, clientEval: false, out _)
: entityReferenceExpression.ParameterEntity.BindMember(
member.Name, entityReferenceExpression.Type, clientEval: false, out _);
if (result == null)
{
AddTranslationErrorDetails(
CoreStrings.QueryUnableToTranslateMember(
member.Name,
entityReferenceExpression.EntityType.DisplayName()));
}
return result switch
{
EntityProjectionExpression entityProjectionExpression => new EntityReferenceExpression(entityProjectionExpression),
ObjectArrayProjectionExpression objectArrayProjectionExpression
=> new EntityReferenceExpression(objectArrayProjectionExpression.InnerProjection),
_ => result
};
}
private static Expression TryRemoveImplicitConvert(Expression expression)
{
if (expression is UnaryExpression unaryExpression
&& (unaryExpression.NodeType == ExpressionType.Convert
|| unaryExpression.NodeType == ExpressionType.ConvertChecked))
{
var innerType = unaryExpression.Operand.Type.UnwrapNullableType();
if (innerType.IsEnum)
{
innerType = Enum.GetUnderlyingType(innerType);
}
var convertedType = unaryExpression.Type.UnwrapNullableType();
if (innerType == convertedType
|| (convertedType == typeof(int)
&& (innerType == typeof(byte)
|| innerType == typeof(sbyte)
|| innerType == typeof(char)
|| innerType == typeof(short)
|| innerType == typeof(ushort)))
|| (convertedType == typeof(double)
&& (innerType == typeof(float))))
{
return TryRemoveImplicitConvert(unaryExpression.Operand);
}
}
/* TODO
if (expression is MethodCallExpression methodCallExpression)
{
var innerType = methodCallExpression.Arguments[0].Type.UnwrapNullableType();
if (innerType.IsEnum)
{
innerType = Enum.GetUnderlyingType(innerType);
}
var convertedType = methodCallExpression.Type.UnwrapNullableType();
if (innerType == convertedType
|| (convertedType == typeof(int)
&& (innerType == typeof(byte)
|| innerType == typeof(sbyte)
|| innerType == typeof(char)
|| innerType == typeof(short)
|| innerType == typeof(ushort)))
|| (convertedType == typeof(double)
&& (innerType == typeof(float))))
{
return TryRemoveImplicitConvert(methodCallExpression.Arguments[0]);
}
}
*/
return expression;
}
private bool TryRewriteContainsEntity(Expression source, Expression item, out Expression result)
{
result = null;
if (!(item is EntityReferenceExpression itemEntityReference))
{
return false;
}
var entityType = itemEntityReference.EntityType;
var primaryKeyProperties = entityType.FindPrimaryKey()?.Properties;
if (primaryKeyProperties == null)
{
throw new InvalidOperationException(CoreStrings.EntityEqualityOnKeylessEntityNotSupported(
nameof(Queryable.Contains), entityType.DisplayName()));
}
if (primaryKeyProperties.Count > 1)
{
throw new InvalidOperationException(
CoreStrings.EntityEqualityOnCompositeKeyEntitySubqueryNotSupported(nameof(Queryable.Contains), entityType.DisplayName()));
}
var property = primaryKeyProperties[0];
Expression rewrittenSource;
switch (source)
{
case SqlConstantExpression sqlConstantExpression:
var values = (IEnumerable)sqlConstantExpression.Value;
var propertyValueList =
(IList)Activator.CreateInstance(typeof(List<>).MakeGenericType(property.ClrType.MakeNullable()));
var propertyGetter = property.GetGetter();
foreach (var value in values)
{
propertyValueList.Add(propertyGetter.GetClrValue(value));
}
rewrittenSource = Expression.Constant(propertyValueList);
break;
case SqlParameterExpression sqlParameterExpression
when sqlParameterExpression.Name.StartsWith(QueryCompilationContext.QueryParameterPrefix, StringComparison.Ordinal):
var lambda = Expression.Lambda(
Expression.Call(
_parameterListValueExtractor.MakeGenericMethod(entityType.ClrType, property.ClrType.MakeNullable()),
QueryCompilationContext.QueryContextParameter,
Expression.Constant(sqlParameterExpression.Name, typeof(string)),
Expression.Constant(property, typeof(IProperty))),
QueryCompilationContext.QueryContextParameter
);
var newParameterName =
$"{_runtimeParameterPrefix}"
+ $"{sqlParameterExpression.Name.Substring(QueryCompilationContext.QueryParameterPrefix.Length)}_{property.Name}";
rewrittenSource = _queryCompilationContext.RegisterRuntimeParameter(newParameterName, lambda);
break;
default:
return false;
}
result = Visit(
Expression.Call(
EnumerableMethods.Contains.MakeGenericMethod(property.ClrType.MakeNullable()),
rewrittenSource,
CreatePropertyAccessExpression(item, property)));
return true;
}
private bool TryRewriteEntityEquality(ExpressionType nodeType, Expression left, Expression right, bool equalsMethod, out Expression result)
{
var leftEntityReference = left as EntityReferenceExpression;
var rightEntityReference = right as EntityReferenceExpression;
if (leftEntityReference == null
&& rightEntityReference == null)
{
result = null;
return false;
}
if (IsNullSqlConstantExpression(left)
|| IsNullSqlConstantExpression(right))
{
var nonNullEntityReference = IsNullSqlConstantExpression(left) ? rightEntityReference : leftEntityReference;
var entityType1 = nonNullEntityReference.EntityType;
var primaryKeyProperties1 = entityType1.FindPrimaryKey()?.Properties;
if (primaryKeyProperties1 == null)
{
throw new InvalidOperationException(CoreStrings.EntityEqualityOnKeylessEntityNotSupported(
nodeType == ExpressionType.Equal
? equalsMethod ? nameof(object.Equals) : "=="
: equalsMethod ? "!" + nameof(object.Equals) : "!=",
entityType1.DisplayName()));
}
result = Visit(
primaryKeyProperties1.Select(
p =>
Expression.MakeBinary(
nodeType, CreatePropertyAccessExpression(nonNullEntityReference, p),
Expression.Constant(null, p.ClrType.MakeNullable())))
.Aggregate((l, r) => nodeType == ExpressionType.Equal ? Expression.OrElse(l, r) : Expression.AndAlso(l, r)));
return true;
}
var leftEntityType = leftEntityReference?.EntityType;
var rightEntityType = rightEntityReference?.EntityType;
var entityType = leftEntityType ?? rightEntityType;
Debug.Assert(entityType != null, "At least either side should be entityReference so entityType should be non-null.");
if (leftEntityType != null
&& rightEntityType != null
&& leftEntityType.GetRootType() != rightEntityType.GetRootType())
{
result = _sqlExpressionFactory.Constant(false);
return true;
}
var primaryKeyProperties = entityType.FindPrimaryKey()?.Properties;
if (primaryKeyProperties == null)
{
throw new InvalidOperationException(CoreStrings.EntityEqualityOnKeylessEntityNotSupported(
nodeType == ExpressionType.Equal
? equalsMethod ? nameof(object.Equals) : "=="
: equalsMethod ? "!" + nameof(object.Equals) : "!=",
entityType.DisplayName()));
}
result = Visit(
primaryKeyProperties.Select(
p =>
Expression.MakeBinary(
nodeType,
CreatePropertyAccessExpression(left, p),
CreatePropertyAccessExpression(right, p)))
.Aggregate((l, r) => nodeType == ExpressionType.Equal
? Expression.AndAlso(l, r)
: Expression.OrElse(l, r)));
return true;
}
private Expression CreatePropertyAccessExpression(Expression target, IProperty property)
{
switch (target)
{
case SqlConstantExpression sqlConstantExpression:
return Expression.Constant(
property.GetGetter().GetClrValue(sqlConstantExpression.Value), property.ClrType.MakeNullable());
case SqlParameterExpression sqlParameterExpression
when sqlParameterExpression.Name.StartsWith(QueryCompilationContext.QueryParameterPrefix, StringComparison.Ordinal):
var lambda = Expression.Lambda(
Expression.Call(
_parameterValueExtractor.MakeGenericMethod(property.ClrType.MakeNullable()),
QueryCompilationContext.QueryContextParameter,
Expression.Constant(sqlParameterExpression.Name, typeof(string)),
Expression.Constant(property, typeof(IProperty))),
QueryCompilationContext.QueryContextParameter);
var newParameterName =
$"{_runtimeParameterPrefix}"
+ $"{sqlParameterExpression.Name.Substring(QueryCompilationContext.QueryParameterPrefix.Length)}_{property.Name}";
return _queryCompilationContext.RegisterRuntimeParameter(newParameterName, lambda);
case MemberInitExpression memberInitExpression
when memberInitExpression.Bindings.SingleOrDefault(
mb => mb.Member.Name == property.Name) is MemberAssignment memberAssignment:
return memberAssignment.Expression;
default:
return target.CreateEFPropertyExpression(property);
}
}
private static T ParameterValueExtractor<T>(QueryContext context, string baseParameterName, IProperty property)
{
var baseParameter = context.ParameterValues[baseParameterName];
return baseParameter == null ? (T)(object)null : (T)property.GetGetter().GetClrValue(baseParameter);
}
private static List<TProperty> ParameterListValueExtractor<TEntity, TProperty>(
QueryContext context,
string baseParameterName,
IProperty property)
{
if (!(context.ParameterValues[baseParameterName] is IEnumerable<TEntity> baseListParameter))
{
return null;
}
var getter = property.GetGetter();
return baseListParameter.Select(e => e != null ? (TProperty)getter.GetClrValue(e) : (TProperty)(object)null).ToList();
}
private static bool IsNullSqlConstantExpression(Expression expression)
=> expression is SqlConstantExpression sqlConstant && sqlConstant.Value == null;
private SqlConstantExpression GetConstantOrNull(Expression expression)
=> CanEvaluate(expression)
? new SqlConstantExpression(
Expression.Constant(
Expression.Lambda<Func<object>>(Expression.Convert(expression, typeof(object))).Compile().Invoke(),
expression.Type),
null)
: null;
private static bool CanEvaluate(Expression expression)
{
#pragma warning disable IDE0066 // Convert switch statement to expression
switch (expression)
#pragma warning restore IDE0066 // Convert switch statement to expression
{
case ConstantExpression constantExpression:
return true;
case NewExpression newExpression:
return newExpression.Arguments.All(e => CanEvaluate(e));
case MemberInitExpression memberInitExpression:
return CanEvaluate(memberInitExpression.NewExpression)
&& memberInitExpression.Bindings.All(
mb => mb is MemberAssignment memberAssignment && CanEvaluate(memberAssignment.Expression));
default:
return false;
}
}
[DebuggerStepThrough]
private bool TranslationFailed(Expression original, Expression translation, out SqlExpression castTranslation)
{
if (original != null
&& !(translation is SqlExpression))
{
castTranslation = null;
return true;
}
castTranslation = translation as SqlExpression;
return false;
}
private sealed class EntityReferenceExpression : Expression
{
public EntityReferenceExpression(EntityProjectionExpression parameter)
{
ParameterEntity = parameter;
EntityType = parameter.EntityType;
Type = EntityType.ClrType;
}
private EntityReferenceExpression(EntityProjectionExpression parameter, Type type)