forked from npgsql/npgsql
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTypeHandlerRegistry.cs
More file actions
1313 lines (1119 loc) · 55.6 KB
/
TypeHandlerRegistry.cs
File metadata and controls
1313 lines (1119 loc) · 55.6 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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#region License
// The PostgreSQL License
//
// Copyright (C) 2016 The Npgsql Development Team
//
// Permission to use, copy, modify, and distribute this software and its
// documentation for any purpose, without fee, and without a written
// agreement is hereby granted, provided that the above copyright notice
// and this paragraph and the following two paragraphs appear in all copies.
//
// IN NO EVENT SHALL THE NPGSQL DEVELOPMENT TEAM BE LIABLE TO ANY PARTY
// FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
// INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS
// DOCUMENTATION, EVEN IF THE NPGSQL DEVELOPMENT TEAM HAS BEEN ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
// THE NPGSQL DEVELOPMENT TEAM SPECIFICALLY DISCLAIMS ANY WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
// ON AN "AS IS" BASIS, AND THE NPGSQL DEVELOPMENT TEAM HAS NO OBLIGATIONS
// TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
#endregion
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Diagnostics.Contracts;
using AsyncRewriter;
using JetBrains.Annotations;
using Npgsql.Logging;
using Npgsql.TypeHandlers;
using NpgsqlTypes;
namespace Npgsql
{
internal partial class TypeHandlerRegistry
{
#region Members
internal NpgsqlConnector Connector { get; private set; }
internal TypeHandler UnrecognizedTypeHandler { get; private set; }
internal Dictionary<uint, TypeHandler> ByOID { get; private set; }
readonly Dictionary<DbType, TypeHandler> _byDbType;
readonly Dictionary<NpgsqlDbType, TypeHandler> _byNpgsqlDbType;
/// <summary>
/// Maps CLR types to their type handlers.
/// </summary>
readonly Dictionary<Type, TypeHandler> _byType;
/// <summary>
/// Maps CLR types to their array handlers.
/// </summary>
Dictionary<Type, TypeHandler> _arrayHandlerByType;
BackendTypes _backendTypes;
/// <summary>
/// A counter that is updated when this registry activates its global mappings.
/// Tracks <see cref="_globalMappingChangeCounter"/>, allows us to know when a pooled
/// connection's mappings are no longer up to date because a global mapping change has
/// occurred.
/// </summary>
int _globalMappingActivationCounter = -1;
/// <summary>
/// A counter that is incremented whenever a global mapping change occurs (e.g.
/// <see cref="MapEnumGlobally{T}"/>, <see cref="UnmapCompositeGlobally{T}"/>.
/// <seealso cref="_globalMappingActivationCounter"/>
/// </summary>
static int _globalMappingChangeCounter;
internal static readonly Dictionary<string, TypeAndMapping> HandlerTypes;
static readonly Dictionary<NpgsqlDbType, TypeAndMapping> HandlerTypesByNpsgqlDbType;
static readonly Dictionary<NpgsqlDbType, DbType> NpgsqlDbTypeToDbType;
static readonly Dictionary<DbType, NpgsqlDbType> DbTypeToNpgsqlDbType;
static readonly Dictionary<Type, NpgsqlDbType> TypeToNpgsqlDbType;
static readonly Dictionary<Type, DbType> TypeToDbType;
/// <summary>
/// Caches, for each connection string, the results of the backend type query in the form of a list of type
/// info structs keyed by the PG name.
/// Repeated connections to the same connection string reuse the query results and avoid an additional
/// roundtrip at open-time.
/// </summary>
static readonly ConcurrentDictionary<string, BackendTypes> BackendTypeCache = new ConcurrentDictionary<string, BackendTypes>();
static readonly ConcurrentDictionary<string, IEnumHandlerFactory> _globalEnumMappings;
static readonly ConcurrentDictionary<string, ICompositeHandlerFactory> _globalCompositeMappings;
internal static IDictionary<string, IEnumHandlerFactory> GlobalEnumMappings => _globalEnumMappings;
internal static IDictionary<string, ICompositeHandlerFactory> GlobalCompositeMappings => _globalCompositeMappings;
static readonly INpgsqlNameTranslator DefaultNameTranslator = new NpgsqlSnakeCaseNameTranslator();
static readonly BackendTypes EmptyBackendTypes = new BackendTypes();
static readonly NpgsqlLogger Log = NpgsqlLogManager.GetCurrentClassLogger();
#endregion
#region Initialization and Loading
[RewriteAsync]
internal static void Setup(NpgsqlConnector connector, NpgsqlTimeout timeout)
{
// Note that there's a chicken and egg problem here - LoadBackendTypes below needs a functional
// connector to load the types, hence the strange initialization code here
connector.TypeHandlerRegistry = new TypeHandlerRegistry(connector);
BackendTypes types;
if (!BackendTypeCache.TryGetValue(connector.ConnectionString, out types))
types = BackendTypeCache[connector.ConnectionString] = LoadBackendTypes(connector, timeout);
connector.TypeHandlerRegistry._backendTypes = types;
connector.TypeHandlerRegistry.ActivateGlobalMappings();
}
TypeHandlerRegistry(NpgsqlConnector connector)
{
Connector = connector;
_backendTypes = EmptyBackendTypes;
UnrecognizedTypeHandler = new UnrecognizedTypeHandler();
ByOID = new Dictionary<uint, TypeHandler>();
_byDbType = new Dictionary<DbType, TypeHandler>();
_byNpgsqlDbType = new Dictionary<NpgsqlDbType, TypeHandler>();
_byType = new Dictionary<Type, TypeHandler> { [typeof(DBNull)] = UnrecognizedTypeHandler };
_byNpgsqlDbType[NpgsqlDbType.Unknown] = UnrecognizedTypeHandler;
}
internal void ActivateGlobalMappings()
{
if (_globalMappingActivationCounter == _globalMappingChangeCounter)
return;
foreach (var kv in _globalEnumMappings)
{
var backendType = GetBackendTypeByName(kv.Key);
var backendEnumType = backendType as BackendEnumType;
if (backendEnumType == null)
{
Log.Warn($"While attempting to activate global enum mappings, PostgreSQL type {kv.Key} was found but is not an enum. Skipping it.", Connector.Id);
continue;
}
backendEnumType.Activate(this, kv.Value);
}
foreach (var kv in _globalCompositeMappings)
{
try
{
GetCompositeType(kv.Key).Activate(this, kv.Value);
}
catch (Exception e)
{
Log.Warn("Caught an exception while attempting to activate global composite mappings", e, Connector.Id);
}
}
_globalMappingActivationCounter = _globalMappingChangeCounter;
}
static readonly string TypesQueryWithRange = GenerateTypesQuery(true);
static readonly string TypesQueryWithoutRange = GenerateTypesQuery(false);
static string GenerateTypesQuery(bool withRange)
{
// Select all types (base, array which is also base, enum, range, composite).
// Note that arrays are distinguished from primitive types through them having typreceive=array_recv.
// Order by primitives first, container later.
// For arrays and ranges, join in the element OID and type (to filter out arrays of unhandled
// types).
return
$@"SELECT ns.nspname, a.typname, a.oid, a.typrelid, a.typbasetype,
CASE WHEN pg_proc.proname='array_recv' THEN 'a' ELSE a.typtype END AS type,
CASE
WHEN pg_proc.proname='array_recv' THEN a.typelem
{(withRange ? "WHEN a.typtype='r' THEN rngsubtype" : "")}
ELSE 0
END AS elemoid,
CASE
WHEN pg_proc.proname IN ('array_recv','oidvectorrecv') THEN 3 /* Arrays last */
WHEN a.typtype='r' THEN 2 /* Ranges before */
WHEN a.typtype='d' THEN 1 /* Domains before */
ELSE 0 /* Base types first */
END AS ord
FROM pg_type AS a
JOIN pg_namespace AS ns ON (ns.oid = a.typnamespace)
JOIN pg_proc ON pg_proc.oid = a.typreceive
LEFT OUTER JOIN pg_type AS b ON (b.oid = a.typelem)
{(withRange ? "LEFT OUTER JOIN pg_range ON (pg_range.rngtypid = a.oid) " : "")}
WHERE
(
a.typtype IN ('b', 'r', 'e', 'd') AND
(b.typtype IS NULL OR b.typtype IN ('b', 'r', 'e', 'd')) /* Either non-array or array of supported element type */
) OR
a.typname IN ('record', 'void')
ORDER BY ord";
}
[RewriteAsync]
static BackendTypes LoadBackendTypes(NpgsqlConnector connector, NpgsqlTimeout timeout)
{
var types = new BackendTypes();
using (var command = new NpgsqlCommand(connector.SupportsRangeTypes ? TypesQueryWithRange : TypesQueryWithoutRange, connector.Connection))
{
command.CommandTimeout = timeout.IsSet ? (int)timeout.TimeLeft.TotalSeconds : 0;
command.AllResultTypesAreUnknown = true;
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
timeout.Check();
LoadBackendType(reader, types, connector);
}
}
}
return types;
}
static void LoadBackendType(NpgsqlDataReader reader, BackendTypes types, NpgsqlConnector connector)
{
var ns = reader.GetString(0);
var name = reader.GetString(1);
var oid = Convert.ToUInt32(reader[2]);
Contract.Assume(name != null);
Contract.Assume(oid != 0);
uint elementOID;
var typeChar = reader.GetString(5)[0];
switch (typeChar)
{
case 'b': // Normal base type
TypeAndMapping typeAndMapping;
(
HandlerTypes.TryGetValue(name, out typeAndMapping)
? new BackendBaseType(ns, name, oid, typeAndMapping.HandlerType, typeAndMapping.Mapping)
: new BackendBaseType(ns, name, oid) // Unsupported by Npgsql
).AddTo(types);
return;
case 'a': // Array
elementOID = Convert.ToUInt32(reader[6]);
Contract.Assume(elementOID > 0);
BackendType elementBackendType;
if (!types.ByOID.TryGetValue(elementOID, out elementBackendType))
{
Log.Trace($"Array type '{name}' refers to unknown element with OID {elementOID}, skipping", connector.Id);
return;
}
new BackendArrayType(ns, name, oid, elementBackendType).AddTo(types);
return;
case 'r': // Range
elementOID = Convert.ToUInt32(reader[6]);
Contract.Assume(elementOID > 0);
if (!types.ByOID.TryGetValue(elementOID, out elementBackendType))
{
Log.Trace($"Range type '{name}' refers to unknown subtype with OID {elementOID}, skipping", connector.Id);
return;
}
new BackendRangeType(ns, name, oid, elementBackendType).AddTo(types);
return;
case 'e': // Enum
new BackendEnumType(ns, name, oid).AddTo(types);
return;
case 'd': // Domain
var baseTypeOID = Convert.ToUInt32(reader[4]);
Contract.Assume(baseTypeOID > 0);
BackendType baseBackendType;
if (!types.ByOID.TryGetValue(baseTypeOID, out baseBackendType))
{
Log.Trace($"Domain type '{name}' refers to unknown base type with OID {baseTypeOID}, skipping", connector.Id);
return;
}
new BackendDomainType(ns, name, oid, baseBackendType).AddTo(types);
return;
case 'p': // pseudo-type (record, void)
// Hack this as a base type
goto case 'b';
default:
throw new ArgumentOutOfRangeException($"Unknown typtype for type '{name}' in pg_type: {typeChar}");
}
}
#endregion
#region Enum
internal void MapEnum<TEnum>([CanBeNull] string pgName, [CanBeNull] INpgsqlNameTranslator nameTranslator) where TEnum : struct
{
if (nameTranslator == null)
nameTranslator = DefaultNameTranslator;
if (pgName == null)
pgName = GetPgName<TEnum>(nameTranslator);
var backendType = GetBackendTypeByName(pgName);
var asEnumType = backendType as BackendEnumType;
if (asEnumType == null)
throw new NpgsqlException($"A PostgreSQL type with the name {pgName} was found in the database but it isn't an enum");
asEnumType.Activate(this, new EnumHandler<TEnum>(backendType, nameTranslator));
}
internal static void MapEnumGlobally<TEnum>([CanBeNull] string pgName, [CanBeNull] INpgsqlNameTranslator nameTranslator) where TEnum : struct
{
if (nameTranslator == null)
nameTranslator = DefaultNameTranslator;
if (pgName == null)
pgName = GetPgName<TEnum>(nameTranslator);
_globalMappingChangeCounter++;
_globalEnumMappings[pgName] = new EnumHandler<TEnum>.Factory(nameTranslator);
}
internal static void UnmapEnumGlobally<TEnum>([CanBeNull] string pgName, [CanBeNull] INpgsqlNameTranslator nameTranslator) where TEnum : struct
{
if (nameTranslator == null)
nameTranslator = DefaultNameTranslator;
if (pgName == null)
pgName = GetPgName<TEnum>(nameTranslator);
_globalMappingChangeCounter++;
IEnumHandlerFactory _;
_globalEnumMappings.TryRemove(pgName, out _);
}
#endregion
#region Composite
internal void MapComposite<T>([CanBeNull] string pgName, [CanBeNull] INpgsqlNameTranslator nameTranslator) where T : new()
{
if (nameTranslator == null)
nameTranslator = DefaultNameTranslator;
if (pgName == null)
pgName = GetPgName<T>(nameTranslator);
// TODO: Check if already mapped dude
var compositeType = GetCompositeType(pgName);
compositeType.Activate(this, new CompositeHandler<T>(compositeType, nameTranslator, this));
}
internal static void MapCompositeGlobally<T>([CanBeNull] string pgName, [CanBeNull] INpgsqlNameTranslator nameTranslator) where T : new()
{
if (nameTranslator == null)
nameTranslator = DefaultNameTranslator;
if (pgName == null)
pgName = GetPgName<T>(nameTranslator);
_globalMappingChangeCounter++;
_globalCompositeMappings[pgName] = new CompositeHandler<T>.Factory(nameTranslator);
}
internal static void UnmapCompositeGlobally<T>([CanBeNull] string pgName, [CanBeNull] INpgsqlNameTranslator nameTranslator) where T : new()
{
if (nameTranslator == null)
nameTranslator = DefaultNameTranslator;
if (pgName == null)
pgName = GetPgName<T>(nameTranslator);
_globalMappingChangeCounter++;
ICompositeHandlerFactory _;
_globalCompositeMappings.TryRemove(pgName, out _);
}
#if WAT
const string LoadCompositeQuery =
@"SELECT ns.nspname, a.typname, a.oid,
CASE
WHEN a.typname = @name THEN 0 /* First we load the composite type */
ELSE 1 /* Then we load its array */
END AS ord
FROM pg_type AS a
JOIN pg_namespace AS ns ON (ns.oid = a.typnamespace)
LEFT OUTER JOIN pg_type AS b ON (b.oid = a.typelem)
WHERE
a.typname = @name OR /* The composite type */
b.typname = @name /* The composite's array type */
ORDER BY ord";
const string LoadCompositeWithSchemaQuery =
@"SELECT ns_a.nspname, a.typname, a.oid, a.typtype,
CASE
WHEN a.typname = @name THEN 0 /* First we load the composite type */
ELSE 1 /* Then we load its array */
END AS ord
FROM pg_type AS a
JOIN pg_namespace AS ns_a ON (ns_a.oid = a.typnamespace)
LEFT OUTER JOIN pg_type AS b ON (b.oid = a.typelem)
LEFT OUTER JOIN pg_namespace AS ns_b ON (ns_b.oid = b.typnamespace)
WHERE
(ns_a.nspname = @schema AND a.typname = @name) OR /* The composite type */
(ns_b.nspname = @schema AND b.typname = @name) /* The composite's array type */
ORDER BY ord";
#endif
static string GenerateLoadCompositeQuery(bool withSchema) =>
$@"SELECT ns.nspname, typ.oid, typ.typtype
FROM pg_type AS typ
JOIN pg_namespace AS ns ON (ns.oid = typ.typnamespace)
WHERE (typ.typname = @name{(withSchema ? " AND a.nspname = @schema" : "")});
SELECT att.attname, att.atttypid
FROM pg_type AS typ
JOIN pg_namespace AS ns ON (ns.oid = typ.typnamespace)
JOIN pg_attribute AS att ON (att.attrelid = typ.typrelid)
WHERE
typ.typname = @name{(withSchema ? " AND a.nspname = @schema" : "")} AND
attnum > 0; /* Don't load system attributes */
SELECT ns.nspname, a.typname, a.oid
FROM pg_type AS a
JOIN pg_type AS b ON (b.oid = a.typelem)
JOIN pg_namespace AS ns ON (ns.oid = b.typnamespace)
WHERE a.typtype = 'b' AND b.typname = @name{(withSchema ? " AND b.nspname = @schema" : "")}";
BackendCompositeType GetCompositeType(string pgName)
{
// First check if the composite type definition has already been loaded from the database
BackendType backendType;
if (pgName.IndexOf('.') == -1
? _backendTypes.ByName.TryGetValue(pgName, out backendType)
: _backendTypes.ByFullName.TryGetValue(pgName, out backendType))
{
var asComposite = backendType as BackendCompositeType;
if (asComposite == null)
throw new NpgsqlException($"Type {pgName} was found but is not a composite");
return asComposite;
}
// This is the first time the composite is mapped, the type definition needs to be loaded
string name, schema;
var i = pgName.IndexOf('.');
if (i == -1)
{
schema = null;
name = pgName;
}
else
{
schema = pgName.Substring(0, i);
name = pgName.Substring(i + 1);
}
using (var cmd = new NpgsqlCommand(GenerateLoadCompositeQuery(schema != null), Connector.Connection))
{
cmd.Parameters.AddWithValue("name", name);
if (schema != null)
cmd.Parameters.AddWithValue("schema", schema);
using (var reader = cmd.ExecuteReader())
{
if (!reader.Read())
throw new Exception($"An PostgreSQL type with the name {pgName} was not found in the database");
// Load some info on the composite type itself, do some checks
var ns = reader.GetString(0);
Contract.Assert(schema == null || ns == schema);
var oid = reader.GetFieldValue<uint>(1);
var typeChar = reader.GetChar(2);
if (typeChar != 'c')
throw new NpgsqlException($"Type {pgName} was found in the database but is not a composite");
reader.NextResult(); // Load the fields
var fields = new List<RawCompositeField>();
while (reader.Read())
fields.Add(new RawCompositeField { PgName = reader.GetString(0), TypeOID = reader.GetFieldValue<uint>(1) });
var compositeType = new BackendCompositeType(ns, name, oid, fields);
compositeType.AddTo(_backendTypes);
reader.NextResult(); // Load the array type
if (reader.Read())
{
var arrayNs = reader.GetString(0);
var arrayName = reader.GetString(1);
var arrayOID = reader.GetFieldValue<uint>(2);
new BackendArrayType(arrayNs, arrayName, arrayOID, compositeType).AddTo(_backendTypes);
} else
Log.Warn($"Could not find array type corresponding to composite {pgName}");
return compositeType;
}
}
}
#endregion
#region Lookups
/// <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 TypeHandler this[uint oid]
{
get
{
TypeHandler result;
return TryGetByOID(oid, out result) ? result : UnrecognizedTypeHandler;
}
set { ByOID[oid] = value; }
}
internal bool TryGetByOID(uint oid, out TypeHandler handler)
{
if (ByOID.TryGetValue(oid, out handler))
return true;
BackendType backendType;
if (!_backendTypes.ByOID.TryGetValue(oid, out backendType))
return false;
handler = backendType.Activate(this);
return true;
}
internal TypeHandler this[NpgsqlDbType npgsqlDbType, Type specificType = null]
{
get
{
if (specificType != null && (npgsqlDbType & NpgsqlDbType.Enum) == 0 && (npgsqlDbType & NpgsqlDbType.Composite) == 0)
throw new ArgumentException($"{nameof(specificType)} can only be used with {nameof(NpgsqlDbType.Enum)} or {nameof(NpgsqlDbType.Composite)}");
Contract.EndContractBlock();
TypeHandler handler;
if (_byNpgsqlDbType.TryGetValue(npgsqlDbType, out handler)) {
return handler;
}
if (specificType != null) // Enum/composite
{
// Note that enums and composites are never lazily activated - they're activated at the
// moment of mapping (or at connection time when globally-mapped)
if ((npgsqlDbType & NpgsqlDbType.Array) != 0)
{
// Already-activated array of enum/composite
if (_arrayHandlerByType != null && _arrayHandlerByType.TryGetValue(specificType, out handler))
return handler;
}
// For non-array enum/composite, simply delegate to type inference
return this[specificType];
}
// Couldn't find already activated type, attempt to activate
if (npgsqlDbType == NpgsqlDbType.Enum || npgsqlDbType == NpgsqlDbType.Composite)
throw new InvalidCastException(string.Format("When specifying NpgsqlDbType.{0}, {0}Type must be specified as well",
npgsqlDbType == NpgsqlDbType.Enum ? "Enum" : "Composite"));
// Base, range or array of base/range
BackendType backendType;
if (_backendTypes.ByNpgsqlDbType.TryGetValue(npgsqlDbType, out backendType))
return backendType.Activate(this);
// We don't have a backend type for this NpgsqlDbType. This could be because it's not yet supported by
// Npgsql, or that the type is missing in the database (old PG, missing extension...)
TypeAndMapping typeAndMapping;
if (!HandlerTypesByNpsgqlDbType.TryGetValue(npgsqlDbType, out typeAndMapping))
throw new NotSupportedException("This NpgsqlDbType isn't supported in Npgsql yet: " + npgsqlDbType);
throw new NpgsqlException($"The PostgreSQL type '{typeAndMapping.Mapping.PgName}', mapped to NpgsqlDbType '{npgsqlDbType}' isn't present in your database. " +
"You may need to install an extension or upgrade to a newer version.");
}
}
internal TypeHandler this[DbType dbType]
{
get
{
Contract.Ensures(Contract.Result<TypeHandler>() != null);
TypeHandler handler;
if (_byDbType.TryGetValue(dbType, out handler))
return handler;
BackendType backendType;
if (_backendTypes.ByDbType.TryGetValue(dbType, out backendType))
return backendType.Activate(this);
throw new NotSupportedException("This DbType is not supported in Npgsql: " + dbType);
}
}
internal TypeHandler this[object value]
{
get
{
Contract.Requires(value != null);
Contract.Ensures(Contract.Result<TypeHandler>() != null);
if (value is DateTime)
{
return ((DateTime) value).Kind == DateTimeKind.Utc
? this[NpgsqlDbType.TimestampTZ]
: this[NpgsqlDbType.Timestamp];
}
if (value is NpgsqlDateTime) {
return ((NpgsqlDateTime)value).Kind == DateTimeKind.Utc
? this[NpgsqlDbType.TimestampTZ]
: this[NpgsqlDbType.Timestamp];
}
return this[value.GetType()];
}
}
internal TypeHandler this[Type type]
{
get
{
Contract.Ensures(Contract.Result<TypeHandler>() != null);
TypeHandler handler;
if (_byType.TryGetValue(type, out handler))
return handler;
Type arrayElementType = null;
// Detect arrays and generic ILists
if (type.IsArray)
arrayElementType = type.GetElementType();
else if (typeof(IList).IsAssignableFrom(type))
{
if (!type.GetTypeInfo().IsGenericType)
throw new NotSupportedException("Non-generic IList is a supported parameter, but the NpgsqlDbType parameter must be set on the parameter");
arrayElementType = type.GetGenericArguments()[0];
}
if (arrayElementType != null)
{
TypeHandler elementHandler;
if (_byType.TryGetValue(arrayElementType, out elementHandler) &&
elementHandler.BackendType.NpgsqlDbType.HasValue &&
_byNpgsqlDbType.TryGetValue(NpgsqlDbType.Array | elementHandler.BackendType.NpgsqlDbType.Value, out handler))
{
return handler;
}
// Enum and composite types go through the special _arrayHandlerByType
if (_arrayHandlerByType != null && _arrayHandlerByType.TryGetValue(arrayElementType, out handler))
return handler;
// Unactivated array
// Special check for byte[] - bytea not array of int2
if (type == typeof(byte[]))
{
BackendType byteaBackendType;
if (!_backendTypes.ByClrType.TryGetValue(typeof(byte[]), out byteaBackendType))
throw new NpgsqlException("The PostgreSQL 'bytea' type is missing");
return byteaBackendType.Activate(this);
}
// Get the elements backend type and activate its array backend type
BackendType elementBackendType;
if (!_backendTypes.ByClrType.TryGetValue(arrayElementType, out elementBackendType))
{
if (arrayElementType.GetTypeInfo().IsEnum)
throw new NotSupportedException($"The CLR enum type {arrayElementType.Name} must be mapped with Npgsql before usage, please refer to the documentation.");
throw new NotSupportedException($"The CLR type {arrayElementType} isn't supported by Npgsql or your PostgreSQL. " +
"If you wish to map it to a PostgreSQL composite type you need to register it before usage, please refer to the documentation.");
}
if (elementBackendType == null)
throw new NotSupportedException($"The PostgreSQL {arrayElementType.Name} does not have an array type in the database");
return elementBackendType.Array.Activate(this);
}
BackendType backendType;
// Try to find the backend type by a simple lookup on the given CLR type, this will handle base types.
if (_backendTypes.ByClrType.TryGetValue(type, out backendType))
return backendType.Activate(this);
// Range type which hasn't yet been set up
if (type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition() == typeof(NpgsqlRange<>))
{
BackendType subtypeBackendType;
if (!_backendTypes.ByClrType.TryGetValue(type.GetGenericArguments()[0], out subtypeBackendType) ||
subtypeBackendType.Range == null)
{
throw new NpgsqlException($"The .NET range type {type.Name} isn't supported in your PostgreSQL, use CREATE TYPE AS RANGE");
}
return subtypeBackendType.Range.Activate(this);
}
// 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 supported by Npgsql or your PostgreSQL. " +
"If you wish to map it to a PostgreSQL composite type you need to register it before usage, please refer to the documentation.");
}
}
internal static NpgsqlDbType ToNpgsqlDbType(DbType dbType)
{
return DbTypeToNpgsqlDbType[dbType];
}
internal static NpgsqlDbType ToNpgsqlDbType(object value)
{
if (value is DateTime)
{
return ((DateTime)value).Kind == DateTimeKind.Utc
? NpgsqlDbType.TimestampTZ
: NpgsqlDbType.Timestamp;
}
if (value is NpgsqlDateTime)
{
return ((NpgsqlDateTime)value).Kind == DateTimeKind.Utc
? NpgsqlDbType.TimestampTZ
: NpgsqlDbType.Timestamp;
}
return ToNpgsqlDbType(value.GetType());
}
static NpgsqlDbType ToNpgsqlDbType(Type type)
{
NpgsqlDbType npgsqlDbType;
if (TypeToNpgsqlDbType.TryGetValue(type, out npgsqlDbType)) {
return npgsqlDbType;
}
if (type.IsArray)
{
if (type == typeof(byte[]))
return NpgsqlDbType.Bytea;
return NpgsqlDbType.Array | ToNpgsqlDbType(type.GetElementType());
}
var typeInfo = type.GetTypeInfo();
if (typeInfo.IsEnum)
return NpgsqlDbType.Enum;
if (typeInfo.IsGenericType && type.GetGenericTypeDefinition() == typeof(NpgsqlRange<>))
return NpgsqlDbType.Range | ToNpgsqlDbType(type.GetGenericArguments()[0]);
if (type == typeof(DBNull))
return NpgsqlDbType.Unknown;
throw new NotSupportedException("Can't infer NpgsqlDbType for type " + type);
}
internal static DbType ToDbType(Type type)
{
DbType dbType;
return TypeToDbType.TryGetValue(type, out dbType) ? dbType : DbType.Object;
}
internal static DbType ToDbType(NpgsqlDbType npgsqlDbType)
{
DbType dbType;
return NpgsqlDbTypeToDbType.TryGetValue(npgsqlDbType, out dbType) ? dbType : DbType.Object;
}
#endregion
#region Backend types
/// <summary>
/// A structure holding information about all PostgreSQL types found in an actual database.
/// Only contains <see cref="BackendType"/> instances and not actual <see cref="TypeHandlers"/>, and is shared between
/// all connections using the same connection string. Consulted when a type handler needs to be created.
/// </summary>
class BackendTypes
{
internal Dictionary<uint, BackendType> ByOID { get; } = new Dictionary<uint, BackendType>();
#if !__MonoCS__
/// <summary>
/// Indexes backend types by their PostgreSQL name, including namespace (e.g. pg_catalog.int4).
/// Only used for enums and composites.
/// </summary>
#endif
internal Dictionary<string, BackendType> ByFullName { get; } = new Dictionary<string, BackendType>();
#if !__MonoCS__
/// <summary>
/// Indexes backend types by their PostgreSQL name, not including namespace.
/// If more than one type exists with the same name (i.e. in different namespaces) this
/// table will contain an entry with a null value.
/// Only used for enums and composites.
/// </summary>
#endif
internal Dictionary<string, BackendType> ByName { get; } = new Dictionary<string, BackendType>();
internal Dictionary<NpgsqlDbType, BackendType> ByNpgsqlDbType { get; } = new Dictionary<NpgsqlDbType, BackendType>();
internal Dictionary<DbType, BackendType> ByDbType { get; } = new Dictionary<DbType, BackendType>();
internal Dictionary<Type, BackendType> ByClrType { get; } = new Dictionary<Type, BackendType>();
}
/// <summary>
/// Represents a single PostgreSQL data type, as discovered from pg_type.
/// Note that this simply a data structure describing a type and not a handler, and is shared between connectors
/// having the same connection string.
/// </summary>
abstract class BackendType : IBackendType
{
protected BackendType(string ns, string name, uint oid)
{
Namespace = ns;
Name = name;
FullName = Namespace + '.' + Name;
DisplayName = Namespace == "pg_catalog"
? Name
: FullName;
OID = oid;
}
public string Namespace { get; }
public string Name { get; }
public uint OID { get; }
public NpgsqlDbType? NpgsqlDbType { get; protected set; }
public string FullName { get; }
public string DisplayName { get; }
internal BackendArrayType Array;
internal BackendRangeType Range;
/// <summary>
/// For base types, contains the handler type.
/// If null, this backend type isn't supported by Npgsql.
/// </summary>
[CanBeNull]
internal Type HandlerType;
internal virtual void AddTo(BackendTypes types)
{
types.ByOID[OID] = this;
if (NpgsqlDbType != null)
types.ByNpgsqlDbType[NpgsqlDbType.Value] = this;
}
internal abstract TypeHandler Activate(TypeHandlerRegistry registry);
/// <summary>
/// Returns a string that represents the current object.
/// </summary>
public override string ToString() => DisplayName;
}
class BackendBaseType : BackendType
{
readonly DbType[] _dbTypes;
readonly Type[] _clrTypes;
[CanBeNull] ConstructorInfo _ctorWithRegistry;
[CanBeNull] ConstructorInfo _ctorWithoutRegistry;
/// <summary>
/// Constructs an unsupported base type (no handler exists in Npgsql for this type)
/// </summary>
internal BackendBaseType(string ns, string name, uint oid) : base(ns, name, oid)
{
_dbTypes = new DbType[0];
_clrTypes = new Type[0];
}
internal BackendBaseType(string ns, string name, uint oid, Type handlerType, TypeMappingAttribute mapping)
: base(ns, name, oid)
{
HandlerType = handlerType;
NpgsqlDbType = mapping.NpgsqlDbType;
_dbTypes = mapping.DbTypes;
_clrTypes = mapping.ClrTypes;
}
internal override void AddTo(BackendTypes types)
{
base.AddTo(types);
foreach (var dbType in _dbTypes)
types.ByDbType[dbType] = this;
foreach (var type in _clrTypes)
types.ByClrType[type] = this;
}
internal override TypeHandler Activate(TypeHandlerRegistry registry)
{
if (HandlerType == null)
{
registry.ByOID[OID] = registry.UnrecognizedTypeHandler;
return registry.UnrecognizedTypeHandler;
}
var handler = InstantiateHandler(registry);
registry.ByOID[OID] = handler;
if (NpgsqlDbType.HasValue)
{
var value = NpgsqlDbType.Value;
if (registry._byNpgsqlDbType.ContainsKey(value))
throw new Exception($"Two type handlers registered on same NpgsqlDbType {NpgsqlDbType}: {registry._byNpgsqlDbType[value].GetType().Name} and {HandlerType.Name}");
registry._byNpgsqlDbType[NpgsqlDbType.Value] = handler;
}
if (_dbTypes != null)
{
foreach (var dbType in _dbTypes)
{
if (registry._byDbType.ContainsKey(dbType))
throw new Exception($"Two type handlers registered on same DbType {dbType}: {registry._byDbType[dbType].GetType().Name} and {HandlerType.Name}");
registry._byDbType[dbType] = handler;
}
}
if (_clrTypes != null)
{
foreach (var type in _clrTypes)
{
if (registry._byType.ContainsKey(type))
throw new Exception($"Two type handlers registered on same .NET type {type}: {registry._byType[type].GetType().Name} and {HandlerType.Name}");
registry._byType[type] = handler;
}
}
return handler;
}
/// <summary>
/// Instantiate the type handler. If it has a constructor that accepts a TypeHandlerRegistry, use that to allow
/// the handler to make connector-specific adjustments. Otherwise (the normal case), use the default constructor.
/// </summary>
/// <param name="registry"></param>
/// <returns></returns>
TypeHandler InstantiateHandler(TypeHandlerRegistry registry)
{
Contract.Assert(HandlerType != null);
if (_ctorWithRegistry == null && _ctorWithoutRegistry == null)
{
var ctors = HandlerType.GetConstructors(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
_ctorWithRegistry = (
from c in ctors
let p = c.GetParameters()
where p.Length == 2 && p[0].ParameterType == typeof(IBackendType) && p[1].ParameterType == typeof(TypeHandlerRegistry)
select c
).FirstOrDefault();
if (_ctorWithRegistry == null)
{
_ctorWithoutRegistry = (
from c in ctors
let p = c.GetParameters()
where p.Length == 1 && p[0].ParameterType == typeof(IBackendType)
select c
).FirstOrDefault();
if (_ctorWithoutRegistry == null)
throw new Exception($"Type handler type {HandlerType.Name} does not have an appropriate constructor");
}
}
if (_ctorWithRegistry != null)
return (TypeHandler)_ctorWithRegistry.Invoke(new object[] { this, registry });
Contract.Assert(_ctorWithoutRegistry != null);
return (TypeHandler)_ctorWithoutRegistry.Invoke(new object[] { this });
}
}
class BackendArrayType : BackendType
{
readonly BackendType _element;
internal BackendArrayType(string ns, string name, uint oid, BackendType elementBackendType)
: base(ns, name, oid)
{
_element = elementBackendType;
if (elementBackendType.NpgsqlDbType.HasValue)
NpgsqlDbType = NpgsqlTypes.NpgsqlDbType.Array | elementBackendType.NpgsqlDbType;
_element.Array = this;
}
internal override TypeHandler Activate(TypeHandlerRegistry registry)
{
TypeHandler elementHandler;
if (!registry.TryGetByOID(_element.OID, out elementHandler))
{
// Element type hasn't been set up yet, do it now
elementHandler = _element.Activate(registry);
}
var arrayHandler = elementHandler.CreateArrayHandler(this);
registry.ByOID[OID] = arrayHandler;
var asEnumHandler = elementHandler as IEnumHandler;
if (asEnumHandler != null)
{