-
Notifications
You must be signed in to change notification settings - Fork 3.2k
/
SelectExpression.cs
4662 lines (4085 loc) · 216 KB
/
SelectExpression.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.IO;
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.
public sealed partial class SelectExpression : TableExpressionBase
{
private const string DiscriminatorColumnAlias = "Discriminator";
private const string SqlQuerySingleColumnAlias = "Value";
private static readonly bool UseOldBehavior30273
= AppContext.TryGetSwitch("Microsoft.EntityFrameworkCore.Issue30273", out var enabled30273) && enabled30273;
private static readonly bool UseOldBehavior31107 =
AppContext.TryGetSwitch("Microsoft.EntityFrameworkCore.Issue31107", out var enabled31107) && enabled31107;
private static readonly IdentifierComparer IdentifierComparerInstance = new();
private static readonly Dictionary<ExpressionType, ExpressionType> MirroredOperationMap =
new()
{
{ ExpressionType.Equal, ExpressionType.Equal },
{ ExpressionType.NotEqual, ExpressionType.NotEqual },
{ ExpressionType.LessThan, ExpressionType.GreaterThan },
{ ExpressionType.LessThanOrEqual, ExpressionType.GreaterThanOrEqual },
{ ExpressionType.GreaterThan, ExpressionType.LessThan },
{ ExpressionType.GreaterThanOrEqual, ExpressionType.LessThanOrEqual }
};
private readonly List<ProjectionExpression> _projection = new();
private readonly List<TableExpressionBase> _tables = new();
private readonly List<TableReferenceExpression> _tableReferences = new();
private readonly List<SqlExpression> _groupBy = new();
private readonly List<OrderingExpression> _orderings = new();
private readonly List<(ColumnExpression Column, ValueComparer Comparer)> _identifier = new();
private readonly List<(ColumnExpression Column, ValueComparer Comparer)> _childIdentifiers = new();
private readonly List<int> _removableJoinTables = new();
private readonly Dictionary<TpcTablesExpression, (ColumnExpression, List<string>)> _tpcDiscriminatorValues
= new(ReferenceEqualityComparer.Instance);
private bool _mutable = true;
private HashSet<string> _usedAliases = new();
private Dictionary<ProjectionMember, Expression> _projectionMapping = new();
private List<Expression> _clientProjections = new();
private readonly List<string?> _aliasForClientProjections = new();
private CloningExpressionVisitor? _cloningExpressionVisitor;
private SortedDictionary<string, IAnnotation>? _annotations;
// We need to remember identfiers before GroupBy in case it is final GroupBy and element selector has a colection
// 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;
#if DEBUG
private List<string>? _removedAliases;
#endif
private SelectExpression(
string? alias,
List<ProjectionExpression> projections,
List<TableExpressionBase> tables,
List<TableReferenceExpression> tableReferences,
List<SqlExpression> groupBy,
List<OrderingExpression> orderings,
IEnumerable<IAnnotation> annotations)
: base(alias)
{
_projection = projections;
_tables = tables;
_tableReferences = tableReferences;
_groupBy = groupBy;
_orderings = orderings;
if (annotations != null)
{
_annotations = new SortedDictionary<string, IAnnotation>();
foreach (var annotation in annotations)
{
_annotations[annotation.Name] = annotation;
}
}
}
private SelectExpression(string? alias)
: base(alias)
{
}
internal SelectExpression(SqlExpression? projection)
: base(null)
{
if (projection != null)
{
_projectionMapping[new ProjectionMember()] = projection;
}
}
internal SelectExpression(Type type, RelationalTypeMapping typeMapping, FromSqlExpression fromSqlExpression)
: base(null)
{
var tableReferenceExpression = new TableReferenceExpression(this, fromSqlExpression.Alias!);
AddTable(fromSqlExpression, tableReferenceExpression);
var columnExpression = new ConcreteColumnExpression(
SqlQuerySingleColumnAlias, tableReferenceExpression, type, typeMapping, type.IsNullableType());
_projectionMapping[new ProjectionMember()] = columnExpression;
}
internal SelectExpression(IEntityType entityType, ISqlExpressionFactory sqlExpressionFactory)
: base(null)
{
switch (entityType.GetMappingStrategy())
{
case RelationalAnnotationNames.TptMappingStrategy:
{
var keyProperties = entityType.FindPrimaryKey()!.Properties;
List<ColumnExpression> joinColumns = default!;
var tables = new List<ITableBase>();
var columns = new Dictionary<IProperty, ColumnExpression>();
foreach (var baseType in entityType.GetAllBaseTypesInclusive())
{
var table = GetTableBaseFiltered(baseType, tables);
tables.Add(table);
var tableExpression = new TableExpression(table);
var tableReferenceExpression = new TableReferenceExpression(this, tableExpression.Alias);
foreach (var property in baseType.GetDeclaredProperties())
{
columns[property] = CreateColumnExpression(property, table, tableReferenceExpression, nullable: false);
}
if (_tables.Count == 0)
{
AddTable(tableExpression, tableReferenceExpression);
joinColumns = new List<ColumnExpression>();
foreach (var property in keyProperties)
{
var columnExpression = columns[property];
joinColumns.Add(columnExpression);
_identifier.Add((columnExpression, property.GetKeyValueComparer()));
}
}
else
{
var innerColumns = keyProperties.Select(
p => CreateColumnExpression(p, table, tableReferenceExpression, nullable: false));
var joinPredicate = joinColumns.Zip(innerColumns, (l, r) => sqlExpressionFactory.Equal(l, r))
.Aggregate((l, r) => sqlExpressionFactory.AndAlso(l, r));
var joinExpression = new InnerJoinExpression(tableExpression, joinPredicate);
AddTable(joinExpression, tableReferenceExpression);
}
}
var caseWhenClauses = new List<CaseWhenClause>();
foreach (var derivedType in entityType.GetDerivedTypes())
{
var table = GetTableBaseFiltered(derivedType, tables);
tables.Add(table);
var tableExpression = new TableExpression(table);
var tableReferenceExpression = new TableReferenceExpression(this, tableExpression.Alias);
foreach (var property in derivedType.GetDeclaredProperties())
{
columns[property] = CreateColumnExpression(property, table, tableReferenceExpression, nullable: true);
}
var keyColumns = keyProperties.Select(p => CreateColumnExpression(p, table, tableReferenceExpression, nullable: true))
.ToArray();
if (!derivedType.IsAbstract())
{
caseWhenClauses.Add(
new CaseWhenClause(
sqlExpressionFactory.IsNotNull(keyColumns[0]),
sqlExpressionFactory.Constant(derivedType.ShortName())));
}
var joinPredicate = joinColumns.Zip(keyColumns, (l, r) => sqlExpressionFactory.Equal(l, r))
.Aggregate((l, r) => sqlExpressionFactory.AndAlso(l, r));
var joinExpression = new LeftJoinExpression(tableExpression, joinPredicate);
_removableJoinTables.Add(_tables.Count);
AddTable(joinExpression, tableReferenceExpression);
}
caseWhenClauses.Reverse();
var discriminatorExpression = caseWhenClauses.Count == 0
? null
: sqlExpressionFactory.ApplyDefaultTypeMapping(
sqlExpressionFactory.Case(caseWhenClauses, elseResult: null));
var entityProjection = new EntityProjectionExpression(entityType, columns, discriminatorExpression);
_projectionMapping[new ProjectionMember()] = entityProjection;
}
break;
case RelationalAnnotationNames.TpcMappingStrategy:
{
// Drop additional table if ofType/is operator used Issue#27957
var entityTypes = entityType.GetDerivedTypesInclusive().Where(e => !e.IsAbstract()).ToArray();
if (entityTypes.Length == 1)
{
// For single entity case, we don't need discriminator.
var table = entityTypes[0].GetViewOrTableMappings().Single().Table;
var tableExpression = new TableExpression(table);
var tableReferenceExpression = new TableReferenceExpression(this, tableExpression.Alias!);
AddTable(tableExpression, tableReferenceExpression);
var propertyExpressions = new Dictionary<IProperty, ColumnExpression>();
foreach (var property in GetAllPropertiesInHierarchy(entityType))
{
propertyExpressions[property] = CreateColumnExpression(property, table, tableReferenceExpression, nullable: false);
}
_projectionMapping[new ProjectionMember()] = new EntityProjectionExpression(entityType, propertyExpressions);
var primaryKey = entityType.FindPrimaryKey();
if (primaryKey != null)
{
foreach (var property in primaryKey.Properties)
{
_identifier.Add((propertyExpressions[property], property.GetKeyValueComparer()));
}
}
}
else
{
var tables = entityTypes.Select(e => e.GetViewOrTableMappings().Single().Table).ToArray();
var properties = GetAllPropertiesInHierarchy(entityType).ToArray();
var propertyNamesMap = new Dictionary<IProperty, string>();
for (var i = 0; i < entityTypes.Length; i++)
{
foreach (var property in entityTypes[i].GetProperties())
{
if (!propertyNamesMap.ContainsKey(property))
{
propertyNamesMap[property] = tables[i].FindColumn(property)!.Name;
}
}
}
var propertyNames = new string[properties.Length];
for (var i = 0; i < properties.Length; i++)
{
var candidateName = propertyNamesMap[properties[i]];
var uniqueAliasIndex = 0;
var currentName = candidateName;
while (propertyNames.Take(i).Any(e => string.Equals(e, currentName, StringComparison.OrdinalIgnoreCase)))
{
currentName = candidateName + uniqueAliasIndex++;
}
propertyNames[i] = currentName;
}
var discriminatorColumnName = DiscriminatorColumnAlias;
if (propertyNames.Any(e => string.Equals(discriminatorColumnName, e, StringComparison.OrdinalIgnoreCase)))
{
var uniqueAliasIndex = 0;
var currentName = discriminatorColumnName;
while (propertyNames.Any(e => string.Equals(e, currentName, StringComparison.OrdinalIgnoreCase)))
{
currentName = discriminatorColumnName + uniqueAliasIndex++;
}
discriminatorColumnName = currentName;
}
var subSelectExpressions = new List<SelectExpression>();
var discriminatorValues = new List<string>();
for (var i = 0; i < entityTypes.Length; i++)
{
var et = entityTypes[i];
var table = tables[i];
var selectExpression = new SelectExpression(alias: null);
// We intentionally do not assign unique aliases here in case some select expression gets pruned later
var tableExpression = new TableExpression(table);
var tableReferenceExpression = new TableReferenceExpression(selectExpression, tableExpression.Alias);
selectExpression._tables.Add(tableExpression);
selectExpression._tableReferences.Add(tableReferenceExpression);
for (var j = 0; j < properties.Length; j++)
{
var property = properties[j];
var projection = property.DeclaringEntityType.IsAssignableFrom(et)
? CreateColumnExpression(
property, table, tableReferenceExpression, property.DeclaringEntityType != entityType)
: (SqlExpression)sqlExpressionFactory.Constant(
null, property.ClrType.MakeNullable(), property.GetRelationalTypeMapping());
selectExpression._projection.Add(new ProjectionExpression(projection, propertyNames[j]));
}
selectExpression._projection.Add(
new ProjectionExpression(
sqlExpressionFactory.ApplyDefaultTypeMapping(sqlExpressionFactory.Constant(et.ShortName())),
discriminatorColumnName));
discriminatorValues.Add(et.ShortName());
subSelectExpressions.Add(selectExpression);
selectExpression._mutable = false;
}
// We only assign unique alias to Tpc
var tableAlias = GenerateUniqueAlias(_usedAliases, "t");
var tpcTables = new TpcTablesExpression(tableAlias, entityType, subSelectExpressions);
var tpcTableReference = new TableReferenceExpression(this, tableAlias);
_tables.Add(tpcTables);
_tableReferences.Add(tpcTableReference);
var firstSelectExpression = subSelectExpressions[0];
var columns = new Dictionary<IProperty, ColumnExpression>();
for (var i = 0; i < properties.Length; i++)
{
columns[properties[i]] = new ConcreteColumnExpression(firstSelectExpression._projection[i], tpcTableReference);
}
foreach (var property in entityType.FindPrimaryKey()!.Properties)
{
var columnExpression = columns[property];
_identifier.Add((columnExpression, property.GetKeyValueComparer()));
}
var discriminatorColumn = new ConcreteColumnExpression(firstSelectExpression._projection[^1], tpcTableReference);
_tpcDiscriminatorValues[tpcTables] = (discriminatorColumn, discriminatorValues);
var entityProjection = new EntityProjectionExpression(entityType, columns, discriminatorColumn);
_projectionMapping[new ProjectionMember()] = entityProjection;
}
}
break;
default:
{
// Also covers TPH
if (entityType.GetFunctionMappings().SingleOrDefault(e => e.IsDefaultFunctionMapping) is IFunctionMapping functionMapping)
{
var storeFunction = functionMapping.Table;
GenerateNonHierarchyNonSplittingEntityType(
storeFunction, new TableValuedFunctionExpression((IStoreFunction)storeFunction, Array.Empty<SqlExpression>()));
}
else
{
var mappings = entityType.GetViewOrTableMappings().ToList();
if (mappings.Count == 1)
{
var table = mappings[0].Table;
GenerateNonHierarchyNonSplittingEntityType(table, new TableExpression(table));
}
else
{
// entity splitting
var keyProperties = entityType.FindPrimaryKey()!.Properties;
List<ColumnExpression> joinColumns = default!;
var columns = new Dictionary<IProperty, ColumnExpression>();
var tableReferenceExpressionMap = new Dictionary<ITableBase, TableReferenceExpression>();
foreach (var mapping in mappings)
{
var table = mapping.Table;
var tableExpression = new TableExpression(table);
var tableReferenceExpression = new TableReferenceExpression(this, tableExpression.Alias);
tableReferenceExpressionMap[table] = tableReferenceExpression;
if (_tables.Count == 0)
{
AddTable(tableExpression, tableReferenceExpression);
joinColumns = new List<ColumnExpression>();
foreach (var property in keyProperties)
{
var columnExpression = CreateColumnExpression(
property, table, tableReferenceExpression, nullable: false);
columns[property] = columnExpression;
joinColumns.Add(columnExpression);
_identifier.Add((columnExpression, property.GetKeyValueComparer()));
}
}
else
{
var innerColumns = keyProperties.Select(
p => CreateColumnExpression(p, table, tableReferenceExpression, nullable: false));
var joinPredicate = joinColumns.Zip(innerColumns, (l, r) => sqlExpressionFactory.Equal(l, r))
.Aggregate((l, r) => sqlExpressionFactory.AndAlso(l, r));
var joinExpression = new InnerJoinExpression(tableExpression, joinPredicate);
_removableJoinTables.Add(_tables.Count);
AddTable(joinExpression, tableReferenceExpression);
}
}
foreach (var property in entityType.GetProperties())
{
if (property.IsPrimaryKey())
{
continue;
}
var columnBase = mappings.Select(e => e.Table.FindColumn(property)).First(e => e != null)!;
columns[property] = CreateColumnExpression(
property, columnBase, tableReferenceExpressionMap[columnBase.Table], nullable: false);
}
var entityProjection = new EntityProjectionExpression(entityType, columns);
_projectionMapping[new ProjectionMember()] = entityProjection;
}
}
}
break;
}
void GenerateNonHierarchyNonSplittingEntityType(ITableBase table, TableExpressionBase tableExpression)
{
var tableReferenceExpression = new TableReferenceExpression(this, tableExpression.Alias!);
AddTable(tableExpression, tableReferenceExpression);
var propertyExpressions = new Dictionary<IProperty, ColumnExpression>();
foreach (var property in GetAllPropertiesInHierarchy(entityType))
{
propertyExpressions[property] = CreateColumnExpression(property, table, tableReferenceExpression, nullable: false);
}
var entityProjection = new EntityProjectionExpression(entityType, propertyExpressions);
AddJsonNavigationBindings(entityType, entityProjection, propertyExpressions, tableReferenceExpression);
_projectionMapping[new ProjectionMember()] = entityProjection;
var primaryKey = entityType.FindPrimaryKey();
if (primaryKey != null)
{
foreach (var property in primaryKey.Properties)
{
_identifier.Add((propertyExpressions[property], property.GetKeyValueComparer()));
}
}
}
static ITableBase GetTableBaseFiltered(IEntityType entityType, List<ITableBase> existingTables)
=> entityType.GetViewOrTableMappings().Single(m => !existingTables.Contains(m.Table)).Table;
}
internal SelectExpression(IEntityType entityType, TableExpressionBase tableExpressionBase)
: base(null)
{
if ((entityType.BaseType != null || entityType.GetDirectlyDerivedTypes().Any())
&& entityType.FindDiscriminatorProperty() == null)
{
throw new InvalidOperationException(RelationalStrings.SelectExpressionNonTphWithCustomTable(entityType.DisplayName()));
}
var table = (tableExpressionBase as FromSqlExpression)?.Table ?? ((ITableBasedExpression)tableExpressionBase).Table;
var tableReferenceExpression = new TableReferenceExpression(this, tableExpressionBase.Alias!);
AddTable(tableExpressionBase, tableReferenceExpression);
var propertyExpressions = new Dictionary<IProperty, ColumnExpression>();
foreach (var property in GetAllPropertiesInHierarchy(entityType))
{
propertyExpressions[property] = CreateColumnExpression(property, table, tableReferenceExpression, nullable: false);
}
var entityProjection = new EntityProjectionExpression(entityType, propertyExpressions);
AddJsonNavigationBindings(entityType, entityProjection, propertyExpressions, tableReferenceExpression);
_projectionMapping[new ProjectionMember()] = entityProjection;
var primaryKey = entityType.FindPrimaryKey();
if (primaryKey != null)
{
foreach (var property in primaryKey.Properties)
{
_identifier.Add((propertyExpressions[property], property.GetKeyValueComparer()));
}
}
}
private void AddJsonNavigationBindings(
IEntityType entityType,
EntityProjectionExpression entityProjection,
Dictionary<IProperty, ColumnExpression> propertyExpressions,
TableReferenceExpression tableReferenceExpression)
{
foreach (var ownedJsonNavigation in GetAllNavigationsInHierarchy(entityType)
.Where(
n => n.ForeignKey.IsOwnership
&& n.TargetEntityType.IsMappedToJson()
&& n.ForeignKey.PrincipalToDependent == n))
{
var targetEntityType = ownedJsonNavigation.TargetEntityType;
var jsonColumnName = targetEntityType.GetContainerColumnName()!;
var jsonColumnTypeMapping = targetEntityType.GetContainerColumnTypeMapping()!;
var jsonColumn = new ConcreteColumnExpression(
jsonColumnName,
tableReferenceExpression,
jsonColumnTypeMapping.ClrType,
jsonColumnTypeMapping,
nullable: !ownedJsonNavigation.ForeignKey.IsRequiredDependent || ownedJsonNavigation.IsCollection);
// for json collections we need to skip ordinal key (which is always the last one)
// simple copy from parent is safe here, because we only do it at top level
// so there is no danger of multiple keys being synthesized (like we have in multi-level nav chains)
var keyPropertiesMap = new Dictionary<IProperty, ColumnExpression>();
var keyProperties = targetEntityType.FindPrimaryKey()!.Properties;
var keyPropertiesCount = ownedJsonNavigation.IsCollection
? keyProperties.Count - 1
: keyProperties.Count;
for (var i = 0; i < keyPropertiesCount; i++)
{
var correspondingParentKeyProperty = ownedJsonNavigation.ForeignKey.PrincipalKey.Properties[i];
keyPropertiesMap[keyProperties[i]] = propertyExpressions[correspondingParentKeyProperty];
}
var entityShaperExpression = new RelationalEntityShaperExpression(
targetEntityType,
new JsonQueryExpression(
targetEntityType,
jsonColumn,
keyPropertiesMap,
ownedJsonNavigation.ClrType,
ownedJsonNavigation.IsCollection),
!ownedJsonNavigation.ForeignKey.IsRequiredDependent);
entityProjection.AddNavigationBinding(ownedJsonNavigation, entityShaperExpression);
}
}
/// <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; private 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>
/// 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 sqe && sqe.ResultCardinality == ResultCardinality.Enumerable))
{
throw new InvalidOperationException(RelationalStrings.DistinctOnCollectionNotSupported);
}
if (Limit != null
|| Offset != null)
{
PushdownIntoSubquery();
}
IsDistinct = true;
if (_identifier.Count > 0)
{
var entityProjectionIdentifiers = new List<ColumnExpression>();
var entityProjectionValueComparers = 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)
{
if (projection is EntityProjectionExpression entityProjection)
{
var primaryKey = entityProjection.EntityType.FindPrimaryKey();
// If there are any existing identifier then all entity projection must have a key
// else keyless entity would have wiped identifier when generating join.
Check.DebugAssert(primaryKey != null, "primary key is null.");
foreach (var property in primaryKey.Properties)
{
entityProjectionIdentifiers.Add(entityProjection.BindProperty(property));
entityProjectionValueComparers.Add(property.GetKeyValueComparer());
}
}
else if (projection is JsonQueryExpression jsonQueryExpression)
{
if (jsonQueryExpression.IsCollection)
{
throw new InvalidOperationException(RelationalStrings.DistinctOnCollectionNotSupported);
}
var primaryKeyProperties = jsonQueryExpression.EntityType.FindPrimaryKey()!.Properties;
var primaryKeyPropertiesCount = jsonQueryExpression.IsCollection
? primaryKeyProperties.Count - 1
: primaryKeyProperties.Count;
for (var i = 0; i < primaryKeyPropertiesCount; i++)
{
var keyProperty = primaryKeyProperties[i];
entityProjectionIdentifiers.Add((ColumnExpression)jsonQueryExpression.BindProperty(keyProperty));
entityProjectionValueComparers.Add(keyProperty.GetKeyValueComparer());
}
}
else if (projection is SqlExpression sqlExpression)
{
otherExpressions.Add(sqlExpression);
}
else
{
nonProcessableExpressionFound = true;
break;
}
}
if (nonProcessableExpressionFound)
{
_identifier.Clear();
}
else
{
var allOtherExpressions = entityProjectionIdentifiers.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(entityProjectionIdentifiers.Zip(entityProjectionValueComparers));
}
else if (otherExpressions.All(e => e is ColumnExpression))
{
_identifier.AddRange(entityProjectionIdentifiers.Zip(entityProjectionValueComparers));
_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 (!_mutable)
{
throw new InvalidOperationException("Applying projection on already finalized select expression");
}
_mutable = false;
if (_clientProjections.Count > 0)
{
for (var i = 0; i < _clientProjections.Count; i++)
{
switch (_clientProjections[i])
{
case EntityProjectionExpression entityProjectionExpression:
AddEntityProjection(entityProjectionExpression);
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 EntityProjectionExpression entityProjectionExpression)
{
AddEntityProjection(entityProjectionExpression);
}
else
{
AddToProjection((SqlExpression)expression);
}
}
_projectionMapping.Clear();
}
void AddEntityProjection(EntityProjectionExpression entityProjectionExpression)
{
foreach (var property in GetAllPropertiesInHierarchy(entityProjectionExpression.EntityType))
{
AddToProjection(entityProjectionExpression.BindProperty(property), null);
}
if (entityProjectionExpression.DiscriminatorExpression != null)
{
AddToProjection(entityProjectionExpression.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 (!_mutable)
{
throw new InvalidOperationException("Applying projection on already finalized select expression");
}
_mutable = 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)
{
if (projection is ShapedQueryExpression sqe)
{
if (sqe.ResultCardinality == ResultCardinality.Enumerable)
{
containsCollection = true;
}
if (sqe.ResultCardinality == ResultCardinality.Single
|| sqe.ResultCardinality == ResultCardinality.SingleOrDefault)
{
containsSingleResult = true;
}
}
if (projection is JsonQueryExpression)
{
jsonClientProjectionsCount++;
}
}
if (containsSingleResult
|| (querySplittingBehavior == QuerySplittingBehavior.SingleQuery && containsCollection))
{
// Pushdown outer since we will be adding join to this
// For grouping query pushown 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
cloningExpressionVisitor = new CloningExpressionVisitor();
}
var jsonClientProjectionDeduplicationMap = BuildJsonProjectionDeduplicationMap(_clientProjections.OfType<JsonQueryExpression>());
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 unaryExpression
when unaryExpression.NodeType == ExpressionType.Convert
|| unaryExpression.NodeType == ExpressionType.ConvertChecked:
return unaryExpression.Update(
AddGroupByKeySelectorToProjection(
selectExpression, clientProjectionList, projectionBindingMap, unaryExpression.Operand));
case EntityShaperExpression entityShaperExpression
when entityShaperExpression.ValueBufferExpression is EntityProjectionExpression entityProjectionExpression:
{
var clientProjectionToAdd = AddEntityProjection(entityProjectionExpression);
var existingIndex = clientProjectionList.FindIndex(
e => ExpressionEqualityComparer.Instance.Equals(e, clientProjectionToAdd));
if (existingIndex == -1)
{
clientProjectionList.Add(clientProjectionToAdd);
existingIndex = clientProjectionList.Count - 1;
}
return entityShaperExpression.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 mappedExpresssion))
{
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;