-
Notifications
You must be signed in to change notification settings - Fork 3.2k
/
Copy pathCosmosSqlTranslatingExpressionVisitor.cs
1343 lines (1151 loc) · 60.8 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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections;
using System.Diagnostics.CodeAnalysis;
using Microsoft.EntityFrameworkCore.Cosmos.Internal;
using Microsoft.EntityFrameworkCore.Internal;
using static Microsoft.EntityFrameworkCore.Query.QueryHelpers;
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(
QueryCompilationContext queryCompilationContext,
ISqlExpressionFactory sqlExpressionFactory,
ITypeMappingSource typeMappingSource,
IMemberTranslatorProvider memberTranslatorProvider,
IMethodCallTranslatorProvider methodCallTranslatorProvider,
QueryableMethodTranslatingExpressionVisitor queryableMethodTranslatingExpressionVisitor)
: ExpressionVisitor
{
private const string RuntimeParameterPrefix = QueryCompilationContext.QueryParameterPrefix + "entity_equality_";
private static readonly MethodInfo ParameterValueExtractorMethod =
typeof(CosmosSqlTranslatingExpressionVisitor).GetTypeInfo().GetDeclaredMethod(nameof(ParameterValueExtractor))!;
private static readonly MethodInfo ParameterListValueExtractorMethod =
typeof(CosmosSqlTranslatingExpressionVisitor).GetTypeInfo().GetDeclaredMethod(nameof(ParameterListValueExtractor))!;
private static readonly MethodInfo ConcatMethodInfo
= typeof(string).GetRuntimeMethod(nameof(string.Concat), [typeof(object), typeof(object)])!;
private static readonly MethodInfo StringEqualsWithStringComparison
= typeof(string).GetRuntimeMethod(nameof(string.Equals), [typeof(string), typeof(StringComparison)])!;
private static readonly MethodInfo StringEqualsWithStringComparisonStatic
= typeof(string).GetRuntimeMethod(nameof(string.Equals), [typeof(string), typeof(string), typeof(StringComparison)])!;
private static readonly MethodInfo GetTypeMethodInfo = typeof(object).GetTypeInfo().GetDeclaredMethod(nameof(GetType))!;
private readonly IModel _model = queryCompilationContext.Model;
private readonly SqlTypeMappingVerifyingExpressionVisitor _sqlVerifyingExpressionVisitor = 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 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)
{
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, bool applyDefaultTypeMapping = true)
{
TranslationErrorDetails = null;
return TranslateInternal(expression, applyDefaultTypeMapping);
}
private SqlExpression? TranslateInternal(Expression expression, bool applyDefaultTypeMapping = true)
{
var result = Visit(expression);
if (result is SqlExpression translation)
{
if (applyDefaultTypeMapping)
{
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)
{
switch (binaryExpression.NodeType)
{
case 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));
case ExpressionType.Equal:
case ExpressionType.NotEqual when binaryExpression.Left.Type == typeof(Type):
if (IsGetTypeMethodCall(binaryExpression.Left, out var entityReference1)
&& IsTypeConstant(binaryExpression.Right, out var type1))
{
return ProcessGetType(entityReference1!, type1!, binaryExpression.NodeType == ExpressionType.Equal);
}
if (IsGetTypeMethodCall(binaryExpression.Right, out var entityReference2)
&& IsTypeConstant(binaryExpression.Left, out var type2))
{
return ProcessGetType(entityReference2!, type2!, binaryExpression.NodeType == ExpressionType.Equal);
}
break;
}
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);
switch (binaryExpression)
{
// Visited expression could be null, We need to pass MemberInitExpression
case { NodeType: ExpressionType.Equal or ExpressionType.NotEqual }
when TryRewriteEntityEquality(
binaryExpression.NodeType,
visitedLeft == QueryCompilationContext.NotTranslatedExpression ? left : visitedLeft,
visitedRight == QueryCompilationContext.NotTranslatedExpression ? right : visitedRight,
equalsMethod: false,
out var result):
return result;
case { Method: var method } when method == ConcatMethodInfo:
return QueryCompilationContext.NotTranslatedExpression;
default:
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)
? QueryCompilationContext.NotTranslatedExpression
: sqlExpressionFactory.MakeBinary(
uncheckedNodeTypeVariant,
sqlLeft!,
sqlRight!,
typeMapping: null)
?? QueryCompilationContext.NotTranslatedExpression;
}
Expression ProcessGetType(EntityReferenceExpression entityReferenceExpression, Type comparisonType, bool match)
{
var entityType = entityReferenceExpression.EntityType;
if (entityType.BaseType == null
&& !entityType.GetDirectlyDerivedTypes().Any())
{
// No hierarchy
return sqlExpressionFactory.Constant((entityType.ClrType == comparisonType) == match);
}
if (entityType.GetAllBaseTypes().Any(e => e.ClrType == comparisonType))
{
// EntitySet will never contain a type of base type
return sqlExpressionFactory.Constant(!match);
}
var derivedType = entityType.GetDerivedTypesInclusive().SingleOrDefault(et => et.ClrType == comparisonType);
// If no derived type matches then fail the translation
if (derivedType != null)
{
// If the derived type is abstract type then predicate will always be false
if (derivedType.IsAbstract())
{
return sqlExpressionFactory.Constant(!match);
}
// Or add predicate for matching that particular type discriminator value
// All hierarchies have discriminator property
if (TryBindMember(
entityReferenceExpression,
MemberIdentity.Create(entityType.GetDiscriminatorPropertyName()),
out var discriminatorMember,
out _)
&& discriminatorMember is SqlExpression discriminatorColumn)
{
return match
? sqlExpressionFactory.Equal(
discriminatorColumn,
sqlExpressionFactory.Constant(derivedType.GetDiscriminatorValue(), discriminatorColumn.Type))
: sqlExpressionFactory.NotEqual(
discriminatorColumn,
sqlExpressionFactory.Constant(derivedType.GetDiscriminatorValue(), discriminatorColumn.Type));
}
}
return QueryCompilationContext.NotTranslatedExpression;
}
bool IsGetTypeMethodCall(Expression expression, [NotNullWhen(true)] out EntityReferenceExpression? entityReferenceExpression)
{
entityReferenceExpression = null;
if (expression is not MethodCallExpression methodCallExpression
|| methodCallExpression.Method != GetTypeMethodInfo)
{
return false;
}
entityReferenceExpression = Visit(methodCallExpression.Object) as EntityReferenceExpression;
return entityReferenceExpression != null;
}
static bool IsTypeConstant(Expression expression, [NotNullWhen(true)] out Type? type)
{
if (expression is UnaryExpression
{
NodeType: ExpressionType.Convert or ExpressionType.ConvertChecked,
Operand: ConstantExpression { Value: Type t }
})
{
type = t;
return true;
}
type = null;
return false;
}
static bool TryUnwrapConvertToObject(Expression expression, [NotNullWhen(true)] out Expression? operand)
{
if (expression is UnaryExpression { NodeType: ExpressionType.Convert or ExpressionType.ConvertChecked } convertExpression
&& 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)
{
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)
? QueryCompilationContext.NotTranslatedExpression
: 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(constantExpression.Value, constantExpression.Type, typeMapping: 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)
{
switch (extensionExpression)
{
case EntityProjectionExpression:
case EntityReferenceExpression:
case SqlExpression:
return extensionExpression;
case StructuralTypeShaperExpression shaper:
return new EntityReferenceExpression(shaper);
// var result = Visit(entityShaperExpression.ValueBufferExpression);
//
// if (result is UnaryExpression
// {
// NodeType: ExpressionType.Convert,
// Operand.NodeType: ExpressionType.Convert
// } outerUnary
// && outerUnary.Type == typeof(ValueBuffer)
// && outerUnary.Operand.Type == typeof(object))
// {
// result = ((UnaryExpression)outerUnary.Operand).Operand;
// }
//
// return result is EntityProjectionExpression entityProjectionExpression
// ? new EntityReferenceExpression(entityProjectionExpression)
// : QueryCompilationContext.NotTranslatedExpression;
case ProjectionBindingExpression projectionBindingExpression:
return projectionBindingExpression.ProjectionMember != null
? ((SelectExpression)projectionBindingExpression.QueryExpression)
.GetMappedProjection(projectionBindingExpression.ProjectionMember)
: QueryCompilationContext.NotTranslatedExpression;
// This case is for a subquery embedded in a lambda, returning a scalar, e.g. Where(b => b.Posts.Count() > 0).
// For most cases, generate a scalar subquery (WHERE (SELECT COUNT(*) FROM Posts) > 0).
case ShapedQueryExpression { ResultCardinality: not ResultCardinality.Enumerable } shapedQuery:
{
var shaperExpression = shapedQuery.ShaperExpression;
ProjectionBindingExpression? mappedProjectionBindingExpression = null;
var innerExpression = shaperExpression;
Type? convertedType = null;
if (shaperExpression is UnaryExpression { NodeType: ExpressionType.Convert } unaryExpression)
{
convertedType = unaryExpression.Type;
innerExpression = unaryExpression.Operand;
}
if (innerExpression is StructuralTypeShaperExpression ese
&& (convertedType == null
|| convertedType.IsAssignableFrom(ese.Type)))
{
return new EntityReferenceExpression(shapedQuery.UpdateShaperExpression(innerExpression));
}
if (innerExpression is ProjectionBindingExpression pbe
&& (convertedType == null
|| convertedType.MakeNullable() == innerExpression.Type))
{
mappedProjectionBindingExpression = pbe;
}
if (mappedProjectionBindingExpression == null
&& shaperExpression is BlockExpression
{
Expressions: [BinaryExpression { NodeType: ExpressionType.Assign, Right: ProjectionBindingExpression pbe2 }, _]
})
{
mappedProjectionBindingExpression = pbe2;
}
if (mappedProjectionBindingExpression == null)
{
return QueryCompilationContext.NotTranslatedExpression;
}
var subquery = (SelectExpression)shapedQuery.QueryExpression;
var projection = mappedProjectionBindingExpression.ProjectionMember is ProjectionMember projectionMember
? subquery.GetMappedProjection(projectionMember)
: throw new NotImplementedException("Subquery with index projection binding");
if (projection is not SqlExpression sqlExpression)
{
return QueryCompilationContext.NotTranslatedExpression;
}
if (subquery.Sources.Count == 0)
{
return sqlExpression;
}
// TODO TODO
// subquery.ReplaceProjection(new List<Expression> { sqlExpression });
subquery.ApplyProjection();
// Add VALUE to the subquery's projection (SELECT VALUE x ...), to make it project that value rather than a JSON object
// wrapping that value.
subquery = subquery.WithSingleValueProjection();
Check.DebugAssert(shapedQuery.ResultCardinality == ResultCardinality.Single, "SingleOrDefault not supported in subqueries");
return new ScalarSubqueryExpression(subquery);
}
// This case is for a subquery embedded in a lambda, returning an array, e.g. Where(b => b.Ints == new[] { 1, 2, 3 }).
// If the subquery represents a bare array (without any operators composed on top), simply extract and return that.
// Otherwise, wrap the subquery with an ARRAY() operator, converting the subquery to an array first.
case ShapedQueryExpression { ResultCardinality: ResultCardinality.Enumerable } shapedQuery
when shapedQuery.TryConvertToArray(typeMappingSource, out var array):
return array;
default:
return QueryCompilationContext.NotTranslatedExpression;
}
}
/// <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)
=> QueryCompilationContext.NotTranslatedExpression;
/// <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)
=> QueryCompilationContext.NotTranslatedExpression;
/// <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)
{
var innerExpression = Visit(memberExpression.Expression);
return TryBindMember(innerExpression, MemberIdentity.Create(memberExpression.Member), out var expression, out _)
? expression
: (TranslationFailed(memberExpression.Expression, innerExpression, out var sqlInnerExpression)
? QueryCompilationContext.NotTranslatedExpression
: memberTranslatorProvider.Translate(
sqlInnerExpression, memberExpression.Member, memberExpression.Type, queryCompilationContext.Logger))
?? QueryCompilationContext.NotTranslatedExpression;
}
/// <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)
=> TryEvaluateToConstant(memberInitExpression, out var sqlConstantExpression)
? sqlConstantExpression
: QueryCompilationContext.NotTranslatedExpression;
/// <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)
{
if (IsMemberAccess(methodCallExpression, _model, out var source, out var memberIdentity))
{
return TryBindMember(Visit(source), memberIdentity, out var result, out _)
? result
: QueryCompilationContext.NotTranslatedExpression;
}
SqlExpression? sqlObject = null;
SqlExpression[] arguments;
var method = methodCallExpression.Method;
switch (methodCallExpression)
{
case
{
Method.Name: nameof(object.Equals),
Object: not null,
Arguments.Count: 1
}:
{
var left = Visit(methodCallExpression.Object);
var right = Visit(RemoveObjectConvert(methodCallExpression.Arguments[0]));
if (TryRewriteEntityEquality(
ExpressionType.Equal,
left == QueryCompilationContext.NotTranslatedExpression ? methodCallExpression.Object : left,
right == QueryCompilationContext.NotTranslatedExpression ? methodCallExpression.Arguments[0] : right,
equalsMethod: true,
out var result))
{
return result;
}
if (left is SqlExpression leftSql
&& right is SqlExpression rightSql)
{
sqlObject = leftSql;
arguments = [rightSql];
}
else
{
return QueryCompilationContext.NotTranslatedExpression;
}
break;
}
case
{
Method.Name: nameof(object.Equals),
Object: null,
Arguments.Count: 2
}:
{
var left = Visit(RemoveObjectConvert(methodCallExpression.Arguments[0]));
var right = Visit(RemoveObjectConvert(methodCallExpression.Arguments[1]));
if (TryRewriteEntityEquality(
ExpressionType.Equal,
left == QueryCompilationContext.NotTranslatedExpression ? methodCallExpression.Arguments[0] : left,
right == QueryCompilationContext.NotTranslatedExpression ? methodCallExpression.Arguments[1] : right,
equalsMethod: true,
out var result))
{
return result;
}
if (left is SqlExpression leftSql
&& right is SqlExpression rightSql)
{
arguments = [leftSql, rightSql];
}
else
{
return QueryCompilationContext.NotTranslatedExpression;
}
break;
}
case { Method: { Name: nameof(Enumerable.Contains), IsGenericMethod: true } }
when method.GetGenericMethodDefinition().Equals(EnumerableMethods.Contains):
return TranslateContains(methodCallExpression.Arguments[1], methodCallExpression.Arguments[0]);
case { Arguments: [var argument] } when method.IsContainsMethod():
return TranslateContains(argument, methodCallExpression.Object!);
// For queryable methods, either we translate the whole aggregate or we go to subquery mode
case { Method.IsStatic: true, Arguments.Count: > 0 }
when method.DeclaringType == typeof(Queryable)
|| method.DeclaringType == typeof(EntityFrameworkQueryableExtensions)
|| method.DeclaringType == typeof(CosmosQueryableExtensions):
return TranslateAsSubquery(methodCallExpression);
default:
{
if (TranslationFailed(methodCallExpression.Object, Visit(methodCallExpression.Object), out sqlObject))
{
return QueryCompilationContext.NotTranslatedExpression;
}
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 TranslateAsSubquery(methodCallExpression);
}
arguments[i] = sqlArgument!;
}
break;
}
}
Expression? translation = methodCallTranslatorProvider.Translate(
_model, sqlObject, methodCallExpression.Method, arguments, queryCompilationContext.Logger);
if (translation is not null)
{
return translation;
}
translation = TranslateAsSubquery(methodCallExpression);
if (translation != QueryCompilationContext.NotTranslatedExpression)
{
return translation;
}
if (methodCallExpression.Method == StringEqualsWithStringComparison
|| methodCallExpression.Method == StringEqualsWithStringComparisonStatic)
{
AddTranslationErrorDetails(CoreStrings.QueryUnableToTranslateStringEqualsWithStringComparison);
}
else
{
AddTranslationErrorDetails(
CoreStrings.QueryUnableToTranslateMethod(
methodCallExpression.Method.DeclaringType?.DisplayName(),
methodCallExpression.Method.Name));
}
return QueryCompilationContext.NotTranslatedExpression;
Expression TranslateAsSubquery(Expression expression)
{
var subqueryTranslation = queryableMethodTranslatingExpressionVisitor.TranslateSubquery(expression);
return subqueryTranslation == null
? QueryCompilationContext.NotTranslatedExpression
: Visit(subqueryTranslation);
}
Expression TranslateContains(Expression untranslatedItem, Expression untranslatedCollection)
{
var collection = Visit(untranslatedCollection);
var itemUnchecked = Visit(untranslatedItem);
if (TryRewriteContainsEntity(
collection,
itemUnchecked == QueryCompilationContext.NotTranslatedExpression ? untranslatedItem : itemUnchecked,
out var result))
{
return result;
}
if (itemUnchecked is not SqlExpression translatedItem)
{
return QueryCompilationContext.NotTranslatedExpression;
}
switch (collection)
{
// If the collection was an inline NewArrayExpression with constants only, we get a single constant for that array.
case SqlConstantExpression { Value: IEnumerable values, TypeMapping: var typeMapping }:
{
var translatedValues = values is IList iList
? new List<SqlExpression>(iList.Count)
: [];
foreach (var value in values)
{
translatedValues.Add(sqlExpressionFactory.Constant(value, typeMapping));
}
return sqlExpressionFactory.In(translatedItem, translatedValues);
}
// If the collection was an inline NewArrayExpression with at least one non-constant, the NewArrayExpression makes it
// as-is to translation, where it (currently) cannot be translated. Identify this case and translate the elements.
case not SqlExpression when untranslatedCollection is NewArrayExpression { Expressions: var values }:
{
var translatedValues = new SqlExpression[values.Count];
for (var i = 0; i < values.Count; i++)
{
if (Visit(values[i]) is not SqlExpression value)
{
return QueryCompilationContext.NotTranslatedExpression;
}
translatedValues[i] = value;
}
return sqlExpressionFactory.In(translatedItem, translatedValues);
}
// If the collection was a captured variable (parameter), construct an InExpression over that;
// InExpressionValuesExpandingExpressionVisitor will expand the values as constants later.
case SqlParameterExpression sqlParameterExpression:
return sqlExpressionFactory.In(translatedItem, sqlParameterExpression);
default:
return QueryCompilationContext.NotTranslatedExpression;
}
}
static Expression RemoveObjectConvert(Expression expression)
=> expression is UnaryExpression { NodeType: ExpressionType.Convert or ExpressionType.ConvertChecked } unaryExpression
&& 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)
=> TryEvaluateToConstant(newExpression, out var sqlConstantExpression)
? sqlConstantExpression
: QueryCompilationContext.NotTranslatedExpression;
/// <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)
{
var expressions = newArrayExpression.Expressions;
var translatedItems = new SqlExpression[expressions.Count];
for (var i = 0; i < expressions.Count; i++)
{
if (Translate(expressions[i]) is not SqlExpression translatedItem)
{
return QueryCompilationContext.NotTranslatedExpression;
}
translatedItems[i] = translatedItem;
}
var arrayTypeMapping = typeMappingSource.FindMapping(newArrayExpression.Type);
var elementClrType = newArrayExpression.Type.GetElementType()!;
var inlineArray = new ArrayConstantExpression(elementClrType, translatedItems, arrayTypeMapping);
return inlineArray;
}
/// <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(parameterExpression.Name, parameterExpression.Type, null)
: QueryCompilationContext.NotTranslatedExpression;
/// <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)
{
var operand = Visit(unaryExpression.Operand);
if (operand is EntityReferenceExpression entityReferenceExpression
&& unaryExpression.NodeType is ExpressionType.Convert or ExpressionType.ConvertChecked or ExpressionType.TypeAs)
{
return entityReferenceExpression.Convert(unaryExpression.Type);
}
if (TranslationFailed(unaryExpression.Operand, operand, out var sqlOperand))
{
return QueryCompilationContext.NotTranslatedExpression;
}
return unaryExpression.NodeType switch
{
ExpressionType.Not
=> sqlExpressionFactory.Not(sqlOperand!),
ExpressionType.Negate or ExpressionType.NegateChecked
=> sqlExpressionFactory.Negate(sqlOperand!),
// Convert nodes can be an explicit user gesture in the query, or they may get introduced by the compiler (e.g. when a Child is
// passed as an argument for a parameter of type Parent). The latter type should generally get stripped out as a pure C#/LINQ
// artifact that shouldn't affect translation, but the latter may be an indication from the user that they want to apply a
// type change.
ExpressionType.Convert or ExpressionType.ConvertChecked or ExpressionType.TypeAs
when operand.Type.IsInterface && unaryExpression.Type.GetInterfaces().Any(e => e == operand.Type)
// We strip out implicit conversions, e.g. float[] -> ReadOnlyMemory<float> (for vector search)
|| (unaryExpression.Method is { IsSpecialName: true, Name: "op_Implicit" }
&& IsReadOnlyMemory(unaryExpression.Type.UnwrapNullableType()))
|| 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 it 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)
=> sqlOperand!,
_ => QueryCompilationContext.NotTranslatedExpression
};
static bool IsReadOnlyMemory(Type type)
=> type is { IsGenericType: true, IsGenericTypeDefinition: false }
&& type.GetGenericTypeDefinition() == typeof(ReadOnlyMemory<>);
}
/// <inheritdoc />
protected override Expression VisitTypeBinary(TypeBinaryExpression 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()),
out var discriminatorMember,
out _)
&& discriminatorMember is SqlExpression discriminatorColumn)
{
var concreteEntityTypes = derivedType.GetConcreteDerivedTypesInclusive().ToList();
return concreteEntityTypes.Count == 1
? sqlExpressionFactory.Equal(
discriminatorColumn,
sqlExpressionFactory.Constant(concreteEntityTypes[0].GetDiscriminatorValue(), discriminatorColumn.Type))
: sqlExpressionFactory.In(
discriminatorColumn,
concreteEntityTypes
.Select(et => sqlExpressionFactory.Constant(et.GetDiscriminatorValue(), discriminatorColumn.Type)).ToArray());
}
}
return QueryCompilationContext.NotTranslatedExpression;
}
/// <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>
[EntityFrameworkInternal]
public virtual bool TryBindMember(
Expression? source,
MemberIdentity member,
[NotNullWhen(true)] out Expression? expression,
[NotNullWhen(true)] out IPropertyBase? property,
bool wrapResultExpressionInReferenceExpression = true)
{
if (source is not EntityReferenceExpression typeReference)
{
expression = null;
property = null;
return false;
}
switch (typeReference)
{
case { Parameter: StructuralTypeShaperExpression shaper }:
var valueBufferExpression = Visit(shaper.ValueBufferExpression);
var entityProjection = (EntityProjectionExpression)valueBufferExpression;
expression = member switch
{
{ MemberInfo: MemberInfo memberInfo }
=> entityProjection.BindMember(
memberInfo, typeReference.Type, clientEval: false, out property),
{ Name: string name }
=> entityProjection.BindMember(
name, typeReference.Type, clientEval: false, out property),
_ => throw new UnreachableException()
};
break;
case { Subquery: ShapedQueryExpression }:
throw new NotImplementedException("Bind property on structural type coming out of scalar subquery");
default:
throw new UnreachableException();
}
if (expression is null)
{
AddTranslationErrorDetails(
CoreStrings.QueryUnableToTranslateMember(
member.Name,
typeReference.EntityType.DisplayName()));
return false;
}
Check.DebugAssert(property is not null, "Property cannot be null if binding result was non-null");
switch (expression)
{
case StructuralTypeShaperExpression shaper when wrapResultExpressionInReferenceExpression:
expression = new EntityReferenceExpression(shaper);
return true;
// case ObjectArrayAccessExpression objectArrayProjectionExpression:
// expression = objectArrayProjectionExpression;
// return true;
default:
return true;
}
// return true;
}
private static Expression TryRemoveImplicitConvert(Expression expression)
{
if (expression is UnaryExpression { NodeType: ExpressionType.Convert or ExpressionType.ConvertChecked } unaryExpression)
{
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);
}
}
return expression;
}
private bool TryRewriteContainsEntity(Expression source, Expression item, [NotNullWhen(true)] out Expression? result)
{
result = null;
if (item is not EntityReferenceExpression itemEntityReference)
{
return false;
}
var entityType = itemEntityReference.EntityType;
var primaryKeyProperties = entityType.FindPrimaryKey()?.Properties;