-
Notifications
You must be signed in to change notification settings - Fork 226
/
NpgsqlQueryableMethodTranslatingExpressionVisitor.cs
1203 lines (1078 loc) · 62.8 KB
/
NpgsqlQueryableMethodTranslatingExpressionVisitor.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
using System.Diagnostics.CodeAnalysis;
using Npgsql.EntityFrameworkCore.PostgreSQL.Extensions.Internal;
using Npgsql.EntityFrameworkCore.PostgreSQL.Infrastructure.Internal;
using Npgsql.EntityFrameworkCore.PostgreSQL.Query.Expressions;
using Npgsql.EntityFrameworkCore.PostgreSQL.Query.Expressions.Internal;
using Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal;
using Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.Mapping;
using static Npgsql.EntityFrameworkCore.PostgreSQL.Utilities.Statics;
namespace Npgsql.EntityFrameworkCore.PostgreSQL.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 NpgsqlQueryableMethodTranslatingExpressionVisitor : RelationalQueryableMethodTranslatingExpressionVisitor
{
private readonly RelationalQueryCompilationContext _queryCompilationContext;
private readonly NpgsqlTypeMappingSource _typeMappingSource;
private readonly NpgsqlSqlExpressionFactory _sqlExpressionFactory;
private readonly bool _isRedshift;
private RelationalTypeMapping? _ordinalityTypeMapping;
#region MethodInfos
private static readonly MethodInfo Like2MethodInfo =
typeof(DbFunctionsExtensions).GetRuntimeMethod(
nameof(DbFunctionsExtensions.Like), [typeof(DbFunctions), typeof(string), typeof(string)])!;
// ReSharper disable once InconsistentNaming
private static readonly MethodInfo ILike2MethodInfo
= typeof(NpgsqlDbFunctionsExtensions).GetRuntimeMethod(
nameof(NpgsqlDbFunctionsExtensions.ILike), [typeof(DbFunctions), typeof(string), typeof(string)])!;
private static readonly MethodInfo MatchesLQuery =
typeof(LTree).GetRuntimeMethod(nameof(LTree.MatchesLQuery), [typeof(string)])!;
#endregion
/// <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 NpgsqlQueryableMethodTranslatingExpressionVisitor(
QueryableMethodTranslatingExpressionVisitorDependencies dependencies,
RelationalQueryableMethodTranslatingExpressionVisitorDependencies relationalDependencies,
RelationalQueryCompilationContext queryCompilationContext,
INpgsqlSingletonOptions npgsqlSingletonOptions)
: base(dependencies, relationalDependencies, queryCompilationContext)
{
_queryCompilationContext = queryCompilationContext;
_typeMappingSource = (NpgsqlTypeMappingSource)relationalDependencies.TypeMappingSource;
_sqlExpressionFactory = (NpgsqlSqlExpressionFactory)relationalDependencies.SqlExpressionFactory;
_isRedshift = npgsqlSingletonOptions.UseRedshift;
}
/// <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 NpgsqlQueryableMethodTranslatingExpressionVisitor(NpgsqlQueryableMethodTranslatingExpressionVisitor parentVisitor)
: base(parentVisitor)
{
_queryCompilationContext = parentVisitor._queryCompilationContext;
_typeMappingSource = parentVisitor._typeMappingSource;
_sqlExpressionFactory = parentVisitor._sqlExpressionFactory;
_isRedshift = parentVisitor._isRedshift;
}
/// <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 NpgsqlQueryableMethodTranslatingExpressionVisitor(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>
protected override ShapedQueryExpression? TranslatePrimitiveCollection(
SqlExpression sqlExpression,
IProperty? property,
string tableAlias)
{
if (_isRedshift)
{
AddTranslationErrorDetails("Redshift does not support unnest, which is required for most forms of querying of JSON arrays.");
return null;
}
var elementClrType = sqlExpression.Type.GetSequenceType();
var elementTypeMapping = (RelationalTypeMapping?)sqlExpression.TypeMapping?.ElementTypeMapping;
// If this is a collection property, get the element's nullability out of metadata. Otherwise, this is a parameter property, in
// which case we only have the CLR type (note that we cannot produce different SQLs based on the nullability of an *element* in
// a parameter collection - our caching mechanism only supports varying by the nullability of the parameter itself (i.e. the
// collection).
// TODO: if property is non-null, GetElementType() should never be null, but we have #31469 for shadow properties
var isElementNullable = property?.GetElementType() is null
? elementClrType.IsNullableType()
: property.GetElementType()!.IsNullable;
// We support two kinds of primitive collections: the standard one with PostgreSQL arrays (where we use the unnest function), and
// a special case for geometry collections, where we use
SelectExpression selectExpression;
#pragma warning disable EF1001 // SelectExpression constructors are currently internal
// TODO: Parameters have no type mapping. We can check whether the expression type is one of the NTS geometry collection types,
// though in a perfect world we'd actually infer this. In other words, when the type mapping of the element is inferred further on,
// we'd replace the unnest expression with ST_Dump. We could even have a special expression type which means "indeterminate, must be
// inferred".
if (sqlExpression.TypeMapping is { StoreTypeNameBase: "geometry" or "geography" })
{
// TODO: For geometry collection support (not yet supported), see #2850.
selectExpression = new SelectExpression(
[new TableValuedFunctionExpression(tableAlias, "ST_Dump", [sqlExpression])],
new ColumnExpression("geom", tableAlias, elementClrType.UnwrapNullableType(), elementTypeMapping, isElementNullable),
identifier: [], // TODO
_queryCompilationContext.SqlAliasManager);
}
else
{
// Note that for unnest we have a special expression type extending TableValuedFunctionExpression, adding the ability to provide
// an explicit column name for its output (SELECT * FROM unnest(array) AS f(foo)).
// This is necessary since when the column name isn't explicitly specified, it is automatically identical to the table alias
// (f above); since the table alias may get uniquified by EF, this would break queries.
// TODO: When we have metadata to determine if the element is nullable, pass that here to SelectExpression
// Note also that with PostgreSQL unnest, the output ordering is guaranteed to be the same as the input array. However, we still
// need to add an explicit ordering on the ordinality column, since once the unnest is joined into a select, its "natural"
// orderings is lost and an explicit ordering is needed again (see #3207).
var (ordinalityColumn, ordinalityComparer) = GenerateOrdinalityIdentifier(tableAlias);
selectExpression = new SelectExpression(
[new PgUnnestExpression(tableAlias, sqlExpression, "value")],
new ColumnExpression(
"value",
tableAlias,
elementClrType.UnwrapNullableType(),
elementTypeMapping,
isElementNullable),
identifier: [(ordinalityColumn, ordinalityComparer)],
_queryCompilationContext.SqlAliasManager);
selectExpression.AppendOrdering(new OrderingExpression(ordinalityColumn, ascending: true));
}
#pragma warning restore EF1001
Expression shaperExpression = new ProjectionBindingExpression(
selectExpression, new ProjectionMember(), elementClrType.MakeNullable());
if (elementClrType != shaperExpression.Type)
{
Check.DebugAssert(
elementClrType.MakeNullable() == shaperExpression.Type,
"expression.Type must be nullable of targetType");
shaperExpression = Expression.Convert(shaperExpression, elementClrType);
}
return new ShapedQueryExpression(selectExpression, 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 TransformJsonQueryToTable(JsonQueryExpression jsonQueryExpression)
{
// Calculate the table alias for the jsonb_to_recordset function based on the last named path segment
// (or the JSON column name if there are none)
var lastNamedPathSegment = jsonQueryExpression.Path.LastOrDefault(ps => ps.PropertyName is not null);
var tableAlias =
_queryCompilationContext.SqlAliasManager.GenerateTableAlias(
lastNamedPathSegment.PropertyName ?? jsonQueryExpression.JsonColumn.Name);
// TODO: This relies on nested JSON columns flowing across the type mapping of the top-most containing JSON column, check this.
var functionName = jsonQueryExpression.JsonColumn switch
{
{ TypeMapping.StoreType: "jsonb" } => "jsonb_to_recordset",
{ TypeMapping.StoreType: "json" } => "json_to_recordset",
{ TypeMapping: null } => throw new UnreachableException("Missing type mapping on JSON column"),
_ => throw new UnreachableException()
};
var jsonTypeMapping = jsonQueryExpression.JsonColumn.TypeMapping!;
Check.DebugAssert(jsonTypeMapping is NpgsqlOwnedJsonTypeMapping, "JSON column has a non-JSON mapping");
// We now add all of projected entity's the properties and navigations into the jsonb_to_recordset's AS clause, which defines the
// names and types of columns to come out of the JSON fragments.
var columnInfos = new List<PgTableValuedFunctionExpression.ColumnInfo>();
// We're only interested in properties which actually exist in the JSON, filter out uninteresting shadow keys
foreach (var property in GetAllPropertiesInHierarchy(jsonQueryExpression.EntityType))
{
if (property.GetJsonPropertyName() is string jsonPropertyName)
{
columnInfos.Add(
new PgTableValuedFunctionExpression.ColumnInfo
{
Name = jsonPropertyName, TypeMapping = property.GetRelationalTypeMapping()
});
}
}
// Navigations represent nested JSON owned entities, which we also add to the AS clause, but with the JSON type.
foreach (var navigation in GetAllNavigationsInHierarchy(jsonQueryExpression.EntityType)
.Where(
n => n.ForeignKey.IsOwnership
&& n.TargetEntityType.IsMappedToJson()
&& n.ForeignKey.PrincipalToDependent == n))
{
var jsonNavigationName = navigation.TargetEntityType.GetJsonPropertyName();
Check.DebugAssert(jsonNavigationName is not null, $"No JSON property name for navigation {navigation.Name}");
columnInfos.Add(
new PgTableValuedFunctionExpression.ColumnInfo { Name = jsonNavigationName, TypeMapping = jsonTypeMapping });
}
// json_to_recordset requires the nested JSON document - it does not accept a path within a containing JSON document (like SQL
// Server OPENJSON or SQLite json_each). So we wrap json_to_recordset around a JsonScalarExpression which will extract the nested
// document.
var jsonScalarExpression = new JsonScalarExpression(
jsonQueryExpression.JsonColumn, jsonQueryExpression.Path, typeof(string), jsonTypeMapping, jsonQueryExpression.IsNullable);
// Construct the json_to_recordset around the JsonScalarExpression, and wrap it in a SelectExpression
var jsonToRecordSetExpression = new PgTableValuedFunctionExpression(
tableAlias, functionName, [jsonScalarExpression], columnInfos, withOrdinality: true);
#pragma warning disable EF1001 // SelectExpression constructors are currently internal
var selectExpression = CreateSelect(
jsonQueryExpression,
jsonToRecordSetExpression,
"ordinality",
typeof(int),
_typeMappingSource.FindMapping(typeof(int))!);
#pragma warning restore EF1001 // Internal EF Core API usage.
return new ShapedQueryExpression(
selectExpression,
new RelationalStructuralTypeShaperExpression(
jsonQueryExpression.EntityType,
new ProjectionBindingExpression(
selectExpression,
new ProjectionMember(),
typeof(ValueBuffer)),
false));
// TODO: Move these to IEntityType?
static IEnumerable<IProperty> GetAllPropertiesInHierarchy(IEntityType entityType)
=> entityType.GetAllBaseTypes().Concat(entityType.GetDerivedTypesInclusive())
.SelectMany(t => t.GetDeclaredProperties());
static IEnumerable<INavigation> GetAllNavigationsInHierarchy(IEntityType entityType)
=> entityType.GetAllBaseTypes().Concat(entityType.GetDerivedTypesInclusive())
.SelectMany(t => t.GetDeclaredNavigations());
}
/// <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)
{
if ((source.TryExtractArray(out var array, ignoreOrderings: true)
|| source.TryConvertValuesToArray(out array, ignoreOrderings: true))
&& source.QueryExpression is SelectExpression { Tables: [{ Alias: var tableAlias }] }
&& TranslateLambdaExpression(source, predicate) is { } translatedPredicate)
{
switch (translatedPredicate)
{
// Pattern match for: new[] { "a", "b", "c" }.All(p => EF.Functions.Like(e.SomeText, p)),
// which we translate to WHERE s.""SomeText"" LIKE ALL (ARRAY['a','b','c'])
case LikeExpression
{
Match: var match,
Pattern: ColumnExpression pattern,
EscapeChar: SqlConstantExpression { Value: "" }
}
when pattern.TableAlias == tableAlias:
{
return BuildSimplifiedShapedQuery(
source,
_sqlExpressionFactory.All(match, array, PgAllOperatorType.Like));
}
// Pattern match for: new[] { "a", "b", "c" }.All(p => EF.Functions.Like(e.SomeText, p)),
// which we translate to WHERE s.""SomeText"" LIKE ALL (ARRAY['a','b','c'])
case PgILikeExpression
{
Match: var match,
Pattern: ColumnExpression pattern,
EscapeChar: SqlConstantExpression { Value: "" }
}
when pattern.TableAlias == tableAlias:
{
return BuildSimplifiedShapedQuery(
source,
_sqlExpressionFactory.All(match, array, PgAllOperatorType.ILike));
}
// Pattern match for: e.SomeArray.All(p => ints.Contains(p)) over non-column,
// using array containment (<@)
case PgAnyExpression
{
Item: ColumnExpression sourceColumn,
Array: var otherArray
}
when sourceColumn.TableAlias == tableAlias:
{
return BuildSimplifiedShapedQuery(source, _sqlExpressionFactory.ContainedBy(array, otherArray));
}
// Pattern match for: new[] { 4, 5 }.All(p => e.SomeArray.Contains(p)) over column,
// using array containment (<@)
case PgBinaryExpression
{
OperatorType: PgExpressionType.Contains,
Left: var otherArray,
Right: PgNewArrayExpression { Expressions: [ColumnExpression sourceColumn] }
}
when sourceColumn.TableAlias == tableAlias:
{
return BuildSimplifiedShapedQuery(source, _sqlExpressionFactory.ContainedBy(array, otherArray));
}
}
}
return base.TranslateAll(source, predicate);
}
/// <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 ((source.TryExtractArray(out var array, ignoreOrderings: true)
|| source.TryConvertValuesToArray(out array, ignoreOrderings: true))
&& source.QueryExpression is SelectExpression { Tables: [{ Alias: var tableAlias }] })
{
// Pattern match: x.Array.Any()
// Translation: cardinality(x.array) > 0 instead of EXISTS (SELECT 1 FROM FROM unnest(x.Array))
if (predicate is null)
{
return BuildSimplifiedShapedQuery(
source,
_sqlExpressionFactory.GreaterThan(
_sqlExpressionFactory.Function(
"cardinality",
[array],
nullable: true,
argumentsPropagateNullability: TrueArrays[1],
typeof(int)),
_sqlExpressionFactory.Constant(0)));
}
if (TranslateLambdaExpression(source, predicate) is not SqlExpression translatedPredicate)
{
return null;
}
switch (translatedPredicate)
{
// Pattern match: new[] { "a", "b", "c" }.Any(p => EF.Functions.Like(e.SomeText, p))
// Translation: s.SomeText LIKE ANY (ARRAY['a','b','c'])
case LikeExpression
{
Match: var match,
Pattern: ColumnExpression pattern,
EscapeChar: SqlConstantExpression { Value: "" }
}
when pattern.TableAlias == tableAlias:
{
return BuildSimplifiedShapedQuery(
source, _sqlExpressionFactory.Any(match, array, PgAnyOperatorType.Like));
}
// Pattern match: new[] { "a", "b", "c" }.Any(p => EF.Functions.Like(e.SomeText, p))
// Translation: s.SomeText LIKE ANY (ARRAY['a','b','c'])
case PgILikeExpression
{
Match: var match,
Pattern: ColumnExpression pattern,
EscapeChar: SqlConstantExpression { Value: "" }
}
when pattern.TableAlias == tableAlias:
{
return BuildSimplifiedShapedQuery(
source, _sqlExpressionFactory.Any(match, array, PgAnyOperatorType.ILike));
}
// Array overlap over non-column
// Pattern match: e.SomeArray.Any(p => ints.Contains(p))
// Translation: @ints && s.SomeArray
case PgAnyExpression
{
Item: ColumnExpression sourceColumn,
Array: var otherArray
}
when sourceColumn.TableAlias == tableAlias:
{
return BuildSimplifiedShapedQuery(source, _sqlExpressionFactory.Overlaps(array, otherArray));
}
// Array overlap over column
// Pattern match: new[] { 4, 5 }.Any(p => e.SomeArray.Contains(p))
// Translation: s.SomeArray && ARRAY[4, 5]
case PgBinaryExpression
{
OperatorType: PgExpressionType.Contains,
Left: var otherArray,
Right: PgNewArrayExpression { Expressions: [ColumnExpression sourceColumn] }
}
when sourceColumn.TableAlias == tableAlias:
{
return BuildSimplifiedShapedQuery(source, _sqlExpressionFactory.Overlaps(array, otherArray));
}
#region LTree translations
// Pattern match: new[] { "q1", "q2" }.Any(q => e.SomeLTree.MatchesLQuery(q))
// Translation: s.SomeLTree ? ARRAY['q1','q2']
case PgBinaryExpression
{
OperatorType: PgExpressionType.LTreeMatches,
Left: var ltree,
Right: SqlUnaryExpression { OperatorType: ExpressionType.Convert, Operand: ColumnExpression lqueryColumn }
}
when lqueryColumn.TableAlias == tableAlias:
{
return BuildSimplifiedShapedQuery(
source,
new PgBinaryExpression(
PgExpressionType.LTreeMatchesAny,
ltree,
_sqlExpressionFactory.ApplyTypeMapping(array, _typeMappingSource.FindMapping("lquery[]")),
typeof(bool),
typeMapping: _typeMappingSource.FindMapping(typeof(bool))));
}
// Pattern match: new[] { "t1", "t2" }.Any(t => t.IsAncestorOf(e.SomeLTree))
// Translation: ARRAY['t1','t2'] @> s.SomeLTree
// Pattern match: new[] { "t1", "t2" }.Any(t => t.IsDescendantOf(e.SomeLTree))
// Translation: ARRAY['t1','t2'] <@ s.SomeLTree
case PgBinaryExpression
{
OperatorType: (PgExpressionType.Contains or PgExpressionType.ContainedBy) and var operatorType,
Left: ColumnExpression ltreeColumn,
// Contains/ContainedBy can happen for non-LTree types too, so check that
Right: { TypeMapping: NpgsqlLTreeTypeMapping } ltree
}
when ltreeColumn.TableAlias == tableAlias:
{
return BuildSimplifiedShapedQuery(
source,
new PgBinaryExpression(
operatorType,
_sqlExpressionFactory.ApplyDefaultTypeMapping(array),
ltree,
typeof(bool),
typeMapping: _typeMappingSource.FindMapping(typeof(bool))));
}
// Pattern match: new[] { "t1", "t2" }.Any(t => t.MatchesLQuery(lquery))
// Translation: ARRAY['t1','t2'] ~ lquery
// Pattern match: new[] { "t1", "t2" }.Any(t => t.MatchesLTxtQuery(ltxtquery))
// Translation: ARRAY['t1','t2'] @ ltxtquery
case PgBinaryExpression
{
OperatorType: PgExpressionType.LTreeMatches,
Left: ColumnExpression ltreeColumn,
Right: var lquery
}
when ltreeColumn.TableAlias == tableAlias:
{
return BuildSimplifiedShapedQuery(
source,
new PgBinaryExpression(
PgExpressionType.LTreeMatches,
_sqlExpressionFactory.ApplyDefaultTypeMapping(array),
lquery,
typeof(bool),
typeMapping: _typeMappingSource.FindMapping(typeof(bool))));
}
// Any within Any (i.e. intersection)
// Pattern match: ltrees.Any(t => lqueries.Any(q => t.MatchesLQuery(q)))
// Translate: ltrees ? lqueries
case PgBinaryExpression
{
OperatorType: PgExpressionType.LTreeMatchesAny,
Left: ColumnExpression ltreeColumn,
Right: var lqueries
}
when ltreeColumn.TableAlias == tableAlias:
{
return BuildSimplifiedShapedQuery(
source,
new PgBinaryExpression(
PgExpressionType.LTreeMatchesAny,
_sqlExpressionFactory.ApplyDefaultTypeMapping(array),
lqueries,
typeof(bool),
typeMapping: _typeMappingSource.FindMapping(typeof(bool))));
}
#endregion LTree translations
}
}
// Pattern match: x.Array1.Intersect(x.Array2).Any()
// Translation: x.Array1 && x.Array2
if (predicate is null
&& source.QueryExpression is SelectExpression
{
Tables:
[
IntersectExpression
{
Source1:
{
Tables: [PgUnnestExpression { Array: var array1 }],
Predicate: null,
GroupBy: [],
Having: null,
IsDistinct: false,
Limit: null,
Offset: null
},
Source2:
{
Tables: [PgUnnestExpression { Array: var array2 }],
Predicate: null,
GroupBy: [],
Having: null,
IsDistinct: false,
Limit: null,
Offset: null
}
}
],
GroupBy: [],
Having: null,
IsDistinct: false,
Limit: null,
Offset: null
})
{
return BuildSimplifiedShapedQuery(source, _sqlExpressionFactory.Overlaps(array1, array2));
}
return base.TranslateAny(source, predicate);
}
/// <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)
{
// Note that most other simplifications convert ValuesExpression to unnest over array constructor, but we avoid doing that
// here for Contains, since the relational translation for ValuesExpression is better.
if (source.TryExtractArray(out var array, ignoreOrderings: true)
&& TranslateExpression(item, applyDefaultTypeMapping: false) is SqlExpression translatedItem)
{
(translatedItem, array) = _sqlExpressionFactory.ApplyTypeMappingsOnItemAndArray(translatedItem, array);
// When the array is a column, we translate Contains to array @> ARRAY[item]. GIN indexes on array are used, but null
// semantics is impossible without preventing index use.
switch (array)
{
case ColumnExpression:
if (translatedItem is SqlConstantExpression { Value: null })
{
// We special-case null constant item and use array_position instead, since it does
// nulls correctly (but doesn't use indexes)
// TODO: once lambda-based caching is implemented, move this to NpgsqlSqlNullabilityProcessor
// (https://github.com/dotnet/efcore/issues/17598) and do for parameters as well.
return BuildSimplifiedShapedQuery(
source,
_sqlExpressionFactory.IsNotNull(
_sqlExpressionFactory.Function(
"array_position",
[array, translatedItem],
nullable: true,
argumentsPropagateNullability: FalseArrays[2],
typeof(int))));
}
return BuildSimplifiedShapedQuery(
source,
_sqlExpressionFactory.Contains(
array,
_sqlExpressionFactory.NewArrayOrConstant([translatedItem], array.Type, array.TypeMapping)));
// For constant arrays (new[] { 1, 2, 3 }) or inline arrays (new[] { 1, param, 3 }), don't do anything PG-specific for since
// the general EF Core mechanism is fine for that case: item IN (1, 2, 3).
case SqlConstantExpression or PgNewArrayExpression:
break;
// Similar to ParameterExpression below, but when a bare subquery is present inside ANY(), PostgreSQL just compares
// against each of its resulting rows (just like IN). To "extract" the array result of the scalar subquery, we need
// to add an explicit cast (see #1803).
case ScalarSubqueryExpression subqueryExpression:
return BuildSimplifiedShapedQuery(
source,
_sqlExpressionFactory.Any(
translatedItem,
_sqlExpressionFactory.Convert(
subqueryExpression, subqueryExpression.Type, subqueryExpression.TypeMapping),
PgAnyOperatorType.Equal));
// For ParameterExpression, and for all other cases - e.g. array returned from some function -
// translate to e.SomeText = ANY (@p). This is superior to the general solution which will expand
// parameters to constants, since non-PG SQL does not support arrays.
// Note that this will allow indexes on the item to be used.
default:
return BuildSimplifiedShapedQuery(
source, _sqlExpressionFactory.Any(translatedItem, array, PgAnyOperatorType.Equal));
}
}
return base.TranslateContains(source, item);
}
/// <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)
{
// Simplify x.Array.Count() => cardinality(x.Array) instead of SELECT COUNT(*) FROM unnest(x.Array)
if (predicate is null && source.TryExtractArray(out var array, ignoreOrderings: true))
{
var translation = _sqlExpressionFactory.Function(
"cardinality",
[array],
nullable: true,
argumentsPropagateNullability: TrueArrays[1],
typeof(int));
#pragma warning disable EF1001 // SelectExpression constructors are currently internal
return source.Update(
new SelectExpression(translation, _queryCompilationContext.SqlAliasManager),
Expression.Convert(
new ProjectionBindingExpression(source.QueryExpression, new ProjectionMember(), typeof(int?)),
typeof(int)));
#pragma warning restore EF1001
}
return base.TranslateCount(source, predicate);
}
/// <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)
{
// Simplify x.Array.Concat(y.Array) => x.Array || y.Array instead of:
// SELECT u.value FROM unnest(x.Array) UNION ALL SELECT u.value FROM unnest(y.Array)
if (source1.TryExtractArray(out var array1, out var projectedColumn1)
&& source2.TryExtractArray(out var array2, out var projectedColumn2))
{
Check.DebugAssert(projectedColumn1.Type == projectedColumn2.Type, "projectedColumn1.Type == projectedColumn2.Type");
Check.DebugAssert(
projectedColumn1.TypeMapping is not null || projectedColumn2.TypeMapping is not null,
"Concat with no type mapping on either side (operation should be client-evaluated over parameters/constants");
// TODO: Conflicting type mappings from both sides?
var inferredTypeMapping = projectedColumn1.TypeMapping ?? projectedColumn2.TypeMapping;
#pragma warning disable EF1001 // SelectExpression constructors are currently internal
var tableAlias = ((SelectExpression)source1.QueryExpression).Tables.Single().Alias!;
var selectExpression = new SelectExpression(
[new PgUnnestExpression(tableAlias, _sqlExpressionFactory.Add(array1, array2), "value")],
new ColumnExpression("value", tableAlias, projectedColumn1.Type, inferredTypeMapping, projectedColumn1.IsNullable || projectedColumn2.IsNullable),
identifier: [GenerateOrdinalityIdentifier(tableAlias)],
_queryCompilationContext.SqlAliasManager);
#pragma warning restore EF1001 // Internal EF Core API usage.
// TODO: Simplify by using UpdateQueryExpression after https://github.com/dotnet/efcore/issues/31511
Expression shaperExpression = new ProjectionBindingExpression(
selectExpression, new ProjectionMember(), source1.ShaperExpression.Type.MakeNullable());
if (source1.ShaperExpression.Type != shaperExpression.Type)
{
Check.DebugAssert(
source1.ShaperExpression.Type.MakeNullable() == shaperExpression.Type,
"expression.Type must be nullable of targetType");
shaperExpression = Expression.Convert(shaperExpression, source1.ShaperExpression.Type);
}
return new ShapedQueryExpression(selectExpression, shaperExpression);
}
return base.TranslateConcat(source1, source2);
}
/// <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)
{
// Simplify x.Array[1] => x.Array[1] (using the PG array subscript operator) instead of a subquery with LIMIT/OFFSET
// Note that we have unnest over multiranges, not just arrays - but multiranges don't support subscripting/slicing.
if (!returnDefault
&& source.TryExtractArray(out var array, out var projectedColumn)
&& TranslateExpression(index) is { } translatedIndex)
{
// Note that PostgreSQL arrays are 1-based, so adjust the index.
#pragma warning disable EF1001 // SelectExpression constructors are currently internal
return source.UpdateQueryExpression(
new SelectExpression(
_sqlExpressionFactory.ArrayIndex(
array,
GenerateOneBasedIndexExpression(translatedIndex), projectedColumn.IsNullable),
_queryCompilationContext.SqlAliasManager));
#pragma warning restore EF1001
}
return base.TranslateElementAtOrDefault(source, index, returnDefault);
}
/// <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)
{
// Some LTree translations (see LTreeQueryTest)
// Note that preprocessing normalizes FirstOrDefault(predicate) to Where(predicate).FirstOrDefault(), so the source's
// select expression should already contain our predicate.
if ((source.TryExtractArray(out var array, ignorePredicate: true)
|| source.TryConvertValuesToArray(out array, ignorePredicate: true))
&& source.QueryExpression is SelectExpression { Tables: [{ Alias: var tableAlias }], Predicate: var translatedPredicate }
&& translatedPredicate is null ^ predicate is null)
{
if (translatedPredicate is null)
{
translatedPredicate = TranslateLambdaExpression(source, predicate!);
if (translatedPredicate is null)
{
return null;
}
}
switch (translatedPredicate)
{
// Pattern match: new[] { "t1", "t2" }.FirstOrDefault(t => t.IsAncestorOf(e.SomeLTree))
// Translation: ARRAY['t1','t2'] ?@> e.SomeLTree
// Pattern match: new[] { "t1", "t2" }.FirstOrDefault(t => t.IsDescendant(e.SomeLTree))
// Translation: ARRAY['t1','t2'] ?<@ e.SomeLTree
case PgBinaryExpression
{
OperatorType: (PgExpressionType.Contains or PgExpressionType.ContainedBy) and var operatorType,
Left: ColumnExpression ltreeColumn,
// Contains/ContainedBy can happen for non-LTree types too, so check that
Right: { TypeMapping: NpgsqlLTreeTypeMapping } ltree
}
when ltreeColumn.TableAlias == tableAlias:
{
return BuildSimplifiedShapedQuery(
source,
new PgBinaryExpression(
operatorType == PgExpressionType.Contains
? PgExpressionType.LTreeFirstAncestor
: PgExpressionType.LTreeFirstDescendent,
_sqlExpressionFactory.ApplyDefaultTypeMapping(array),
ltree,
typeof(LTree),
_typeMappingSource.FindMapping(typeof(LTree))));
}
// Pattern match: new[] { "t1", "t2" }.FirstOrDefault(t => t.MatchesLQuery(lquery))
// Translation: ARRAY['t1','t2'] ?~ e.lquery
// Pattern match: new[] { "t1", "t2" }.FirstOrDefault(t => t.MatchesLQuery(ltxtquery))
// Translation: ARRAY['t1','t2'] ?@ e.ltxtquery
case PgBinaryExpression
{
OperatorType: PgExpressionType.LTreeMatches,
Left: ColumnExpression ltreeColumn,
Right: var lquery
}
when ltreeColumn.TableAlias == tableAlias:
{
return BuildSimplifiedShapedQuery(
source,
new PgBinaryExpression(
PgExpressionType.LTreeFirstMatches,
_sqlExpressionFactory.ApplyDefaultTypeMapping(array),
lquery,
typeof(LTree),
_typeMappingSource.FindMapping(typeof(LTree))));
}
}
}
return base.TranslateFirstOrDefault(source, predicate, returnType, returnDefault);
}
/// <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? TranslateSkip(ShapedQueryExpression source, Expression count)
{
// Translate Skip over array to the PostgreSQL slice operator (array.Skip(2) -> array[3,])
// Note that we have unnest over multiranges, not just arrays - but multiranges don't support subscripting/slicing.
if (source.TryExtractArray(out var array, out var projectedColumn)
&& TranslateExpression(count) is { } translatedCount)
{
#pragma warning disable EF1001 // SelectExpression constructors are currently internal
var tableAlias = ((SelectExpression)source.QueryExpression).Tables[0].Alias!;
var selectExpression = new SelectExpression(
[
new PgUnnestExpression(
tableAlias,
_sqlExpressionFactory.ArraySlice(
array,
lowerBound: GenerateOneBasedIndexExpression(translatedCount),
upperBound: null,
// isColumnNullable: /*projectedColumn.IsNullable*/ true, // TODO: This fails because of a shaper check
projectedColumn.IsNullable),
"value"),
],
new ColumnExpression("value", tableAlias, projectedColumn.Type, projectedColumn.TypeMapping, projectedColumn.IsNullable),
identifier: [GenerateOrdinalityIdentifier(tableAlias)],
_queryCompilationContext.SqlAliasManager);
#pragma warning restore EF1001
// TODO: Simplify by using UpdateQueryExpression after https://github.com/dotnet/efcore/issues/31511
Expression shaperExpression = new ProjectionBindingExpression(
selectExpression, new ProjectionMember(), source.ShaperExpression.Type.MakeNullable());
if (source.ShaperExpression.Type != shaperExpression.Type)
{
Check.DebugAssert(
source.ShaperExpression.Type.MakeNullable() == shaperExpression.Type,
"expression.Type must be nullable of targetType");
shaperExpression = Expression.Convert(shaperExpression, source.ShaperExpression.Type);
}
return new ShapedQueryExpression(selectExpression, shaperExpression);
}
return base.TranslateSkip(source, count);
}
/// <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? TranslateTake(ShapedQueryExpression source, Expression count)
{
// Translate Take over array to the PostgreSQL slice operator (array.Take(2) -> array[,2])
// Note that we have unnest over multiranges, not just arrays - but multiranges don't support subscripting/slicing.
if (source.TryExtractArray(out var array, out var projectedColumn)
&& TranslateExpression(count) is { } translatedCount)
{
PgArraySliceExpression sliceExpression;
// If Skip has been called before, an array slice expression is already there; try to integrate this Take into it.
// Note that we need to take the Skip (lower bound) into account for the Take (upper bound), since the slice upper bound
// operates on the original array (Skip hasn't yet taken place).
if (array is PgArraySliceExpression existingSliceExpression)
{
if (existingSliceExpression is
{
LowerBound: SqlConstantExpression { Value: int lowerBoundValue } lowerBound,
UpperBound: null
})
{
sliceExpression = existingSliceExpression.Update(
existingSliceExpression.Array,
existingSliceExpression.LowerBound,
translatedCount is SqlConstantExpression { Value: int takeCount }
? _sqlExpressionFactory.Constant(lowerBoundValue + takeCount - 1, lowerBound.TypeMapping)
: _sqlExpressionFactory.Subtract(
_sqlExpressionFactory.Add(lowerBound, translatedCount),
_sqlExpressionFactory.Constant(1, lowerBound.TypeMapping)));
}
else
{
// For any other case, we allow relational to translate with normal querying. For non-constant lower bounds, we could
// duplicate them into the upper bound, but that could cause expensive double evaluation.
return base.TranslateTake(source, count);
}
}
else
{
sliceExpression = _sqlExpressionFactory.ArraySlice(
array,
lowerBound: null,
upperBound: translatedCount,
projectedColumn.IsNullable);
}
#pragma warning disable EF1001 // SelectExpression constructors are currently internal
var tableAlias = ((SelectExpression)source.QueryExpression).Tables[0].Alias!;
var selectExpression = new SelectExpression(
[new PgUnnestExpression(tableAlias, sliceExpression, "value")],
new ColumnExpression("value", tableAlias, projectedColumn.Type, projectedColumn.TypeMapping, projectedColumn.IsNullable),
[GenerateOrdinalityIdentifier(tableAlias)],
_queryCompilationContext.SqlAliasManager);
#pragma warning restore EF1001 // Internal EF Core API usage.
// TODO: Simplify by using UpdateQueryExpression after https://github.com/dotnet/efcore/issues/31511
Expression shaperExpression = new ProjectionBindingExpression(
selectExpression, new ProjectionMember(), source.ShaperExpression.Type.MakeNullable());
if (source.ShaperExpression.Type != shaperExpression.Type)
{
Check.DebugAssert(
source.ShaperExpression.Type.MakeNullable() == shaperExpression.Type,
"expression.Type must be nullable of targetType");
shaperExpression = Expression.Convert(shaperExpression, source.ShaperExpression.Type);
}
return new ShapedQueryExpression(selectExpression, shaperExpression);
}
return base.TranslateTake(source, count);
}
/// <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? TranslateWhere(ShapedQueryExpression source, LambdaExpression predicate)
{
// Simplify x.Array.Where(i => i != 3) => array_remove(x.Array, 3) instead of subquery
if (predicate.Body is BinaryExpression
{
NodeType: ExpressionType.NotEqual,
Left: var left,
Right: var right
}
&& (left == predicate.Parameters[0] ? right : right == predicate.Parameters[0] ? left : null) is Expression itemToFilterOut
&& source.TryExtractArray(out var array, out var projectedColumn)
&& TranslateExpression(itemToFilterOut) is SqlExpression translatedItemToFilterOut)
{
var simplifiedTranslation = _sqlExpressionFactory.Function(
"array_remove",
[array, translatedItemToFilterOut],
nullable: true,
argumentsPropagateNullability: TrueArrays[2],
array.Type,
array.TypeMapping);
#pragma warning disable EF1001 // SelectExpression constructors are currently internal
var tableAlias = ((SelectExpression)source.QueryExpression).Tables[0].Alias!;
var selectExpression = new SelectExpression(