-
Notifications
You must be signed in to change notification settings - Fork 3.2k
/
RelationalSqlTranslatingExpressionVisitor.cs
2190 lines (1885 loc) · 97.5 KB
/
RelationalSqlTranslatingExpressionVisitor.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.Metadata.Internal;
using Microsoft.EntityFrameworkCore.Query.SqlExpressions;
namespace Microsoft.EntityFrameworkCore.Query;
/// <summary>
/// <para>
/// A class that translates expressions to corresponding SQL representation.
/// </para>
/// <para>
/// This type is typically used by database providers (and other extensions). It is generally
/// not used in application code.
/// </para>
/// </summary>
public class RelationalSqlTranslatingExpressionVisitor : ExpressionVisitor
{
private const string RuntimeParameterPrefix = QueryCompilationContext.QueryParameterPrefix + "entity_equality_";
private static readonly List<MethodInfo> SingleResultMethodInfos = new()
{
QueryableMethods.FirstWithPredicate,
QueryableMethods.FirstWithoutPredicate,
QueryableMethods.FirstOrDefaultWithPredicate,
QueryableMethods.FirstOrDefaultWithoutPredicate,
QueryableMethods.SingleWithPredicate,
QueryableMethods.SingleWithoutPredicate,
QueryableMethods.SingleOrDefaultWithPredicate,
QueryableMethods.SingleOrDefaultWithoutPredicate,
QueryableMethods.LastWithPredicate,
QueryableMethods.LastWithoutPredicate,
QueryableMethods.LastOrDefaultWithPredicate,
QueryableMethods.LastOrDefaultWithoutPredicate,
QueryableMethods.ElementAt,
QueryableMethods.ElementAtOrDefault
};
private static readonly MethodInfo ParameterValueExtractorMethod =
typeof(RelationalSqlTranslatingExpressionVisitor).GetTypeInfo().GetDeclaredMethod(nameof(ParameterValueExtractor))!;
private static readonly MethodInfo ParameterListValueExtractorMethod =
typeof(RelationalSqlTranslatingExpressionVisitor).GetTypeInfo().GetDeclaredMethod(nameof(ParameterListValueExtractor))!;
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 static readonly MethodInfo GetTypeMethodInfo = typeof(object).GetTypeInfo().GetDeclaredMethod(nameof(GetType))!;
private readonly QueryCompilationContext _queryCompilationContext;
private readonly IModel _model;
private readonly ISqlExpressionFactory _sqlExpressionFactory;
private readonly QueryableMethodTranslatingExpressionVisitor _queryableMethodTranslatingExpressionVisitor;
private bool _throwForNotTranslatedEfProperty;
/// <summary>
/// Creates a new instance of the <see cref="RelationalSqlTranslatingExpressionVisitor" /> class.
/// </summary>
/// <param name="dependencies">Parameter object containing dependencies for this class.</param>
/// <param name="queryCompilationContext">The query compilation context object to use.</param>
/// <param name="queryableMethodTranslatingExpressionVisitor">A parent queryable method translating expression visitor to translate subquery.</param>
public RelationalSqlTranslatingExpressionVisitor(
RelationalSqlTranslatingExpressionVisitorDependencies dependencies,
QueryCompilationContext queryCompilationContext,
QueryableMethodTranslatingExpressionVisitor queryableMethodTranslatingExpressionVisitor)
{
Dependencies = dependencies;
_sqlExpressionFactory = dependencies.SqlExpressionFactory;
_queryCompilationContext = queryCompilationContext;
_model = queryCompilationContext.Model;
_queryableMethodTranslatingExpressionVisitor = queryableMethodTranslatingExpressionVisitor;
_throwForNotTranslatedEfProperty = true;
}
/// <summary>
/// Detailed information about errors encountered during translation.
/// </summary>
public virtual string? TranslationErrorDetails { get; private set; }
/// <summary>
/// Adds detailed information about error encountered during translation.
/// </summary>
/// <param name="details">Detailed information about error encountered during translation.</param>
protected virtual void AddTranslationErrorDetails(string details)
{
if (TranslationErrorDetails == null)
{
TranslationErrorDetails = details;
}
else
{
TranslationErrorDetails += Environment.NewLine + details;
}
}
/// <summary>
/// Relational provider-specific dependencies for this service.
/// </summary>
protected virtual RelationalSqlTranslatingExpressionVisitorDependencies Dependencies { get; }
/// <summary>
/// Translates an expression to an equivalent SQL representation.
/// </summary>
/// <param name="expression">An expression to translate.</param>
/// <param name="applyDefaultTypeMapping">
/// Whether to apply the default type mapping on the top-most element if it has none. Defaults to <see langword="true" />.
/// </param>
/// <returns>A SQL translation of the given expression.</returns>
public virtual SqlExpression? Translate(Expression expression, bool applyDefaultTypeMapping = true)
{
TranslationErrorDetails = null;
return TranslateInternal(expression, applyDefaultTypeMapping) as SqlExpression;
}
/// <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 Expression? TranslateProjection(Expression expression, bool applyDefaultTypeMapping = true)
{
TranslationErrorDetails = null;
return TranslateInternal(expression, applyDefaultTypeMapping) switch
{
// This is the case of a structural type getting projected out via Select (possibly also an owned entity one day, if we stop
// expanding them in pre-visitation)
StructuralTypeReferenceExpression { Parameter: StructuralTypeShaperExpression shaper }
=> shaper,
StructuralTypeReferenceExpression { Subquery: not null }
=> null, // TODO: think about this - probably unsupported (if so, message)
SqlExpression s => s,
_ => null
};
}
private Expression? TranslateInternal(Expression expression, bool applyDefaultTypeMapping = true)
{
var result = Visit(expression);
if (result is SqlExpression translation)
{
if (translation is SqlUnaryExpression { OperatorType: ExpressionType.Convert } sqlUnaryExpression
&& sqlUnaryExpression.Type == typeof(object))
{
translation = sqlUnaryExpression.Operand;
}
if (applyDefaultTypeMapping)
{
translation = _sqlExpressionFactory.ApplyDefaultTypeMapping(translation);
if (translation.TypeMapping == null)
{
// The return type is not-mappable hence return null
return null;
}
}
return translation;
}
return result;
}
/// <summary>
/// Translates Average over an expression to an equivalent SQL representation.
/// </summary>
/// <param name="sqlExpression">An expression to translate Average over.</param>
/// <returns>A SQL translation of Average over the given expression.</returns>
[Obsolete("Use IAggregateMethodCallTranslatorProvider to add translation for aggregate methods")]
public virtual SqlExpression? TranslateAverage(SqlExpression sqlExpression)
{
var inputType = sqlExpression.Type;
if (inputType == typeof(int)
|| inputType == typeof(long))
{
sqlExpression = sqlExpression is DistinctExpression distinctExpression
? new DistinctExpression(
_sqlExpressionFactory.ApplyDefaultTypeMapping(
_sqlExpressionFactory.Convert(distinctExpression.Operand, typeof(double))))
: _sqlExpressionFactory.ApplyDefaultTypeMapping(
_sqlExpressionFactory.Convert(sqlExpression, typeof(double)));
}
return inputType == typeof(float)
? _sqlExpressionFactory.Convert(
_sqlExpressionFactory.Function(
"AVG",
new[] { sqlExpression },
nullable: true,
argumentsPropagateNullability: new[] { false },
typeof(double)),
sqlExpression.Type,
sqlExpression.TypeMapping)
: _sqlExpressionFactory.Function(
"AVG",
new[] { sqlExpression },
nullable: true,
argumentsPropagateNullability: new[] { false },
sqlExpression.Type,
sqlExpression.TypeMapping);
}
/// <summary>
/// Translates Count over an expression to an equivalent SQL representation.
/// </summary>
/// <param name="sqlExpression">An expression to translate Count over.</param>
/// <returns>A SQL translation of Count over the given expression.</returns>
[Obsolete("Use IAggregateMethodCallTranslatorProvider to add translation for aggregate methods")]
public virtual SqlExpression? TranslateCount(SqlExpression sqlExpression)
=> _sqlExpressionFactory.ApplyDefaultTypeMapping(
_sqlExpressionFactory.Function(
"COUNT",
new[] { sqlExpression },
nullable: false,
argumentsPropagateNullability: new[] { false },
typeof(int)));
/// <summary>
/// Translates LongCount over an expression to an equivalent SQL representation.
/// </summary>
/// <param name="sqlExpression">An expression to translate LongCount over.</param>
/// <returns>A SQL translation of LongCount over the given expression.</returns>
[Obsolete("Use IAggregateMethodCallTranslatorProvider to add translation for aggregate methods")]
public virtual SqlExpression? TranslateLongCount(SqlExpression sqlExpression)
=> _sqlExpressionFactory.ApplyDefaultTypeMapping(
_sqlExpressionFactory.Function(
"COUNT",
new[] { sqlExpression },
nullable: false,
argumentsPropagateNullability: new[] { false },
typeof(long)));
/// <summary>
/// Translates Max over an expression to an equivalent SQL representation.
/// </summary>
/// <param name="sqlExpression">An expression to translate Max over.</param>
/// <returns>A SQL translation of Max over the given expression.</returns>
[Obsolete("Use IAggregateMethodCallTranslatorProvider to add translation for aggregate methods")]
public virtual SqlExpression? TranslateMax(SqlExpression sqlExpression)
=> sqlExpression != null
? _sqlExpressionFactory.Function(
"MAX",
new[] { sqlExpression },
nullable: true,
argumentsPropagateNullability: new[] { false },
sqlExpression.Type,
sqlExpression.TypeMapping)
: null;
/// <summary>
/// Translates Min over an expression to an equivalent SQL representation.
/// </summary>
/// <param name="sqlExpression">An expression to translate Min over.</param>
/// <returns>A SQL translation of Min over the given expression.</returns>
[Obsolete("Use IAggregateMethodCallTranslatorProvider to add translation for aggregate methods")]
public virtual SqlExpression? TranslateMin(SqlExpression sqlExpression)
=> sqlExpression != null
? _sqlExpressionFactory.Function(
"MIN",
new[] { sqlExpression },
nullable: true,
argumentsPropagateNullability: new[] { false },
sqlExpression.Type,
sqlExpression.TypeMapping)
: null;
/// <summary>
/// Translates Sum over an expression to an equivalent SQL representation.
/// </summary>
/// <param name="sqlExpression">An expression to translate Sum over.</param>
/// <returns>A SQL translation of Sum over the given expression.</returns>
[Obsolete("Use IAggregateMethodCallTranslatorProvider to add translation for aggregate methods")]
public virtual SqlExpression? TranslateSum(SqlExpression sqlExpression)
{
var inputType = sqlExpression.Type;
return inputType == typeof(float)
? _sqlExpressionFactory.Convert(
_sqlExpressionFactory.Function(
"SUM",
new[] { sqlExpression },
nullable: true,
argumentsPropagateNullability: new[] { false },
typeof(double)),
inputType,
sqlExpression.TypeMapping)
: _sqlExpressionFactory.Function(
"SUM",
new[] { sqlExpression },
nullable: true,
argumentsPropagateNullability: new[] { false },
inputType,
sqlExpression.TypeMapping);
}
/// <inheritdoc />
protected override Expression VisitBinary(BinaryExpression binaryExpression)
{
if (binaryExpression.Left.Type == typeof(object[])
&& binaryExpression is { Left: NewArrayExpression, NodeType: ExpressionType.Equal })
{
return Visit(ConvertObjectArrayEqualityComparison(binaryExpression.Left, binaryExpression.Right));
}
if (binaryExpression.NodeType == ExpressionType.Equal
|| binaryExpression.NodeType == ExpressionType.NotEqual
&& 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);
}
}
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!;
}
if (binaryExpression.NodeType is ExpressionType.Equal or ExpressionType.NotEqual
&& (left.IsNullConstantExpression() || right.IsNullConstantExpression()))
{
var nonNullExpression = left.IsNullConstantExpression() ? right : left;
if (nonNullExpression is MethodCallExpression nonNullMethodCallExpression
&& nonNullMethodCallExpression.Method.DeclaringType == typeof(Queryable)
&& nonNullMethodCallExpression.Method.IsGenericMethod
&& SingleResultMethodInfos.Contains(nonNullMethodCallExpression.Method.GetGenericMethodDefinition()))
{
var source = nonNullMethodCallExpression.Arguments[0];
var genericMethod = nonNullMethodCallExpression.Method.GetGenericMethodDefinition();
if (genericMethod == QueryableMethods.FirstWithPredicate
|| genericMethod == QueryableMethods.FirstOrDefaultWithPredicate
|| genericMethod == QueryableMethods.SingleWithPredicate
|| genericMethod == QueryableMethods.SingleOrDefaultWithPredicate
|| genericMethod == QueryableMethods.LastWithPredicate
|| genericMethod == QueryableMethods.LastOrDefaultWithPredicate)
{
source = Expression.Call(
QueryableMethods.Where.MakeGenericMethod(source.Type.GetSequenceType()),
source,
nonNullMethodCallExpression.Arguments[1]);
}
else if ((genericMethod == QueryableMethods.ElementAt || genericMethod == QueryableMethods.ElementAtOrDefault)
&& nonNullMethodCallExpression.Arguments[1] is not ConstantExpression { Value: 0 })
{
source = Expression.Call(
QueryableMethods.Skip.MakeGenericMethod(source.Type.GetSequenceType()),
source,
nonNullMethodCallExpression.Arguments[1]);
}
var translatedSubquery = _queryableMethodTranslatingExpressionVisitor.TranslateSubquery(source);
if (translatedSubquery != null)
{
var projection = translatedSubquery.ShaperExpression;
if (projection is NewExpression
|| RemoveConvert(projection) is StructuralTypeShaperExpression { IsNullable: false }
|| RemoveConvert(projection) is CollectionResultExpression)
{
var anySubquery = Expression.Call(
QueryableMethods.AnyWithoutPredicate.MakeGenericMethod(translatedSubquery.Type.GetSequenceType()),
translatedSubquery);
return Visit(
binaryExpression.NodeType == ExpressionType.Equal
? Expression.Not(anySubquery)
: anySubquery);
}
static Expression RemoveConvert(Expression e)
=> e is UnaryExpression { NodeType: ExpressionType.Convert or ExpressionType.ConvertChecked } unary
? RemoveConvert(unary.Operand)
: e;
}
}
}
var visitedLeft = Visit(left);
var visitedRight = Visit(right);
if (binaryExpression.NodeType is ExpressionType.Equal or ExpressionType.NotEqual
// Visited expression could be null, We need to pass MemberInitExpression
&& TryRewriteStructuralTypeEquality(
binaryExpression.NodeType,
visitedLeft == QueryCompilationContext.NotTranslatedExpression ? left : visitedLeft,
visitedRight == QueryCompilationContext.NotTranslatedExpression ? right : visitedRight,
equalsMethod: false, out var result))
{
return result;
}
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
: uncheckedNodeTypeVariant == ExpressionType.Coalesce
? _sqlExpressionFactory.Coalesce(sqlLeft!, sqlRight!)
: _sqlExpressionFactory.MakeBinary(
uncheckedNodeTypeVariant,
sqlLeft!,
sqlRight!,
null)
?? QueryCompilationContext.NotTranslatedExpression;
Expression ProcessGetType(StructuralTypeReferenceExpression typeReference, Type comparisonType, bool match)
{
if (typeReference.StructuralType is not IEntityType entityType
|| (entityType.BaseType == null
&& !entityType.GetDirectlyDerivedTypes().Any()))
{
// No hierarchy
return _sqlExpressionFactory.Constant((typeReference.StructuralType.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)
{
return QueryCompilationContext.NotTranslatedExpression;
}
// 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
var discriminatorProperty = entityType.FindDiscriminatorProperty();
if (discriminatorProperty == null)
{
// TPT or TPC
var discriminatorValue = derivedType.ShortName();
if (typeReference.Subquery != null)
{
var shaper = (StructuralTypeShaperExpression)typeReference.Subquery.ShaperExpression;
var projection = (StructuralTypeProjectionExpression)Visit(shaper.ValueBufferExpression);
var subSelectExpression = (SelectExpression)typeReference.Subquery.QueryExpression;
var predicate = GeneratePredicateTpt(projection);
subSelectExpression.ApplyPredicate(predicate);
subSelectExpression.ReplaceProjection(new List<Expression>());
subSelectExpression.ApplyProjection();
if (subSelectExpression.Limit == null
&& subSelectExpression.Offset == null)
{
subSelectExpression.ClearOrdering();
}
return _sqlExpressionFactory.Exists(subSelectExpression);
}
if (typeReference.Parameter != null)
{
var projection = (StructuralTypeProjectionExpression)Visit(typeReference.Parameter.ValueBufferExpression);
return GeneratePredicateTpt(projection);
}
SqlExpression GeneratePredicateTpt(StructuralTypeProjectionExpression projection)
{
if (projection.DiscriminatorExpression is CaseExpression caseExpression)
{
// TPT case
// Most root type doesn't have matching case
// All derived types needs to be excluded
var derivedTypeValues = derivedType.GetDerivedTypes().Where(e => !e.IsAbstract()).Select(e => e.ShortName())
.ToList();
var predicates = new List<SqlExpression>();
foreach (var caseWhenClause in caseExpression.WhenClauses)
{
var value = (string)((SqlConstantExpression)caseWhenClause.Result).Value!;
if (value == discriminatorValue)
{
predicates.Add(caseWhenClause.Test);
}
else if (derivedTypeValues.Contains(value))
{
predicates.Add(_sqlExpressionFactory.Not(caseWhenClause.Test));
}
}
var result = predicates.Aggregate((a, b) => _sqlExpressionFactory.AndAlso(a, b));
return match ? result : _sqlExpressionFactory.Not(result);
}
return match
? _sqlExpressionFactory.Equal(
projection.DiscriminatorExpression!,
_sqlExpressionFactory.Constant(discriminatorValue))
: _sqlExpressionFactory.NotEqual(
projection.DiscriminatorExpression!,
_sqlExpressionFactory.Constant(discriminatorValue));
}
}
else
{
var discriminatorColumn = BindProperty(typeReference, discriminatorProperty);
return match
? _sqlExpressionFactory.Equal(
discriminatorColumn,
_sqlExpressionFactory.Constant(derivedType.GetDiscriminatorValue()))
: _sqlExpressionFactory.NotEqual(
discriminatorColumn,
_sqlExpressionFactory.Constant(derivedType.GetDiscriminatorValue()));
}
return QueryCompilationContext.NotTranslatedExpression;
}
bool IsGetTypeMethodCall(Expression expression, out StructuralTypeReferenceExpression? typeReference)
{
typeReference = null;
if (expression is not MethodCallExpression methodCallExpression
|| methodCallExpression.Method != GetTypeMethodInfo)
{
return false;
}
typeReference = Visit(methodCallExpression.Object) as StructuralTypeReferenceExpression;
return typeReference != null;
}
static bool IsTypeConstant(Expression expression, out Type? type)
{
type = null;
if (expression is not UnaryExpression { NodeType: ExpressionType.Convert or ExpressionType.ConvertChecked, Operand: ConstantExpression constantExpression })
{
return false;
}
type = constantExpression.Value as Type;
return type != null;
}
static bool TryUnwrapConvertToObject(Expression expression, 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;
}
}
/// <inheritdoc />
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.Case(new[] { new CaseWhenClause(sqlTest!, sqlIfTrue!) }, sqlIfFalse);
}
/// <inheritdoc />
protected override Expression VisitConstant(ConstantExpression constantExpression)
=> new SqlConstantExpression(constantExpression, null);
/// <inheritdoc />
protected override Expression VisitExtension(Expression extensionExpression)
{
switch (extensionExpression)
{
case StructuralTypeProjectionExpression:
case StructuralTypeReferenceExpression:
case SqlExpression:
case EnumerableExpression:
case JsonQueryExpression:
return extensionExpression;
case StructuralTypeShaperExpression shaper:
return new StructuralTypeReferenceExpression(shaper);
case ProjectionBindingExpression projectionBindingExpression:
return Visit(
((SelectExpression)projectionBindingExpression.QueryExpression)
.GetProjection(projectionBindingExpression));
case ShapedQueryExpression shapedQueryExpression:
if (shapedQueryExpression.ResultCardinality == ResultCardinality.Enumerable)
{
return QueryCompilationContext.NotTranslatedExpression;
}
var shaperExpression = shapedQueryExpression.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 StructuralTypeReferenceExpression(shapedQueryExpression.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)shapedQueryExpression.QueryExpression;
var projection = subquery.GetProjection(mappedProjectionBindingExpression);
if (projection is not SqlExpression sqlExpression)
{
return QueryCompilationContext.NotTranslatedExpression;
}
if (subquery.Tables.Count == 0)
{
return sqlExpression;
}
subquery.ReplaceProjection(new List<Expression> { sqlExpression });
subquery.ApplyProjection();
SqlExpression scalarSubqueryExpression = new ScalarSubqueryExpression(subquery);
if (shapedQueryExpression.ResultCardinality == ResultCardinality.SingleOrDefault
&& !shaperExpression.Type.IsNullableType())
{
scalarSubqueryExpression = _sqlExpressionFactory.Coalesce(
scalarSubqueryExpression,
(SqlExpression)Visit(shaperExpression.Type.GetDefaultValueConstant()));
}
return scalarSubqueryExpression;
// We have e.g. an array parameter inside a Where clause; this is represented as a QueryableParameterQueryRootExpression so
// that we can translate queryable operators over it (query root in subquery context), but in normal SQL translation context
// we just unwrap the query root expression to get the parameter out.
case ParameterQueryRootExpression queryableParameterQueryRootExpression:
return Visit(queryableParameterQueryRootExpression.ParameterExpression);
default:
return QueryCompilationContext.NotTranslatedExpression;
}
}
/// <inheritdoc />
protected override Expression VisitInvocation(InvocationExpression invocationExpression)
=> QueryCompilationContext.NotTranslatedExpression;
/// <inheritdoc />
protected override Expression VisitLambda<T>(Expression<T> lambdaExpression)
=> throw new InvalidOperationException(CoreStrings.TranslationFailed(lambdaExpression.Print()));
/// <inheritdoc />
protected override Expression VisitListInit(ListInitExpression listInitExpression)
=> QueryCompilationContext.NotTranslatedExpression;
/// <inheritdoc />
protected override Expression VisitMember(MemberExpression memberExpression)
{
var innerExpression = Visit(memberExpression.Expression);
return TryBindMember(innerExpression, MemberIdentity.Create(memberExpression.Member), out var expression)
? expression
: (TranslationFailed(memberExpression.Expression, innerExpression, out var sqlInnerExpression)
? QueryCompilationContext.NotTranslatedExpression
: Dependencies.MemberTranslatorProvider.Translate(
sqlInnerExpression, memberExpression.Member, memberExpression.Type, _queryCompilationContext.Logger))
?? QueryCompilationContext.NotTranslatedExpression;
}
/// <inheritdoc />
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>
[EntityFrameworkInternal]
public virtual bool TryTranslatePropertyAccess(
Expression expression,
[NotNullWhen(true)] out Expression? translatedExpression,
[NotNullWhen(true)] out IPropertyBase? property)
{
if (expression is MethodCallExpression methodCallExpression)
{
if (methodCallExpression.TryGetEFPropertyArguments(out var source, out var propertyName)
&& TryBindMember(Visit(source), MemberIdentity.Create(propertyName), out translatedExpression, out property))
{
return true;
}
if (methodCallExpression.TryGetIndexerArguments(_model, out source, out propertyName)
&& TryBindMember(Visit(source), MemberIdentity.Create(propertyName), out translatedExpression, out property))
{
return true;
}
}
translatedExpression = null;
property = null;
return false;
}
/// <inheritdoc />
protected override Expression VisitMethodCall(MethodCallExpression methodCallExpression)
{
// EF.Property case
if (methodCallExpression.TryGetEFPropertyArguments(out var source, out var propertyName))
{
if (TryBindMember(Visit(source), MemberIdentity.Create(propertyName), out var result))
{
return result;
}
var message = CoreStrings.QueryUnableToTranslateEFProperty(methodCallExpression.Print());
if (_throwForNotTranslatedEfProperty)
{
throw new InvalidOperationException(message);
}
AddTranslationErrorDetails(message);
return QueryCompilationContext.NotTranslatedExpression;
}
// EF Indexer property
if (methodCallExpression.TryGetIndexerArguments(_model, out source, out propertyName)
&& TryBindMember(Visit(source), MemberIdentity.Create(propertyName), out var indexerResult))
{
return indexerResult;
}
var method = methodCallExpression.Method;
var arguments = methodCallExpression.Arguments;
EnumerableExpression? enumerableExpression = null;
SqlExpression? sqlObject = null;
List<SqlExpression> scalarArguments;
if (method.Name == nameof(object.Equals)
&& methodCallExpression.Object != null
&& arguments.Count == 1)
{
var left = Visit(methodCallExpression.Object);
var right = Visit(RemoveObjectConvert(arguments[0]));
if (TryRewriteStructuralTypeEquality(
ExpressionType.Equal,
left == QueryCompilationContext.NotTranslatedExpression ? methodCallExpression.Object : left,
right == QueryCompilationContext.NotTranslatedExpression ? arguments[0] : right,
equalsMethod: true,
out var result))
{
return result;
}
if (left is SqlExpression leftSql
&& right is SqlExpression rightSql)
{
sqlObject = leftSql;
scalarArguments = new List<SqlExpression> { rightSql };
}
else
{
return QueryCompilationContext.NotTranslatedExpression;
}
}
else if (method.Name == nameof(object.Equals)
&& methodCallExpression.Object == null
&& arguments.Count == 2)
{
if (arguments[0].Type == typeof(object[])
&& arguments[0] is NewArrayExpression)
{
return Visit(
ConvertObjectArrayEqualityComparison(
arguments[0], arguments[1]));
}
var left = Visit(RemoveObjectConvert(arguments[0]));
var right = Visit(RemoveObjectConvert(arguments[1]));
if (TryRewriteStructuralTypeEquality(
ExpressionType.Equal,
left == QueryCompilationContext.NotTranslatedExpression ? arguments[0] : left,
right == QueryCompilationContext.NotTranslatedExpression ? arguments[1] : right,
equalsMethod: true,
out var result))
{
return result;
}
if (left is SqlExpression leftSql
&& right is SqlExpression rightSql)
{
scalarArguments = new List<SqlExpression> { leftSql, rightSql };
}
else
{
return QueryCompilationContext.NotTranslatedExpression;
}
}
else if (method.IsGenericMethod
&& method.GetGenericMethodDefinition().Equals(EnumerableMethods.Contains))
{
var enumerable = Visit(arguments[0]);
var item = Visit(arguments[1]);
if (TryRewriteContainsEntity(
enumerable,
item == QueryCompilationContext.NotTranslatedExpression ? arguments[1] : item, out var result))
{
return result;
}
if (enumerable is SqlExpression sqlEnumerable
&& item is SqlExpression sqlItem)
{
scalarArguments = new List<SqlExpression> { sqlEnumerable, sqlItem };
}
else
{
return QueryCompilationContext.NotTranslatedExpression;
}
}
else if (arguments.Count == 1
&& method.IsContainsMethod())
{
var enumerable = Visit(methodCallExpression.Object);
var item = Visit(arguments[0]);
if (TryRewriteContainsEntity(
enumerable!,
item == QueryCompilationContext.NotTranslatedExpression ? arguments[0] : item, out var result))
{
return result;
}
if (enumerable is SqlExpression sqlEnumerable
&& item is SqlExpression sqlItem)
{
sqlObject = sqlEnumerable;
scalarArguments = new List<SqlExpression> { sqlItem };
}
else
{
return QueryCompilationContext.NotTranslatedExpression;
}
}
else
{
if (method.IsStatic
&& arguments.Count > 0
&& method.DeclaringType == typeof(Queryable))
{
// For queryable methods, either we translate the whole aggregate or we go to subquery mode
// We don't try to translate component-wise it. Providers should implement in subquery translation.
if (TryTranslateAggregateMethodCall(methodCallExpression, out var translatedAggregate))
{
return translatedAggregate;
}
goto SubqueryTranslation;
}
scalarArguments = new List<SqlExpression>();
if (!TryTranslateAsEnumerableExpression(methodCallExpression.Object, out enumerableExpression)
&& TranslationFailed(methodCallExpression.Object, Visit(methodCallExpression.Object), out sqlObject))
{
goto SubqueryTranslation;
}
for (var i = 0; i < arguments.Count; i++)
{
var argument = arguments[i];
if (TryTranslateAsEnumerableExpression(argument, out var eea))
{
if (enumerableExpression != null)
{
goto SubqueryTranslation;
}
enumerableExpression = eea;
continue;
}
var visitedArgument = Visit(argument);
if (TranslationFailed(argument, visitedArgument, out var sqlArgument))
{
goto SubqueryTranslation;
}
scalarArguments.Add(sqlArgument!);
}
}
var translation = enumerableExpression != null
? TranslateAggregateMethod(enumerableExpression, method, scalarArguments)
: Dependencies.MethodCallTranslatorProvider.Translate(
_model, sqlObject, method, scalarArguments, _queryCompilationContext.Logger);
if (translation != null)
{
return translation;
}
if (method == StringEqualsWithStringComparison
|| method == StringEqualsWithStringComparisonStatic)
{
AddTranslationErrorDetails(CoreStrings.QueryUnableToTranslateStringEqualsWithStringComparison);
}
else
{
AddTranslationErrorDetails(
CoreStrings.QueryUnableToTranslateMethod(
method.DeclaringType?.DisplayName(),
method.Name));
}