-
Notifications
You must be signed in to change notification settings - Fork 257
Expand file tree
/
Copy pathNpgsqlQuerySqlGenerator.cs
More file actions
1703 lines (1435 loc) · 66.5 KB
/
NpgsqlQuerySqlGenerator.cs
File metadata and controls
1703 lines (1435 loc) · 66.5 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
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.NetworkInformation;
using System.Text.RegularExpressions;
using Npgsql.EntityFrameworkCore.PostgreSQL.Query.Expressions;
using Npgsql.EntityFrameworkCore.PostgreSQL.Query.Expressions.Internal;
using Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.Mapping;
namespace Npgsql.EntityFrameworkCore.PostgreSQL.Query.Internal;
/// <summary>
/// The default query SQL generator for Npgsql.
/// </summary>
public class NpgsqlQuerySqlGenerator : QuerySqlGenerator
{
private readonly ISqlGenerationHelper _sqlGenerationHelper;
private readonly IRelationalTypeMappingSource _typeMappingSource;
private RelationalTypeMapping? _textTypeMapping;
/// <summary>
/// True if null ordering is reversed; otherwise false.
/// </summary>
private readonly bool _reverseNullOrderingEnabled;
private readonly Version _postgresVersion;
/// <summary>
/// True for PG17 and above (JSON_VALUE, JSON_QUERY)
/// </summary>
private readonly bool _useNewJsonFunctions;
/// <inheritdoc />
public NpgsqlQuerySqlGenerator(
QuerySqlGeneratorDependencies dependencies,
IRelationalTypeMappingSource typeMappingSource,
bool reverseNullOrderingEnabled,
Version postgresVersion)
: base(dependencies)
{
_sqlGenerationHelper = dependencies.SqlGenerationHelper;
_typeMappingSource = typeMappingSource;
_reverseNullOrderingEnabled = reverseNullOrderingEnabled;
_postgresVersion = postgresVersion;
_useNewJsonFunctions = postgresVersion >= new Version(17, 0);
}
/// <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 Expression VisitExtension(Expression extensionExpression)
=> extensionExpression switch
{
PgAllExpression e => VisitArrayAll(e),
PgAnyExpression e => VisitArrayAny(e),
PgArrayIndexExpression e => VisitArrayIndex(e),
PgArraySliceExpression e => VisitArraySlice(e),
PgBinaryExpression e => VisitPgBinary(e),
PgDeleteExpression e => VisitPgDelete(e),
PgFunctionExpression e => VisitPgFunction(e),
PgILikeExpression e => VisitILike(e),
PgJsonTraversalExpression e => VisitJsonPathTraversal(e),
PgNewArrayExpression e => VisitNewArray(e),
PgRegexMatchExpression e => VisitRegexMatch(e),
PgRowValueExpression e => VisitRowValue(e),
PgUnknownBinaryExpression e => VisitUnknownBinary(e),
PgTableValuedFunctionExpression e => VisitPgTableValuedFunctionExpression(e),
_ => base.VisitExtension(extensionExpression)
};
/// <inheritdoc />
protected override void GenerateRootCommand(Expression queryExpression)
{
switch (queryExpression)
{
case PgDeleteExpression postgresDeleteExpression:
GenerateTagsHeaderComment(postgresDeleteExpression.Tags);
VisitPgDelete(postgresDeleteExpression);
break;
default:
base.GenerateRootCommand(queryExpression);
break;
}
}
/// <inheritdoc />
protected override void GenerateLimitOffset(SelectExpression selectExpression)
{
Check.NotNull(selectExpression, nameof(selectExpression));
if (selectExpression.Limit is not null)
{
Sql.AppendLine().Append("LIMIT ");
Visit(selectExpression.Limit);
}
if (selectExpression.Offset is not null)
{
if (selectExpression.Limit is null)
{
Sql.AppendLine();
}
else
{
Sql.Append(" ");
}
Sql.Append("OFFSET ");
Visit(selectExpression.Offset);
}
}
/// <inheritdoc />
protected override string GetOperator(SqlBinaryExpression e)
=> e.OperatorType switch
{
// PostgreSQL has a special string concatenation operator: ||
// We switch to it if the expression itself has type string, or if one of the sides has a string type mapping.
// Same for full-text search's TsVector, arrays.
ExpressionType.Add when
e.Type == typeof(string)
|| e.Left.TypeMapping?.ClrType == typeof(string)
|| e.Right.TypeMapping?.ClrType == typeof(string)
|| e.Type == typeof(NpgsqlTsVector)
|| e.Left.TypeMapping?.ClrType == typeof(NpgsqlTsVector)
|| e.Right.TypeMapping?.ClrType == typeof(NpgsqlTsVector)
|| e.Left.TypeMapping is NpgsqlArrayTypeMapping && e.Right.TypeMapping is NpgsqlArrayTypeMapping
=> " || ",
ExpressionType.And when e.Type == typeof(bool) => " AND ",
ExpressionType.Or when e.Type == typeof(bool) => " OR ",
// In most databases/languages, the caret (^) is the bitwise XOR operator. But in PostgreSQL the caret is the exponentiation
// operator, and hash (#) is used instead.
ExpressionType.ExclusiveOr when e.Type == typeof(bool) => " <> ",
ExpressionType.ExclusiveOr => " # ",
_ => base.GetOperator(e)
};
/// <inheritdoc />
protected override Expression VisitOrdering(OrderingExpression ordering)
{
var result = base.VisitOrdering(ordering);
if (_reverseNullOrderingEnabled)
{
Sql.Append(ordering.IsAscending ? " NULLS FIRST" : " NULLS LAST");
}
return result;
}
/// <inheritdoc />
protected override void GenerateTop(SelectExpression selectExpression)
{
// No TOP() in PostgreSQL, see GenerateLimitOffset
}
/// <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 Expression VisitCrossApply(CrossApplyExpression crossApplyExpression)
{
Sql.Append("JOIN LATERAL ");
if (crossApplyExpression.Table is TableExpression table)
{
// PostgreSQL doesn't support LATERAL JOIN over table, and it doesn't really make sense to do it - but EF Core
// will sometimes generate that. #1560
Sql
.Append("(SELECT * FROM ")
.Append(_sqlGenerationHelper.DelimitIdentifier(table.Name, table.Schema))
.Append(")")
.Append(AliasSeparator)
.Append(_sqlGenerationHelper.DelimitIdentifier(table.Alias));
}
else
{
Visit(crossApplyExpression.Table);
}
Sql.Append(" ON TRUE");
return crossApplyExpression;
}
/// <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 Expression VisitOuterApply(OuterApplyExpression outerApplyExpression)
{
Sql.Append("LEFT JOIN LATERAL ");
if (outerApplyExpression.Table is TableExpression table)
{
// PostgreSQL doesn't support LATERAL JOIN over table, and it doesn't really make sense to do it - but EF Core
// will sometimes generate that. #1560
Sql
.Append("(SELECT * FROM ")
.Append(_sqlGenerationHelper.DelimitIdentifier(table.Name, table.Schema))
.Append(")")
.Append(AliasSeparator)
.Append(_sqlGenerationHelper.DelimitIdentifier(table.Alias));
}
else
{
Visit(outerApplyExpression.Table);
}
Sql.Append(" ON TRUE");
return outerApplyExpression;
}
/// <inheritdoc />
protected override Expression VisitSqlBinary(SqlBinaryExpression binary)
{
switch (binary.OperatorType)
{
case ExpressionType.Add:
{
if (_postgresVersion >= new Version(9, 5))
{
return base.VisitSqlBinary(binary);
}
// PostgreSQL 9.4 and below has some weird operator precedence fixed in 9.5 and described here:
// http://git.postgresql.org/gitweb/?p=postgresql.git&a=commitdiff&h=c6b3c939b7e0f1d35f4ed4996e71420a993810d2
// As a result we must surround string concatenation with parentheses
if (binary.Left.Type == typeof(string) && binary.Right.Type == typeof(string))
{
Sql.Append("(");
var exp = base.VisitSqlBinary(binary);
Sql.Append(")");
return exp;
}
return base.VisitSqlBinary(binary);
}
case ExpressionType.ArrayIndex:
return VisitArrayIndex(binary);
default:
return base.VisitSqlBinary(binary);
}
}
// NonQueryConvertingExpressionVisitor converts the relational DeleteExpression to PostgresDeleteExpression, so we should never
// get here
/// <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 Expression VisitDelete(DeleteExpression deleteExpression)
=> throw new InvalidOperationException("Inconceivable!");
/// <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 virtual Expression VisitPgDelete(PgDeleteExpression pgDeleteExpression)
{
Sql.Append("DELETE FROM ");
Visit(pgDeleteExpression.Table);
if (pgDeleteExpression.FromItems.Count > 0)
{
Sql.AppendLine().Append("USING ");
GenerateList(pgDeleteExpression.FromItems, t => Visit(t), sql => sql.Append(", "));
}
if (pgDeleteExpression.Predicate != null)
{
Sql.AppendLine().Append("WHERE ");
Visit(pgDeleteExpression.Predicate);
}
return pgDeleteExpression;
}
/// <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 Expression VisitUpdate(UpdateExpression updateExpression)
{
var selectExpression = updateExpression.SelectExpression;
if (selectExpression.Offset == null
&& selectExpression.Limit == null
&& selectExpression.Having == null
&& selectExpression.Orderings.Count == 0
&& selectExpression.GroupBy.Count == 0
&& selectExpression.Projection.Count == 0
&& (selectExpression.Tables.Count == 1
|| !ReferenceEquals(selectExpression.Tables[0], updateExpression.Table)
|| selectExpression.Tables[1] is InnerJoinExpression
|| selectExpression.Tables[1] is CrossJoinExpression))
{
Sql.Append("UPDATE ");
Visit(updateExpression.Table);
Sql.AppendLine();
Sql.Append("SET ");
Sql.Append(
$"{_sqlGenerationHelper.DelimitIdentifier(updateExpression.ColumnValueSetters[0].Column.Name)} = ");
Visit(updateExpression.ColumnValueSetters[0].Value);
using (Sql.Indent())
{
foreach (var columnValueSetter in updateExpression.ColumnValueSetters.Skip(1))
{
Sql.AppendLine(",");
Sql.Append($"{_sqlGenerationHelper.DelimitIdentifier(columnValueSetter.Column.Name)} = ");
Visit(columnValueSetter.Value);
}
}
var predicate = selectExpression.Predicate;
var firstTable = true;
OuterReferenceFindingExpressionVisitor? visitor = null;
if (selectExpression.Tables.Count > 1)
{
Sql.AppendLine().Append("FROM ");
for (var i = 0; i < selectExpression.Tables.Count; i++)
{
var table = selectExpression.Tables[i];
var joinExpression = table as JoinExpressionBase;
if (updateExpression.Table.Alias == (joinExpression?.Table.Alias ?? table.Alias))
{
LiftPredicate(table);
continue;
}
visitor ??= new OuterReferenceFindingExpressionVisitor(updateExpression.Table);
// PostgreSQL doesn't support referencing the main update table from anywhere except for the UPDATE WHERE clause.
// This specifically makes it impossible to have joins which reference the main table in their predicate (ON ...).
// Because of this, we detect all such inner joins and lift their predicates to the main WHERE clause (where a reference to the
// main table is allowed), producing UPDATE ... FROM x, y WHERE y.foreign_key = x.id instead of INNER JOIN ... ON.
if (firstTable)
{
LiftPredicate(table);
table = joinExpression?.Table ?? table;
}
else if (joinExpression is InnerJoinExpression innerJoinExpression
&& visitor.ContainsReferenceToMainTable(innerJoinExpression.JoinPredicate))
{
LiftPredicate(innerJoinExpression);
Sql.AppendLine(",");
using (Sql.Indent())
{
Visit(innerJoinExpression.Table);
}
continue;
}
if (firstTable)
{
firstTable = false;
}
else
{
Sql.AppendLine();
}
Visit(table);
void LiftPredicate(TableExpressionBase joinTable)
{
if (joinTable is PredicateJoinExpressionBase predicateJoinExpression)
{
Check.DebugAssert(joinExpression is not LeftJoinExpression, "Cannot lift predicate for left join");
predicate = predicate == null
? predicateJoinExpression.JoinPredicate
: new SqlBinaryExpression(
ExpressionType.AndAlso,
predicateJoinExpression.JoinPredicate,
predicate,
typeof(bool),
predicate.TypeMapping);
}
}
}
}
if (predicate != null)
{
Sql.AppendLine().Append("WHERE ");
Visit(predicate);
}
return updateExpression;
}
throw new InvalidOperationException(
RelationalStrings.ExecuteOperationWithUnsupportedOperatorInSqlGeneration(nameof(EntityFrameworkQueryableExtensions.ExecuteUpdate)));
}
/// <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 virtual Expression VisitNewArray(PgNewArrayExpression pgNewArrayExpression)
{
Debug.Assert(pgNewArrayExpression.TypeMapping is not null);
Sql.Append("ARRAY[");
var first = true;
foreach (var initializer in pgNewArrayExpression.Expressions)
{
if (!first)
{
Sql.Append(",");
}
first = false;
Visit(initializer);
}
// Not sure if the explicit store type is necessary, but just to be sure.
Sql
.Append("]::")
.Append(pgNewArrayExpression.TypeMapping.StoreType);
return pgNewArrayExpression;
}
/// <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 virtual Expression VisitPgBinary(PgBinaryExpression binaryExpression)
{
Check.NotNull(binaryExpression, nameof(binaryExpression));
var requiresParentheses = RequiresParentheses(binaryExpression, binaryExpression.Left);
if (requiresParentheses)
{
Sql.Append("(");
}
Visit(binaryExpression.Left);
if (requiresParentheses)
{
Sql.Append(")");
}
Debug.Assert(binaryExpression.Left.TypeMapping is not null);
Debug.Assert(binaryExpression.Right.TypeMapping is not null);
Sql
.Append(" ")
.Append(
binaryExpression.OperatorType switch
{
PgExpressionType.Contains
when binaryExpression.Left.TypeMapping is NpgsqlInetTypeMapping or NpgsqlCidrTypeMapping
=> ">>",
PgExpressionType.ContainedBy
when binaryExpression.Left.TypeMapping is NpgsqlInetTypeMapping or NpgsqlCidrTypeMapping
=> "<<",
PgExpressionType.Contains => "@>",
PgExpressionType.ContainedBy => "<@",
PgExpressionType.Overlaps => "&&",
PgExpressionType.NetworkContainedByOrEqual => "<<=",
PgExpressionType.NetworkContainsOrEqual => ">>=",
PgExpressionType.NetworkContainsOrContainedBy => "&&",
PgExpressionType.RangeIsStrictlyLeftOf => "<<",
PgExpressionType.RangeIsStrictlyRightOf => ">>",
PgExpressionType.RangeDoesNotExtendRightOf => "&<",
PgExpressionType.RangeDoesNotExtendLeftOf => "&>",
PgExpressionType.RangeIsAdjacentTo => "-|-",
PgExpressionType.RangeUnion => "+",
PgExpressionType.RangeIntersect => "*",
PgExpressionType.RangeExcept => "-",
PgExpressionType.TextSearchMatch => "@@",
PgExpressionType.TextSearchAnd => "&&",
PgExpressionType.TextSearchOr => "||",
PgExpressionType.JsonExists => "?",
PgExpressionType.JsonExistsAny => "?|",
PgExpressionType.JsonExistsAll => "?&",
PgExpressionType.LTreeMatches
when binaryExpression.Right.TypeMapping.StoreType == "lquery"
|| binaryExpression.Right.TypeMapping is NpgsqlArrayTypeMapping { ElementTypeMapping.StoreType: "lquery" } => "~",
PgExpressionType.LTreeMatches
when binaryExpression.Right.TypeMapping.StoreType == "ltxtquery"
=> "@",
PgExpressionType.LTreeMatchesAny => "?",
PgExpressionType.LTreeFirstAncestor => "?@>",
PgExpressionType.LTreeFirstDescendent => "?<@",
PgExpressionType.LTreeFirstMatches
when binaryExpression.Right.TypeMapping.StoreType == "lquery" => "?~",
PgExpressionType.LTreeFirstMatches
when binaryExpression.Right.TypeMapping.StoreType == "ltxtquery" => "?@",
PgExpressionType.Distance => "<->",
_ => throw new ArgumentOutOfRangeException($"Unhandled operator type: {binaryExpression.OperatorType}")
})
.Append(" ");
requiresParentheses = RequiresParentheses(binaryExpression, binaryExpression.Right);
if (requiresParentheses)
{
Sql.Append("(");
}
Visit(binaryExpression.Right);
if (requiresParentheses)
{
Sql.Append(")");
}
return binaryExpression;
}
/// <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 virtual Expression VisitArrayIndex(SqlBinaryExpression expression)
{
Visit(expression.Left);
Sql.Append("[");
Visit(expression.Right);
Sql.Append("]");
return expression;
}
/// <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 Expression VisitSqlUnary(SqlUnaryExpression sqlUnaryExpression)
{
Debug.Assert(sqlUnaryExpression.TypeMapping is not null);
Debug.Assert(sqlUnaryExpression.Operand.TypeMapping is not null);
switch (sqlUnaryExpression.OperatorType)
{
case ExpressionType.Convert:
{
// PostgreSQL supports the standard CAST(x AS y), but also a lighter x::y which we use
// where there's no precedence issues
switch (sqlUnaryExpression.Operand)
{
case SqlConstantExpression:
case SqlParameterExpression:
case SqlUnaryExpression { OperatorType: ExpressionType.Convert }:
case ColumnExpression:
case SqlFunctionExpression:
case ScalarSubqueryExpression:
var storeType = sqlUnaryExpression.TypeMapping.StoreType switch
{
"integer" => "int",
"timestamp with time zone" => "timestamptz",
"timestamp without time zone" => "timestamp",
var s => s
};
Visit(sqlUnaryExpression.Operand);
Sql.Append("::");
Sql.Append(storeType);
return sqlUnaryExpression;
}
break;
}
// Bitwise complement on networking types
case ExpressionType.Not when
sqlUnaryExpression.Operand.TypeMapping.ClrType == typeof(IPAddress)
|| sqlUnaryExpression.Operand.TypeMapping.ClrType == typeof((IPAddress, int))
|| sqlUnaryExpression.Operand.TypeMapping.ClrType == typeof(PhysicalAddress):
Sql.Append("~");
Visit(sqlUnaryExpression.Operand);
return sqlUnaryExpression;
// NOT operation on full-text queries
case ExpressionType.Not when sqlUnaryExpression.Operand.TypeMapping.ClrType == typeof(NpgsqlTsQuery):
Sql.Append("!!");
Visit(sqlUnaryExpression.Operand);
return sqlUnaryExpression;
// NOT over expression types which have fancy embedded negation
case ExpressionType.Not
when sqlUnaryExpression.Type == typeof(bool):
{
switch (sqlUnaryExpression.Operand)
{
case PgRegexMatchExpression regexMatch:
VisitRegexMatch(regexMatch, negated: true);
return sqlUnaryExpression;
case PgILikeExpression iLike:
VisitILike(iLike, negated: true);
return sqlUnaryExpression;
}
break;
}
}
return base.VisitSqlUnary(sqlUnaryExpression);
}
/// <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 void GenerateSetOperationOperand(SetOperationBase setOperation, SelectExpression operand)
{
// PostgreSQL allows ORDER BY and LIMIT in set operation operands, but requires parentheses
if (operand.Orderings.Count > 0 || operand.Limit is not null)
{
Sql.AppendLine("(");
using (Sql.Indent())
{
Visit(operand);
}
Sql.AppendLine().Append(")");
return;
}
base.GenerateSetOperationOperand(setOperation, operand);
}
/// <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 Expression VisitCollate(CollateExpression collateExpression)
{
Check.NotNull(collateExpression, nameof(collateExpression));
Visit(collateExpression.Operand);
// In PG, collation names are regular identifiers which need to be quoted for case-sensitivity.
Sql
.Append(" COLLATE ")
.Append(_sqlGenerationHelper.DelimitIdentifier(collateExpression.Collation));
return collateExpression;
}
/// <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 bool TryGenerateWithoutWrappingSelect(SelectExpression selectExpression)
// PostgreSQL supports VALUES as a top-level statement - and directly under set operations.
// However, when on the left side of a set operation, we need the column coming out of VALUES to be named, so we need the wrapping
// SELECT for that.
=> selectExpression.Tables is not [ValuesExpression]
&& base.TryGenerateWithoutWrappingSelect(selectExpression);
/// <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 void GenerateSetOperation(SetOperationBase setOperation)
{
GenerateSetOperationOperand(setOperation, setOperation.Source1);
Sql
.AppendLine()
.Append(
setOperation switch
{
ExceptExpression => "EXCEPT",
IntersectExpression => "INTERSECT",
UnionExpression => "UNION",
_ => throw new InvalidOperationException(CoreStrings.UnknownEntity("SetOperationType"))
})
.AppendLine(setOperation.IsDistinct ? string.Empty : " ALL");
// For ValuesExpression, we can remove its wrapping SelectExpression but only if on the right side of a set operation, since on
// the left side we need the column name to be specified.
if (setOperation.Source2 is
{
Tables: [ValuesExpression valuesExpression],
Offset: null,
Limit: null,
IsDistinct: false,
Predicate: null,
Having: null,
Orderings.Count: 0,
GroupBy.Count: 0,
} rightSelectExpression
&& rightSelectExpression.Projection.Count == valuesExpression.ColumnNames.Count
&& rightSelectExpression.Projection.Select(
(pe, index) => pe.Expression is ColumnExpression column
&& column.Name == valuesExpression.ColumnNames[index])
.All(e => e))
{
GenerateValues(valuesExpression);
}
else
{
GenerateSetOperationOperand(setOperation, setOperation.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 Expression VisitValues(ValuesExpression valuesExpression)
{
base.VisitValues(valuesExpression);
// PostgreSQL VALUES supports setting the projects column names: FROM (VALUES (1), (2)) AS v(foo)
Sql.Append("(");
for (var i = 0; i < valuesExpression.ColumnNames.Count; i++)
{
if (i > 0)
{
Sql.Append(", ");
}
Sql.Append(_sqlGenerationHelper.DelimitIdentifier(valuesExpression.ColumnNames[i]));
}
Sql.Append(")");
return valuesExpression;
}
/// <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 void GenerateValues(ValuesExpression valuesExpression)
{
if (valuesExpression.RowValues is null)
{
throw new UnreachableException();
}
if (valuesExpression.RowValues.Count == 0)
{
throw new InvalidOperationException(RelationalStrings.EmptyCollectionNotSupportedAsInlineQueryRoot);
}
// PostgreSQL supports providing the names of columns projected out of VALUES: (VALUES (1, 3), (2, 4)) AS x(a, b).
// But since other databases sometimes don't, the default relational implementation is complex, involving a SELECT for the first row
// and a UNION All on the rest. Override to do the nice simple thing.
var rowValues = valuesExpression.RowValues;
Sql.Append("VALUES ");
for (var i = 0; i < rowValues.Count; i++)
{
// TODO: Do we want newlines here?
if (i > 0)
{
Sql.Append(", ");
}
Visit(valuesExpression.RowValues[i]);
}
}
#region PostgreSQL-specific expression types
/// <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 virtual Expression VisitArrayAll(PgAllExpression expression)
{
Visit(expression.Item);
Sql
.Append(" ")
.Append(
expression.OperatorType switch
{
PgAllOperatorType.Like => "LIKE",
PgAllOperatorType.ILike => "ILIKE",
_ => throw new ArgumentOutOfRangeException($"Unhandled operator type: {expression.OperatorType}")
})
.Append(" ALL (");
Visit(expression.Array);
Sql.Append(")");
return expression;
}
/// <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 virtual Expression VisitArrayAny(PgAnyExpression expression)
{
Visit(expression.Item);
Sql
.Append(" ")
.Append(
expression.OperatorType switch
{
PgAnyOperatorType.Equal => "=",
PgAnyOperatorType.Like => "LIKE",
PgAnyOperatorType.ILike => "ILIKE",
_ => throw new ArgumentOutOfRangeException($"Unhandled operator type: {expression.OperatorType}")
})
.Append(" ANY (");
Visit(expression.Array);
Sql.Append(")");
return expression;
}
/// <summary>
/// Produces SQL array index expression (e.g. arr[1]).
/// </summary>
protected virtual Expression VisitArrayIndex(PgArrayIndexExpression expression)
{
var requiresParentheses = RequiresParentheses(expression, expression.Array);
if (requiresParentheses)
{
Sql.Append("(");
}
Visit(expression.Array);
if (requiresParentheses)
{
Sql.Append(")");
}
Sql.Append("[");
Visit(expression.Index);
Sql.Append("]");
return expression;
}
/// <summary>
/// Produces SQL array slice expression (e.g. arr[1:2]).
/// </summary>
protected virtual Expression VisitArraySlice(PgArraySliceExpression expression)
{
var requiresParentheses = RequiresParentheses(expression, expression.Array);
if (requiresParentheses)
{
Sql.Append("(");
}
Visit(expression.Array);
if (requiresParentheses)
{
Sql.Append(")");
}
Sql.Append("[");
Visit(expression.LowerBound);
Sql.Append(":");
Visit(expression.UpperBound);
Sql.Append("]");
return expression;
}
/// <summary>
/// Produces SQL for PostgreSQL regex matching.
/// </summary>
/// <remarks>
/// See: http://www.postgresql.org/docs/current/static/functions-matching.html
/// </remarks>
protected virtual Expression VisitRegexMatch(PgRegexMatchExpression expression, bool negated = false)
{
var options = expression.Options;
Visit(expression.Match);
if (options.HasFlag(RegexOptions.IgnoreCase))
{
Sql.Append(negated ? " !~* " : " ~* ");
options &= ~RegexOptions.IgnoreCase;
}
else
{
Sql.Append(negated ? " !~ " : " ~ ");
}
// PG regexps are single-line by default
if (options == RegexOptions.Singleline)
{
Visit(expression.Pattern);
return expression;
}
var constantPattern = (expression.Pattern as SqlConstantExpression)?.Value as string;
if (constantPattern is null)
{
Sql.Append("(");
}
Sql.Append("'(?");
if (options.HasFlag(RegexOptions.Multiline))
{
Sql.Append("n");
}
else if (!options.HasFlag(RegexOptions.Singleline))
{
// In .NET's default mode, . doesn't match newlines but in PostgreSQL it does.
Sql.Append("p");
}
if (options.HasFlag(RegexOptions.IgnorePatternWhitespace))
{
Sql.Append("x");
}
Sql.Append(")");
if (constantPattern is null)
{
Sql.Append("' || ");
Visit(expression.Pattern);
Sql.Append(")");
}
else
{
Sql.Append(constantPattern.Replace("'", "''"));
Sql.Append("'");
}
return expression;
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to