-
Notifications
You must be signed in to change notification settings - Fork 874
Expand file tree
/
Copy pathGlobalTypeMapper.cs
More file actions
350 lines (316 loc) · 13.1 KB
/
GlobalTypeMapper.cs
File metadata and controls
350 lines (316 loc) · 13.1 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
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
using System.Threading;
using Npgsql.Internal;
using Npgsql.Internal.Postgres;
using Npgsql.Internal.ResolverFactories;
namespace Npgsql.TypeMapping;
/// <inheritdoc />
sealed class GlobalTypeMapper : INpgsqlTypeMapper
{
readonly UserTypeMapper _userTypeMapper = new();
readonly List<PgTypeInfoResolverFactory> _pluginResolverFactories = [];
readonly ReaderWriterLockSlim _lock = new();
PgTypeInfoResolverFactory[] _typeMappingResolvers = [];
internal IEnumerable<PgTypeInfoResolverFactory> GetPluginResolverFactories()
{
var resolvers = new List<PgTypeInfoResolverFactory>();
_lock.EnterReadLock();
try
{
resolvers.AddRange(_pluginResolverFactories);
}
finally
{
_lock.ExitReadLock();
}
return resolvers;
}
internal PgTypeInfoResolverFactory? GetUserMappingsResolverFactory()
{
_lock.EnterReadLock();
try
{
return _userTypeMapper.Items.Count > 0 ? _userTypeMapper : null;
}
finally
{
_lock.ExitReadLock();
}
}
internal void AddGlobalTypeMappingResolvers(PgTypeInfoResolverFactory[] factories, Func<PgTypeInfoResolverChainBuilder>? builderFactory = null, bool overwrite = false)
{
// Good enough logic to prevent SlimBuilder overriding the normal Builder.
if (overwrite || factories.Length > _typeMappingResolvers.Length)
{
_builderFactory = builderFactory;
_typeMappingResolvers = factories;
ResetTypeMappingCache();
}
}
void ResetTypeMappingCache() => _typeMappingOptions = null;
PgSerializerOptions? _typeMappingOptions;
Func<PgTypeInfoResolverChainBuilder>? _builderFactory;
JsonSerializerOptions? _jsonSerializerOptions;
PgSerializerOptions TypeMappingOptions
{
get
{
if (_typeMappingOptions is not null)
return _typeMappingOptions;
_lock.EnterReadLock();
try
{
var builder = _builderFactory?.Invoke() ?? new();
builder.AppendResolverFactory(_userTypeMapper);
foreach (var factory in _pluginResolverFactories)
builder.AppendResolverFactory(factory);
foreach (var factory in _typeMappingResolvers)
builder.AppendResolverFactory(factory);
var chain = builder.Build();
return _typeMappingOptions = new(PostgresMinimalDatabaseInfo.DefaultTypeCatalog, chain)
{
// This means we don't ever have a missing oid for a datatypename as our canonical format is datatypenames.
PortableTypeIds = true,
// Don't throw if our catalog doesn't know the datatypename.
IntrospectionMode = true
};
}
finally
{
_lock.ExitReadLock();
}
}
}
internal DataTypeName? FindDataTypeName(Type type, object? value)
{
DataTypeName? dataTypeName;
try
{
var typeInfo = TypeMappingOptions.GetTypeInfoInternal(type, null);
if (typeInfo is PgResolverTypeInfo info)
dataTypeName = info.GetObjectResolution(value).PgTypeId.DataTypeName;
else
dataTypeName = typeInfo?.GetResolution().PgTypeId.DataTypeName;
}
catch
{
dataTypeName = null;
}
return dataTypeName;
}
internal static GlobalTypeMapper Instance { get; }
static GlobalTypeMapper()
=> Instance = new GlobalTypeMapper();
/// <inheritdoc />
public void AddTypeInfoResolverFactory(PgTypeInfoResolverFactory factory)
{
_lock.EnterWriteLock();
try
{
var type = factory.GetType();
// Since EFCore.PG plugins (and possibly other users) repeatedly call NpgsqlConnection.GlobalTypeMapper.UseNodaTime,
// we replace an existing resolver of the same CLR type.
if (_pluginResolverFactories.Count > 0 && _pluginResolverFactories[0].GetType() == type)
_pluginResolverFactories[0] = factory;
for (var i = 0; i < _pluginResolverFactories.Count; i++)
{
if (_pluginResolverFactories[i].GetType() == type)
{
_pluginResolverFactories.RemoveAt(i);
break;
}
}
_pluginResolverFactories.Insert(0, factory);
ResetTypeMappingCache();
}
finally
{
_lock.ExitWriteLock();
}
}
public void AddDbTypeResolverFactory(DbTypeResolverFactory factory)
=> throw new NotSupportedException("The global type mapper does not support DbTypeResolverFactories. Call this method on a data source builder instead.");
void ReplaceTypeInfoResolverFactory(PgTypeInfoResolverFactory factory)
{
_lock.EnterWriteLock();
try
{
var type = factory.GetType();
for (var i = 0; i < _pluginResolverFactories.Count; i++)
{
if (_pluginResolverFactories[i].GetType() == type)
{
_pluginResolverFactories[i] = factory;
break;
}
}
ResetTypeMappingCache();
}
finally
{
_lock.ExitWriteLock();
}
}
/// <inheritdoc />
public void Reset()
{
_lock.EnterWriteLock();
try
{
_pluginResolverFactories.Clear();
_userTypeMapper.Items.Clear();
}
finally
{
_lock.ExitWriteLock();
}
}
/// <inheritdoc />
public INpgsqlNameTranslator DefaultNameTranslator
{
get => _userTypeMapper.DefaultNameTranslator;
set => _userTypeMapper.DefaultNameTranslator = value;
}
/// <inheritdoc />
public INpgsqlTypeMapper ConfigureJsonOptions(JsonSerializerOptions serializerOptions)
{
_jsonSerializerOptions = serializerOptions;
// If JsonTypeInfoResolverFactory exists we replace it with a configured instance on the same index of the array.
ReplaceTypeInfoResolverFactory(new JsonTypeInfoResolverFactory(serializerOptions));
return this;
}
/// <inheritdoc />
[RequiresUnreferencedCode("Json serializer may perform reflection on trimmed types.")]
[RequiresDynamicCode("Serializing arbitrary types to json can require creating new generic types or methods, which requires creating code at runtime. This may not work when AOT compiling.")]
public INpgsqlTypeMapper EnableDynamicJson(
Type[]? jsonbClrTypes = null,
Type[]? jsonClrTypes = null)
{
AddTypeInfoResolverFactory(new JsonDynamicTypeInfoResolverFactory(jsonbClrTypes, jsonClrTypes, _jsonSerializerOptions));
return this;
}
/// <inheritdoc />
[RequiresUnreferencedCode("The mapping of PostgreSQL records as .NET tuples requires reflection usage which is incompatible with trimming.")]
[RequiresDynamicCode("The mapping of PostgreSQL records as .NET tuples requires dynamic code usage which is incompatible with NativeAOT.")]
public INpgsqlTypeMapper EnableRecordsAsTuples()
{
AddTypeInfoResolverFactory(new TupledRecordTypeInfoResolverFactory());
return this;
}
/// <inheritdoc />
[RequiresUnreferencedCode("The use of unmapped enums, ranges or multiranges requires reflection usage which is incompatible with trimming.")]
[RequiresDynamicCode("The use of unmapped enums, ranges or multiranges requires dynamic code usage which is incompatible with NativeAOT.")]
public INpgsqlTypeMapper EnableUnmappedTypes()
{
AddTypeInfoResolverFactory(new UnmappedTypeInfoResolverFactory());
return this;
}
/// <inheritdoc />
public INpgsqlTypeMapper MapEnum<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)] TEnum>(string? pgName = null, INpgsqlNameTranslator? nameTranslator = null) where TEnum : struct, Enum
{
_lock.EnterWriteLock();
try
{
_userTypeMapper.MapEnum<TEnum>(pgName, nameTranslator);
ResetTypeMappingCache();
return this;
}
finally
{
_lock.ExitWriteLock();
}
}
/// <inheritdoc />
public bool UnmapEnum<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)] TEnum>(string? pgName = null, INpgsqlNameTranslator? nameTranslator = null) where TEnum : struct, Enum
{
_lock.EnterWriteLock();
try
{
var removed = _userTypeMapper.UnmapEnum<TEnum>(pgName, nameTranslator);
ResetTypeMappingCache();
return removed;
}
finally
{
_lock.ExitWriteLock();
}
}
/// <inheritdoc />
[RequiresDynamicCode("Calling MapEnum with a Type can require creating new generic types or methods. This may not work when AOT compiling.")]
public INpgsqlTypeMapper MapEnum([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)]
Type clrType, string? pgName = null, INpgsqlNameTranslator? nameTranslator = null)
{
_lock.EnterWriteLock();
try
{
_userTypeMapper.MapEnum(clrType, pgName, nameTranslator);
ResetTypeMappingCache();
return this;
}
finally
{
_lock.ExitWriteLock();
}
}
/// <inheritdoc />
public bool UnmapEnum([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)]
Type clrType, string? pgName = null, INpgsqlNameTranslator? nameTranslator = null)
{
_lock.EnterWriteLock();
try
{
var removed = _userTypeMapper.UnmapEnum(clrType, pgName, nameTranslator);
ResetTypeMappingCache();
return removed;
}
finally
{
_lock.ExitWriteLock();
}
}
/// <inheritdoc />
[RequiresDynamicCode("Mapping composite types involves serializing arbitrary types which can require creating new generic types or methods. This is currently unsupported with NativeAOT, vote on issue #5303 if this is important to you.")]
public INpgsqlTypeMapper MapComposite<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.PublicFields)] T>(string? pgName = null, INpgsqlNameTranslator? nameTranslator = null)
=> MapComposite(typeof(T), pgName, nameTranslator);
/// <inheritdoc />
[RequiresDynamicCode("Mapping composite types involves serializing arbitrary types which can require creating new generic types or methods. This is currently unsupported with NativeAOT, vote on issue #5303 if this is important to you.")]
public bool UnmapComposite<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.PublicFields)] T>(string? pgName = null, INpgsqlNameTranslator? nameTranslator = null)
=> UnmapComposite(typeof(T), pgName, nameTranslator);
/// <inheritdoc />
[RequiresDynamicCode("Mapping composite types involves serializing arbitrary types which can require creating new generic types or methods. This is currently unsupported with NativeAOT, vote on issue #5303 if this is important to you.")]
public INpgsqlTypeMapper MapComposite([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.PublicFields)]
Type clrType, string? pgName = null, INpgsqlNameTranslator? nameTranslator = null)
{
_lock.EnterWriteLock();
try
{
_userTypeMapper.MapComposite(clrType, pgName, nameTranslator);
ResetTypeMappingCache();
return this;
}
finally
{
_lock.ExitWriteLock();
}
}
/// <inheritdoc />
[RequiresDynamicCode("Mapping composite types involves serializing arbitrary types which can require creating new generic types or methods. This is currently unsupported with NativeAOT, vote on issue #5303 if this is important to you.")]
public bool UnmapComposite([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.PublicFields)]
Type clrType, string? pgName = null, INpgsqlNameTranslator? nameTranslator = null)
{
_lock.EnterWriteLock();
try
{
var result = _userTypeMapper.UnmapComposite(clrType, pgName, nameTranslator);
ResetTypeMappingCache();
return result;
}
finally
{
_lock.ExitWriteLock();
}
}
}