-
Notifications
You must be signed in to change notification settings - Fork 876
Expand file tree
/
Copy pathGlobalTypeMapper.cs
More file actions
290 lines (257 loc) · 12.2 KB
/
GlobalTypeMapper.cs
File metadata and controls
290 lines (257 loc) · 12.2 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
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
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 object _sync = new();
PgTypeInfoResolverFactory[] _typeMappingResolvers = [];
internal IEnumerable<PgTypeInfoResolverFactory> GetPluginResolverFactories()
{
lock (_sync)
return new List<PgTypeInfoResolverFactory>(_pluginResolverFactories);
}
internal PgTypeInfoResolverFactory? GetUserMappingsResolverFactory()
{
lock (_sync)
return _userTypeMapper.Items.Count > 0 ? _userTypeMapper : null;
}
internal void AddGlobalTypeMappingResolvers(PgTypeInfoResolverFactory[] factories, Func<PgTypeInfoResolverChainBuilder>? builderFactory = null, bool overwrite = false)
{
lock (_sync)
{
// Good enough logic to prevent SlimBuilder overriding the normal Builder.
if (overwrite || factories.Length > _typeMappingResolvers.Length)
{
_builderFactory = builderFactory;
_typeMappingResolvers = factories;
_typeMappingOptions = null;
}
}
}
PgSerializerOptions? _typeMappingOptions;
Func<PgTypeInfoResolverChainBuilder>? _builderFactory;
JsonSerializerOptions? _jsonSerializerOptions;
PgSerializerOptions TypeMappingOptions => _typeMappingOptions ?? BuildTypeMappingOptions();
PgSerializerOptions BuildTypeMappingOptions()
{
lock (_sync)
{
if (_typeMappingOptions is { } existing)
return existing;
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();
var options = new PgSerializerOptions(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
};
_typeMappingOptions = options;
return options;
}
}
internal DataTypeName? FindDataTypeName(Type type, object? value)
{
DataTypeName? dataTypeName;
try
{
var typeInfo = TypeMappingOptions.GetTypeInfoInternal(type, null);
if (typeInfo is PgProviderTypeInfo providerInfo)
{
dataTypeName = providerInfo.GetObjectConcreteTypeInfo(value, out var state).PgTypeId.DataTypeName;
if (state is not null)
providerInfo.DisposeWriteState(state);
}
else
{
dataTypeName = ((PgConcreteTypeInfo?)typeInfo)?.PgTypeId.DataTypeName;
}
}
catch
{
dataTypeName = null;
}
return dataTypeName;
}
internal static GlobalTypeMapper Instance { get; }
static GlobalTypeMapper()
=> Instance = new GlobalTypeMapper();
/// <inheritdoc />
public void AddTypeInfoResolverFactory(PgTypeInfoResolverFactory factory)
{
lock (_sync)
{
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);
_typeMappingOptions = null;
}
}
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.");
/// <inheritdoc />
public void Reset()
{
lock (_sync)
{
_pluginResolverFactories.Clear();
_userTypeMapper.Items.Clear();
_typeMappingOptions = null;
}
}
/// <inheritdoc />
public INpgsqlNameTranslator DefaultNameTranslator
{
get => _userTypeMapper.DefaultNameTranslator;
set => _userTypeMapper.DefaultNameTranslator = value;
}
/// <inheritdoc />
public INpgsqlTypeMapper ConfigureJsonOptions(JsonSerializerOptions serializerOptions)
{
lock (_sync)
{
_jsonSerializerOptions = serializerOptions;
// If JsonTypeInfoResolverFactory exists we replace it with a configured instance on the same index of the array.
var factory = new JsonTypeInfoResolverFactory(serializerOptions);
var type = factory.GetType();
for (var i = 0; i < _pluginResolverFactories.Count; i++)
{
if (_pluginResolverFactories[i].GetType() == type)
{
_pluginResolverFactories[i] = factory;
break;
}
}
_typeMappingOptions = null;
}
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)
{
// Use a re-entered lock to add the read of _jsonSerializerOptions to the total scope.
lock (_sync)
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 (_sync)
{
_userTypeMapper.MapEnum<TEnum>(pgName, nameTranslator);
_typeMappingOptions = null;
return this;
}
}
/// <inheritdoc />
public bool UnmapEnum<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)] TEnum>(string? pgName = null, INpgsqlNameTranslator? nameTranslator = null) where TEnum : struct, Enum
{
lock (_sync)
{
var removed = _userTypeMapper.UnmapEnum<TEnum>(pgName, nameTranslator);
_typeMappingOptions = null;
return removed;
}
}
/// <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 (_sync)
{
_userTypeMapper.MapEnum(clrType, pgName, nameTranslator);
_typeMappingOptions = null;
return this;
}
}
/// <inheritdoc />
public bool UnmapEnum([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)]
Type clrType, string? pgName = null, INpgsqlNameTranslator? nameTranslator = null)
{
lock (_sync)
{
var removed = _userTypeMapper.UnmapEnum(clrType, pgName, nameTranslator);
_typeMappingOptions = null;
return removed;
}
}
/// <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 (_sync)
{
_userTypeMapper.MapComposite(clrType, pgName, nameTranslator);
_typeMappingOptions = null;
return this;
}
}
/// <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 (_sync)
{
var result = _userTypeMapper.UnmapComposite(clrType, pgName, nameTranslator);
_typeMappingOptions = null;
return result;
}
}
}