forked from npgsql/efcore.pg
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNpgsqlNodaTimeMemberTranslatorPlugin.cs
More file actions
395 lines (339 loc) · 16.3 KB
/
Copy pathNpgsqlNodaTimeMemberTranslatorPlugin.cs
File metadata and controls
395 lines (339 loc) · 16.3 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
using Npgsql.EntityFrameworkCore.PostgreSQL.Query;
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 NpgsqlNodaTimeMemberTranslatorPlugin : IMemberTranslatorPlugin
{
/// <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 NpgsqlNodaTimeMemberTranslatorPlugin(
IRelationalTypeMappingSource typeMappingSource,
ISqlExpressionFactory sqlExpressionFactory)
{
Translators = new IMemberTranslator[]
{
new NpgsqlNodaTimeMemberTranslator(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<IMemberTranslator> 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 NpgsqlNodaTimeMemberTranslator : IMemberTranslator
{
private static readonly MemberInfo SystemClock_Instance =
typeof(SystemClock).GetRuntimeProperty(nameof(SystemClock.Instance))!;
private static readonly MemberInfo ZonedDateTime_LocalDateTime =
typeof(ZonedDateTime).GetRuntimeProperty(nameof(ZonedDateTime.LocalDateTime))!;
private static readonly MemberInfo Interval_Start =
typeof(Interval).GetRuntimeProperty(nameof(Interval.Start))!;
private static readonly MemberInfo Interval_End =
typeof(Interval).GetRuntimeProperty(nameof(Interval.End))!;
private static readonly MemberInfo Interval_HasStart =
typeof(Interval).GetRuntimeProperty(nameof(Interval.HasStart))!;
private static readonly MemberInfo Interval_HasEnd =
typeof(Interval).GetRuntimeProperty(nameof(Interval.HasEnd))!;
private static readonly MemberInfo Interval_Duration =
typeof(Interval).GetRuntimeProperty(nameof(Interval.Duration))!;
private static readonly MemberInfo DateInterval_Start =
typeof(DateInterval).GetRuntimeProperty(nameof(DateInterval.Start))!;
private static readonly MemberInfo DateInterval_End =
typeof(DateInterval).GetRuntimeProperty(nameof(DateInterval.End))!;
private static readonly MemberInfo DateInterval_Length =
typeof(DateInterval).GetRuntimeProperty(nameof(DateInterval.Length))!;
private static readonly MemberInfo DateTimeZoneProviders_TzDb =
typeof(DateTimeZoneProviders).GetRuntimeProperty(nameof(DateTimeZoneProviders.Tzdb))!;
private readonly NpgsqlSqlExpressionFactory _sqlExpressionFactory;
private readonly IRelationalTypeMappingSource _typeMappingSource;
private readonly RelationalTypeMapping _dateTypeMapping;
private readonly RelationalTypeMapping _periodTypeMapping;
private readonly RelationalTypeMapping _localDateTimeTypeMapping;
/// <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 NpgsqlNodaTimeMemberTranslator(
IRelationalTypeMappingSource typeMappingSource,
NpgsqlSqlExpressionFactory sqlExpressionFactory)
{
_typeMappingSource = typeMappingSource;
_sqlExpressionFactory = sqlExpressionFactory;
_dateTypeMapping = typeMappingSource.FindMapping(typeof(LocalDate))!;
_periodTypeMapping = typeMappingSource.FindMapping(typeof(Period))!;
_localDateTimeTypeMapping = typeMappingSource.FindMapping(typeof(LocalDateTime))!;
}
private static readonly bool[][] TrueArrays = [[], [true], [true, true]];
/// <inheritdoc />
public virtual SqlExpression? Translate(
SqlExpression? instance,
MemberInfo member,
Type returnType,
IDiagnosticsLogger<DbLoggerCategory.Query> logger)
{
// This is necessary to allow translation of methods on SystemClock.Instance
if (member == SystemClock_Instance)
{
return _sqlExpressionFactory.Constant(SystemClock.Instance);
}
if (member == DateTimeZoneProviders_TzDb)
{
return PendingDateTimeZoneProviderExpression.Instance;
}
if (instance is null)
{
return null;
}
var declaringType = member.DeclaringType;
if (declaringType == typeof(LocalDateTime)
|| declaringType == typeof(LocalDate)
|| declaringType == typeof(LocalTime)
|| declaringType == typeof(Period))
{
return TranslateDateTime(instance, member);
}
if (declaringType == typeof(ZonedDateTime))
{
return TranslateZonedDateTime(instance, member, returnType);
}
if (declaringType == typeof(Duration))
{
return TranslateDuration(instance, member);
}
if (declaringType == typeof(Interval))
{
return TranslateInterval(instance, member);
}
if (declaringType == typeof(DateInterval))
{
return TranslateDateInterval(instance, member);
}
return null;
}
private SqlExpression? TranslateDuration(SqlExpression instance, MemberInfo member)
{
return member.Name switch
{
nameof(Duration.TotalDays) => TranslateDurationTotalMember(instance, 86400),
nameof(Duration.TotalHours) => TranslateDurationTotalMember(instance, 3600),
nameof(Duration.TotalMinutes) => TranslateDurationTotalMember(instance, 60),
nameof(Duration.TotalSeconds) => GetDatePartExpressionDouble(instance, "epoch"),
nameof(Duration.TotalMilliseconds) => TranslateDurationTotalMember(instance, 0.001),
nameof(Duration.Days) => GetDatePartExpression(instance, "day"),
nameof(Duration.Hours) => GetDatePartExpression(instance, "hour"),
nameof(Duration.Minutes) => GetDatePartExpression(instance, "minute"),
nameof(Duration.Seconds) => GetDatePartExpression(instance, "second", true),
nameof(Duration.Milliseconds) => null, // Too annoying, floating point and sub-millisecond handling
_ => null,
};
SqlExpression TranslateDurationTotalMember(SqlExpression instance, double divisor)
=> _sqlExpressionFactory.Divide(GetDatePartExpressionDouble(instance, "epoch"), _sqlExpressionFactory.Constant(divisor));
}
private SqlExpression? TranslateInterval(SqlExpression instance, MemberInfo member)
{
if (member == Interval_Start)
{
return Lower();
}
if (member == Interval_End)
{
return Upper();
}
if (member == Interval_HasStart)
{
return _sqlExpressionFactory.Not(
_sqlExpressionFactory.Function(
"lower_inf",
new[] { instance },
nullable: true,
argumentsPropagateNullability: TrueArrays[1],
typeof(bool)));
}
if (member == Interval_HasEnd)
{
return _sqlExpressionFactory.Not(
_sqlExpressionFactory.Function(
"upper_inf",
new[] { instance },
nullable: true,
argumentsPropagateNullability: TrueArrays[1],
typeof(bool)));
}
if (member == Interval_Duration)
{
return _sqlExpressionFactory.Subtract(Upper(), Lower(), _typeMappingSource.FindMapping(typeof(Duration)));
}
return null;
SqlExpression Lower()
=> _sqlExpressionFactory.Function(
"lower",
new[] { instance },
nullable: true,
argumentsPropagateNullability: TrueArrays[1],
typeof(Interval),
_typeMappingSource.FindMapping(typeof(Instant)));
SqlExpression Upper()
=> _sqlExpressionFactory.Function(
"upper",
new[] { instance },
nullable: true,
argumentsPropagateNullability: TrueArrays[1],
typeof(Interval),
_typeMappingSource.FindMapping(typeof(Instant)));
}
private SqlExpression? TranslateDateInterval(SqlExpression instance, MemberInfo member)
{
// NodaTime DateInterval is inclusive on both ends.
// PostgreSQL daterange is a discrete range type; this means it gets normalized to inclusive lower bound, exclusive upper bound.
// So we can translate Start as-is, but need to subtract a day for End.
if (member == DateInterval_Start)
{
return Lower();
}
if (member == DateInterval_End)
{
// PostgreSQL creates a result of type 'timestamp without time zone' when subtracting intervals from dates, so add a cast back
// to date.
return _sqlExpressionFactory.Convert(
_sqlExpressionFactory.Subtract(
Upper(),
_sqlExpressionFactory.Constant(Period.FromDays(1), _periodTypeMapping)), typeof(LocalDate),
_typeMappingSource.FindMapping(typeof(LocalDate)));
}
if (member == DateInterval_Length)
{
return _sqlExpressionFactory.Subtract(Upper(), Lower());
}
return null;
SqlExpression Lower()
=> _sqlExpressionFactory.Function(
"lower",
new[] { instance },
nullable: true,
argumentsPropagateNullability: TrueArrays[1],
typeof(LocalDate),
_dateTypeMapping);
SqlExpression Upper()
=> _sqlExpressionFactory.Function(
"upper",
new[] { instance },
nullable: true,
argumentsPropagateNullability: TrueArrays[1],
typeof(LocalDate),
_dateTypeMapping);
}
private SqlExpression? TranslateDateTime(SqlExpression instance, MemberInfo member)
=> member.Name switch
{
"Year" or "Years" => GetDatePartExpression(instance, "year"),
"Month" or "Months" => GetDatePartExpression(instance, "month"),
"DayOfYear" => GetDatePartExpression(instance, "doy"),
"Day" or "Days" => GetDatePartExpression(instance, "day"),
"Hour" or "Hours" => GetDatePartExpression(instance, "hour"),
"Minute" or "Minutes" => GetDatePartExpression(instance, "minute"),
"Second" or "Seconds" => GetDatePartExpression(instance, "second", true),
"Millisecond" or "Milliseconds" => null, // Too annoying
// Unlike DateTime.DayOfWeek, NodaTime's IsoDayOfWeek enum doesn't exactly correspond to PostgreSQL's
// values returned by date_part('dow', ...): in NodaTime Sunday is 7 and not 0, which is None.
// So we generate a CASE WHEN expression to translate PostgreSQL's 0 to 7.
"DayOfWeek" when GetDatePartExpression(instance, "dow", true) is var getValueExpression
=> _sqlExpressionFactory.Case(
getValueExpression,
new[] { new CaseWhenClause(_sqlExpressionFactory.Constant(0), _sqlExpressionFactory.Constant(7)) },
getValueExpression),
// PG allows converting a timestamp directly to date, truncating the time; but given a timestamptz, it performs a time zone
// conversion (based on TimeZone), which we don't want (so avoid translating except on timestamp).
// The translation for ZonedDateTime.Date converts to timestamp before ending up here.
"Date" when instance.TypeMapping is TimestampLocalDateTimeMapping or LegacyTimestampInstantMapping
=> _sqlExpressionFactory.Convert(instance, typeof(LocalDate), _typeMappingSource.FindMapping(typeof(LocalDate))!),
"TimeOfDay" => _sqlExpressionFactory.Convert(
instance,
typeof(LocalTime),
_typeMappingSource.FindMapping(typeof(LocalTime), storeTypeName: "time")),
_ => null
};
/// <summary>
/// Constructs the date_part expression.
/// </summary>
/// <param name="instance">The expression.</param>
/// <param name="partName">The name of the date_part to construct.</param>
/// <param name="floor">True if the result should be wrapped with floor(...); otherwise, false.</param>
/// <returns>
/// The date_part expression.
/// </returns>
/// <remarks>
/// date_part returns doubles, which we floor and cast into ints
/// This also gets rid of sub-second components when retrieving seconds.
/// </remarks>
private SqlExpression GetDatePartExpression(
SqlExpression instance,
string partName,
bool floor = false)
{
var result = GetDatePartExpressionDouble(instance, partName, floor);
return _sqlExpressionFactory.Convert(result, typeof(int));
}
private SqlExpression GetDatePartExpressionDouble(
SqlExpression instance,
string partName,
bool floor = false)
{
var result = _sqlExpressionFactory.Function(
"date_part",
new[] { _sqlExpressionFactory.Constant(partName), instance },
nullable: true,
argumentsPropagateNullability: TrueArrays[2],
typeof(double));
if (floor)
{
result = _sqlExpressionFactory.Function(
"floor",
new[] { result },
nullable: true,
argumentsPropagateNullability: TrueArrays[1],
typeof(double));
}
return result;
}
private SqlExpression? TranslateZonedDateTime(SqlExpression instance, MemberInfo member, Type returnType)
{
if (instance is PendingZonedDateTimeExpression pendingZonedDateTime)
{
instance = _sqlExpressionFactory.AtTimeZone(
pendingZonedDateTime.Operand,
pendingZonedDateTime.TimeZoneId,
typeof(LocalDateTime),
_localDateTimeTypeMapping);
return member == ZonedDateTime_LocalDateTime
? instance
: TranslateDateTime(instance, member);
}
// date_part, which is used to extract most components, doesn't have an overload for timestamptz, so passing one directly
// converts it to the local timezone as per TimeZone. Explicitly convert it to a 'timestamp without time zone' in UTC.
// The same works also for the LocalDateTime member.
instance = _sqlExpressionFactory.AtUtc(instance);
return member == ZonedDateTime_LocalDateTime
? instance
: TranslateDateTime(instance, member);
}
}