-
Notifications
You must be signed in to change notification settings - Fork 3.4k
Expand file tree
/
Copy pathSelectExpression.cs
More file actions
4855 lines (4227 loc) · 224 KB
/
SelectExpression.cs
File metadata and controls
4855 lines (4227 loc) · 224 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.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Microsoft.EntityFrameworkCore.Query.Internal;
namespace Microsoft.EntityFrameworkCore.Query.SqlExpressions;
/// <summary>
/// <para>
/// An expression that represents a SELECT in a SQL tree.
/// </para>
/// <para>
/// This type is typically used by database providers (and other extensions). It is generally
/// not used in application code.
/// </para>
/// </summary>
/// <remarks>
/// This class is not publicly constructable. If this is a problem for your application or provider, then please file
/// an issue at <see href="https://github.com/dotnet/efcore">github.com/dotnet/efcore</see>.
/// </remarks>
// Class is sealed because there are no public/protected constructors. Can be unsealed if this is changed.
[DebuggerDisplay("{PrintShortSql(), nq}")]
public sealed partial class SelectExpression : TableExpressionBase
{
internal const string DiscriminatorColumnAlias = "Discriminator";
private static readonly IdentifierComparer IdentifierComparerInstance = new();
private readonly List<ProjectionExpression> _projection = [];
private readonly List<TableExpressionBase> _tables = [];
private readonly List<SqlExpression> _groupBy = [];
private readonly List<OrderingExpression> _orderings = [];
private readonly List<(ColumnExpression Column, ValueComparer Comparer)> _identifier = [];
private readonly List<(ColumnExpression Column, ValueComparer Comparer)> _childIdentifiers = [];
private readonly SqlAliasManager _sqlAliasManager;
internal bool IsMutable { get; private set; } = true;
private Dictionary<ProjectionMember, Expression> _projectionMapping = new();
private List<Expression> _clientProjections = [];
private readonly List<string?> _aliasForClientProjections = [];
private CloningExpressionVisitor? _cloningExpressionVisitor;
// We need to remember identifiers before GroupBy in case it is final GroupBy and element selector has a collection
// This state doesn't need to propagate
// It should be only at top-level otherwise GroupBy won't be final operator.
// Cloning skips it altogether (we don't clone top level with GroupBy)
// Pushdown should null it out as if GroupBy was present was pushed down.
private List<(ColumnExpression Column, ValueComparer Comparer)>? _preGroupByIdentifier;
private static ConstructorInfo? _quotingConstructor;
/// <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 SelectExpression(
string? alias,
List<TableExpressionBase> tables,
SqlExpression? predicate,
List<SqlExpression> groupBy,
SqlExpression? having,
List<ProjectionExpression> projections,
bool distinct,
List<OrderingExpression> orderings,
SqlExpression? offset,
SqlExpression? limit,
ISet<string> tags,
IReadOnlyDictionary<string, IAnnotation>? annotations,
SqlAliasManager sqlAliasManager,
bool isMutable)
: base(alias, annotations)
{
Check.DebugAssert(!(isMutable && sqlAliasManager is null), "Need SqlAliasManager when the SelectExpression is mutable");
_tables = tables;
Predicate = predicate;
_groupBy = groupBy;
Having = having;
_projection = projections;
IsDistinct = distinct;
_orderings = orderings;
Offset = offset;
Limit = limit;
Tags = tags;
IsMutable = isMutable;
_sqlAliasManager = sqlAliasManager;
}
/// <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 SelectExpression(
string? alias,
IReadOnlyList<TableExpressionBase> tables,
SqlExpression? predicate,
IReadOnlyList<SqlExpression> groupBy,
SqlExpression? having,
IReadOnlyList<ProjectionExpression> projections,
bool distinct,
IReadOnlyList<OrderingExpression> orderings,
SqlExpression? offset,
SqlExpression? limit,
SqlAliasManager sqlAliasManager,
IReadOnlySet<string>? tags = null,
IReadOnlyDictionary<string, IAnnotation>? annotations = null)
: this(
alias, tables.ToList(), predicate, groupBy.ToList(), having, projections.ToList(), distinct, orderings.ToList(),
offset, limit, tags?.ToHashSet() ?? [], annotations, sqlAliasManager, isMutable: false)
{
}
private SelectExpression(
string? alias,
List<TableExpressionBase> tables,
List<SqlExpression> groupBy,
List<ProjectionExpression> projections,
List<OrderingExpression> orderings,
IReadOnlyDictionary<string, IAnnotation>? annotations,
SqlAliasManager sqlAliasManager)
: this(
alias, tables, predicate: null, groupBy: groupBy, having: null, projections: projections, distinct: false, orderings: orderings,
offset: null,
limit: null, tags: new HashSet<string>(),
annotations: annotations, sqlAliasManager: sqlAliasManager, isMutable: 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>
[EntityFrameworkInternal]
public SelectExpression(
List<TableExpressionBase> tables,
Expression projection,
List<(ColumnExpression Column, ValueComparer Comparer)> identifier,
SqlAliasManager sqlAliasManager)
: base(null)
{
_tables = tables;
_projectionMapping[new ProjectionMember()] = projection;
_identifier = identifier;
_sqlAliasManager = sqlAliasManager;
}
/// <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 SelectExpression(SqlExpression projection, SqlAliasManager sqlAliasManager)
: this(tables: [], projection, identifier: [], sqlAliasManager)
{
}
/// <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>
// Immutable selects no longer need to create tables, so no need for an alias manager (note that in the long term, SelectExpression
// should have an alias manager at all, so this is temporary).
[EntityFrameworkInternal]
public static SelectExpression CreateImmutable(
string alias,
List<TableExpressionBase> tables,
List<ProjectionExpression> projection,
SqlAliasManager sqlAliasManager)
=> new(
alias, tables, predicate: null, groupBy: [], having: null, projections: projection, distinct: false, orderings: [],
offset: null, limit: null,
tags: new HashSet<string>(), sqlAliasManager: sqlAliasManager, annotations: new Dictionary<string, IAnnotation>(),
isMutable: false);
/// <summary>
/// The list of tags applied to this <see cref="SelectExpression" />.
/// </summary>
public ISet<string> Tags { get; private set; } = new HashSet<string>();
/// <summary>
/// A bool value indicating if DISTINCT is applied to projection of this <see cref="SelectExpression" />.
/// </summary>
public bool IsDistinct { get; set; }
/// <summary>
/// The list of expressions being projected out from the result set.
/// </summary>
public IReadOnlyList<ProjectionExpression> Projection
=> _projection;
/// <summary>
/// The list of tables sources used to generate the result set.
/// </summary>
public IReadOnlyList<TableExpressionBase> Tables
=> _tables;
/// <summary>
/// The WHERE predicate for the SELECT.
/// </summary>
public SqlExpression? Predicate { get; private set; }
/// <summary>
/// The SQL GROUP BY clause for the SELECT.
/// </summary>
public IReadOnlyList<SqlExpression> GroupBy
=> _groupBy;
/// <summary>
/// The HAVING predicate for the SELECT when <see cref="GroupBy" /> clause exists.
/// </summary>
public SqlExpression? Having { get; private set; }
/// <summary>
/// The list of orderings used to sort the result set.
/// </summary>
public IReadOnlyList<OrderingExpression> Orderings
=> _orderings;
/// <summary>
/// The limit applied to the number of rows in the result set.
/// </summary>
public SqlExpression? Limit { get; private set; }
/// <summary>
/// The offset to skip rows from the result set.
/// </summary>
public SqlExpression? Offset { get; private set; }
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public void SetTables(IReadOnlyList<TableExpressionBase> tables)
{
Check.DebugAssert(IsMutable, "Attempt to mutate an immutable SelectExpression");
_tables.Clear();
_tables.AddRange(tables);
}
/// <summary>
/// Applies a given set of tags.
/// </summary>
/// <param name="tags">A list of tags to apply.</param>
public void ApplyTags(ISet<string> tags)
=> Tags = tags;
/// <summary>
/// Applies DISTINCT operator to the projections of the <see cref="SelectExpression" />.
/// </summary>
public void ApplyDistinct()
{
if (_clientProjections.Count > 0
&& _clientProjections.Any(e => e is ShapedQueryExpression { ResultCardinality: ResultCardinality.Enumerable }))
{
throw new InvalidOperationException(RelationalStrings.DistinctOnCollectionNotSupported);
}
if (Limit is SqlConstantExpression { Value: 1 })
{
return;
}
if (Limit != null
|| Offset != null)
{
PushdownIntoSubquery();
}
IsDistinct = true;
if (_identifier.Count > 0)
{
var typeProjectionIdentifiers = new List<ColumnExpression>();
var typeProjectionValueComparers = new List<ValueComparer>();
var otherExpressions = new List<SqlExpression>();
var nonProcessableExpressionFound = false;
var projections = _clientProjections.Count > 0 ? _clientProjections : _projectionMapping.Values.ToList();
foreach (var projection in projections)
{
switch (projection)
{
case StructuralTypeProjectionExpression { StructuralType: IEntityType entityType } entityProjection
when entityType.IsMappedToJson():
{
// For JSON owned entities, the identifier is the key that was generated when we convert from json to query root
// (OPENJSON, json_each, etc), but we can't use it for distinct, as it would warp the results.
// Instead, we will treat every non-key property as identifier.
foreach (var property in entityType.GetDeclaredProperties().Where(p => !p.IsPrimaryKey()))
{
typeProjectionIdentifiers.Add(entityProjection.BindProperty(property));
typeProjectionValueComparers.Add(property.GetKeyValueComparer());
}
break;
}
case StructuralTypeProjectionExpression { StructuralType: IEntityType entityType } entityProjection
when !entityType.IsMappedToJson():
{
var primaryKey = entityType.FindPrimaryKey();
// We know that there are existing identifiers (see condition above); we know we must have a key since a keyless
// entity type would have wiped the identifiers when generating the join.
Check.DebugAssert(primaryKey != null, "primary key is null.");
foreach (var property in primaryKey.Properties)
{
typeProjectionIdentifiers.Add(entityProjection.BindProperty(property));
typeProjectionValueComparers.Add(property.GetKeyValueComparer());
}
break;
}
case StructuralTypeProjectionExpression { StructuralType: IComplexType } complexTypeProjection:
// When distinct is applied to complex types, all columns - including ones in nested complex types - become
// the identifier. Any JSON complex types found will simply have its single container column added like any
// other column.
ProcessComplexType(complexTypeProjection);
void ProcessComplexType(StructuralTypeProjectionExpression complexTypeProjection)
{
var complexType = (IComplexType)complexTypeProjection.StructuralType;
foreach (var property in complexType.GetProperties())
{
typeProjectionIdentifiers.Add(complexTypeProjection.BindProperty(property));
typeProjectionValueComparers.Add(property.GetKeyValueComparer());
}
foreach (var complexProperty in complexType.GetComplexProperties())
{
switch (complexTypeProjection.BindComplexProperty(complexProperty))
{
// Non-JSON non-collection type (table splitting): recurse inside and process all properties,
// as each property is mapped to its own column.
case StructuralTypeShaperExpression
{
ValueBufferExpression: StructuralTypeProjectionExpression projection
}:
ProcessComplexType(projection);
continue;
// We have a JSON-mapped complex type.
// Ideally, we'd simply add the JSON container column to the identifiers list - just like for
// any regular property - but JSON columns aren't currently supported as identifiers (#36421).
case StructuralTypeShaperExpression { ValueBufferExpression: JsonQueryExpression }:
case CollectionResultExpression { QueryExpression: JsonQueryExpression }:
nonProcessableExpressionFound = true;
continue;
default:
throw new UnreachableException();
}
}
}
break;
case JsonQueryExpression { StructuralType: IEntityType entityType } jsonQueryExpression:
if (jsonQueryExpression.IsCollection)
{
throw new InvalidOperationException(RelationalStrings.DistinctOnCollectionNotSupported);
}
var primaryKeyProperties = entityType.FindPrimaryKey()!.Properties;
var primaryKeyPropertiesCount = jsonQueryExpression.IsCollection
? primaryKeyProperties.Count - 1
: primaryKeyProperties.Count;
for (var i = 0; i < primaryKeyPropertiesCount; i++)
{
var keyProperty = primaryKeyProperties[i];
typeProjectionIdentifiers.Add((ColumnExpression)jsonQueryExpression.BindProperty(keyProperty));
typeProjectionValueComparers.Add(keyProperty.GetKeyValueComparer());
}
break;
// We have a JSON-mapped complex type.
// Ideally, we'd simply add the JSON container column to the identifiers list - just like for
// any regular property - but JSON columns aren't currently supported as identifiers (#36421).
case JsonQueryExpression jsonQueryExpression:
nonProcessableExpressionFound = true;
break;
case SqlExpression sqlExpression:
otherExpressions.Add(sqlExpression);
break;
default:
nonProcessableExpressionFound = true;
break;
}
}
if (nonProcessableExpressionFound)
{
_identifier.Clear();
}
else
{
var allOtherExpressions = typeProjectionIdentifiers.Concat(otherExpressions).ToList();
if (!_identifier.All(e => allOtherExpressions.Contains(e.Column)))
{
_identifier.Clear();
if (otherExpressions.Count == 0)
{
// If there are no other expressions then we can use all entityProjectionIdentifiers
_identifier.AddRange(typeProjectionIdentifiers.Zip(typeProjectionValueComparers));
}
else if (otherExpressions.All(e => e is ColumnExpression))
{
_identifier.AddRange(typeProjectionIdentifiers.Zip(typeProjectionValueComparers));
_identifier.AddRange(otherExpressions.Select(e => ((ColumnExpression)e, e.TypeMapping!.KeyComparer)));
}
}
}
}
ClearOrdering();
}
/// <summary>
/// Adds expressions from projection mapping to projection ignoring the shaper expression. This method should only be used
/// when populating projection in subquery.
/// </summary>
public void ApplyProjection()
{
if (!IsMutable)
{
throw new InvalidOperationException("Applying projection on already finalized select expression");
}
IsMutable = false;
if (_clientProjections.Count > 0)
{
for (var i = 0; i < _clientProjections.Count; i++)
{
switch (_clientProjections[i])
{
case StructuralTypeProjectionExpression projection:
AddStructuralTypeProjection(projection);
break;
case SqlExpression sqlExpression:
AddToProjection(sqlExpression, _aliasForClientProjections[i]);
break;
default:
throw new InvalidOperationException(
"Invalid type of projection to add when not associated with shaper expression.");
}
}
_clientProjections.Clear();
}
else
{
foreach (var (_, expression) in _projectionMapping)
{
if (expression is StructuralTypeProjectionExpression projection)
{
AddStructuralTypeProjection(projection);
}
else
{
AddToProjection((SqlExpression)expression);
}
}
_projectionMapping.Clear();
}
void AddStructuralTypeProjection(StructuralTypeProjectionExpression projection)
{
ProcessTypeProjection(projection);
void ProcessTypeProjection(StructuralTypeProjectionExpression projection)
{
foreach (var property in projection.StructuralType.GetPropertiesInHierarchy())
{
AddToProjection(projection.BindProperty(property), alias: null);
}
foreach (var complexProperty in GetAllComplexPropertiesInHierarchy(projection.StructuralType))
{
if (complexProperty.IsCollection)
{
throw new NotImplementedException(); // #36296
}
var propertyShaper = (StructuralTypeShaperExpression)projection.BindComplexProperty(complexProperty);
ProcessTypeProjection((StructuralTypeProjectionExpression)propertyShaper.ValueBufferExpression);
}
}
if (projection.DiscriminatorExpression != null)
{
AddToProjection(projection.DiscriminatorExpression, DiscriminatorColumnAlias);
}
}
}
/// <summary>
/// Adds expressions from projection mapping to projection and generate updated shaper expression for materialization.
/// </summary>
/// <param name="shaperExpression">Current shaper expression which will shape results of this select expression.</param>
/// <param name="resultCardinality">The result cardinality of this query expression.</param>
/// <param name="querySplittingBehavior">The query splitting behavior to use when applying projection for nested collections.</param>
/// <returns>Returns modified shaper expression to shape results of this select expression.</returns>
public Expression ApplyProjection(
Expression shaperExpression,
ResultCardinality resultCardinality,
QuerySplittingBehavior querySplittingBehavior)
{
if (!IsMutable)
{
throw new InvalidOperationException("Applying projection on already finalized select expression");
}
IsMutable = false;
if (shaperExpression is RelationalGroupByShaperExpression relationalGroupByShaperExpression)
{
// This is final GroupBy operation
Check.DebugAssert(_groupBy.Count > 0, "The selectExpression doesn't have grouping terms.");
if (_clientProjections.Count == 0)
{
// Force client projection because we would be injecting keys and client-side key comparison
var mapping = ConvertProjectionMappingToClientProjections(_projectionMapping);
var innerShaperExpression = new ProjectionMemberToIndexConvertingExpressionVisitor(this, mapping).Visit(
relationalGroupByShaperExpression.ElementSelector);
shaperExpression = new RelationalGroupByShaperExpression(
relationalGroupByShaperExpression.KeySelector,
innerShaperExpression,
relationalGroupByShaperExpression.GroupingEnumerable);
}
// Convert GroupBy to OrderBy
foreach (var groupingTerm in _groupBy)
{
AppendOrdering(new OrderingExpression(groupingTerm, ascending: true));
}
_groupBy.Clear();
// We do processing of adding key terms to projection when applying projection so we can move offsets for other
// projections correctly
}
if (_clientProjections.Count > 0)
{
EntityShaperNullableMarkingExpressionVisitor? entityShaperNullableMarkingExpressionVisitor = null;
CloningExpressionVisitor? cloningExpressionVisitor = null;
var pushdownOccurred = false;
var containsCollection = false;
var containsSingleResult = false;
var jsonClientProjectionsCount = 0;
foreach (var projection in _clientProjections)
{
switch (projection)
{
case ShapedQueryExpression { ResultCardinality: ResultCardinality.Enumerable }:
containsCollection = true;
break;
case ShapedQueryExpression { ResultCardinality: ResultCardinality.Single or ResultCardinality.SingleOrDefault }:
containsSingleResult = true;
break;
case JsonQueryExpression:
jsonClientProjectionsCount++;
break;
}
}
if (containsSingleResult
|| (querySplittingBehavior == QuerySplittingBehavior.SingleQuery && containsCollection))
{
// Pushdown outer since we will be adding join to this
// For grouping query pushdown will not occur since we don't allow this terms to compose (yet!).
if (Limit != null
|| Offset != null
|| IsDistinct
|| GroupBy.Count > 0)
{
PushdownIntoSubqueryInternal();
pushdownOccurred = true;
}
entityShaperNullableMarkingExpressionVisitor = new EntityShaperNullableMarkingExpressionVisitor();
}
if (querySplittingBehavior == QuerySplittingBehavior.SplitQuery
&& (containsSingleResult || containsCollection))
{
// SingleResult can lift collection from inner
// Specifically for here, we want to avoid cloning the client projection; if we do, when applying the projection on the
// cloned inner query we go into an endless recursion.
// Note that we create a CloningExpressionVisitor without a SQL alias manager - this means that aliases won't get uniquified
// as expressions are being cloned. Since we're cloning here to get a completely separate (split) query, that makes sense
// as we don't want aliases to be unique across different queries (but in other contexts, when the cloned fragment gets
// integrated back into the same query (e.g. GroupBy) we do want to uniquify aliases).
cloningExpressionVisitor = new CloningExpressionVisitor(sqlAliasManager: null, cloneClientProjections: false);
}
var earlierClientProjectionCount = _clientProjections.Count;
var newClientProjections = new List<Expression>();
var clientProjectionIndexMap = new List<object>();
var remappingRequired = false;
if (shaperExpression is RelationalGroupByShaperExpression groupByShaper)
{
// We need to add key to projection and generate key selector in terms of projectionBindings
var projectionBindingMap = new Dictionary<SqlExpression, Expression>();
var keySelector = AddGroupByKeySelectorToProjection(
this, newClientProjections, projectionBindingMap, groupByShaper.KeySelector);
var (keyIdentifier, keyIdentifierValueComparers) = GetIdentifierAccessor(
this, newClientProjections, projectionBindingMap, _identifier);
_identifier.Clear();
_identifier.AddRange(_preGroupByIdentifier!);
_preGroupByIdentifier!.Clear();
Expression AddGroupByKeySelectorToProjection(
SelectExpression selectExpression,
List<Expression> clientProjectionList,
Dictionary<SqlExpression, Expression> projectionBindingMap,
Expression keySelector)
{
switch (keySelector)
{
case SqlExpression sqlExpression:
{
var index = selectExpression.AddToProjection(sqlExpression);
var clientProjectionToAdd = Constant(index);
var existingIndex = clientProjectionList.FindIndex(e
=> ExpressionEqualityComparer.Instance.Equals(e, clientProjectionToAdd));
if (existingIndex == -1)
{
clientProjectionList.Add(clientProjectionToAdd);
existingIndex = clientProjectionList.Count - 1;
}
var projectionBindingExpression = sqlExpression.Type.IsNullableType()
? (Expression)new ProjectionBindingExpression(selectExpression, existingIndex, sqlExpression.Type)
: Convert(
new ProjectionBindingExpression(
selectExpression, existingIndex, sqlExpression.Type.MakeNullable()),
sqlExpression.Type);
projectionBindingMap[sqlExpression] = projectionBindingExpression;
return projectionBindingExpression;
}
case NewExpression newExpression:
var newArguments = new Expression[newExpression.Arguments.Count];
for (var i = 0; i < newExpression.Arguments.Count; i++)
{
var newArgument = AddGroupByKeySelectorToProjection(
selectExpression, clientProjectionList, projectionBindingMap, newExpression.Arguments[i]);
newArguments[i] = newExpression.Arguments[i].Type != newArgument.Type
? Convert(newArgument, newExpression.Arguments[i].Type)
: newArgument;
}
return newExpression.Update(newArguments);
case MemberInitExpression memberInitExpression:
var updatedNewExpression = AddGroupByKeySelectorToProjection(
selectExpression, clientProjectionList, projectionBindingMap, memberInitExpression.NewExpression);
var newBindings = new MemberBinding[memberInitExpression.Bindings.Count];
for (var i = 0; i < newBindings.Length; i++)
{
var memberAssignment = (MemberAssignment)memberInitExpression.Bindings[i];
var newAssignmentExpression = AddGroupByKeySelectorToProjection(
selectExpression, clientProjectionList, projectionBindingMap, memberAssignment.Expression);
newBindings[i] = memberAssignment.Update(
memberAssignment.Expression.Type != newAssignmentExpression.Type
? Convert(newAssignmentExpression, memberAssignment.Expression.Type)
: newAssignmentExpression);
}
return memberInitExpression.Update((NewExpression)updatedNewExpression, newBindings);
case UnaryExpression { NodeType: ExpressionType.Convert or ExpressionType.ConvertChecked } unaryExpression:
return unaryExpression.Update(
AddGroupByKeySelectorToProjection(
selectExpression, clientProjectionList, projectionBindingMap, unaryExpression.Operand));
case StructuralTypeShaperExpression
{
ValueBufferExpression: StructuralTypeProjectionExpression projection
} shaper:
{
var clientProjectionToAdd = AddStructuralTypeProjection(projection);
var existingIndex = clientProjectionList.FindIndex(e
=> ExpressionEqualityComparer.Instance.Equals(e, clientProjectionToAdd));
if (existingIndex == -1)
{
clientProjectionList.Add(clientProjectionToAdd);
existingIndex = clientProjectionList.Count - 1;
}
return shaper.Update(
new ProjectionBindingExpression(selectExpression, existingIndex, typeof(ValueBuffer)));
}
default:
throw new InvalidOperationException(
RelationalStrings.InvalidKeySelectorForGroupBy(keySelector, keySelector.GetType()));
}
}
static (Expression, IReadOnlyList<ValueComparer>) GetIdentifierAccessor(
SelectExpression selectExpression,
List<Expression> clientProjectionList,
Dictionary<SqlExpression, Expression> projectionBindingMap,
IEnumerable<(ColumnExpression Column, ValueComparer Comparer)> identifyingProjection)
{
var updatedExpressions = new List<Expression>();
var comparers = new List<ValueComparer>();
foreach (var (column, comparer) in identifyingProjection)
{
if (!projectionBindingMap.TryGetValue(column, out var mappedExpression))
{
var index = selectExpression.AddToProjection(column);
var clientProjectionToAdd = Constant(index);
var existingIndex = clientProjectionList.FindIndex(e
=> ExpressionEqualityComparer.Instance.Equals(e, clientProjectionToAdd));
if (existingIndex == -1)
{
clientProjectionList.Add(clientProjectionToAdd);
existingIndex = clientProjectionList.Count - 1;
}
mappedExpression = new ProjectionBindingExpression(selectExpression, existingIndex, column.Type.MakeNullable());
}
updatedExpressions.Add(
mappedExpression.Type.IsValueType
? Convert(mappedExpression, typeof(object))
: mappedExpression);
comparers.Add(comparer);
}
return (NewArrayInit(typeof(object), updatedExpressions), comparers);
}
remappingRequired = true;
shaperExpression = new RelationalGroupByResultExpression(
keyIdentifier, keyIdentifierValueComparers, keySelector, groupByShaper.ElementSelector);
}
SelectExpression? baseSelectExpression = null;
if (querySplittingBehavior == QuerySplittingBehavior.SplitQuery && containsCollection)
{
// Needs to happen after converting final GroupBy so we clone correct form.
baseSelectExpression = (SelectExpression)cloningExpressionVisitor!.Visit(this);
// We mark this as mutable because the split query will combine into this and take it over.
baseSelectExpression.IsMutable = true;
if (resultCardinality is ResultCardinality.Single or ResultCardinality.SingleOrDefault)
{
// Update limit since split queries don't need limit 2
if (pushdownOccurred)
{
UpdateLimit((SelectExpression)baseSelectExpression.Tables[0]);
}
else
{
UpdateLimit(baseSelectExpression);
}
static void UpdateLimit(SelectExpression selectExpression)
{
if (selectExpression.Limit is SqlConstantExpression { Value: 2 } limitConstantExpression)
{
selectExpression.Limit = new SqlConstantExpression(1, limitConstantExpression.TypeMapping);
}
}
}
}
for (var i = 0; i < _clientProjections.Count; i++)
{
if (i == earlierClientProjectionCount)
{
// Since we lift nested client projections for single results up, we may need to re-clone the baseSelectExpression
// again so it does contain the single result subquery too. We erase projections for it since it would be non-empty.
earlierClientProjectionCount = _clientProjections.Count;
if (cloningExpressionVisitor != null)
{
baseSelectExpression = (SelectExpression)cloningExpressionVisitor.Visit(this);
baseSelectExpression.IsMutable = true;
baseSelectExpression._projection.Clear();
}
}
var value = _clientProjections[i];
switch (value)
{
case StructuralTypeProjectionExpression projection:
{
var result = AddStructuralTypeProjection(projection);
newClientProjections.Add(result);
clientProjectionIndexMap.Add(newClientProjections.Count - 1);
break;
}
case JsonQueryExpression jsonQueryExpression:
{
var jsonProjectionResult = AddJsonProjection(jsonQueryExpression);
newClientProjections.Add(jsonProjectionResult);
clientProjectionIndexMap.Add(newClientProjections.Count - 1);
break;
}
case SqlExpression sqlExpression:
{
var result = Constant(AddToProjection(sqlExpression, _aliasForClientProjections[i]));
newClientProjections.Add(result);
clientProjectionIndexMap.Add(newClientProjections.Count - 1);
break;
}
case ShapedQueryExpression
{
ResultCardinality: ResultCardinality.Single or ResultCardinality.SingleOrDefault
} shapedQueryExpression:
{
var innerSelectExpression = (SelectExpression)shapedQueryExpression.QueryExpression;
var innerShaperExpression = shapedQueryExpression.ShaperExpression;
if (innerSelectExpression._clientProjections.Count == 0)
{
var mapping = innerSelectExpression.ConvertProjectionMappingToClientProjections(
innerSelectExpression._projectionMapping);
innerShaperExpression =
new ProjectionMemberToIndexConvertingExpressionVisitor(innerSelectExpression, mapping)
.Visit(innerShaperExpression);
}
var innerExpression = RemoveConvert(innerShaperExpression);
if (innerExpression is not (StructuralTypeShaperExpression or IncludeExpression))
{
var sentinelExpression = innerSelectExpression.Limit!;
var sentinelNullableType = sentinelExpression.Type.MakeNullable();
innerSelectExpression._clientProjections.Add(sentinelExpression);
innerSelectExpression._aliasForClientProjections.Add(null);
var dummyProjection = new ProjectionBindingExpression(
innerSelectExpression, innerSelectExpression._clientProjections.Count - 1, sentinelNullableType);
var defaultResult = shapedQueryExpression.ResultCardinality == ResultCardinality.SingleOrDefault
? (Expression)Default(innerShaperExpression.Type)
: Block(
Throw(
New(
typeof(InvalidOperationException).GetConstructors()
.Single(ci =>
{
var parameters = ci.GetParameters();
return parameters.Length == 1
&& parameters[0].ParameterType == typeof(string);
}),
Constant(CoreStrings.SequenceContainsNoElements))),
Default(innerShaperExpression.Type));
innerShaperExpression = Condition(
Equal(dummyProjection, Default(sentinelNullableType)),
defaultResult,
innerShaperExpression);
}
// Single-result (to-one) joins never increase result cardinality, so the outer entity's
// identifiers are already sufficient to uniquely identify rows. We don't need to add the
// inner's identifiers to our own; doing so would cause unnecessary reference table JOINs,
// ORDER BY columns, and projections in split collection queries (#29182).
AddJoin(JoinType.OuterApply, ref innerSelectExpression, out _, isToOneJoin: true, isPrunableJoin: true);
var offset = _clientProjections.Count;
var count = innerSelectExpression._clientProjections.Count;
_clientProjections.AddRange(
innerSelectExpression._clientProjections.Select(e => MakeNullable(e, nullable: true)));
_aliasForClientProjections.AddRange(innerSelectExpression._aliasForClientProjections);
innerShaperExpression = new ProjectionIndexRemappingExpressionVisitor(
innerSelectExpression,
this,
Enumerable.Range(offset, count).ToArray())
.Visit(innerShaperExpression);
innerShaperExpression = entityShaperNullableMarkingExpressionVisitor!.Visit(innerShaperExpression);
clientProjectionIndexMap.Add(innerShaperExpression);
remappingRequired = true;
break;
static Expression RemoveConvert(Expression expression)
=> expression is UnaryExpression { NodeType: ExpressionType.Convert } unaryExpression
? RemoveConvert(unaryExpression.Operand)
: expression;
}
case ShapedQueryExpression { ResultCardinality: ResultCardinality.Enumerable } shapedQueryExpression:
{
var innerSelectExpression = (SelectExpression)shapedQueryExpression.QueryExpression;
if (_identifier.Count == 0
|| innerSelectExpression._identifier.Count == 0)
{
throw new InvalidOperationException(
RelationalStrings.InsufficientInformationToIdentifyElementOfCollectionJoin);
}
var innerShaperExpression = shapedQueryExpression.ShaperExpression;
if (innerSelectExpression._clientProjections.Count == 0)
{
var mapping = innerSelectExpression.ConvertProjectionMappingToClientProjections(
innerSelectExpression._projectionMapping);
innerShaperExpression =
new ProjectionMemberToIndexConvertingExpressionVisitor(innerSelectExpression, mapping)
.Visit(innerShaperExpression);
}
if (querySplittingBehavior == QuerySplittingBehavior.SplitQuery)
{
var outerSelectExpression = (SelectExpression)cloningExpressionVisitor!.Visit(baseSelectExpression!);
// Inject deterministic orderings (the identifier columns) to both the main query and the split query.
// Note that just below we pushdown the split query if it has limit/offset/distinct/groupby; this ensures
// that the orderings are also propagated to that split subquery if it has limit/offset, which ensures that
// that subquery returns the same rows as the main query (#26808)
var actualParentIdentifier = _identifier.Take(outerSelectExpression._identifier.Count).ToList();
for (var j = 0; j < actualParentIdentifier.Count; j++)
{
AppendOrderingInternal(new OrderingExpression(actualParentIdentifier[j].Column, ascending: true));
outerSelectExpression.AppendOrderingInternal(
new OrderingExpression(outerSelectExpression._identifier[j].Column, ascending: true));
}
if (outerSelectExpression.Limit != null
|| outerSelectExpression.Offset != null
|| outerSelectExpression.IsDistinct
|| outerSelectExpression._groupBy.Count > 0)
{
// We do pushdown after making sure that inner contains references to outer only
// so that when we do pushdown, we can update inner and maintain graph
var sqlRemappingVisitor = outerSelectExpression.PushdownIntoSubqueryInternal();
innerSelectExpression = sqlRemappingVisitor.Remap(innerSelectExpression);
}
var containsOrdering = innerSelectExpression.Orderings.Count > 0;
List<OrderingExpression>? orderingsToBeErased = null;
if (containsOrdering
&& innerSelectExpression.Limit == null
&& innerSelectExpression.Offset == null)
{
orderingsToBeErased = innerSelectExpression.Orderings.ToList();
}
var parentIdentifier = GetIdentifierAccessor(this, newClientProjections, actualParentIdentifier).Item1;
outerSelectExpression.AddJoin(
JoinType.CrossApply, ref innerSelectExpression, out var pushdownOccurredWhenJoining);
outerSelectExpression._clientProjections.AddRange(innerSelectExpression._clientProjections);
outerSelectExpression._aliasForClientProjections.AddRange(innerSelectExpression._aliasForClientProjections);
innerSelectExpression = outerSelectExpression;
// Copy over any nested ordering if there were any
if (containsOrdering)
{
var collectionJoinedInnerTable = ((JoinExpressionBase)innerSelectExpression._tables[^1]).Table;
var innerOrderingExpressions = new List<OrderingExpression>();
if (orderingsToBeErased != null)
{
// Ordering was present but erased so we add again
if (pushdownOccurredWhenJoining)
{