-
Notifications
You must be signed in to change notification settings - Fork 874
Expand file tree
/
Copy pathUserTypeMapper.cs
More file actions
278 lines (220 loc) · 14.2 KB
/
UserTypeMapper.cs
File metadata and controls
278 lines (220 loc) · 14.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
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using Npgsql.Internal;
using Npgsql.Internal.Composites;
using Npgsql.Internal.Converters;
using Npgsql.Internal.Postgres;
using Npgsql.NameTranslation;
using Npgsql.PostgresTypes;
using NpgsqlTypes;
namespace Npgsql.TypeMapping;
/// <summary>
/// The base class for user type mappings.
/// </summary>
public abstract class UserTypeMapping
{
/// <summary>
/// The name of the PostgreSQL type that this mapping is for.
/// </summary>
public string PgTypeName { get; }
/// <summary>
/// The CLR type that this mapping is for.
/// </summary>
public Type ClrType { get; }
internal UserTypeMapping(string pgTypeName, Type type)
=> (PgTypeName, ClrType) = (pgTypeName, type);
internal abstract void AddMapping(TypeInfoMappingCollection mappings);
internal abstract void AddArrayMapping(TypeInfoMappingCollection mappings);
}
sealed class UserTypeMapper : PgTypeInfoResolverFactory
{
readonly List<UserTypeMapping> _mappings;
public IList<UserTypeMapping> Items => _mappings;
public INpgsqlNameTranslator DefaultNameTranslator { get; set; } = NpgsqlSnakeCaseNameTranslator.Instance;
UserTypeMapper(IEnumerable<UserTypeMapping> mappings) => _mappings = new List<UserTypeMapping>(mappings);
public UserTypeMapper() => _mappings = new();
public UserTypeMapper Clone() => new(_mappings) { DefaultNameTranslator = DefaultNameTranslator };
public UserTypeMapper MapEnum<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)] TEnum>(string? pgName = null, INpgsqlNameTranslator? nameTranslator = null)
where TEnum : struct, Enum
{
Unmap(typeof(TEnum), out var resolvedName, pgName, nameTranslator);
Items.Add(new EnumMapping<TEnum>(resolvedName, nameTranslator ?? DefaultNameTranslator));
return this;
}
public bool UnmapEnum<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)] TEnum>(
string? pgName = null, INpgsqlNameTranslator? nameTranslator = null)
where TEnum : struct, Enum
=> Unmap(typeof(TEnum), out _, pgName, nameTranslator ?? DefaultNameTranslator);
[UnconditionalSuppressMessage("Trimming", "IL2111", Justification = "MapEnum<TEnum> TEnum has less DAM annotations than clrType.")]
[RequiresDynamicCode("Calling MapEnum with a Type can require creating new generic types or methods. This may not work when AOT compiling.")]
public UserTypeMapper MapEnum([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)]Type clrType, string? pgName = null, INpgsqlNameTranslator? nameTranslator = null)
{
if (!clrType.IsEnum || !clrType.IsValueType)
throw new ArgumentException("Type must be a concrete Enum", nameof(clrType));
var openMethod = typeof(UserTypeMapper).GetMethod(nameof(MapEnum), new[] { typeof(string), typeof(INpgsqlNameTranslator) })!;
var method = openMethod.MakeGenericMethod(clrType);
method.Invoke(this, new object?[] { pgName, nameTranslator });
return this;
}
public bool UnmapEnum([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)]Type clrType,string? pgName = null, INpgsqlNameTranslator? nameTranslator = null)
{
if (!clrType.IsEnum || !clrType.IsValueType)
throw new ArgumentException("Type must be a concrete Enum", nameof(clrType));
return Unmap(clrType, out _, pgName, nameTranslator ?? DefaultNameTranslator);
}
[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 UserTypeMapper MapComposite<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.PublicProperties)] T>(
string? pgName = null, INpgsqlNameTranslator? nameTranslator = null) where T : class
{
Unmap(typeof(T), out var resolvedName, pgName, nameTranslator);
Items.Add(new CompositeMapping<T>(resolvedName, nameTranslator ?? DefaultNameTranslator));
return this;
}
[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 UserTypeMapper MapStructComposite<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.PublicProperties)] T>(
string? pgName = null, INpgsqlNameTranslator? nameTranslator = null) where T : struct
{
Unmap(typeof(T), out var resolvedName, pgName, nameTranslator);
Items.Add(new StructCompositeMapping<T>(resolvedName, nameTranslator ?? DefaultNameTranslator));
return this;
}
[UnconditionalSuppressMessage("Trimming", "IL2111", Justification = "MapStructComposite and MapComposite have identical DAM annotations to clrType.")]
[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 UserTypeMapper MapComposite([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.PublicFields)]
Type clrType, string? pgName = null, INpgsqlNameTranslator? nameTranslator = null)
{
if (clrType.IsConstructedGenericType && clrType.GetGenericTypeDefinition() == typeof(Nullable<>))
throw new ArgumentException("Cannot map nullable.", nameof(clrType));
var openMethod = typeof(UserTypeMapper).GetMethod(
clrType.IsValueType ? nameof(MapStructComposite) : nameof(MapComposite),
new[] { typeof(string), typeof(INpgsqlNameTranslator) })!;
var method = openMethod.MakeGenericMethod(clrType);
method.Invoke(this, new object?[] { pgName, nameTranslator });
return this;
}
public bool UnmapComposite<T>(string? pgName = null, INpgsqlNameTranslator? nameTranslator = null) where T : class
=> UnmapComposite(typeof(T), pgName, nameTranslator);
public bool UnmapStructComposite<T>(string? pgName = null, INpgsqlNameTranslator? nameTranslator = null) where T : struct
=> UnmapComposite(typeof(T), pgName, nameTranslator);
public bool UnmapComposite(Type clrType, string? pgName = null, INpgsqlNameTranslator? nameTranslator = null)
=> Unmap(clrType, out _, pgName, nameTranslator);
bool Unmap(Type type, out string resolvedName, string? pgName = null, INpgsqlNameTranslator? nameTranslator = null)
{
if (pgName != null && pgName.Trim() == "")
throw new ArgumentException("pgName can't be empty", nameof(pgName));
nameTranslator ??= DefaultNameTranslator;
resolvedName = pgName ??= GetPgName(type, nameTranslator);
UserTypeMapping? toRemove = null;
foreach (var item in _mappings)
if (item.PgTypeName == pgName)
toRemove = item;
return toRemove is not null && _mappings.Remove(toRemove);
}
static string GetPgName(Type type, INpgsqlNameTranslator nameTranslator)
=> type.GetCustomAttribute<PgNameAttribute>()?.PgName
?? nameTranslator.TranslateTypeName(type.Name);
public override IPgTypeInfoResolver CreateResolver() => new Resolver(new(_mappings));
public override IPgTypeInfoResolver CreateArrayResolver() => new ArrayResolver(new(_mappings));
class Resolver : IPgTypeInfoResolver
{
protected readonly List<UserTypeMapping> _userTypeMappings;
TypeInfoMappingCollection? _mappings;
protected TypeInfoMappingCollection Mappings => _mappings ??= AddMappings(new());
public Resolver(List<UserTypeMapping> userTypeMappings) => _userTypeMappings = userTypeMappings;
PgTypeInfo? IPgTypeInfoResolver.GetTypeInfo(Type? type, DataTypeName? dataTypeName, PgSerializerOptions options)
=> Mappings.Find(type, dataTypeName, options);
TypeInfoMappingCollection AddMappings(TypeInfoMappingCollection mappings)
{
foreach (var userTypeMapping in _userTypeMappings)
userTypeMapping.AddMapping(mappings);
return mappings;
}
}
sealed class ArrayResolver : Resolver, IPgTypeInfoResolver
{
TypeInfoMappingCollection? _mappings;
new TypeInfoMappingCollection Mappings => _mappings ??= AddMappings(new(base.Mappings));
public ArrayResolver(List<UserTypeMapping> userTypeMappings) : base(userTypeMappings) { }
PgTypeInfo? IPgTypeInfoResolver.GetTypeInfo(Type? type, DataTypeName? dataTypeName, PgSerializerOptions options)
=> Mappings.Find(type, dataTypeName, options);
TypeInfoMappingCollection AddMappings(TypeInfoMappingCollection mappings)
{
foreach (var userTypeMapping in _userTypeMappings)
userTypeMapping.AddArrayMapping(mappings);
return mappings;
}
}
[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.")]
sealed class CompositeMapping<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.PublicProperties)] T> : UserTypeMapping where T : class
{
readonly INpgsqlNameTranslator _nameTranslator;
public CompositeMapping(string pgTypeName, INpgsqlNameTranslator nameTranslator)
: base(pgTypeName, typeof(T))
=> _nameTranslator = nameTranslator;
internal override void AddMapping(TypeInfoMappingCollection mappings)
{
mappings.AddType<T>(PgTypeName, (options, mapping, _) =>
{
var pgType = mapping.GetPgType(options);
if (pgType is not PostgresCompositeType compositeType)
throw new InvalidOperationException("Composite mapping must be to a composite type");
return mapping.CreateInfo(options, new CompositeConverter<T>(
ReflectionCompositeInfoFactory.CreateCompositeInfo<T>(compositeType, _nameTranslator, options)));
}, isDefault: true);
}
internal override void AddArrayMapping(TypeInfoMappingCollection mappings) => mappings.AddArrayType<T>(PgTypeName);
}
[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.")]
sealed class StructCompositeMapping<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.PublicProperties)] T> : UserTypeMapping where T : struct
{
readonly INpgsqlNameTranslator _nameTranslator;
public StructCompositeMapping(string pgTypeName, INpgsqlNameTranslator nameTranslator)
: base(pgTypeName, typeof(T))
=> _nameTranslator = nameTranslator;
internal override void AddMapping(TypeInfoMappingCollection mappings)
{
mappings.AddStructType<T>(PgTypeName, (options, mapping, dataTypeNameMatch) =>
{
var pgType = mapping.GetPgType(options);
if (pgType is not PostgresCompositeType compositeType)
throw new InvalidOperationException("Composite mapping must be to a composite type");
return mapping.CreateInfo(options, new CompositeConverter<T>(
ReflectionCompositeInfoFactory.CreateCompositeInfo<T>(compositeType, _nameTranslator, options)));
}, isDefault: true);
}
internal override void AddArrayMapping(TypeInfoMappingCollection mappings) => mappings.AddStructArrayType<T>(PgTypeName);
}
internal abstract class EnumMapping : UserTypeMapping
{
internal INpgsqlNameTranslator NameTranslator { get; }
public EnumMapping(string pgTypeName, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)]Type enumClrType, INpgsqlNameTranslator nameTranslator)
: base(pgTypeName, enumClrType)
=> NameTranslator = nameTranslator;
}
sealed class EnumMapping<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)] TEnum> : EnumMapping
where TEnum : struct, Enum
{
readonly Dictionary<TEnum, string> _enumToLabel = new();
readonly Dictionary<string, TEnum> _labelToEnum = new();
public EnumMapping(string pgTypeName, INpgsqlNameTranslator nameTranslator)
: base(pgTypeName, typeof(TEnum), nameTranslator)
{
foreach (var field in typeof(TEnum).GetFields(BindingFlags.Static | BindingFlags.Public))
{
var attribute = (PgNameAttribute?)field.GetCustomAttribute(typeof(PgNameAttribute), false);
var enumName = attribute is null
? nameTranslator.TranslateMemberName(field.Name)
: attribute.PgName;
var enumValue = (TEnum)field.GetValue(null)!;
_enumToLabel[enumValue] = enumName;
_labelToEnum[enumName] = enumValue;
}
}
internal override void AddMapping(TypeInfoMappingCollection mappings)
=> mappings.AddStructType<TEnum>(PgTypeName, (options, mapping, _) =>
mapping.CreateInfo(options, new EnumConverter<TEnum>(_enumToLabel, _labelToEnum, options.TextEncoding), preferredFormat: DataFormat.Text), isDefault: true);
internal override void AddArrayMapping(TypeInfoMappingCollection mappings) => mappings.AddStructArrayType<TEnum>(PgTypeName);
}
}