-
Notifications
You must be signed in to change notification settings - Fork 3.4k
Expand file tree
/
Copy pathRelationalQueryableMethodTranslatingExpressionVisitor.cs
More file actions
2564 lines (2160 loc) · 114 KB
/
RelationalQueryableMethodTranslatingExpressionVisitor.cs
File metadata and controls
2564 lines (2160 loc) · 114 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
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;
using System.Diagnostics.CodeAnalysis;
using Microsoft.EntityFrameworkCore.Query.Internal;
using Microsoft.EntityFrameworkCore.Query.SqlExpressions;
namespace Microsoft.EntityFrameworkCore.Query;
/// <inheritdoc />
public partial class RelationalQueryableMethodTranslatingExpressionVisitor : QueryableMethodTranslatingExpressionVisitor
{
private const string SqlQuerySingleColumnAlias = "Value";
private readonly RelationalSqlTranslatingExpressionVisitor _sqlTranslator;
private readonly SharedTypeEntityExpandingExpressionVisitor _sharedTypeEntityExpandingExpressionVisitor;
private readonly RelationalProjectionBindingExpressionVisitor _projectionBindingExpressionVisitor;
private readonly RelationalQueryCompilationContext _queryCompilationContext;
private readonly SqlAliasManager _sqlAliasManager;
private readonly IRelationalTypeMappingSource _typeMappingSource;
private readonly ISqlExpressionFactory _sqlExpressionFactory;
private readonly bool _subquery;
private readonly ParameterTranslationMode _collectionParameterTranslationMode;
/// <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 const string ValuesOrderingColumnName = "_ord";
/// <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 const string ValuesValueColumnName = "Value";
/// <summary>
/// Creates a new instance of the <see cref="QueryableMethodTranslatingExpressionVisitor" /> class.
/// </summary>
/// <param name="dependencies">Parameter object containing dependencies for this class.</param>
/// <param name="relationalDependencies">Parameter object containing relational dependencies for this class.</param>
/// <param name="queryCompilationContext">The query compilation context object to use.</param>
public RelationalQueryableMethodTranslatingExpressionVisitor(
QueryableMethodTranslatingExpressionVisitorDependencies dependencies,
RelationalQueryableMethodTranslatingExpressionVisitorDependencies relationalDependencies,
RelationalQueryCompilationContext queryCompilationContext)
: base(dependencies, queryCompilationContext, subquery: false)
{
RelationalDependencies = relationalDependencies;
var sqlExpressionFactory = relationalDependencies.SqlExpressionFactory;
_queryCompilationContext = queryCompilationContext;
_sqlAliasManager = queryCompilationContext.SqlAliasManager;
_sqlTranslator = relationalDependencies.RelationalSqlTranslatingExpressionVisitorFactory.Create(queryCompilationContext, this);
_sharedTypeEntityExpandingExpressionVisitor = new SharedTypeEntityExpandingExpressionVisitor(this);
_projectionBindingExpressionVisitor = new RelationalProjectionBindingExpressionVisitor(this, _sqlTranslator);
_typeMappingSource = relationalDependencies.TypeMappingSource;
_sqlExpressionFactory = sqlExpressionFactory;
_subquery = false;
_collectionParameterTranslationMode =
RelationalOptionsExtension.Extract(queryCompilationContext.ContextOptions).ParameterizedCollectionMode;
}
/// <summary>
/// Relational provider-specific dependencies for this service.
/// </summary>
protected virtual RelationalQueryableMethodTranslatingExpressionVisitorDependencies RelationalDependencies { get; }
/// <summary>
/// Creates a new instance of the <see cref="QueryableMethodTranslatingExpressionVisitor" /> class.
/// </summary>
/// <param name="parentVisitor">A parent visitor to create subquery visitor for.</param>
protected RelationalQueryableMethodTranslatingExpressionVisitor(
RelationalQueryableMethodTranslatingExpressionVisitor parentVisitor)
: base(parentVisitor.Dependencies, parentVisitor.QueryCompilationContext, subquery: true)
{
RelationalDependencies = parentVisitor.RelationalDependencies;
_queryCompilationContext = parentVisitor._queryCompilationContext;
_sqlAliasManager = _queryCompilationContext.SqlAliasManager;
_sqlTranslator = RelationalDependencies.RelationalSqlTranslatingExpressionVisitorFactory.Create(
parentVisitor._queryCompilationContext, parentVisitor);
_sharedTypeEntityExpandingExpressionVisitor = new SharedTypeEntityExpandingExpressionVisitor(this);
_projectionBindingExpressionVisitor = new RelationalProjectionBindingExpressionVisitor(this, _sqlTranslator);
_typeMappingSource = parentVisitor._typeMappingSource;
_sqlExpressionFactory = parentVisitor._sqlExpressionFactory;
_subquery = true;
_collectionParameterTranslationMode = RelationalOptionsExtension.Extract(parentVisitor._queryCompilationContext.ContextOptions)
.ParameterizedCollectionMode;
}
/// <inheritdoc />
protected override Expression VisitExtension(Expression extensionExpression)
{
switch (extensionExpression)
{
case FromSqlQueryRootExpression fromSqlQueryRootExpression:
{
var table = fromSqlQueryRootExpression.EntityType.GetDefaultMappings().Single().Table;
var alias = _sqlAliasManager.GenerateTableAlias(table);
return CreateShapedQueryExpression(
fromSqlQueryRootExpression.EntityType,
CreateSelect(
fromSqlQueryRootExpression.EntityType,
new FromSqlExpression(alias, table, fromSqlQueryRootExpression.Sql, fromSqlQueryRootExpression.Argument)));
}
case TableValuedFunctionQueryRootExpression tableValuedFunctionQueryRootExpression:
{
var function = tableValuedFunctionQueryRootExpression.Function;
var arguments = new List<SqlExpression>();
foreach (var arg in tableValuedFunctionQueryRootExpression.Arguments)
{
var sqlArgument = TranslateExpression(arg);
if (sqlArgument == null)
{
string call;
var methodInfo = function.DbFunctions.Last().MethodInfo;
if (methodInfo != null)
{
var methodCall = Expression.Call(
// Declaring types would be derived db context.
Expression.Default(methodInfo.DeclaringType!),
methodInfo,
tableValuedFunctionQueryRootExpression.Arguments);
call = methodCall.Print();
}
else
{
call = $"{function.DbFunctions.Last().Name}()";
}
throw new InvalidOperationException(
TranslationErrorDetails == null
? CoreStrings.TranslationFailed(call)
: CoreStrings.TranslationFailedWithDetails(call, TranslationErrorDetails));
}
arguments.Add(sqlArgument);
}
var entityType = tableValuedFunctionQueryRootExpression.EntityType;
var alias = _sqlAliasManager.GenerateTableAlias(function);
var translation = new TableValuedFunctionExpression(alias, function, arguments);
var queryExpression = CreateSelect(entityType, translation);
return CreateShapedQueryExpression(entityType, queryExpression);
}
case EntityQueryRootExpression entityQueryRootExpression
when entityQueryRootExpression.GetType() == typeof(EntityQueryRootExpression)
&& entityQueryRootExpression.EntityType.GetSqlQueryMappings().FirstOrDefault(m => m.IsDefaultSqlQueryMapping)?.SqlQuery is
{ } sqlQuery:
{
var table = entityQueryRootExpression.EntityType.GetDefaultMappings().Single().Table;
var alias = _sqlAliasManager.GenerateTableAlias(table);
return CreateShapedQueryExpression(
entityQueryRootExpression.EntityType,
CreateSelect(
entityQueryRootExpression.EntityType,
new FromSqlExpression(alias, table, sqlQuery.Sql, Expression.Constant(Array.Empty<object>(), typeof(object[])))));
}
case GroupByShaperExpression groupByShaperExpression:
var groupShapedQueryExpression = groupByShaperExpression.GroupingEnumerable;
var groupClonedSelectExpression = ((SelectExpression)groupShapedQueryExpression.QueryExpression).Clone();
return new ShapedQueryExpression(
groupClonedSelectExpression,
new QueryExpressionReplacingExpressionVisitor(
groupShapedQueryExpression.QueryExpression, groupClonedSelectExpression)
.Visit(groupShapedQueryExpression.ShaperExpression));
case ShapedQueryExpression shapedQueryExpression:
var clonedSelectExpression = ((SelectExpression)shapedQueryExpression.QueryExpression).Clone();
return new ShapedQueryExpression(
clonedSelectExpression,
new QueryExpressionReplacingExpressionVisitor(shapedQueryExpression.QueryExpression, clonedSelectExpression)
.Visit(shapedQueryExpression.ShaperExpression));
case SqlQueryRootExpression sqlQueryRootExpression:
{
var typeMapping = RelationalDependencies.TypeMappingSource.FindMapping(
sqlQueryRootExpression.ElementType, RelationalDependencies.Model);
if (typeMapping == null)
{
throw new InvalidOperationException(
RelationalStrings.SqlQueryUnmappedType(sqlQueryRootExpression.ElementType.DisplayName()));
}
var alias = _sqlAliasManager.GenerateTableAlias("sql");
var selectExpression = new SelectExpression(
[new FromSqlExpression(alias, sqlQueryRootExpression.Sql, sqlQueryRootExpression.Argument)],
new ColumnExpression(
SqlQuerySingleColumnAlias,
alias,
sqlQueryRootExpression.Type.UnwrapNullableType(),
typeMapping,
sqlQueryRootExpression.Type.IsNullableType()),
identifier: [],
_sqlAliasManager);
Expression shaperExpression = new ProjectionBindingExpression(
selectExpression, new ProjectionMember(), sqlQueryRootExpression.ElementType.MakeNullable());
if (sqlQueryRootExpression.ElementType != shaperExpression.Type)
{
Check.DebugAssert(
sqlQueryRootExpression.ElementType.MakeNullable() == shaperExpression.Type,
"expression.Type must be nullable of targetType");
shaperExpression = Expression.Convert(shaperExpression, sqlQueryRootExpression.ElementType);
}
return new ShapedQueryExpression(selectExpression, shaperExpression);
}
case JsonQueryExpression jsonQueryExpression:
return TransformJsonQueryToTable(jsonQueryExpression) ?? base.VisitExtension(extensionExpression);
default:
return base.VisitExtension(extensionExpression);
}
}
/// <inheritdoc />
protected override Expression VisitMethodCall(MethodCallExpression methodCallExpression)
{
var method = methodCallExpression.Method;
if (method.DeclaringType == typeof(RelationalQueryableMethodTranslatingExpressionVisitor)
&& method.IsGenericMethod
&& method.GetGenericMethodDefinition() == _fakeDefaultIfEmptyMethodInfo.Value
&& Visit(methodCallExpression.Arguments[0]) is ShapedQueryExpression source)
{
((SelectExpression)source.QueryExpression).MakeProjectionNullable(_sqlExpressionFactory, source.ShaperExpression.Type.IsNullableType());
return source.UpdateShaperExpression(MarkShaperNullable(source.ShaperExpression));
}
var translated = base.VisitMethodCall(methodCallExpression);
// For Contains over a collection parameter, if the provider hasn't implemented TranslateCollection (e.g. OPENJSON on SQL
// Server), we need to fall back to the previous IN translation.
if (translated == QueryCompilationContext.NotTranslatedExpression
&& method.IsGenericMethod
&& method.GetGenericMethodDefinition() == QueryableMethods.Contains
&& methodCallExpression.Arguments[0] is ParameterQueryRootExpression parameterSource
&& TranslateExpression(methodCallExpression.Arguments[1]) is { } item
&& _sqlTranslator.Visit(parameterSource.QueryParameterExpression) is SqlParameterExpression sqlParameterExpression
&& (parameterSource.QueryParameterExpression.TranslationMode is ParameterTranslationMode.Constant
or null))
{
var inExpression = _sqlExpressionFactory.In(item, sqlParameterExpression);
var selectExpression = new SelectExpression(inExpression, _sqlAliasManager);
var shaperExpression = Expression.Convert(
new ProjectionBindingExpression(selectExpression, new ProjectionMember(), typeof(bool?)), typeof(bool));
var shapedQueryExpression = new ShapedQueryExpression(selectExpression, shaperExpression)
.UpdateResultCardinality(ResultCardinality.Single);
return shapedQueryExpression;
}
return translated;
}
/// <inheritdoc />
protected override ShapedQueryExpression? TranslateMemberAccess(Expression source, MemberIdentity member)
{
// Attempt to translate access into a primitive or complex collection property (i.e. array column)
if (_sqlTranslator.TryBindMember(_sqlTranslator.Visit(source), member, out var translatedExpression, out var property))
{
switch (property)
{
case IProperty { IsPrimitiveCollection: true } scalarProperty
when translatedExpression is SqlExpression sqlExpression
&& TranslatePrimitiveCollection(
sqlExpression,
scalarProperty,
_sqlAliasManager.GenerateTableAlias(GenerateTableAlias(sqlExpression))) is { } primitiveCollectionTranslation:
{
return primitiveCollectionTranslation;
}
case IComplexProperty { IsCollection: true, ComplexType: var complexType }:
Check.DebugAssert(complexType.IsMappedToJson());
if (translatedExpression is not CollectionResultExpression { QueryExpression: JsonQueryExpression jsonQuery })
{
throw new UnreachableException();
}
return TransformJsonQueryToTable(jsonQuery);
}
}
return null;
string GenerateTableAlias(SqlExpression sqlExpression)
=> sqlExpression switch
{
ColumnExpression c => c.Name,
JsonScalarExpression jsonScalar
=> jsonScalar.Path.Select(s => s.PropertyName).LastOrDefault()
?? GenerateTableAlias(jsonScalar.Json),
ScalarSubqueryExpression scalarSubquery => scalarSubquery.Subquery.Projection[0].Alias,
_ => "collection"
};
}
/// <inheritdoc />
protected override ShapedQueryExpression? TranslateParameterQueryRoot(ParameterQueryRootExpression parameterQueryRootExpression)
{
var queryParameter = parameterQueryRootExpression.QueryParameterExpression;
var sqlParameterExpression = _sqlTranslator.Visit(queryParameter) as SqlParameterExpression;
Check.DebugAssert(sqlParameterExpression is not null);
var tableAlias = _sqlAliasManager.GenerateTableAlias(sqlParameterExpression.Name.TrimStart('_'));
return (queryParameter.TranslationMode ?? _collectionParameterTranslationMode) switch
{
ParameterTranslationMode.Constant or ParameterTranslationMode.MultipleParameters
=> CreateShapedQueryExpressionForValuesExpression(
new ValuesExpression(
tableAlias,
sqlParameterExpression,
[ValuesOrderingColumnName, ValuesValueColumnName]),
tableAlias,
parameterQueryRootExpression.ElementType,
sqlParameterExpression.TypeMapping,
sqlParameterExpression.IsNullable),
ParameterTranslationMode.Parameter
=> TranslatePrimitiveCollection(sqlParameterExpression, property: null, tableAlias),
_ => throw new UnreachableException()
};
}
/// <summary>
/// Translates a parameter or column collection of primitive values. Providers can override this to translate e.g. int[] columns or
/// parameters to a queryable table (OPENJSON on SQL Server, unnest on PostgreSQL...). The default implementation always returns
/// <see langword="null" /> (no translation).
/// </summary>
/// <remarks>
/// Inline collections aren't passed to this method; see <see cref="TranslateInlineQueryRoot" /> for the translation of inline
/// collections.
/// </remarks>
/// <param name="sqlExpression">The expression to try to translate as a primitive collection expression.</param>
/// <param name="property">
/// If the primitive collection is a property, contains the <see cref="IProperty" /> for that property. Otherwise, the collection
/// represents a parameter, and this contains <see langword="null" />.
/// </param>
/// <param name="tableAlias">
/// Provides an alias to be used for the table returned from translation, which will represent the collection.
/// </param>
/// <returns>A <see cref="ShapedQueryExpression" /> if the translation was successful, otherwise <see langword="null" />.</returns>
protected virtual ShapedQueryExpression? TranslatePrimitiveCollection(
SqlExpression sqlExpression,
IProperty? property,
string tableAlias)
=> null;
/// <summary>
/// Invoked when LINQ operators are composed over a collection within a JSON document.
/// Transforms the provided <see cref="JsonQueryExpression" /> - representing access to the collection - into a provider-specific
/// means to expand the JSON array into a relational table/rowset (e.g. SQL Server OPENJSON).
/// </summary>
/// <param name="jsonQueryExpression">The <see cref="JsonQueryExpression" /> referencing the JSON array.</param>
/// <returns>A <see cref="ShapedQueryExpression" /> if the translation was successful, otherwise <see langword="null" />.</returns>
protected virtual ShapedQueryExpression? TransformJsonQueryToTable(JsonQueryExpression jsonQueryExpression)
{
AddTranslationErrorDetails(RelationalStrings.JsonQueryLinqOperatorsNotSupported);
return null;
}
/// <summary>
/// Translates an inline collection into a queryable SQL VALUES expression.
/// </summary>
/// <param name="inlineQueryRootExpression">The inline collection to be translated.</param>
/// <returns>A queryable SQL VALUES expression.</returns>
protected override ShapedQueryExpression? TranslateInlineQueryRoot(InlineQueryRootExpression inlineQueryRootExpression)
{
var elementType = inlineQueryRootExpression.ElementType;
var encounteredNull = false;
var intTypeMapping = _typeMappingSource.FindMapping(typeof(int), RelationalDependencies.Model);
RelationalTypeMapping? inferredTypeMaping = null;
var sqlExpressions = new SqlExpression[inlineQueryRootExpression.Values.Count];
// Do a first pass, translating the elements and inferring type mappings/nullability.
for (var i = 0; i < inlineQueryRootExpression.Values.Count; i++)
{
// Note that we specifically don't apply the default type mapping to the translation, to allow it to get inferred later based
// on usage.
if (TranslateExpression(inlineQueryRootExpression.Values[i], applyDefaultTypeMapping: false)
is not { } translatedValue)
{
return null;
}
// Infer the type mapping from the different inline elements, applying the type mapping of a column to constants/parameters, and
// also to the projection of the VALUES expression as a whole.
// TODO: This currently picks up the first type mapping; we can do better once we have a type compatibility chart (#15586)
// TODO: See similarity with SqlExpressionFactory.ApplyTypeMappingOnIn()
inferredTypeMaping ??= translatedValue.TypeMapping;
// TODO: Poor man's null semantics: in SqlNullabilityProcessor we don't fully handle the nullability of SelectExpression
// projections. Whether the SelectExpression's projection is nullable or not is determined here in translation, but at this
// point we don't know how to properly calculate nullability (and can't look at parameters).
// So for now, we assume the projected column is nullable if we see anything but non-null constants and non-nullable columns.
encounteredNull |=
translatedValue is not SqlConstantExpression { Value: not null } and not ColumnExpression { IsNullable: false };
sqlExpressions[i] = translatedValue;
}
// Second pass: create the VALUES expression's row value expressions.
var rowExpressions = new RowValueExpression[sqlExpressions.Length];
for (var i = 0; i < sqlExpressions.Length; i++)
{
var sqlExpression = sqlExpressions[i];
rowExpressions[i] =
new RowValueExpression(
[
// Since VALUES may not guarantee row ordering, we add an _ord value by which we'll order.
_sqlExpressionFactory.Constant(i, intTypeMapping),
// If no type mapping was inferred (i.e. no column in the inline collection), it's left null, to allow it to get
// inferred later based on usage. Note that for the element in the VALUES expression, we'll also apply an explicit
// CONVERT to make sure the database gets the right type (see
// RelationalTypeMappingPostprocessor.ApplyTypeMappingsOnValuesExpression)
sqlExpression.TypeMapping is null && inferredTypeMaping is not null
? _sqlExpressionFactory.ApplyTypeMapping(sqlExpression, inferredTypeMaping)
: sqlExpression
]);
}
var alias = _sqlAliasManager.GenerateTableAlias("values");
var valuesExpression = new ValuesExpression(alias, rowExpressions, [ValuesOrderingColumnName, ValuesValueColumnName]);
return CreateShapedQueryExpressionForValuesExpression(
valuesExpression,
alias,
elementType,
inferredTypeMaping,
encounteredNull);
}
/// <inheritdoc />
protected override QueryableMethodTranslatingExpressionVisitor CreateSubqueryVisitor()
=> new RelationalQueryableMethodTranslatingExpressionVisitor(this);
/// <inheritdoc />
protected override ShapedQueryExpression CreateShapedQueryExpression(IEntityType entityType)
=> CreateShapedQueryExpression(entityType, CreateSelect(entityType));
private static ShapedQueryExpression CreateShapedQueryExpression(IEntityType entityType, SelectExpression selectExpression)
=> new(
selectExpression,
new RelationalStructuralTypeShaperExpression(
entityType,
new ProjectionBindingExpression(
selectExpression,
new ProjectionMember(),
typeof(ValueBuffer)),
false));
/// <inheritdoc />
protected override ShapedQueryExpression? TranslateAll(ShapedQueryExpression source, LambdaExpression predicate)
{
var translation = TranslateLambdaExpression(source, predicate);
if (translation == null)
{
return null;
}
var subquery = (SelectExpression)source.QueryExpression;
// Negate the predicate, unless it's already negated, in which case remove that.
subquery.ApplyPredicate(
translation is SqlUnaryExpression { OperatorType: ExpressionType.Not, Operand: var nestedOperand }
? nestedOperand
: _sqlExpressionFactory.Not(translation));
subquery.ReplaceProjection(new List<Expression>());
subquery.ApplyProjection();
if (subquery.Limit == null
&& subquery.Offset == null)
{
subquery.ClearOrdering();
}
subquery.IsDistinct = false;
translation = _sqlExpressionFactory.Not(_sqlExpressionFactory.Exists(subquery));
subquery = new SelectExpression(translation, _sqlAliasManager);
return source.Update(
subquery,
Expression.Convert(new ProjectionBindingExpression(subquery, new ProjectionMember(), typeof(bool?)), typeof(bool)));
}
/// <inheritdoc />
protected override ShapedQueryExpression? TranslateAny(ShapedQueryExpression source, LambdaExpression? predicate)
{
if (predicate != null)
{
var translatedSource = TranslateWhere(source, predicate);
if (translatedSource == null)
{
return null;
}
source = translatedSource;
}
var subquery = (SelectExpression)source.QueryExpression;
subquery.ReplaceProjection(new List<Expression>());
subquery.ApplyProjection();
if (subquery.Limit == null
&& subquery.Offset == null)
{
subquery.ClearOrdering();
}
subquery.IsDistinct = false;
var translation = _sqlExpressionFactory.Exists(subquery);
var selectExpression = new SelectExpression(translation, _sqlAliasManager);
return source.Update(
selectExpression,
Expression.Convert(new ProjectionBindingExpression(selectExpression, new ProjectionMember(), typeof(bool?)), typeof(bool)));
}
/// <inheritdoc />
protected override ShapedQueryExpression? TranslateAverage(
ShapedQueryExpression source,
LambdaExpression? selector,
Type resultType)
=> TranslateAggregateWithSelector(source, selector, QueryableMethods.GetAverageWithoutSelector, resultType);
/// <inheritdoc />
protected override ShapedQueryExpression TranslateCast(ShapedQueryExpression source, Type resultType)
=> source.ShaperExpression.Type != resultType
? source.UpdateShaperExpression(Expression.Convert(source.ShaperExpression, resultType))
: source;
/// <inheritdoc />
protected override ShapedQueryExpression TranslateConcat(ShapedQueryExpression source1, ShapedQueryExpression source2)
{
((SelectExpression)source1.QueryExpression).ApplyUnion((SelectExpression)source2.QueryExpression, distinct: false);
return source1.UpdateShaperExpression(
MatchShaperNullabilityForSetOperation(source1.ShaperExpression, source2.ShaperExpression, makeNullable: true));
}
/// <inheritdoc />
protected override ShapedQueryExpression? TranslateContains(ShapedQueryExpression source, Expression item)
{
// Note that we don't apply the default type mapping to the item in order to allow it to be inferred from e.g. the subquery
// projection on the other side.
if (TranslateExpression(item, applyDefaultTypeMapping: false) is not { } translatedItem
|| !TryGetProjection(source, out var projection))
{
// If the item can't be translated, we can't translate to an IN expression.
// We do attempt one thing: if this is a contains over an entity type which has a single key property (non-composite key),
// we can project its key property (entity equality/containment) and translate to InExpression over that.
if (item is StructuralTypeShaperExpression { StructuralType: IEntityType entityType }
&& entityType.FindPrimaryKey()?.Properties is [var singleKeyProperty])
{
var keySelectorParam = Expression.Parameter(source.Type);
return TranslateContains(
TranslateSelect(
source,
Expression.Lambda(keySelectorParam.CreateEFPropertyExpression(singleKeyProperty), keySelectorParam)),
item.CreateEFPropertyExpression(singleKeyProperty));
}
// Otherwise, attempt to translate as Any since that passes through Where predicate translation. This will e.g. take care of
// entity, which e.g. does entity equality/containment for entities with composite keys.
var anyLambdaParameter = Expression.Parameter(item.Type, "p");
var anyLambda = Expression.Lambda(
Infrastructure.ExpressionExtensions.CreateEqualsExpression(anyLambdaParameter, item),
anyLambdaParameter);
return TranslateAny(source, anyLambda);
}
// Pattern-match Contains over ValuesExpression, translating to simplified 'item IN (1, 2, 3)' with constant elements.
if (TryExtractBareInlineCollectionValues(source, out var values, out var valuesParameter))
{
var inExpression = (values, valuesParameter) switch
{
(not null, null) => _sqlExpressionFactory.In(translatedItem, values),
(null, not null) => _sqlExpressionFactory.In(translatedItem, valuesParameter),
_ => throw new UnreachableException(),
};
return source.Update(new SelectExpression(inExpression, _sqlAliasManager), source.ShaperExpression);
}
// Translate to IN with a subquery.
// Note that because of null semantics, this may get transformed to an EXISTS subquery in SqlNullabilityProcessor.
var subquery = (SelectExpression)source.QueryExpression;
if (subquery.Limit == null
&& subquery.Offset == null)
{
subquery.ClearOrdering();
}
subquery.IsDistinct = false;
subquery.ReplaceProjection(new List<Expression> { projection });
subquery.ApplyProjection();
var translation = _sqlExpressionFactory.In(translatedItem, subquery);
subquery = new SelectExpression(translation, _sqlAliasManager);
return source.Update(
subquery,
Expression.Convert(
new ProjectionBindingExpression(subquery, new ProjectionMember(), typeof(bool?)), typeof(bool)));
}
/// <inheritdoc />
protected override ShapedQueryExpression? TranslateCount(ShapedQueryExpression source, LambdaExpression? predicate)
=> TranslateAggregateWithPredicate(source, predicate, QueryableMethods.CountWithoutPredicate, liftOrderings: false);
/// <inheritdoc />
protected override ShapedQueryExpression? TranslateDefaultIfEmpty(ShapedQueryExpression source, Expression? defaultValue)
{
if (defaultValue == null)
{
((SelectExpression)source.QueryExpression).ApplyDefaultIfEmpty(_sqlExpressionFactory, source.ShaperExpression.Type.IsNullableType());
return source.UpdateShaperExpression(MarkShaperNullable(source.ShaperExpression));
}
return null;
}
/// <inheritdoc />
protected override ShapedQueryExpression TranslateDistinct(ShapedQueryExpression source)
{
var selectExpression = (SelectExpression)source.QueryExpression;
if (selectExpression is { Orderings.Count: > 0, Limit: null, Offset: null }
&& !IsNaturallyOrdered(selectExpression))
{
_queryCompilationContext.Logger.DistinctAfterOrderByWithoutRowLimitingOperatorWarning();
}
selectExpression.ApplyDistinct();
return source;
}
/// <inheritdoc />
protected override ShapedQueryExpression? TranslateElementAtOrDefault(
ShapedQueryExpression source,
Expression index,
bool returnDefault)
{
var selectExpression = (SelectExpression)source.QueryExpression;
var translation = TranslateExpression(index);
if (translation == null)
{
return null;
}
if (!IsOrdered(selectExpression))
{
_queryCompilationContext.Logger.RowLimitingOperationWithoutOrderByWarning();
}
selectExpression.ApplyOffset(translation);
ApplyLimit(selectExpression, TranslateExpression(Expression.Constant(1))!);
return source;
}
/// <inheritdoc />
protected override ShapedQueryExpression TranslateExcept(ShapedQueryExpression source1, ShapedQueryExpression source2)
{
((SelectExpression)source1.QueryExpression).ApplyExcept((SelectExpression)source2.QueryExpression, distinct: true);
// Since except has result from source1, we don't need to change shaper
return source1;
}
/// <inheritdoc />
protected override ShapedQueryExpression? TranslateFirstOrDefault(
ShapedQueryExpression source,
LambdaExpression? predicate,
Type returnType,
bool returnDefault)
{
if (predicate != null)
{
var translatedSource = TranslateWhere(source, predicate);
if (translatedSource == null)
{
return null;
}
source = translatedSource;
}
var selectExpression = (SelectExpression)source.QueryExpression;
if (selectExpression.Predicate == null
&& selectExpression.Orderings.Count == 0)
{
_queryCompilationContext.Logger.FirstWithoutOrderByAndFilterWarning();
}
ApplyLimit(selectExpression, TranslateExpression(Expression.Constant(1))!);
return source.ShaperExpression.Type != returnType
? source.UpdateShaperExpression(Expression.Convert(source.ShaperExpression, returnType))
: source;
}
/// <inheritdoc />
protected override ShapedQueryExpression? TranslateGroupBy(
ShapedQueryExpression source,
LambdaExpression keySelector,
LambdaExpression? elementSelector,
LambdaExpression? resultSelector)
{
var selectExpression = (SelectExpression)source.QueryExpression;
selectExpression.PrepareForAggregate();
var remappedKeySelector = RemapLambdaBody(source, keySelector);
var translatedKey = TranslateGroupingKey(remappedKeySelector);
switch (translatedKey)
{
// Special handling for GroupBy over entity type: get the entity projection expression out.
// For GroupBy over a complex type, we already get the projection expression out.
case StructuralTypeShaperExpression { StructuralType: IEntityType } shaper:
if (shaper.ValueBufferExpression is not ProjectionBindingExpression pbe)
{
// ValueBufferExpression can be JsonQuery, ProjectionBindingExpression, EntityProjection
// We only allow ProjectionBindingExpression which represents a regular entity
return null;
}
translatedKey = shaper.Update(((SelectExpression)pbe.QueryExpression).GetProjection(pbe));
break;
case null:
return null;
}
if (elementSelector != null)
{
source = TranslateSelect(source, elementSelector);
}
var groupByShaper = selectExpression.ApplyGrouping(translatedKey, source.ShaperExpression, _sqlExpressionFactory);
if (resultSelector == null)
{
return source.UpdateShaperExpression(groupByShaper);
}
var original1 = resultSelector.Parameters[0];
var original2 = resultSelector.Parameters[1];
var newResultSelectorBody = new ReplacingExpressionVisitor(
[original1, original2],
[groupByShaper.KeySelector, groupByShaper])
.Visit(resultSelector.Body);
newResultSelectorBody = ExpandSharedTypeEntities(selectExpression, newResultSelectorBody);
return source.UpdateShaperExpression(
_projectionBindingExpressionVisitor.Translate(selectExpression, newResultSelectorBody));
}
private Expression? TranslateGroupingKey(Expression expression)
{
switch (expression)
{
case NewExpression newExpression:
if (newExpression.Arguments.Count == 0)
{
return newExpression;
}
var newArguments = new Expression[newExpression.Arguments.Count];
for (var i = 0; i < newArguments.Length; i++)
{
var key = TranslateGroupingKey(newExpression.Arguments[i]);
if (key == null)
{
return null;
}
newArguments[i] = key;
}
return newExpression.Update(newArguments);
case MemberInitExpression memberInitExpression:
var updatedNewExpression = (NewExpression?)TranslateGroupingKey(memberInitExpression.NewExpression);
if (updatedNewExpression == null)
{
return null;
}
var newBindings = new MemberAssignment[memberInitExpression.Bindings.Count];
for (var i = 0; i < newBindings.Length; i++)
{
var memberAssignment = (MemberAssignment)memberInitExpression.Bindings[i];
var visitedExpression = TranslateGroupingKey(memberAssignment.Expression);
if (visitedExpression == null)
{
return null;
}
newBindings[i] = memberAssignment.Update(visitedExpression);
}
return memberInitExpression.Update(updatedNewExpression, newBindings);
default:
var translation = TranslateProjection(expression);
if (translation == null)
{
return null;
}
return translation.Type == expression.Type
? translation
: Expression.Convert(translation, expression.Type);
}
}
/// <inheritdoc />
protected override ShapedQueryExpression? TranslateGroupJoin(
ShapedQueryExpression outer,
ShapedQueryExpression inner,
LambdaExpression outerKeySelector,
LambdaExpression innerKeySelector,
LambdaExpression resultSelector)
=> null;
/// <inheritdoc />
protected override ShapedQueryExpression TranslateIntersect(ShapedQueryExpression source1, ShapedQueryExpression source2)
{
((SelectExpression)source1.QueryExpression).ApplyIntersect((SelectExpression)source2.QueryExpression, distinct: true);
// For intersect since result comes from both sides, if one of them is non-nullable then both are non-nullable
return source1.UpdateShaperExpression(
MatchShaperNullabilityForSetOperation(source1.ShaperExpression, source2.ShaperExpression, makeNullable: false));
}
/// <inheritdoc />
protected override ShapedQueryExpression? TranslateJoin(
ShapedQueryExpression outer,
ShapedQueryExpression inner,
LambdaExpression outerKeySelector,
LambdaExpression innerKeySelector,
LambdaExpression resultSelector)
{
var joinPredicate = CreateJoinPredicate(outer, outerKeySelector, inner, innerKeySelector);
if (joinPredicate != null)
{
var isToOneJoin = IsToOneJoin(inner, innerKeySelector);
var isPrunable = isToOneJoin && IsPrunableInnerJoin();
var outerSelectExpression = (SelectExpression)outer.QueryExpression;
var outerShaperExpression = outerSelectExpression.AddInnerJoin(
inner, joinPredicate, outer.ShaperExpression, isToOneJoin, isPrunable);
outer = outer.UpdateShaperExpression(outerShaperExpression);
return TranslateTwoParameterSelector(outer, resultSelector);
}
return null;
// An INNER JOIN is safe to prune when every outer row is guaranteed to have exactly one matching inner row.
// The caller checks IsToOneJoin (at most one match via PK/AK/unique index); this method checks that at least
// one matching row exists by looking for a required FK between the outer and inner entity types.
// However, the FK guarantee only holds when the full inner table is available. If the inner query has been
// filtered (via predicates, limit, offset, etc.), some rows may be missing and the join may filter the outer
// side; in that case, the join must not be pruned.
bool IsPrunableInnerJoin()
{
if ((SelectExpression)inner.QueryExpression is
{
Predicate: null,
Limit: null,
Offset: null,
Having: null,
IsDistinct: false,
GroupBy.Count: 0
}
&& outer.ShaperExpression is StructuralTypeShaperExpression { StructuralType: IEntityType outerEntityType }
&& inner.ShaperExpression is StructuralTypeShaperExpression { StructuralType: IEntityType innerEntityType })
{
var outerKeyProperties = ExtractKeyProperties(outerEntityType, outerKeySelector);
var innerKeyProperties = ExtractKeyProperties(innerEntityType, innerKeySelector);
if (outerKeyProperties is null || innerKeyProperties is null)
{
return false;
}
Debug.Assert(outerKeyProperties.Count == innerKeyProperties.Count);
// Case 1: Outer is dependent, inner is principal — FK.IsRequired guarantees every dependent has a principal.
// Case 2: Outer is principal, inner is dependent — FK.IsRequiredDependent guarantees every principal has a dependent.
return HasMatchingRequiredForeignKey(
outerEntityType, innerEntityType, outerKeyProperties, innerKeyProperties, checkIsRequired: true)
|| HasMatchingRequiredForeignKey(
innerEntityType, outerEntityType, innerKeyProperties, outerKeyProperties, checkIsRequired: false);
}
return false;
// Checks whether the dependent entity type has a required FK to the principal whose properties match the key selectors.
// When checkIsRequired is true, checks FK.IsRequired (every dependent has a principal);
// when false, checks FK.IsRequiredDependent (every principal has a dependent).
// The key selector properties may appear in a different order than the FK properties, so we match positionally:
// for each (fkProperty[i], principalKeyProperty[i]) pair, both must appear at the same index in the respective key selectors.
static bool HasMatchingRequiredForeignKey(
IEntityType dependentEntityType,
IEntityType principalEntityType,
IReadOnlyList<IReadOnlyProperty> dependentKeyProperties,
IReadOnlyList<IReadOnlyProperty> principalKeyProperties,
bool checkIsRequired)
{
foreach (var fk in dependentEntityType.GetForeignKeys())
{
if (fk.PrincipalEntityType == principalEntityType
&& (checkIsRequired ? fk.IsRequired : fk.IsRequiredDependent)
&& fk.Properties.Count == dependentKeyProperties.Count)
{
for (var i = 0; i < fk.Properties.Count; i++)
{
var dependentIndex = dependentKeyProperties.IndexOf(fk.Properties[i]);
if (dependentIndex == -1
|| dependentIndex >= principalKeyProperties.Count
|| principalKeyProperties[dependentIndex] != fk.PrincipalKey.Properties[i])
{
goto NextForeignKey;
}
}
return true;
NextForeignKey:;
}
}
return false;
}
}
}
/// <inheritdoc />
protected override ShapedQueryExpression? TranslateLeftJoin(
ShapedQueryExpression outer,
ShapedQueryExpression inner,
LambdaExpression outerKeySelector,
LambdaExpression innerKeySelector,
LambdaExpression resultSelector)
{
var joinPredicate = CreateJoinPredicate(outer, outerKeySelector, inner, innerKeySelector);
if (joinPredicate != null)
{
var isToOneJoin = IsToOneJoin(inner, innerKeySelector);
var outerSelectExpression = (SelectExpression)outer.QueryExpression;
var outerShaperExpression = outerSelectExpression.AddLeftJoin(
inner, joinPredicate, outer.ShaperExpression, isToOneJoin, prunableJoin: isToOneJoin);
outer = outer.UpdateShaperExpression(outerShaperExpression);
return TranslateTwoParameterSelector(outer, resultSelector);
}
return null;
}
/// <inheritdoc />
protected override ShapedQueryExpression? TranslateRightJoin(
ShapedQueryExpression outer,
ShapedQueryExpression inner,
LambdaExpression outerKeySelector,
LambdaExpression innerKeySelector,
LambdaExpression resultSelector)
{