forked from dotnet/efcore
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCosmosQueryableMethodTranslatingExpressionVisitor.cs
1729 lines (1503 loc) · 86.6 KB
/
CosmosQueryableMethodTranslatingExpressionVisitor.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 Microsoft.EntityFrameworkCore.Cosmos.Internal;
using Microsoft.EntityFrameworkCore.Cosmos.Storage.Internal;
using Microsoft.EntityFrameworkCore.Internal;
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 CosmosQueryableMethodTranslatingExpressionVisitor : QueryableMethodTranslatingExpressionVisitor
{
private readonly CosmosQueryCompilationContext _queryCompilationContext;
private readonly ISqlExpressionFactory _sqlExpressionFactory;
private readonly ITypeMappingSource _typeMappingSource;
private readonly IMemberTranslatorProvider _memberTranslatorProvider;
private readonly IMethodCallTranslatorProvider _methodCallTranslatorProvider;
private readonly CosmosSqlTranslatingExpressionVisitor _sqlTranslator;
private readonly CosmosProjectionBindingExpressionVisitor _projectionBindingExpressionVisitor;
private readonly CosmosAliasManager _aliasManager;
private bool _subquery;
/// <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 CosmosQueryableMethodTranslatingExpressionVisitor(
QueryableMethodTranslatingExpressionVisitorDependencies dependencies,
CosmosQueryCompilationContext queryCompilationContext,
ISqlExpressionFactory sqlExpressionFactory,
ITypeMappingSource typeMappingSource,
IMemberTranslatorProvider memberTranslatorProvider,
IMethodCallTranslatorProvider methodCallTranslatorProvider)
: base(dependencies, queryCompilationContext, subquery: false)
{
_queryCompilationContext = queryCompilationContext;
_sqlExpressionFactory = sqlExpressionFactory;
_typeMappingSource = typeMappingSource;
_memberTranslatorProvider = memberTranslatorProvider;
_methodCallTranslatorProvider = methodCallTranslatorProvider;
_sqlTranslator = new CosmosSqlTranslatingExpressionVisitor(
queryCompilationContext,
_sqlExpressionFactory,
_typeMappingSource,
_memberTranslatorProvider,
_methodCallTranslatorProvider,
this);
_projectionBindingExpressionVisitor =
new CosmosProjectionBindingExpressionVisitor(_queryCompilationContext.Model, this, _sqlTranslator, _typeMappingSource);
_aliasManager = queryCompilationContext.AliasManager;
_subquery = 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 CosmosQueryableMethodTranslatingExpressionVisitor(
CosmosQueryableMethodTranslatingExpressionVisitor parentVisitor)
: base(parentVisitor.Dependencies, parentVisitor.QueryCompilationContext, subquery: true)
{
_queryCompilationContext = parentVisitor._queryCompilationContext;
_sqlExpressionFactory = parentVisitor._sqlExpressionFactory;
_typeMappingSource = parentVisitor._typeMappingSource;
_memberTranslatorProvider = parentVisitor._memberTranslatorProvider;
_methodCallTranslatorProvider = parentVisitor._methodCallTranslatorProvider;
_sqlTranslator = new CosmosSqlTranslatingExpressionVisitor(
QueryCompilationContext,
_sqlExpressionFactory,
_typeMappingSource,
_memberTranslatorProvider,
_methodCallTranslatorProvider,
parentVisitor);
_projectionBindingExpressionVisitor =
new CosmosProjectionBindingExpressionVisitor(_queryCompilationContext.Model, this, _sqlTranslator, _typeMappingSource);
_aliasManager = parentVisitor._aliasManager;
_subquery = true;
}
/// <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 override Expression Translate(Expression expression)
{
// Handle ToPageAsync(), which can only ever be the top-level node in the query tree.
if (expression is MethodCallExpression { Method: var method, Arguments: var arguments }
&& method.DeclaringType == typeof(CosmosQueryableExtensions)
&& method.Name is nameof(CosmosQueryableExtensions.ToPageAsync))
{
if (_subquery)
{
AddTranslationErrorDetails(CosmosStrings.ToPageAsyncAtTopLevelOnly);
return QueryCompilationContext.NotTranslatedExpression;
}
var source = base.Translate(arguments[0]);
if (source == QueryCompilationContext.NotTranslatedExpression)
{
return source;
}
if (source is not ShapedQueryExpression shapedQuery)
{
throw new UnreachableException($"Expected a ShapedQueryExpression but found {source.GetType().Name}");
}
// The arguments to ToPage/ToPageAsync must have been parameterized by the funcletizer, since they're non-lambda arguments to
// a top-level function (like Skip/Take). Translate to get these as SqlParameterExpressions.
if (arguments is not
[
_, // source
QueryParameterExpression maxItemCount,
QueryParameterExpression continuationToken,
QueryParameterExpression responseContinuationTokenLimitInKb,
_ // cancellation token
]
|| _sqlTranslator.Translate(maxItemCount) is not SqlParameterExpression translatedMaxItemCount
|| _sqlTranslator.Translate(continuationToken) is not SqlParameterExpression translatedContinuationToken
|| _sqlTranslator.Translate(responseContinuationTokenLimitInKb) is not SqlParameterExpression
translatedResponseContinuationTokenLimitInKb)
{
throw new UnreachableException("ToPageAsync without the appropriate parameterized arguments");
}
// Wrap the shaper for the entire query in a PagingExpression which also contains the paging arguments, and update
// the final cardinality to Single (since we'll be returning a single Page).
return shapedQuery
.UpdateShaperExpression(
new PagingExpression(
shapedQuery.ShaperExpression,
translatedMaxItemCount,
translatedContinuationToken,
translatedResponseContinuationTokenLimitInKb,
typeof(CosmosPage<>).MakeGenericType(shapedQuery.ShaperExpression.Type)))
.UpdateResultCardinality(ResultCardinality.Single);
}
return base.Translate(expression);
}
/// <inheritdoc />
protected override Expression VisitMethodCall(MethodCallExpression methodCallExpression)
{
var method = methodCallExpression.Method;
if (methodCallExpression.Method.DeclaringType == typeof(CosmosQueryableExtensions)
&& methodCallExpression.Method.Name == nameof(CosmosQueryableExtensions.WithPartitionKey))
{
if (_queryCompilationContext.PartitionKeyPropertyValues.Count > 0)
{
throw new InvalidOperationException(CosmosStrings.WithPartitionKeyAlreadyCalled);
}
if (methodCallExpression.Arguments[0] is not EntityQueryRootExpression)
{
throw new InvalidOperationException(CosmosStrings.WithPartitionKeyBadNode);
}
var innerQueryable = Visit(methodCallExpression.Arguments[0]);
for (var i = 1; i < methodCallExpression.Arguments.Count; i++)
{
var value = _sqlTranslator.Translate(methodCallExpression.Arguments[i], applyDefaultTypeMapping: false);
if (value is not SqlConstantExpression and not SqlParameterExpression)
{
throw new InvalidOperationException(CosmosStrings.WithPartitionKeyNotConstantOrParameter);
}
_queryCompilationContext.PartitionKeyPropertyValues.Add(value);
}
return innerQueryable;
}
if (method.DeclaringType == typeof(Queryable) && method.IsGenericMethod)
{
switch (methodCallExpression.Method.Name)
{
// The following is a bad hack to account for https://github.com/dotnet/efcore/issues/32957#issuecomment-2165864086.
// Basically for the query form Where(b => b.Posts.GetElementAt(0).Id == 1), nav expansion moves the property access
// forward, generating Where(b => b.Posts.Select(p => p.Id).GetElementAt(0)); unfortunately that means that GetElementAt()
// over a bare array in Cosmos doesn't get translated to a simple indexer as it should (b["Posts"][0].Id), since the
// reordering messes things up.
case nameof(Queryable.ElementAt) or nameof(Queryable.ElementAtOrDefault)
when methodCallExpression.Arguments[0] is MethodCallExpression
{
Method: { Name: "Select", IsGenericMethod: true }
} innerMethodCall
&& method.GetGenericMethodDefinition() is var genericDefinition
&& (genericDefinition == QueryableMethods.ElementAt || genericDefinition == QueryableMethods.ElementAtOrDefault)
&& innerMethodCall.Method.GetGenericMethodDefinition() == QueryableMethods.Select:
{
var returnDefault = method.Name == nameof(Queryable.ElementAtOrDefault);
if (Visit(innerMethodCall) is ShapedQueryExpression translatedSelect
&& translatedSelect.TryExtractArray(out _, out _, out _, out var boundMember)
&& boundMember is IAccessExpression { PropertyName: string boundPropertyName }
&& Visit(innerMethodCall.Arguments[0]) is ShapedQueryExpression innerSource
&& TranslateElementAtOrDefault(
innerSource, methodCallExpression.Arguments[1], returnDefault) is ShapedQueryExpression elementAtTranslation)
{
#pragma warning disable EF1001 // Internal EF Core API usage.
var translation = _sqlTranslator.Translate(
EntityFrameworkCore.Infrastructure.ExpressionExtensions.CreateEFPropertyExpression(
elementAtTranslation.ShaperExpression,
elementAtTranslation.ShaperExpression.Type,
boundMember.Type,
boundPropertyName,
makeNullable: true));
#pragma warning restore EF1001 // Internal EF Core API usage.
if (translation is not null)
{
var finalShapedQuery = CreateShapedQueryExpression(new SelectExpression(translation), boundMember.Type);
return finalShapedQuery.UpdateResultCardinality(
returnDefault ? ResultCardinality.SingleOrDefault : ResultCardinality.Single);
}
}
break;
}
}
}
return base.VisitMethodCall(methodCallExpression);
}
/// <inheritdoc />
protected override Expression VisitExtension(Expression extensionExpression)
{
switch (extensionExpression)
{
case EntityQueryRootExpression when _subquery:
AddTranslationErrorDetails(CosmosStrings.NonCorrelatedSubqueriesNotSupported);
return QueryCompilationContext.NotTranslatedExpression;
case FromSqlQueryRootExpression fromSqlQueryRoot:
var entityType = fromSqlQueryRoot.EntityType;
var fromSql = new FromSqlExpression(entityType.ClrType, fromSqlQueryRoot.Sql, fromSqlQueryRoot.Argument);
var alias = _aliasManager.GenerateSourceAlias(fromSql);
var selectExpression = new SelectExpression(
new SourceExpression(fromSql, alias),
new EntityProjectionExpression(new ObjectReferenceExpression(entityType, alias), entityType));
return CreateShapedQueryExpression(entityType, selectExpression) ?? QueryCompilationContext.NotTranslatedExpression;
default:
return base.VisitExtension(extensionExpression);
}
}
/// <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 QueryableMethodTranslatingExpressionVisitor CreateSubqueryVisitor()
=> new CosmosQueryableMethodTranslatingExpressionVisitor(this);
/// <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 override ShapedQueryExpression? TranslateSubquery(Expression expression)
{
var subqueryVisitor = CreateSubqueryVisitor();
var translation = subqueryVisitor.Translate(expression) as ShapedQueryExpression;
if (translation == null && subqueryVisitor.TranslationErrorDetails != null)
{
AddTranslationErrorDetails(subqueryVisitor.TranslationErrorDetails);
}
return translation;
}
/// <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 ShapedQueryExpression? CreateShapedQueryExpression(IEntityType entityType)
{
Check.DebugAssert(!entityType.IsOwned(), "Can't create ShapedQueryExpression for owned entity type");
var alias = _aliasManager.GenerateSourceAlias("c");
var selectExpression = new SelectExpression(
new SourceExpression(new ObjectReferenceExpression(entityType, "root"), alias),
new EntityProjectionExpression(new ObjectReferenceExpression(entityType, alias), entityType));
// Add discriminator predicate
var concreteEntityTypes = entityType.GetConcreteDerivedTypesInclusive().ToList();
if (concreteEntityTypes is [var singleEntityType]
&& singleEntityType.GetIsDiscriminatorMappingComplete()
&& entityType.GetContainer() is var container
&& !entityType.Model.GetEntityTypes().Any(
// If a read-only/view type is mapped to the same container with the same discriminator, then we still don't need
// the discriminator, allowing ReadItem in more places.
e => e.GetContainer() == container && !Equals(e.GetDiscriminatorValue(), singleEntityType.GetDiscriminatorValue())))
{
// There's a single entity type mapped to the container and the discriminator mapping is complete; we can skip the
// discriminator predicate.
}
else
{
var discriminatorProperty = concreteEntityTypes[0].FindDiscriminatorProperty();
Check.DebugAssert(
discriminatorProperty is not null || concreteEntityTypes.Count == 1,
"Missing discriminator property in hierarchy");
if (discriminatorProperty is not null)
{
var discriminatorColumn = ((EntityProjectionExpression)selectExpression.GetMappedProjection(new ProjectionMember()))
.BindProperty(discriminatorProperty, clientEval: false);
var success = TryApplyPredicate(
selectExpression,
_sqlExpressionFactory.In(
(SqlExpression)discriminatorColumn,
concreteEntityTypes.Select(
et => _sqlExpressionFactory.Constant(et.GetDiscriminatorValue(), discriminatorColumn.Type))
.ToArray()));
Check.DebugAssert(success, "Couldn't apply predicate when creating a new ShapedQueryExpression");
}
}
return CreateShapedQueryExpression(entityType, selectExpression);
}
private ShapedQueryExpression? CreateShapedQueryExpression(IEntityType entityType, SelectExpression queryExpression)
{
if (!entityType.IsOwned())
{
var existingEntityType = _queryCompilationContext.RootEntityType;
if (existingEntityType is not null && existingEntityType != entityType)
{
AddTranslationErrorDetails(
CosmosStrings.MultipleRootEntityTypesReferencedInQuery(entityType.DisplayName(), existingEntityType.DisplayName()));
return null;
}
_queryCompilationContext.RootEntityType = entityType;
}
return new ShapedQueryExpression(
queryExpression,
new StructuralTypeShaperExpression(
entityType,
new ProjectionBindingExpression(queryExpression, new ProjectionMember(), typeof(ValueBuffer)),
nullable: false));
}
private ShapedQueryExpression CreateShapedQueryExpression(SelectExpression select, Type elementClrType)
{
var shaperExpression = (Expression)new ProjectionBindingExpression(
select, new ProjectionMember(), elementClrType.MakeNullable());
if (shaperExpression.Type != elementClrType)
{
Check.DebugAssert(
elementClrType.MakeNullable() == shaperExpression.Type,
"expression.Type must be nullable of targetType");
shaperExpression = Expression.Convert(shaperExpression, elementClrType);
}
return new ShapedQueryExpression(select, shaperExpression);
}
/// <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 ShapedQueryExpression? TranslateAll(ShapedQueryExpression source, LambdaExpression predicate)
=> 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 ShapedQueryExpression? TranslateAny(ShapedQueryExpression source, LambdaExpression? predicate)
{
if (predicate != null)
{
var translatedSource = TranslateWhere(source, predicate);
if (translatedSource == null)
{
return null;
}
source = translatedSource;
}
// Simplify x.Array.Any() => ARRAY_LENGTH(x.Array) > 0 instead of (EXISTS(SELECT 1 FROM i IN x.Array))
if (source.TryExtractArray(out var array, ignoreOrderings: true))
{
var simplifiedTranslation = _sqlExpressionFactory.GreaterThan(
_sqlExpressionFactory.Function(
"ARRAY_LENGTH", new[] { array }, typeof(int), _typeMappingSource.FindMapping(typeof(int))),
_sqlExpressionFactory.Constant(0));
var select = new SelectExpression(simplifiedTranslation);
return source.Update(select, new ProjectionBindingExpression(select, new ProjectionMember(), typeof(int)));
}
var subquery = (SelectExpression)source.QueryExpression;
subquery.ClearProjection();
subquery.ApplyProjection();
if (subquery.Limit == null
&& subquery.Offset == null)
{
subquery.ClearOrdering();
}
var translation = _sqlExpressionFactory.Exists(subquery);
var selectExpression = new SelectExpression(translation);
return source.Update(
selectExpression,
Expression.Convert(new ProjectionBindingExpression(selectExpression, new ProjectionMember(), typeof(bool?)), typeof(bool)));
}
/// <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 ShapedQueryExpression? TranslateAverage(ShapedQueryExpression source, LambdaExpression? selector, Type resultType)
=> TranslateAggregate(source, selector, resultType, "AVG");
/// <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 ShapedQueryExpression TranslateCast(ShapedQueryExpression source, Type resultType)
=> source.ShaperExpression.Type == resultType
? source
: source.UpdateShaperExpression(Expression.Convert(source.ShaperExpression, resultType));
/// <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 ShapedQueryExpression? TranslateConcat(ShapedQueryExpression source1, ShapedQueryExpression source2)
=> TranslateSetOperation(source1, source2, "ARRAY_CONCAT");
/// <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 ShapedQueryExpression? TranslateContains(ShapedQueryExpression source, Expression item)
{
// Simplify x.Array.Contains[1] => ARRAY_CONTAINS(x.Array, 1) insert of IN+subquery
if (source.TryExtractArray(out var array, ignoreOrderings: true)
&& array is SqlExpression scalarArray // TODO: Contains over arrays of structural types, #34027
&& TranslateExpression(item) is SqlExpression translatedItem)
{
if (array is ArrayConstantExpression arrayConstant)
{
var inExpression = _sqlExpressionFactory.In(translatedItem, arrayConstant.Items);
return source.Update(new SelectExpression(inExpression), source.ShaperExpression);
}
(translatedItem, scalarArray) = _sqlExpressionFactory.ApplyTypeMappingsOnItemAndArray(translatedItem, scalarArray);
var simplifiedTranslation = _sqlExpressionFactory.Function("ARRAY_CONTAINS", [scalarArray, translatedItem], typeof(bool));
return source.UpdateQueryExpression(new SelectExpression(simplifiedTranslation));
}
// Translate to EXISTS
var anyLambdaParameter = Expression.Parameter(item.Type, "p");
var anyLambda = Expression.Lambda(
EntityFrameworkCore.Infrastructure.ExpressionExtensions.CreateEqualsExpression(anyLambdaParameter, item),
anyLambdaParameter);
return TranslateAny(source, anyLambda);
}
/// <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 ShapedQueryExpression? TranslateCount(ShapedQueryExpression source, LambdaExpression? predicate)
=> TranslateCountLongCount(source, predicate, typeof(int));
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override ShapedQueryExpression? TranslateDefaultIfEmpty(ShapedQueryExpression source, Expression? defaultValue)
=> 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 ShapedQueryExpression? TranslateDistinct(ShapedQueryExpression source)
{
var select = (SelectExpression)source.QueryExpression;
if ((select.Limit is not null || select.Offset is not null)
&& !TryPushdownIntoSubquery(select))
{
return null;
}
select.ApplyDistinct();
return source;
}
/// <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 ShapedQueryExpression? TranslateElementAtOrDefault(
ShapedQueryExpression source,
Expression index,
bool returnDefault)
{
if (TranslateExpression(index) is not SqlExpression translatedIndex)
{
return null;
}
var select = (SelectExpression)source.QueryExpression;
// If the source query represents a bare array (e.g. x.Array), simplify x.Array.Skip(2) => ARRAY_SLICE(x.Array, 2) instead of
// subquery+OFFSET (which isn't supported by Cosmos).
// Even if the source is a full query (not a bare array), convert it to an array via the Cosmos ARRAY() operator; we do this
// only in subqueries, because Cosmos supports OFFSET/LIMIT at the top-level but not in subqueries.
var array = source.TryExtractArray(out var a, out var projection, out var projectedStructuralTypeShaper, out _)
? a
: _subquery && source.TryConvertToArray(_typeMappingSource, out a, out projection)
? a
: null;
// Simplify x.Array[1] => x.Array[1] (using the Cosmos array subscript operator) instead of a subquery with LIMIT/OFFSET
switch (array)
{
// ElementAtOrDefault over an array of scalars
case SqlExpression scalarArray when projection is SqlExpression element:
{
var translation = _sqlExpressionFactory.ArrayIndex(
scalarArray, translatedIndex, element.Type, element.TypeMapping);
// ElementAt may access indexes beyond the end of the array; Cosmos returns undefined for those cases.
// If ElementAtOrDefault is used, add the Cosmos undefined-coalescing operator (??) to return a default value instead.
if (returnDefault)
{
translation = _sqlExpressionFactory.CoalesceUndefined(
translation, TranslateExpression(translation.Type.GetDefaultValueConstant())!);
}
var translatedSelect = new SelectExpression(translation);
return source.Update(
translatedSelect,
new ProjectionBindingExpression(translatedSelect, new ProjectionMember(), element.Type));
}
// ElementAtOrDefault over an array of structural types
case not null when projectedStructuralTypeShaper is not null:
{
Expression translation = new ObjectArrayIndexExpression(array, translatedIndex, projectedStructuralTypeShaper.Type);
// ElementAt may access indexes beyond the end of the array; Cosmos returns undefined for those cases.
// If ElementAtOrDefault is used, add the Cosmos undefined-coalescing operator (??) to return a default value instead.
if (returnDefault)
{
// TODO: The following uses SqlConstantExpression as a hack to produce a null for the structural type (#33999)
translation = new ObjectBinaryExpression(
ExpressionType.Coalesce,
translation,
new SqlConstantExpression(null, typeof(object), _typeMappingSource.FindMapping(typeof(int))),
translation.Type);
}
var translatedSelect =
new SelectExpression(
new EntityProjectionExpression(translation, (IEntityType)projectedStructuralTypeShaper.StructuralType));
return source.Update(
translatedSelect,
new StructuralTypeShaperExpression(
projectedStructuralTypeShaper.StructuralType,
new ProjectionBindingExpression(translatedSelect, new ProjectionMember(), typeof(ValueBuffer)),
nullable: true));
}
}
// Simplification to indexing failed, translate using OFFSET/LIMIT, except in subqueries where it isn't supported.
if (_subquery)
{
AddTranslationErrorDetails(CosmosStrings.LimitOffsetNotSupportedInSubqueries);
return null;
}
// Ordering of documents is not guaranteed in Cosmos, so we warn for Take without OrderBy.
// However, when querying on JSON arrays within documents, the order of elements is guaranteed, and Take without OrderBy is
// fine. Since subqueries must be correlated (i.e. reference an array in the outer query), we use that to decide whether to
// warn or not.
if (select.Orderings.Count == 0 && !_subquery)
{
_queryCompilationContext.Logger.RowLimitingOperationWithoutOrderByWarning();
}
if (!TryApplyOffset(select, translatedIndex)
|| !TryApplyLimit(select, TranslateExpression(Expression.Constant(1))!))
{
return null;
}
// TODO: ElementAt on top level
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 ShapedQueryExpression? TranslateExcept(ShapedQueryExpression source1, ShapedQueryExpression source2)
{
AddTranslationErrorDetails(CosmosStrings.ExceptNotSupported);
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 ShapedQueryExpression? TranslateFirstOrDefault(
ShapedQueryExpression source,
LambdaExpression? predicate,
Type returnType,
bool returnDefault)
{
if (predicate != null)
{
if (TranslateWhere(source, predicate) is not ShapedQueryExpression translatedSource)
{
return null;
}
source = translatedSource;
}
// Cosmos does not support LIMIT in subqueries, so call into TranslateElementAtOrDefault which knows how to either extract an
// array from the source or wrap it in a Cosmos ARRAY() operator, to turn it into an array. At that point, a regular array index
// (x.Array[0]) can be used to get the first element.
if (_subquery)
{
return TranslateElementAtOrDefault(source, Expression.Constant(0), returnDefault);
}
var select = (SelectExpression)source.QueryExpression;
if (!TryApplyLimit(select, TranslateExpression(Expression.Constant(1))!))
{
return null;
}
if (select is { Orderings: [], Predicate: null, ReadItemInfo: null })
{
_queryCompilationContext.Logger.FirstWithoutOrderByAndFilterWarning();
}
return source.ShaperExpression.Type != returnType
? source.UpdateShaperExpression(Expression.Convert(source.ShaperExpression, returnType))
: source;
}
/// <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 ShapedQueryExpression? TranslateGroupBy(
ShapedQueryExpression source,
LambdaExpression keySelector,
LambdaExpression? elementSelector,
LambdaExpression? resultSelector)
=> 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 ShapedQueryExpression? TranslateGroupJoin(
ShapedQueryExpression outer,
ShapedQueryExpression inner,
LambdaExpression outerKeySelector,
LambdaExpression innerKeySelector,
LambdaExpression resultSelector)
=> 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 ShapedQueryExpression? TranslateIntersect(ShapedQueryExpression source1, ShapedQueryExpression source2)
=> TranslateSetOperation(source1, source2, "SetIntersect", ignoreOrderings: true);
/// <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 ShapedQueryExpression? TranslateJoin(
ShapedQueryExpression outer,
ShapedQueryExpression inner,
LambdaExpression outerKeySelector,
LambdaExpression innerKeySelector,
LambdaExpression resultSelector)
{
AddTranslationErrorDetails(CosmosStrings.CrossDocumentJoinNotSupported);
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 ShapedQueryExpression? TranslateLastOrDefault(
ShapedQueryExpression source,
LambdaExpression? predicate,
Type returnType,
bool returnDefault)
{
if (predicate != null)
{
if (TranslateWhere(source, predicate) is not ShapedQueryExpression translatedSource)
{
return null;
}
source = translatedSource;
}
var select = (SelectExpression)source.QueryExpression;
select.ReverseOrderings();
if (!TryApplyLimit(select, TranslateExpression(Expression.Constant(1))!))
{
return null;
}
return source.ShaperExpression.Type != returnType
? source.UpdateShaperExpression(Expression.Convert(source.ShaperExpression, returnType))
: source;
}
/// <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 ShapedQueryExpression? TranslateLeftJoin(
ShapedQueryExpression outer,
ShapedQueryExpression inner,
LambdaExpression outerKeySelector,
LambdaExpression innerKeySelector,
LambdaExpression resultSelector)
{
AddTranslationErrorDetails(CosmosStrings.CrossDocumentJoinNotSupported);
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 ShapedQueryExpression? TranslateRightJoin(
ShapedQueryExpression outer,
ShapedQueryExpression inner,
LambdaExpression outerKeySelector,
LambdaExpression innerKeySelector,
LambdaExpression resultSelector)
{
AddTranslationErrorDetails(CosmosStrings.CrossDocumentJoinNotSupported);
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 ShapedQueryExpression? TranslateLongCount(ShapedQueryExpression source, LambdaExpression? predicate)
=> TranslateCountLongCount(source, predicate, typeof(long));
/// <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 ShapedQueryExpression? TranslateMax(ShapedQueryExpression source, LambdaExpression? selector, Type resultType)
=> TranslateAggregate(source, selector, resultType, "MAX");
/// <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 ShapedQueryExpression? TranslateMin(ShapedQueryExpression source, LambdaExpression? selector, Type resultType)
=> TranslateAggregate(source, selector, resultType, "MIN");
/// <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 ShapedQueryExpression? TranslateOfType(ShapedQueryExpression source, Type resultType)
{
if (source.ShaperExpression is not StructuralTypeShaperExpression entityShaperExpression)
{
return null;
}
if (entityShaperExpression.StructuralType is not IEntityType entityType)
{
throw new UnreachableException("Complex types not supported in Cosmos");
}
if (entityType.ClrType == resultType)
{
return source;
}
var select = (SelectExpression)source.QueryExpression;
var parameterExpression = Expression.Parameter(entityShaperExpression.Type);
var predicate = Expression.Lambda(Expression.TypeIs(parameterExpression, resultType), parameterExpression);
if (!TryApplyPredicate(source, predicate))
{
return null;
}
var baseType = entityType.GetAllBaseTypes().SingleOrDefault(et => et.ClrType == resultType);
if (baseType != null)
{
return source.UpdateShaperExpression(entityShaperExpression.WithType(baseType));
}
var derivedType = entityType.GetDerivedTypes().Single(et => et.ClrType == resultType);
var projectionBindingExpression = (ProjectionBindingExpression)entityShaperExpression.ValueBufferExpression;
var projectionMember = projectionBindingExpression.ProjectionMember;
Check.DebugAssert(new ProjectionMember().Equals(projectionMember), "Invalid ProjectionMember when processing OfType");
var entityProjectionExpression = (EntityProjectionExpression)select.GetMappedProjection(projectionMember);
select.ReplaceProjectionMapping(
new Dictionary<ProjectionMember, Expression>
{
{ projectionMember, entityProjectionExpression.UpdateEntityType(derivedType) }
});
return source.UpdateShaperExpression(entityShaperExpression.WithType(derivedType));
}
/// <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 ShapedQueryExpression? TranslateOrderBy(
ShapedQueryExpression source,
LambdaExpression keySelector,
bool ascending)
{
var select = (SelectExpression)source.QueryExpression;
if ((select.IsDistinct || select.Limit is not null || select.Offset is not null)
&& !TryPushdownIntoSubquery(select))
{
return null;
}
if (TranslateLambdaExpression(source, keySelector) is SqlExpression translation)
{
((SelectExpression)source.QueryExpression).ApplyOrdering(new OrderingExpression(translation, ascending));
return source;
}
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 ShapedQueryExpression? TranslateReverse(ShapedQueryExpression source)
{
var selectExpression = (SelectExpression)source.QueryExpression;
if (selectExpression.Orderings.Count == 0)
{
AddTranslationErrorDetails(CosmosStrings.MissingOrderingInSelectExpression);
return null;
}
selectExpression.ReverseOrderings();
return source;
}
/// <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 ShapedQueryExpression TranslateSelect(ShapedQueryExpression source, LambdaExpression selector)
{
if (selector.Body == selector.Parameters[0])
{
return source;
}
var selectExpression = (SelectExpression)source.QueryExpression;
if (selectExpression.IsDistinct)
{
// TODO: The base TranslateSelect does not allow returning null (presumably because client eval should always be possible)
return null!;
}
var newSelectorBody = RemapLambdaBody(source, selector);
return source.UpdateShaperExpression(_projectionBindingExpressionVisitor.Translate(selectExpression, newSelectorBody));
}
/// <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 ShapedQueryExpression? TranslateSelectMany(
ShapedQueryExpression source,
LambdaExpression collectionSelector,
LambdaExpression resultSelector)
{
var collectionSelectorBody = RemapLambdaBody(source, collectionSelector);
// The collection selector gets translated in subquery context; specifically, if an uncorrelated SelectMany() is attempted
// (from b in context.Blogs from p in context.Posts...), we want to detect that and fail translation as an uncorrelated query
// (see VisitExtension visitation for EntityQueryRootExpression)
var previousSubquery = _subquery;
_subquery = true;