forked from npgsql/npgsql
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConnectorTypeMapper.cs
More file actions
433 lines (355 loc) · 18.7 KB
/
ConnectorTypeMapper.cs
File metadata and controls
433 lines (355 loc) · 18.7 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
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using Npgsql.Logging;
using Npgsql.PostgresTypes;
using Npgsql.TypeHandlers;
using Npgsql.TypeHandling;
using NpgsqlTypes;
namespace Npgsql.TypeMapping
{
class ConnectorTypeMapper : TypeMapperBase
{
/// <summary>
/// The connector to which this type mapper belongs.
/// </summary>
readonly NpgsqlConnector _connector;
NpgsqlDatabaseInfo? _databaseInfo;
/// <summary>
/// Type information for the database of this mapper.
/// </summary>
internal NpgsqlDatabaseInfo DatabaseInfo
=> _databaseInfo ?? throw new InvalidOperationException("Internal error: this type mapper hasn't yet been bound to a database info object");
internal NpgsqlTypeHandler UnrecognizedTypeHandler { get; }
readonly Dictionary<uint, NpgsqlTypeHandler> _byOID = new Dictionary<uint, NpgsqlTypeHandler>();
readonly Dictionary<NpgsqlDbType, NpgsqlTypeHandler> _byNpgsqlDbType = new Dictionary<NpgsqlDbType, NpgsqlTypeHandler>();
readonly Dictionary<DbType, NpgsqlTypeHandler> _byDbType = new Dictionary<DbType, NpgsqlTypeHandler>();
readonly Dictionary<string, NpgsqlTypeHandler> _byTypeName = new Dictionary<string, NpgsqlTypeHandler>();
/// <summary>
/// Maps CLR types to their type handlers.
/// </summary>
readonly Dictionary<Type, NpgsqlTypeHandler> _byClrType= new Dictionary<Type, NpgsqlTypeHandler>();
/// <summary>
/// Maps CLR types to their array handlers.
/// </summary>
readonly Dictionary<Type, NpgsqlTypeHandler> _arrayHandlerByClrType = new Dictionary<Type, NpgsqlTypeHandler>();
/// <summary>
/// Copy of <see cref="GlobalTypeMapper.ChangeCounter"/> at the time when this
/// mapper was created, to detect mapping changes. If changes are made to this connection's
/// mapper, the change counter is set to -1.
/// </summary>
internal int ChangeCounter { get; private set; }
static readonly NpgsqlLogger Log = NpgsqlLogManager.CreateLogger(nameof(ConnectorTypeMapper));
#region Construction
internal ConnectorTypeMapper(NpgsqlConnector connector): base(GlobalTypeMapper.Instance.DefaultNameTranslator)
{
_connector = connector;
UnrecognizedTypeHandler = new UnknownTypeHandler(_connector.Connection!);
ClearBindings();
ResetMappings();
}
#endregion Constructors
#region Type handler lookup
/// <summary>
/// Looks up a type handler by its PostgreSQL type's OID.
/// </summary>
/// <param name="oid">A PostgreSQL type OID</param>
/// <returns>A type handler that can be used to encode and decode values.</returns>
internal NpgsqlTypeHandler GetByOID(uint oid)
=> TryGetByOID(oid, out var result) ? result : UnrecognizedTypeHandler;
internal bool TryGetByOID(uint oid, [NotNullWhen(true)] out NpgsqlTypeHandler? handler)
=> _byOID.TryGetValue(oid, out handler);
internal NpgsqlTypeHandler GetByNpgsqlDbType(NpgsqlDbType npgsqlDbType)
=> _byNpgsqlDbType.TryGetValue(npgsqlDbType, out var handler)
? handler
: throw new NpgsqlException($"The NpgsqlDbType '{npgsqlDbType}' isn't present in your database. " +
"You may need to install an extension or upgrade to a newer version.");
internal NpgsqlTypeHandler GetByDbType(DbType dbType)
=> _byDbType.TryGetValue(dbType, out var handler)
? handler
: throw new NotSupportedException("This DbType is not supported in Npgsql: " + dbType);
internal NpgsqlTypeHandler GetByDataTypeName(string typeName)
=> _byTypeName.TryGetValue(typeName, out var handler)
? handler
: throw new NotSupportedException("Could not find PostgreSQL type " + typeName);
internal NpgsqlTypeHandler GetByClrType(Type type)
{
if (_byClrType.TryGetValue(type, out var handler))
return handler;
if (Nullable.GetUnderlyingType(type) is Type underlyingType && _byClrType.TryGetValue(underlyingType, out handler))
return handler;
// Try to see if it is an array type
var arrayElementType = GetArrayElementType(type);
if (arrayElementType != null)
{
if (_arrayHandlerByClrType.TryGetValue(arrayElementType, out var elementHandler))
return elementHandler;
throw new NotSupportedException($"The CLR array type {type} isn't supported by Npgsql or your PostgreSQL. " +
"If you wish to map it to an PostgreSQL composite type array you need to register it before usage, please refer to the documentation.");
}
// Nothing worked
if (type.GetTypeInfo().IsEnum)
throw new NotSupportedException($"The CLR enum type {type.Name} must be registered with Npgsql before usage, please refer to the documentation.");
if (typeof(IEnumerable).IsAssignableFrom(type))
throw new NotSupportedException("Npgsql 3.x removed support for writing a parameter with an IEnumerable value, use .ToList()/.ToArray() instead");
throw new NotSupportedException($"The CLR type {type} isn't natively supported by Npgsql or your PostgreSQL. " +
$"To use it with a PostgreSQL composite you need to specify {nameof(NpgsqlParameter.DataTypeName)} or to map it, please refer to the documentation.");
}
static Type? GetArrayElementType(Type type)
{
var typeInfo = type.GetTypeInfo();
if (typeInfo.IsArray)
return GetUnderlyingType(type.GetElementType()!); // The use of bang operator is justified here as Type.GetElementType() only returns null for the Array base class which can't be mapped in a useful way.
var ilist = typeInfo.ImplementedInterfaces.FirstOrDefault(x => x.GetTypeInfo().IsGenericType && x.GetGenericTypeDefinition() == typeof(IList<>));
if (ilist != null)
return GetUnderlyingType(ilist.GetGenericArguments()[0]);
if (typeof(IList).IsAssignableFrom(type))
throw new NotSupportedException("Non-generic IList is a supported parameter, but the NpgsqlDbType parameter must be set on the parameter");
return null;
Type GetUnderlyingType(Type t)
=> Nullable.GetUnderlyingType(t) ?? t;
}
#endregion Type handler lookup
#region Mapping management
public override INpgsqlTypeMapper AddMapping(NpgsqlTypeMapping mapping)
{
CheckReady();
base.AddMapping(mapping);
BindType(mapping, _connector, true);
ChangeCounter = -1;
return this;
}
public override bool RemoveMapping(string pgTypeName)
{
CheckReady();
var removed = base.RemoveMapping(pgTypeName);
if (!removed)
return false;
// Rebind everything. We redo rather than trying to update the
// existing dictionaries because it's complex to remove arrays, ranges...
ClearBindings();
BindTypes();
ChangeCounter = -1;
return true;
}
void CheckReady()
{
if (_connector.State != ConnectorState.Ready)
throw new InvalidOperationException("Connection must be open and idle to perform registration");
}
void ResetMappings()
{
var globalMapper = GlobalTypeMapper.Instance;
globalMapper.Lock.EnterReadLock();
try
{
Mappings.Clear();
foreach (var kv in globalMapper.Mappings)
Mappings.Add(kv.Key, kv.Value);
}
finally
{
globalMapper.Lock.ExitReadLock();
}
ChangeCounter = GlobalTypeMapper.Instance.ChangeCounter;
}
void ClearBindings()
{
_byOID.Clear();
_byNpgsqlDbType.Clear();
_byDbType.Clear();
_byClrType.Clear();
_arrayHandlerByClrType.Clear();
_byNpgsqlDbType[NpgsqlDbType.Unknown] = UnrecognizedTypeHandler;
_byClrType[typeof(DBNull)] = UnrecognizedTypeHandler;
}
public override void Reset()
{
ClearBindings();
ResetMappings();
BindTypes();
}
#endregion Mapping management
#region Binding
internal void Bind(NpgsqlDatabaseInfo databaseInfo)
{
_databaseInfo = databaseInfo;
BindTypes();
}
void BindTypes()
{
foreach (var mapping in Mappings.Values)
BindType(mapping, _connector, false);
// Enums
var enumFactory = new UnmappedEnumTypeHandlerFactory(DefaultNameTranslator);
foreach (var e in DatabaseInfo.EnumTypes.Where(e => !_byOID.ContainsKey(e.OID)))
BindType(enumFactory.Create(e, _connector.Connection!), e);
// Wire up any domains we find to their base type mappings, this is important
// for reading domain fields of composites
foreach (var domain in DatabaseInfo.DomainTypes)
if (_byOID.TryGetValue(domain.BaseType.OID, out var baseTypeHandler))
{
_byOID[domain.OID] = baseTypeHandler;
if (domain.Array != null)
BindType(baseTypeHandler.CreateArrayHandler(domain.Array), domain.Array);
}
}
void BindType(NpgsqlTypeMapping mapping, NpgsqlConnector connector, bool externalCall)
{
// Binding can occur at two different times:
// 1. When a user adds a mapping for a specific connection (and exception should bubble up to them)
// 2. When binding the global mappings, in which case we want to log rather than throw
// (i.e. missing database type for some unused defined binding shouldn't fail the connection)
var pgName = mapping.PgTypeName;
PostgresType? pgType;
if (pgName.IndexOf('.') > -1)
DatabaseInfo.ByFullName.TryGetValue(pgName, out pgType); // Full type name with namespace
else if (DatabaseInfo.ByName.TryGetValue(pgName, out pgType) && pgType is null) // No dot, partial type name
{
// If the name was found but the value is null, that means that there are
// two db types with the same name (different schemas).
// Try to fall back to pg_catalog, otherwise fail.
if (!DatabaseInfo.ByFullName.TryGetValue($"pg_catalog.{pgName}", out pgType))
{
var msg = $"More than one PostgreSQL type was found with the name {mapping.PgTypeName}, please specify a full name including schema";
if (externalCall)
throw new ArgumentException(msg);
Log.Debug(msg);
return;
}
}
if (pgType is null)
{
var msg = $"A PostgreSQL type with the name {mapping.PgTypeName} was not found in the database";
if (externalCall)
throw new ArgumentException(msg);
Log.Debug(msg);
return;
}
if (pgType is PostgresDomainType)
{
var msg = "Cannot add a mapping to a PostgreSQL domain type";
if (externalCall)
throw new NotSupportedException(msg);
Log.Debug(msg);
return;
}
var handler = mapping.TypeHandlerFactory.CreateNonGeneric(pgType, connector.Connection!);
BindType(handler, pgType, mapping.NpgsqlDbType, mapping.DbTypes, mapping.ClrTypes);
if (!externalCall)
return;
foreach (var domain in DatabaseInfo.DomainTypes)
if (domain.BaseType.OID == pgType.OID)
{
_byOID[domain.OID] = handler;
if (domain.Array != null)
BindType(handler.CreateArrayHandler(domain.Array), domain.Array);
}
}
void BindType(NpgsqlTypeHandler handler, PostgresType pgType, NpgsqlDbType? npgsqlDbType = null, DbType[]? dbTypes = null, Type[]? clrTypes = null)
{
_byOID[pgType.OID] = handler;
_byTypeName[pgType.FullName] = handler;
_byTypeName[pgType.Name] = handler;
if (npgsqlDbType.HasValue)
{
var value = npgsqlDbType.Value;
if (_byNpgsqlDbType.ContainsKey(value))
throw new InvalidOperationException($"Two type handlers registered on same NpgsqlDbType '{npgsqlDbType}': {_byNpgsqlDbType[value].GetType().Name} and {handler.GetType().Name}");
_byNpgsqlDbType[npgsqlDbType.Value] = handler;
}
if (dbTypes != null)
{
foreach (var dbType in dbTypes)
{
if (_byDbType.ContainsKey(dbType))
throw new InvalidOperationException($"Two type handlers registered on same DbType {dbType}: {_byDbType[dbType].GetType().Name} and {handler.GetType().Name}");
_byDbType[dbType] = handler;
}
}
if (clrTypes != null)
{
foreach (var type in clrTypes)
{
if (_byClrType.ContainsKey(type))
throw new InvalidOperationException($"Two type handlers registered on same .NET type '{type}': {_byClrType[type].GetType().Name} and {handler.GetType().Name}");
_byClrType[type] = handler;
}
}
if (pgType.Array != null)
BindArrayType(handler, pgType.Array, npgsqlDbType, clrTypes);
if (pgType.Range != null)
BindRangeType(handler, pgType.Range, npgsqlDbType, clrTypes);
}
void BindArrayType(NpgsqlTypeHandler elementHandler, PostgresArrayType pgArrayType, NpgsqlDbType? elementNpgsqlDbType, Type[]? elementClrTypes)
{
var arrayHandler = elementHandler.CreateArrayHandler(pgArrayType);
var arrayNpgsqlDbType = elementNpgsqlDbType.HasValue
? NpgsqlDbType.Array | elementNpgsqlDbType.Value
: (NpgsqlDbType?)null;
BindType(arrayHandler, pgArrayType, arrayNpgsqlDbType);
// Note that array handlers aren't registered in ByClrType like base types, because they handle all
// dimension types and not just one CLR type (e.g. int[], int[,], int[,,]).
// So the by-type lookup is special and goes via _arrayHandlerByClrType, see this[Type type]
// TODO: register single-dimensional in _byType as a specific optimization? But do PSV as well...
if (elementClrTypes != null)
{
foreach (var elementType in elementClrTypes)
{
if (_arrayHandlerByClrType.ContainsKey(elementType))
throw new Exception(
$"Two array type handlers registered on same .NET type {elementType}: {_arrayHandlerByClrType[elementType].GetType().Name} and {arrayHandler.GetType().Name}");
_arrayHandlerByClrType[elementType] = arrayHandler;
}
}
}
void BindRangeType(NpgsqlTypeHandler elementHandler, PostgresRangeType pgRangeType, NpgsqlDbType? elementNpgsqlDbType, Type[]? elementClrTypes)
{
var rangeHandler = elementHandler.CreateRangeHandler(pgRangeType);
var rangeNpgsqlDbType = elementNpgsqlDbType.HasValue
? NpgsqlDbType.Range | elementNpgsqlDbType.Value
: (NpgsqlDbType?)null;
Type[]? clrTypes = null;
if (elementClrTypes != null)
{
// Somewhat hacky. Although the element may have more than one CLR mapping,
// its range will only be mapped to the "main" one for now.
var defaultElementType = elementHandler.GetFieldType();
clrTypes = elementClrTypes.Contains(defaultElementType)
? new[] { rangeHandler.GetFieldType() }
: null;
}
BindType(rangeHandler, pgRangeType, rangeNpgsqlDbType, null, clrTypes);
}
#endregion Binding
internal (NpgsqlDbType? npgsqlDbType, PostgresType postgresType) GetTypeInfoByOid(uint oid)
{
if (!DatabaseInfo.ByOID.TryGetValue(oid, out var postgresType))
throw new InvalidOperationException($"Couldn't find PostgreSQL type with OID {oid}");
// Try to find the postgresType in the mappings
if (TryGetMapping(postgresType, out var npgsqlTypeMapping))
return (npgsqlTypeMapping.NpgsqlDbType, postgresType);
// Try to find the elements' postgresType in the mappings
if (postgresType is PostgresArrayType arrayType &&
TryGetMapping(arrayType.Element, out var elementNpgsqlTypeMapping))
return (elementNpgsqlTypeMapping.NpgsqlDbType | NpgsqlDbType.Array, postgresType);
// Try to find the elements' postgresType of the base type in the mappings
// this happens with domains over arrays
if (postgresType is PostgresDomainType domainType && domainType.BaseType is PostgresArrayType baseType &&
TryGetMapping(baseType.Element, out var baseTypeElementNpgsqlTypeMapping))
return (baseTypeElementNpgsqlTypeMapping.NpgsqlDbType | NpgsqlDbType.Array, postgresType);
// It might be an unmapped enum/composite type, or some other unmapped type
return (null, postgresType);
}
bool TryGetMapping(PostgresType pgType, [MaybeNullWhen(false)] out NpgsqlTypeMapping? mapping)
=> Mappings.TryGetValue(pgType.Name, out mapping) ||
Mappings.TryGetValue(pgType.FullName, out mapping) ||
pgType is PostgresDomainType domain && (
Mappings.TryGetValue(domain.BaseType.Name, out mapping) ||
Mappings.TryGetValue(domain.BaseType.FullName, out mapping));
}
}