-
Notifications
You must be signed in to change notification settings - Fork 257
Expand file tree
/
Copy pathNpgsqlNodaTimeMethodCallTranslatorPlugin.cs
More file actions
400 lines (347 loc) · 17.4 KB
/
NpgsqlNodaTimeMethodCallTranslatorPlugin.cs
File metadata and controls
400 lines (347 loc) · 17.4 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
using Npgsql.EntityFrameworkCore.PostgreSQL.Query;
using Npgsql.EntityFrameworkCore.PostgreSQL.Query.Expressions;
using Npgsql.EntityFrameworkCore.PostgreSQL.Query.Expressions.Internal;
using Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal;
namespace Npgsql.EntityFrameworkCore.PostgreSQL.NodaTime.Query.Internal;
/// <summary>
/// Provides translation services for <see cref="NodaTime"/> members.
/// </summary>
/// <remarks>
/// See: https://www.postgresql.org/docs/current/static/functions-datetime.html
/// </remarks>
public class NpgsqlNodaTimeMethodCallTranslatorPlugin : IMethodCallTranslatorPlugin
{
/// <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 NpgsqlNodaTimeMethodCallTranslatorPlugin(
IRelationalTypeMappingSource typeMappingSource,
ISqlExpressionFactory sqlExpressionFactory)
{
Translators = new IMethodCallTranslator[]
{
new NpgsqlNodaTimeMethodCallTranslator(typeMappingSource, (NpgsqlSqlExpressionFactory)sqlExpressionFactory),
};
}
/// <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 virtual IEnumerable<IMethodCallTranslator> Translators { get; }
}
/// <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 NpgsqlNodaTimeMethodCallTranslator : IMethodCallTranslator
{
private readonly IRelationalTypeMappingSource _typeMappingSource;
private readonly NpgsqlSqlExpressionFactory _sqlExpressionFactory;
private static readonly MethodInfo SystemClock_GetCurrentInstant =
typeof(SystemClock).GetRuntimeMethod(nameof(SystemClock.GetCurrentInstant), Type.EmptyTypes)!;
private static readonly MethodInfo Instant_InUtc =
typeof(Instant).GetRuntimeMethod(nameof(Instant.InUtc), Type.EmptyTypes)!;
private static readonly MethodInfo Instant_InZone =
typeof(Instant).GetRuntimeMethod(nameof(Instant.InZone), new[] { typeof(DateTimeZone)})!;
private static readonly MethodInfo Instant_ToDateTimeUtc =
typeof(Instant).GetRuntimeMethod(nameof(Instant.ToDateTimeUtc), Type.EmptyTypes)!;
private static readonly MethodInfo Instant_Distance =
typeof(NpgsqlNodaTimeDbFunctionsExtensions).GetRuntimeMethod(
nameof(NpgsqlNodaTimeDbFunctionsExtensions.Distance), new[] { typeof(DbFunctions), typeof(Instant), typeof(Instant) })!;
private static readonly MethodInfo ZonedDateTime_ToInstant =
typeof(ZonedDateTime).GetRuntimeMethod(nameof(ZonedDateTime.ToInstant), Type.EmptyTypes)!;
private static readonly MethodInfo ZonedDateTime_Distance =
typeof(NpgsqlNodaTimeDbFunctionsExtensions).GetRuntimeMethod(
nameof(NpgsqlNodaTimeDbFunctionsExtensions.Distance), new[] { typeof(DbFunctions), typeof(ZonedDateTime), typeof(ZonedDateTime) })!;
private static readonly MethodInfo LocalDateTime_InZoneLeniently =
typeof(LocalDateTime).GetRuntimeMethod(nameof(LocalDateTime.InZoneLeniently), new[] { typeof(DateTimeZone) })!;
private static readonly MethodInfo LocalDateTime_Distance =
typeof(NpgsqlNodaTimeDbFunctionsExtensions).GetRuntimeMethod(
nameof(NpgsqlNodaTimeDbFunctionsExtensions.Distance), new[] { typeof(DbFunctions), typeof(LocalDateTime), typeof(LocalDateTime) })!;
private static readonly MethodInfo LocalDateTime_ToDateTimeUnspecified =
typeof(LocalDateTime).GetRuntimeMethod(nameof(LocalDateTime.ToDateTimeUnspecified), Type.EmptyTypes)!;
private static readonly MethodInfo LocalDate_Distance =
typeof(NpgsqlNodaTimeDbFunctionsExtensions).GetRuntimeMethod(
nameof(NpgsqlNodaTimeDbFunctionsExtensions.Distance), new[] { typeof(DbFunctions), typeof(LocalDate), typeof(LocalDate) })!;
private static readonly MethodInfo Period_FromYears = typeof(Period).GetRuntimeMethod(nameof(Period.FromYears), new[] { typeof(int) })!;
private static readonly MethodInfo Period_FromMonths = typeof(Period).GetRuntimeMethod(nameof(Period.FromMonths), new[] { typeof(int) })!;
private static readonly MethodInfo Period_FromWeeks = typeof(Period).GetRuntimeMethod(nameof(Period.FromWeeks), new[] { typeof(int) })!;
private static readonly MethodInfo Period_FromDays = typeof(Period).GetRuntimeMethod(nameof(Period.FromDays), new[] { typeof(int) })!;
private static readonly MethodInfo Period_FromHours = typeof(Period).GetRuntimeMethod(nameof(Period.FromHours), new[] { typeof(long) })!;
private static readonly MethodInfo Period_FromMinutes = typeof(Period).GetRuntimeMethod(nameof(Period.FromMinutes), new[] { typeof(long) })!;
private static readonly MethodInfo Period_FromSeconds = typeof(Period).GetRuntimeMethod(nameof(Period.FromSeconds), new[] { typeof(long) })!;
private static readonly MethodInfo Interval_Contains
= typeof(Interval).GetRuntimeMethod(nameof(Interval.Contains), new[] { typeof(Instant) })!;
private static readonly MethodInfo DateInterval_Contains_LocalDate
= typeof(DateInterval).GetRuntimeMethod(nameof(DateInterval.Contains), new[] { typeof(LocalDate) })!;
private static readonly MethodInfo DateInterval_Contains_DateInterval
= typeof(DateInterval).GetRuntimeMethod(nameof(DateInterval.Contains), new[] { typeof(DateInterval) })!;
private static readonly MethodInfo DateInterval_Intersection
= typeof(DateInterval).GetRuntimeMethod(nameof(DateInterval.Intersection), new[] { typeof(DateInterval) })!;
private static readonly MethodInfo DateInterval_Union
= typeof(DateInterval).GetRuntimeMethod(nameof(DateInterval.Union), new[] { typeof(DateInterval) })!;
private static readonly MethodInfo IDateTimeZoneProvider_get_Item
= typeof(IDateTimeZoneProvider).GetRuntimeMethod("get_Item", new[] { typeof(string) })!;
private static readonly bool[][] TrueArrays =
{
Array.Empty<bool>(),
new[] { true },
new[] { true, true },
};
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public NpgsqlNodaTimeMethodCallTranslator(
IRelationalTypeMappingSource typeMappingSource,
NpgsqlSqlExpressionFactory sqlExpressionFactory)
{
_typeMappingSource = typeMappingSource;
_sqlExpressionFactory = sqlExpressionFactory;
}
#pragma warning disable EF1001
/// <inheritdoc />
public virtual SqlExpression? Translate(
SqlExpression? instance,
MethodInfo method,
IReadOnlyList<SqlExpression> arguments,
IDiagnosticsLogger<DbLoggerCategory.Query> logger)
{
var translated =
TranslateInstant(instance, method, arguments)
?? TranslateZonedDateTime(instance, method, arguments)
?? TranslateLocalDateTime(instance, method, arguments)
?? TranslateLocalDate(instance, method, arguments)
?? TranslatePeriod(instance, method, arguments, logger)
?? TranslateInterval(instance, method, arguments, logger)
?? TranslateDateInterval(instance, method, arguments, logger);
if (translated is not null)
{
return translated;
}
if (method == IDateTimeZoneProvider_get_Item && instance is PendingDateTimeZoneProviderExpression)
{
// We're translating an expression such as 'DateTimeZoneProviders.Tzdb["Europe/Berlin"]'.
// Note that the .NET type of that expression is DateTimeZone, but we just return the string ID for the time zone.
return arguments[0];
}
return null;
}
private SqlExpression? TranslateInstant(
SqlExpression? instance,
MethodInfo method,
IReadOnlyList<SqlExpression> arguments)
{
if (method == SystemClock_GetCurrentInstant)
{
return NpgsqlNodaTimeTypeMappingSourcePlugin.LegacyTimestampBehavior
? _sqlExpressionFactory.AtTimeZone(
_sqlExpressionFactory.Function(
"NOW",
Array.Empty<SqlExpression>(),
nullable: false,
argumentsPropagateNullability: Array.Empty<bool>(),
method.ReturnType),
_sqlExpressionFactory.Constant("UTC"),
method.ReturnType)
: _sqlExpressionFactory.Function(
"NOW",
Array.Empty<SqlExpression>(),
nullable: false,
argumentsPropagateNullability: Array.Empty<bool>(),
method.ReturnType,
_typeMappingSource.FindMapping(typeof(Instant), "timestamp with time zone"));
}
if (method == Instant_InUtc)
{
// Instant -> ZonedDateTime is a no-op (different types in .NET but both mapped to timestamptz in PG)
return instance;
}
if (method == Instant_InZone)
{
// When InZone is called, we have a mismatch: on the .NET NodaTime side, we have a ZonedDateTime; but on the PostgreSQL side,
// the AT TIME ZONE expression returns a 'timestamp without time zone' (when applied to a 'timestamp with time zone', which is
// what ZonedDateTime is mapped to).
return new PendingZonedDateTimeExpression(instance!, arguments[0]);
}
if (method == Instant_ToDateTimeUtc)
{
return _sqlExpressionFactory.Convert(
instance!,
typeof(DateTime),
_typeMappingSource.FindMapping(typeof(DateTime), "timestamp with time zone"));
}
if (method == Instant_Distance)
{
return _sqlExpressionFactory.MakePostgresBinary(PostgresExpressionType.Distance, arguments[1], arguments[2]);
}
return null;
}
private SqlExpression? TranslateZonedDateTime(
SqlExpression? instance,
MethodInfo method,
IReadOnlyList<SqlExpression> arguments)
{
if (method == ZonedDateTime_ToInstant)
{
// We get here with the expression localDateTime.InZoneLeniently(DateTimeZoneProviders.Tzdb["Europe/Berlin"]).ToInstant()
if (instance is PendingZonedDateTimeExpression pendingZonedDateTime)
{
return _sqlExpressionFactory.AtTimeZone(
pendingZonedDateTime.Operand,
pendingZonedDateTime.TimeZoneId,
typeof(Instant),
_typeMappingSource.FindMapping(typeof(Instant)));
}
// Otherwise, ZonedDateTime -> ToInstant is a no-op (different types in .NET but both mapped to timestamptz in PG)
return instance;
}
if (method == ZonedDateTime_Distance)
{
return _sqlExpressionFactory.MakePostgresBinary(PostgresExpressionType.Distance, arguments[1], arguments[2]);
}
return null;
}
private SqlExpression? TranslateLocalDateTime(
SqlExpression? instance,
MethodInfo method,
IReadOnlyList<SqlExpression> arguments)
{
if (method == LocalDateTime_InZoneLeniently)
{
return new PendingZonedDateTimeExpression(instance!, arguments[0]);
}
if (method == LocalDateTime_Distance)
{
return _sqlExpressionFactory.MakePostgresBinary(PostgresExpressionType.Distance, arguments[1], arguments[2]);
}
if (method == LocalDateTime_ToDateTimeUnspecified)
{
return _sqlExpressionFactory.Convert(
instance!,
typeof(DateTime),
_typeMappingSource.FindMapping(typeof(DateTime), "timestamp without time zone"));
}
return null;
}
private SqlExpression? TranslateLocalDate(
SqlExpression? instance,
MethodInfo method,
IReadOnlyList<SqlExpression> arguments)
{
if (method == LocalDate_Distance)
{
return _sqlExpressionFactory.MakePostgresBinary(PostgresExpressionType.Distance, arguments[1], arguments[2]);
}
return null;
}
private SqlExpression? TranslatePeriod(
SqlExpression? instance,
MethodInfo method,
IReadOnlyList<SqlExpression> arguments,
IDiagnosticsLogger<DbLoggerCategory.Query> logger)
{
if (method.DeclaringType != typeof(Period))
{
return null;
}
if (method == Period_FromYears)
{
return IntervalPart("years", arguments[0]);
}
if (method == Period_FromMonths)
{
return IntervalPart("months", arguments[0]);
}
if (method == Period_FromWeeks)
{
return IntervalPart("weeks", arguments[0]);
}
if (method == Period_FromDays)
{
return IntervalPart("days", arguments[0]);
}
if (method == Period_FromHours)
{
return IntervalPartOverBigInt("hours", arguments[0]);
}
if (method == Period_FromMinutes)
{
return IntervalPartOverBigInt("mins", arguments[0]);
}
if (method == Period_FromSeconds)
{
return IntervalPart(
"secs", _sqlExpressionFactory.Convert(arguments[0], typeof(double), _typeMappingSource.FindMapping(typeof(double))));
}
return null;
static PostgresFunctionExpression IntervalPart(string datePart, SqlExpression parameter)
=> PostgresFunctionExpression.CreateWithNamedArguments(
"make_interval",
new[] { parameter },
new[] { datePart },
nullable: true,
argumentsPropagateNullability: TrueArrays[1],
builtIn: true,
typeof(Period),
typeMapping: null);
PostgresFunctionExpression IntervalPartOverBigInt(string datePart, SqlExpression parameter)
{
parameter = _sqlExpressionFactory.ApplyDefaultTypeMapping(parameter);
// NodaTime Period.FromHours/Minutes/Seconds accept a long parameter, but PG interval_part accepts an int.
// If the parameter happens to be an int cast up to a long, just unwrap it, otherwise downcast from bigint to int
// (this will throw on the PG side if the bigint is out of int range)
if (parameter is SqlUnaryExpression { OperatorType: ExpressionType.Convert } convertExpression
&& convertExpression.TypeMapping!.StoreType == "bigint"
&& convertExpression.Operand.TypeMapping!.StoreType == "integer")
{
return IntervalPart(datePart, convertExpression.Operand);
}
return IntervalPart(
datePart, _sqlExpressionFactory.Convert(parameter, typeof(int), _typeMappingSource.FindMapping(typeof(int))));
}
}
private SqlExpression? TranslateInterval(
SqlExpression? instance,
MethodInfo method,
IReadOnlyList<SqlExpression> arguments,
IDiagnosticsLogger<DbLoggerCategory.Query> logger)
{
if (method == Interval_Contains)
{
return _sqlExpressionFactory.Contains(instance!, arguments[0]);
}
return null;
}
private SqlExpression? TranslateDateInterval(
SqlExpression? instance,
MethodInfo method,
IReadOnlyList<SqlExpression> arguments,
IDiagnosticsLogger<DbLoggerCategory.Query> logger)
{
if (method == DateInterval_Contains_LocalDate
|| method == DateInterval_Contains_DateInterval)
{
return _sqlExpressionFactory.Contains(instance!, arguments[0]);
}
if (method == DateInterval_Intersection)
{
return _sqlExpressionFactory.MakePostgresBinary(PostgresExpressionType.RangeIntersect, instance!, arguments[0]);
}
if (method == DateInterval_Union)
{
return _sqlExpressionFactory.MakePostgresBinary(PostgresExpressionType.RangeUnion, instance!, arguments[0]);
}
return null;
}
#pragma warning restore EF1001
}