-
Notifications
You must be signed in to change notification settings - Fork 890
Expand file tree
/
Copy pathTypeInfoMapping.cs
More file actions
944 lines (812 loc) · 57.9 KB
/
Copy pathTypeInfoMapping.cs
File metadata and controls
944 lines (812 loc) · 57.9 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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Text;
using Npgsql.Internal.Converters;
using Npgsql.Internal.Postgres;
using Npgsql.PostgresTypes;
using NpgsqlTypes;
namespace Npgsql.Internal;
/// <summary>
///
/// </summary>
/// <param name="options"></param>
/// <param name="mapping"></param>
/// <param name="requiresDataTypeName">
/// Relevant for `PgProviderTypeInfo` only: whether the instance can be constructed without passing mapping.DataTypeName, an exception occurs otherwise.
/// </param>
[Experimental(NpgsqlDiagnostics.ConvertersExperimental)]
public delegate PgTypeInfo TypeInfoFactory(PgSerializerOptions options, TypeInfoMapping mapping, bool requiresDataTypeName);
[Experimental(NpgsqlDiagnostics.ConvertersExperimental)]
public enum MatchRequirement
{
/// Match when the clr type and datatype name both match.
/// It's also the only requirement that participates in clr type fallback matching.
All,
/// Match when the datatype name or CLR type matches while the other also matches or is absent.
Single,
/// Match when the datatype name matches and the clr type also matches or is absent.
DataTypeName
}
/// A factory for well-known PgConverters.
[Experimental(NpgsqlDiagnostics.ConvertersExperimental)]
public static class PgConverterFactory
{
public static PgConverter<T[]> CreateArrayMultirangeConverter<T>(PgConverter<T> binaryRange, PgSerializerOptions options) where T : notnull
=> new MultirangeConverter<T[], T>(binaryRange);
public static PgConverter<List<T>> CreateListMultirangeConverter<T>(PgConverter<T> binaryRange, PgSerializerOptions options) where T : notnull
=> new MultirangeConverter<List<T>, T>(binaryRange);
public static PgConverter<NpgsqlRange<T>> CreateRangeConverter<T>(PgConverter<T> binarySubType, PgSerializerOptions options)
=> new RangeConverter<T>(binarySubType);
public static PgConverter<TBase> CreatePolymorphicArrayConverter<TBase>(Func<PgConverter<TBase>> binaryArrayFactory, Func<PgConverter<TBase>> binaryNullableArrayFactory, PgSerializerOptions options)
=> options.ArrayNullabilityMode switch
{
ArrayNullabilityMode.Never => binaryArrayFactory(),
ArrayNullabilityMode.Always => binaryNullableArrayFactory(),
ArrayNullabilityMode.PerInstance => new PolymorphicArrayConverter<TBase>(binaryArrayFactory(), binaryNullableArrayFactory()),
_ => throw new ArgumentOutOfRangeException()
};
}
[DebuggerDisplay("{DebuggerDisplay,nq}")]
[Experimental(NpgsqlDiagnostics.ConvertersExperimental)]
public readonly struct TypeInfoMapping(Type type, string dataTypeName, TypeInfoFactory factory)
{
// For objects it makes no sense to have clr type only matches by default, there are too many implementations.
public TypeInfoFactory Factory { get; init; } = factory;
public Type Type { get; init; } = type;
public string DataTypeName { get; init; } = Postgres.DataTypeName.NormalizeName(dataTypeName);
public MatchRequirement MatchRequirement { get; init; } = type == typeof(object) ? MatchRequirement.DataTypeName : MatchRequirement.All;
public Func<Type?, bool>? TypeMatchPredicate { get; init; }
public bool TypeEquals(Type type) => TypeMatchPredicate?.Invoke(type) ?? Type == type;
bool DataTypeNameEqualsCore(string dataTypeName)
{
var span = DataTypeName.AsSpan();
return Postgres.DataTypeName.IsFullyQualified(span)
? span.Equals(dataTypeName.AsSpan(), StringComparison.Ordinal)
: span.Equals(Postgres.DataTypeName.ValidatedName(dataTypeName).UnqualifiedNameSpan, StringComparison.Ordinal);
}
internal bool DataTypeNameEquals(DataTypeName dataTypeName)
{
var value = dataTypeName.Value;
return DataTypeNameEqualsCore(value);
}
public bool DataTypeNameEquals(string dataTypeName)
{
var normalized = Postgres.DataTypeName.NormalizeName(dataTypeName);
return DataTypeNameEqualsCore(normalized);
}
string DebuggerDisplay
{
get
{
var builder = new StringBuilder()
.Append(Type.Name)
.Append(" <-> ")
.Append(Postgres.DataTypeName.FromDisplayName(DataTypeName).DisplayName);
if (MatchRequirement is not MatchRequirement.All)
builder.Append($" ({MatchRequirement.ToString().ToLowerInvariant()})");
return builder.ToString();
}
}
}
[Experimental(NpgsqlDiagnostics.ConvertersExperimental)]
public sealed class TypeInfoMappingCollection
{
readonly TypeInfoMappingCollection? _baseCollection;
readonly List<TypeInfoMapping> _items;
public TypeInfoMappingCollection(int capacity = 0)
=> _items = new(capacity);
public TypeInfoMappingCollection() : this(0) { }
// Not used for resolving, only for composing (arrays that need to find the element mapping etc).
public TypeInfoMappingCollection(TypeInfoMappingCollection baseCollection) : this(0)
=> _baseCollection = baseCollection;
public TypeInfoMappingCollection(IEnumerable<TypeInfoMapping> items)
=> _items = [..items];
public IReadOnlyList<TypeInfoMapping> Items => _items;
/// Returns the first default converter or the first converter that matches both type and dataTypeName.
/// If just a type was passed and no default was found we return the first converter with a type match.
public PgTypeInfo? Find(Type? type, DataTypeName? dataTypeName, PgSerializerOptions options)
{
TypeInfoMapping? fallback = null;
foreach (var mapping in _items)
{
var looseTypeMatch = mapping.TypeMatchPredicate is { } pred ? pred(type) : type is null || mapping.Type == type;
var typeMatch = type is not null && looseTypeMatch;
var dataTypeMatch = dataTypeName is not null && mapping.DataTypeNameEquals(dataTypeName.Value);
var matchRequirement = mapping.MatchRequirement;
if (dataTypeMatch && typeMatch
|| matchRequirement is not MatchRequirement.All && dataTypeMatch && looseTypeMatch
|| matchRequirement is MatchRequirement.Single && dataTypeName is null && typeMatch)
{
var resolvedDataTypeName = ResolveFullyQualifiedDataTypeName(dataTypeName, mapping.DataTypeName, options);
return mapping.Factory(options, mapping with { Type = type ?? mapping.Type, DataTypeName = resolvedDataTypeName }, dataTypeName is not null);
}
// DataTypeName is explicitly requiring dataTypeName so it won't be used for a fallback, Single would have matched above already.
if (matchRequirement is MatchRequirement.All && fallback is null && dataTypeName is null && typeMatch)
fallback = mapping;
}
if (fallback is { } fbMapping)
{
Debug.Assert(type is not null);
var resolvedDataTypeName = ResolveFullyQualifiedDataTypeName(dataTypeName, fbMapping.DataTypeName, options);
return fbMapping.Factory(options, fbMapping with { Type = type, DataTypeName = resolvedDataTypeName }, dataTypeName is not null);
}
return null;
static string ResolveFullyQualifiedDataTypeName(DataTypeName? dataTypeName, string mappingDataTypeName, PgSerializerOptions options)
{
// Make sure plugins (which match on unqualified names) and type info providers get the fully qualified name to canonicalize.
if (dataTypeName is not null)
return dataTypeName.GetValueOrDefault().Value;
if (TypeInfoMappingHelpers.TryResolveFullyQualifiedName(options, mappingDataTypeName, out var fqDataTypeName))
return fqDataTypeName.Value;
throw new NotSupportedException($"Cannot resolve '{mappingDataTypeName}' to a fully qualified datatype name. The datatype was not found in the current database info.");
}
}
bool TryGetMapping(Type type, string dataTypeName, out TypeInfoMapping value)
{
foreach (var mapping in _baseCollection?._items ?? _items)
{
// During mapping we just use look for the declared type, regardless of TypeMatchPredicate.
if (mapping.Type == type && mapping.DataTypeNameEquals(dataTypeName))
{
value = mapping;
return true;
}
}
value = default;
return false;
}
[MethodImpl(MethodImplOptions.NoInlining)]
TypeInfoMapping GetMapping(Type type, string dataTypeName)
=> TryGetMapping(type, dataTypeName, out var info) ? info : throw new InvalidOperationException($"Could not find mapping for {type} <-> {dataTypeName}");
// Helper to eliminate generic display class duplication.
// Per-format composer: <paramref name="binaryWrap"/> and <paramref name="textWrap"/> are independent;
// each is invoked only when the inner concrete fills the matching slot. Pass only <c>binaryWrap</c> to
// build a binary-only outer (e.g. arrays — PG array wire format is binary). Pass both to mirror the
// inner's slot fill on the outer (nullable structs, object pass-throughs).
static TypeInfoFactory CreateComposedFactory(Type mappingType, TypeInfoMapping innerMapping,
Func<TypeInfoMapping, PgConcreteTypeInfo, PgConverter>? binaryWrap = null,
Func<TypeInfoMapping, PgConcreteTypeInfo, PgConverter>? textWrap = null,
bool copyPreferredFormat = false, bool? supportsReading = null, bool? supportsWriting = null)
=> (options, mapping, requiresDataTypeName) =>
{
var resolvedInnerMapping = innerMapping;
if (!DataTypeName.IsFullyQualified(innerMapping.DataTypeName.AsSpan()))
resolvedInnerMapping = innerMapping with { DataTypeName = new DataTypeName(mapping.DataTypeName).Schema + "." + innerMapping.DataTypeName };
var innerConcrete = (PgConcreteTypeInfo)innerMapping.Factory(options, resolvedInnerMapping, requiresDataTypeName);
PgConverter? binary = null;
PgConverter? text = null;
if (binaryWrap is not null && innerConcrete.TryGetConverter(DataFormat.Binary, out _))
binary = binaryWrap(mapping, innerConcrete);
if (textWrap is not null && innerConcrete.TryGetConverter(DataFormat.Text, out _))
text = textWrap(mapping, innerConcrete);
return innerConcrete.CreateComposition(
binary,
text,
options.GetCanonicalTypeId(new DataTypeName(mapping.DataTypeName)),
requestedType: mapping.Type,
supportsReadingOverride: supportsReading,
supportsWritingOverride: supportsWriting,
preferredFormat: copyPreferredFormat ? innerConcrete.PreferredFormat : null);
};
// Dual-mapper per-format composer: the inner factory may return either PgConcreteTypeInfo (when the
// inner mapping is pgTypeIdClassified and resolution erased the provider) or PgProviderTypeInfo.
// Dispatch on shape — for concretes, the format-specific wrap is invoked per filled slot; for
// providers, <paramref name="providerMapper"/> wraps the inner provider.
static TypeInfoFactory CreateComposedFactory(Type mappingType, TypeInfoMapping innerMapping,
Func<TypeInfoMapping, PgProviderTypeInfo, PgConcreteTypeInfoProvider> providerMapper,
Func<TypeInfoMapping, PgConcreteTypeInfo, PgConverter>? concreteBinaryWrap = null,
Func<TypeInfoMapping, PgConcreteTypeInfo, PgConverter>? concreteTextWrap = null,
bool copyPreferredFormat = false, bool? supportsReading = null, bool? supportsWriting = null)
=> (options, mapping, requiresDataTypeName) =>
{
var resolvedInnerMapping = innerMapping;
if (!DataTypeName.IsFullyQualified(innerMapping.DataTypeName.AsSpan()))
resolvedInnerMapping = innerMapping with { DataTypeName = new DataTypeName(mapping.DataTypeName).Schema + "." + innerMapping.DataTypeName };
var innerInfo = innerMapping.Factory(options, resolvedInnerMapping, requiresDataTypeName);
if (innerInfo is PgConcreteTypeInfo innerConcrete)
{
PgConverter? binary = null;
PgConverter? text = null;
if (concreteBinaryWrap is not null && innerConcrete.TryGetConverter(DataFormat.Binary, out _))
binary = concreteBinaryWrap(mapping, innerConcrete);
if (concreteTextWrap is not null && innerConcrete.TryGetConverter(DataFormat.Text, out _))
text = concreteTextWrap(mapping, innerConcrete);
return innerConcrete.CreateComposition(
binary,
text,
options.GetCanonicalTypeId(new DataTypeName(mapping.DataTypeName)),
requestedType: mapping.Type,
supportsReadingOverride: supportsReading,
supportsWritingOverride: supportsWriting,
preferredFormat: copyPreferredFormat ? innerConcrete.PreferredFormat : null);
}
var providerInfo = (PgProviderTypeInfo)innerInfo;
var typeInfoProvider = providerMapper(mapping, providerInfo);
// We include the data type name if the inner info did so as well.
// This way we can rely on its logic around resolvedDataTypeName, including when it ignores that flag.
PgTypeId? pgTypeId = providerInfo.PgTypeId is not null
? options.GetCanonicalTypeId(new DataTypeName(mapping.DataTypeName))
: null;
return PgProviderTypeInfo.Create(options, typeInfoProvider, pgTypeId, requestedType: mapping.Type);
};
// Wraps a leaf provider factory so that, when the produced PgProviderTypeInfo carries a decided
// PgTypeId, the provider is erased: the default concrete is materialized as a PgConcreteTypeInfo.
// Composers above detect this and skip provider dispatch entirely. Used by registration sites that
// declare their provider's selection is fully pgTypeId-determined (per-value paths only validate or
// re-pick the same default).
static TypeInfoFactory WrapForErasure(TypeInfoFactory inner)
=> (options, mapping, requiresDataTypeName) =>
{
var info = inner(options, mapping, requiresDataTypeName);
if (info is not PgProviderTypeInfo providerInfo || providerInfo.PgTypeId is null)
return info;
return providerInfo.GetDefault(providerInfo.PgTypeId);
};
public void Add(TypeInfoMapping mapping) => _items.Add(mapping);
public void AddRange(TypeInfoMappingCollection collection) => _items.AddRange(collection._items);
Func<TypeInfoMapping, TypeInfoMapping> GetDefaultConfigure(bool isDefault)
=> GetDefaultConfigure(isDefault ? MatchRequirement.Single : MatchRequirement.All);
Func<TypeInfoMapping, TypeInfoMapping> GetDefaultConfigure(MatchRequirement matchRequirement)
=> matchRequirement switch
{
MatchRequirement.All => static mapping => mapping with { MatchRequirement = MatchRequirement.All },
MatchRequirement.DataTypeName => static mapping => mapping with { MatchRequirement = MatchRequirement.DataTypeName },
MatchRequirement.Single => static mapping => mapping with { MatchRequirement = MatchRequirement.Single },
_ => throw new ArgumentOutOfRangeException(nameof(matchRequirement), matchRequirement, null)
};
Func<Type?, bool> GetArrayTypeMatchPredicate(Func<Type?, bool> elementTypeMatchPredicate)
=> type => type is null ? elementTypeMatchPredicate(null) : type.IsArray && elementTypeMatchPredicate(type.GetElementType()!);
Func<Type?, bool> GetListTypeMatchPredicate<TElement>(Func<Type?, bool> elementTypeMatchPredicate)
=> type => type is null ? elementTypeMatchPredicate(null)
// We anti-constrain on IsArray to avoid matching byte/sbyte, short/ushort int/uint
// with the list mapping of the earlier type when an exact match is probably available.
: !type.IsArray && typeof(IList<TElement>).IsAssignableFrom(type) && elementTypeMatchPredicate(typeof(TElement));
public void AddType<T>(string dataTypeName, TypeInfoFactory createInfo, bool isDefault = false) where T : class
=> AddType<T>(dataTypeName, createInfo, GetDefaultConfigure(isDefault));
public void AddType<T>(string dataTypeName, TypeInfoFactory createInfo, MatchRequirement matchRequirement) where T : class
=> AddType<T>(dataTypeName, createInfo, GetDefaultConfigure(matchRequirement));
public void AddType<T>(string dataTypeName, TypeInfoFactory createInfo, Func<TypeInfoMapping, TypeInfoMapping>? configure) where T : class
{
var mapping = new TypeInfoMapping(typeof(T), dataTypeName, createInfo);
mapping = configure?.Invoke(mapping) ?? mapping;
_items.Add(mapping);
if (typeof(T) != typeof(object) && mapping.MatchRequirement is MatchRequirement.DataTypeName or MatchRequirement.Single && !TryGetMapping(typeof(object), mapping.DataTypeName, out _))
_items.Add(new TypeInfoMapping(typeof(object), dataTypeName,
CreateComposedFactory(typeof(T), mapping,
binaryWrap: static (_, c) => c.GetConverter(DataFormat.Binary),
textWrap: static (_, c) => c.GetConverter(DataFormat.Text),
copyPreferredFormat: true))
{
MatchRequirement = mapping.MatchRequirement
});
}
public void AddProviderType<T>(string dataTypeName, TypeInfoFactory createInfo, bool isDefault = false) where T : class
=> AddProviderType<T>(dataTypeName, createInfo, pgTypeIdClassified: false, GetDefaultConfigure(isDefault));
public void AddProviderType<T>(string dataTypeName, TypeInfoFactory createInfo, MatchRequirement matchRequirement) where T : class
=> AddProviderType<T>(dataTypeName, createInfo, pgTypeIdClassified: false, GetDefaultConfigure(matchRequirement));
public void AddProviderType<T>(string dataTypeName, TypeInfoFactory createInfo, Func<TypeInfoMapping, TypeInfoMapping>? configure) where T : class
=> AddProviderType<T>(dataTypeName, createInfo, pgTypeIdClassified: false, configure);
// pgTypeIdClassified: declares that the provider's selection is fully determined by PgTypeId
// (per-value paths only validate or re-pick the same default). When set, registration sites with
// a decided pgTypeId materialize the default concrete directly, erasing the provider — composite
// fields and other decided callers then skip per-value provider dispatch entirely.
internal void AddProviderType<T>(string dataTypeName, TypeInfoFactory createInfo, bool pgTypeIdClassified, bool isDefault = false) where T : class
=> AddProviderType<T>(dataTypeName, createInfo, pgTypeIdClassified, GetDefaultConfigure(isDefault));
internal void AddProviderType<T>(string dataTypeName, TypeInfoFactory createInfo, bool pgTypeIdClassified, MatchRequirement matchRequirement) where T : class
=> AddProviderType<T>(dataTypeName, createInfo, pgTypeIdClassified, GetDefaultConfigure(matchRequirement));
internal void AddProviderType<T>(string dataTypeName, TypeInfoFactory createInfo, bool pgTypeIdClassified, Func<TypeInfoMapping, TypeInfoMapping>? configure) where T : class
{
var factory = pgTypeIdClassified ? WrapForErasure(createInfo) : createInfo;
var mapping = new TypeInfoMapping(typeof(T), dataTypeName, factory);
mapping = configure?.Invoke(mapping) ?? mapping;
if (typeof(T) != typeof(object) && mapping.MatchRequirement is MatchRequirement.DataTypeName or MatchRequirement.Single && !TryGetMapping(typeof(object), mapping.DataTypeName, out _))
_items.Add(new TypeInfoMapping(typeof(object), dataTypeName,
CreateComposedFactory(typeof(T), mapping,
static (_, info) => PgProviderTypeInfo.GetProvider(info),
concreteBinaryWrap: static (_, c) => c.GetConverter(DataFormat.Binary),
concreteTextWrap: static (_, c) => c.GetConverter(DataFormat.Text),
copyPreferredFormat: true))
{
MatchRequirement = mapping.MatchRequirement
});
_items.Add(mapping);
}
public void AddArrayType<TElement>(string elementDataTypeName) where TElement : class
=> AddArrayType<TElement>(GetMapping(typeof(TElement), elementDataTypeName), suppressObjectMapping: false);
public void AddArrayType<TElement>(string elementDataTypeName, bool suppressObjectMapping) where TElement : class
=> AddArrayType<TElement>(GetMapping(typeof(TElement), elementDataTypeName), suppressObjectMapping);
public void AddArrayType<TElement>(TypeInfoMapping elementMapping) where TElement : class
=> AddArrayType<TElement>(elementMapping, suppressObjectMapping: false);
public void AddArrayType<TElement>(TypeInfoMapping elementMapping, bool suppressObjectMapping) where TElement : class
{
// Always use a predicate to match all dimensions.
var arrayTypeMatchPredicate = GetArrayTypeMatchPredicate(elementMapping.TypeMatchPredicate ?? (static type => type is null || type == typeof(TElement)));
var listTypeMatchPredicate = GetListTypeMatchPredicate<TElement>(elementMapping.TypeMatchPredicate ?? (static type => type is null || type == typeof(TElement)));
var arrayDataTypeName = GetArrayDataTypeName(elementMapping.DataTypeName);
AddArrayType(elementMapping, typeof(TElement[]), CreateArrayBasedConverter<TElement>, arrayTypeMatchPredicate, suppressObjectMapping: suppressObjectMapping || TryGetMapping(typeof(object), arrayDataTypeName, out _));
AddArrayType(elementMapping, typeof(IList<TElement>), CreateListBasedConverter<TElement>, listTypeMatchPredicate, suppressObjectMapping: true);
void AddArrayType(TypeInfoMapping elementMapping, Type type, Func<TypeInfoMapping, PgConcreteTypeInfo, PgConverter> converter, Func<Type?, bool>? typeMatchPredicate = null, bool suppressObjectMapping = false)
{
// PG arrays are binary-only on the wire; only the binary slot is filled.
var arrayMapping = new TypeInfoMapping(type, arrayDataTypeName, CreateComposedFactory(type, elementMapping,
binaryWrap: converter, supportsReading: true))
{
MatchRequirement = elementMapping.MatchRequirement,
TypeMatchPredicate = typeMatchPredicate
};
_items.Add(arrayMapping);
suppressObjectMapping = suppressObjectMapping || arrayMapping.TypeEquals(typeof(object));
if (!suppressObjectMapping && arrayMapping.MatchRequirement is MatchRequirement.DataTypeName or MatchRequirement.Single)
_items.Add(new TypeInfoMapping(typeof(object), arrayDataTypeName, (options, mapping, requiresDataTypeName) =>
{
if (!requiresDataTypeName)
throw new InvalidOperationException("Should not happen, please file a bug.");
return arrayMapping.Factory(options, mapping, requiresDataTypeName);
}));
}
}
public void AddProviderArrayType<TElement>(string elementDataTypeName) where TElement : class
=> AddProviderArrayType<TElement>(GetMapping(typeof(TElement), elementDataTypeName), suppressObjectMapping: false);
public void AddProviderArrayType<TElement>(string elementDataTypeName, bool suppressObjectMapping) where TElement : class
=> AddProviderArrayType<TElement>(GetMapping(typeof(TElement), elementDataTypeName), suppressObjectMapping);
public void AddProviderArrayType<TElement>(TypeInfoMapping elementMapping) where TElement : class
=> AddProviderArrayType<TElement>(elementMapping, suppressObjectMapping: false);
public void AddProviderArrayType<TElement>(TypeInfoMapping elementMapping, bool suppressObjectMapping) where TElement : class
{
// Always use a predicate to match all dimensions.
var arrayTypeMatchPredicate = GetArrayTypeMatchPredicate(elementMapping.TypeMatchPredicate ?? (static type => type is null || type == typeof(TElement)));
var listTypeMatchPredicate = GetListTypeMatchPredicate<TElement>(elementMapping.TypeMatchPredicate ?? (static type => type is null || type == typeof(TElement)));
var arrayDataTypeName = GetArrayDataTypeName(elementMapping.DataTypeName);
AddProviderArrayType(elementMapping, typeof(TElement[]), CreateArrayBasedTypeInfoProvider<TElement>, CreateArrayBasedConverter<TElement>, arrayTypeMatchPredicate, suppressObjectMapping: suppressObjectMapping || TryGetMapping(typeof(object), arrayDataTypeName, out _));
AddProviderArrayType(elementMapping, typeof(IList<TElement>), CreateListBasedTypeInfoProvider<TElement>, CreateListBasedConverter<TElement>, listTypeMatchPredicate, suppressObjectMapping: true);
void AddProviderArrayType(TypeInfoMapping elementMapping, Type type,
Func<TypeInfoMapping, PgProviderTypeInfo, PgConcreteTypeInfoProvider> providerConverter,
Func<TypeInfoMapping, PgConcreteTypeInfo, PgConverter> concreteConverter,
Func<Type?, bool>? typeMatchPredicate = null, bool suppressObjectMapping = false)
{
var arrayMapping = new TypeInfoMapping(type, arrayDataTypeName, CreateComposedFactory(type, elementMapping,
providerConverter,
concreteBinaryWrap: concreteConverter,
supportsReading: true))
{
MatchRequirement = elementMapping.MatchRequirement,
TypeMatchPredicate = typeMatchPredicate
};
_items.Add(arrayMapping);
suppressObjectMapping = suppressObjectMapping || arrayMapping.TypeEquals(typeof(object));
if (!suppressObjectMapping && arrayMapping.MatchRequirement is MatchRequirement.DataTypeName or MatchRequirement.Single)
_items.Add(new TypeInfoMapping(typeof(object), arrayDataTypeName, (options, mapping, requiresDataTypeName) =>
{
if (!requiresDataTypeName)
throw new InvalidOperationException("Should not happen, please file a bug.");
return arrayMapping.Factory(options, mapping, requiresDataTypeName);
}));
}
}
public void AddStructType<T>(string dataTypeName, TypeInfoFactory createInfo, bool isDefault = false) where T : struct
=> AddStructType(typeof(T), typeof(T?), dataTypeName, createInfo,
static (_, c) => new NullableConverter<T>((PgConverter<T>)c.GetConverter(DataFormat.Binary)),
static (_, c) => new NullableConverter<T>((PgConverter<T>)c.GetConverter(DataFormat.Text)),
GetDefaultConfigure(isDefault));
public void AddStructType<T>(string dataTypeName, TypeInfoFactory createInfo, MatchRequirement matchRequirement) where T : struct
=> AddStructType(typeof(T), typeof(T?), dataTypeName, createInfo,
static (_, c) => new NullableConverter<T>((PgConverter<T>)c.GetConverter(DataFormat.Binary)),
static (_, c) => new NullableConverter<T>((PgConverter<T>)c.GetConverter(DataFormat.Text)),
GetDefaultConfigure(matchRequirement));
public void AddStructType<T>(string dataTypeName, TypeInfoFactory createInfo, Func<TypeInfoMapping, TypeInfoMapping>? configure) where T : struct
=> AddStructType(typeof(T), typeof(T?), dataTypeName, createInfo,
static (_, c) => new NullableConverter<T>((PgConverter<T>)c.GetConverter(DataFormat.Binary)),
static (_, c) => new NullableConverter<T>((PgConverter<T>)c.GetConverter(DataFormat.Text)),
configure);
// Lives outside to prevent capture of T.
void AddStructType(Type type, Type nullableType, string dataTypeName, TypeInfoFactory createInfo,
Func<TypeInfoMapping, PgConcreteTypeInfo, PgConverter> nullableBinaryWrap,
Func<TypeInfoMapping, PgConcreteTypeInfo, PgConverter> nullableTextWrap,
Func<TypeInfoMapping, TypeInfoMapping>? configure)
{
var mapping = new TypeInfoMapping(type, dataTypeName, createInfo);
mapping = configure?.Invoke(mapping) ?? mapping;
_items.Add(mapping);
if (type != typeof(object) && mapping.MatchRequirement is MatchRequirement.DataTypeName or MatchRequirement.Single && !TryGetMapping(typeof(object), mapping.DataTypeName, out _))
_items.Add(new TypeInfoMapping(typeof(object), dataTypeName,
CreateComposedFactory(type, mapping,
binaryWrap: static (_, c) => c.GetConverter(DataFormat.Binary),
textWrap: static (_, c) => c.GetConverter(DataFormat.Text),
copyPreferredFormat: true))
{
MatchRequirement = mapping.MatchRequirement
});
_items.Add(new TypeInfoMapping(nullableType, dataTypeName,
CreateComposedFactory(nullableType, mapping,
binaryWrap: nullableBinaryWrap,
textWrap: nullableTextWrap,
copyPreferredFormat: true))
{
MatchRequirement = mapping.MatchRequirement,
TypeMatchPredicate = mapping.TypeMatchPredicate is not null
? matchType => matchType is null
? mapping.TypeMatchPredicate(null)
: matchType == nullableType && mapping.TypeMatchPredicate(type)
: null
});
}
public void AddStructArrayType<TElement>(string elementDataTypeName) where TElement : struct
=> AddStructArrayType<TElement>(GetMapping(typeof(TElement), elementDataTypeName), GetMapping(typeof(TElement?), elementDataTypeName), suppressObjectMapping: false);
public void AddStructArrayType<TElement>(string elementDataTypeName, bool suppressObjectMapping) where TElement : struct
=> AddStructArrayType<TElement>(GetMapping(typeof(TElement), elementDataTypeName), GetMapping(typeof(TElement?), elementDataTypeName), suppressObjectMapping);
public void AddStructArrayType<TElement>(TypeInfoMapping elementMapping, TypeInfoMapping nullableElementMapping) where TElement : struct
=> AddStructArrayType<TElement>(elementMapping, nullableElementMapping, suppressObjectMapping: false);
public void AddStructArrayType<TElement>(TypeInfoMapping elementMapping, TypeInfoMapping nullableElementMapping, bool suppressObjectMapping) where TElement : struct
{
// Always use a predicate to match all dimensions.
var arrayTypeMatchPredicate = GetArrayTypeMatchPredicate(elementMapping.TypeMatchPredicate ?? (static type => type is null || type == typeof(TElement)));
var nullableArrayTypeMatchPredicate = GetArrayTypeMatchPredicate(nullableElementMapping.TypeMatchPredicate ?? (static type =>
type is null || type == typeof(TElement?)));
var listTypeMatchPredicate = GetListTypeMatchPredicate<TElement>(elementMapping.TypeMatchPredicate ?? (static type => type is null || type == typeof(TElement)));
var nullableListTypeMatchPredicate = GetListTypeMatchPredicate<TElement?>(nullableElementMapping.TypeMatchPredicate ?? (static type =>
type is null || type == typeof(TElement?)));
var arrayDataTypeName = GetArrayDataTypeName(elementMapping.DataTypeName);
AddStructArrayType(elementMapping, nullableElementMapping, typeof(TElement[]), typeof(TElement?[]),
CreateArrayBasedConverter<TElement>, CreateArrayBasedConverter<TElement?>,
arrayTypeMatchPredicate, nullableArrayTypeMatchPredicate, suppressObjectMapping: suppressObjectMapping || TryGetMapping(typeof(object), arrayDataTypeName, out _));
// Don't add the object converter for the list based converter.
AddStructArrayType(elementMapping, nullableElementMapping, typeof(IList<TElement>), typeof(IList<TElement?>),
CreateListBasedConverter<TElement>, CreateListBasedConverter<TElement?>,
listTypeMatchPredicate, nullableListTypeMatchPredicate, suppressObjectMapping: true);
}
// Lives outside to prevent capture of TElement.
void AddStructArrayType(TypeInfoMapping elementMapping, TypeInfoMapping nullableElementMapping, Type type, Type nullableType,
Func<TypeInfoMapping, PgConcreteTypeInfo, PgConverter> converter, Func<TypeInfoMapping, PgConcreteTypeInfo, PgConverter> nullableConverter,
Func<Type?, bool>? typeMatchPredicate, Func<Type?, bool>? nullableTypeMatchPredicate, bool suppressObjectMapping)
{
var arrayDataTypeName = GetArrayDataTypeName(elementMapping.DataTypeName);
// PG arrays are binary-only; only the binary slot is filled.
var arrayMapping = new TypeInfoMapping(type, arrayDataTypeName, CreateComposedFactory(type, elementMapping,
binaryWrap: converter, supportsReading: true))
{
MatchRequirement = elementMapping.MatchRequirement,
TypeMatchPredicate = typeMatchPredicate
};
var nullableArrayMapping = new TypeInfoMapping(nullableType, arrayDataTypeName, CreateComposedFactory(nullableType, nullableElementMapping,
binaryWrap: nullableConverter, supportsReading: true))
{
MatchRequirement = arrayMapping.MatchRequirement,
TypeMatchPredicate = nullableTypeMatchPredicate
};
_items.Add(arrayMapping);
_items.Add(nullableArrayMapping);
suppressObjectMapping = suppressObjectMapping || arrayMapping.TypeEquals(typeof(object));
if (!suppressObjectMapping && arrayMapping.MatchRequirement is MatchRequirement.DataTypeName or MatchRequirement.Single)
_items.Add(new TypeInfoMapping(typeof(object), arrayDataTypeName, (options, mapping, requiresDataTypeName) =>
{
return options.ArrayNullabilityMode switch
{
_ when !requiresDataTypeName => throw new InvalidOperationException("Should not happen, please file a bug."),
ArrayNullabilityMode.Never => arrayMapping.Factory(options, mapping, requiresDataTypeName),
ArrayNullabilityMode.Always => nullableArrayMapping.Factory(options, mapping, requiresDataTypeName),
ArrayNullabilityMode.PerInstance => CreateComposedPerInstance(
arrayMapping.Factory(options, mapping, requiresDataTypeName),
nullableArrayMapping.Factory(options, mapping, requiresDataTypeName),
mapping.DataTypeName
),
_ => throw new ArgumentOutOfRangeException()
};
}) { MatchRequirement = MatchRequirement.DataTypeName });
PgTypeInfo CreateComposedPerInstance(PgTypeInfo innerInfo, PgTypeInfo nullableInnerInfo, string dataTypeName)
{
var converter =
new PolymorphicArrayConverter<Array>(
(PgConverter<Array>)((PgConcreteTypeInfo)innerInfo).GetConverter(DataFormat.Binary),
(PgConverter<Array>)((PgConcreteTypeInfo)nullableInnerInfo).GetConverter(DataFormat.Binary));
return PgConcreteTypeInfo.Create(innerInfo.Options, converter,
innerInfo.Options.GetCanonicalTypeId(new DataTypeName(dataTypeName)), requestedType: typeof(object), supportsWriting: false);
}
}
public void AddProviderStructType<T>(string dataTypeName, TypeInfoFactory createInfo, bool isDefault = false) where T : struct
=> AddProviderStructType<T>(dataTypeName, createInfo, pgTypeIdClassified: false, GetDefaultConfigure(isDefault));
public void AddProviderStructType<T>(string dataTypeName, TypeInfoFactory createInfo, MatchRequirement matchRequirement) where T : struct
=> AddProviderStructType<T>(dataTypeName, createInfo, pgTypeIdClassified: false, GetDefaultConfigure(matchRequirement));
public void AddProviderStructType<T>(string dataTypeName, TypeInfoFactory createInfo, Func<TypeInfoMapping, TypeInfoMapping>? configure) where T : struct
=> AddProviderStructType<T>(dataTypeName, createInfo, pgTypeIdClassified: false, configure);
// pgTypeIdClassified: see AddProviderType<T>(..., bool pgTypeIdClassified, ...) for the contract.
internal void AddProviderStructType<T>(string dataTypeName, TypeInfoFactory createInfo, bool pgTypeIdClassified, bool isDefault = false) where T : struct
=> AddProviderStructType<T>(dataTypeName, createInfo, pgTypeIdClassified, GetDefaultConfigure(isDefault));
internal void AddProviderStructType<T>(string dataTypeName, TypeInfoFactory createInfo, bool pgTypeIdClassified, MatchRequirement matchRequirement) where T : struct
=> AddProviderStructType<T>(dataTypeName, createInfo, pgTypeIdClassified, GetDefaultConfigure(matchRequirement));
internal void AddProviderStructType<T>(string dataTypeName, TypeInfoFactory createInfo, bool pgTypeIdClassified, Func<TypeInfoMapping, TypeInfoMapping>? configure) where T : struct
=> AddProviderStructType(typeof(T), typeof(T?), dataTypeName, createInfo, pgTypeIdClassified,
static (_, innerInfo) => new NullableTypeInfoProvider<T>(innerInfo),
static (_, c) => new NullableConverter<T>((PgConverter<T>)c.GetConverter(DataFormat.Binary)),
static (_, c) => new NullableConverter<T>((PgConverter<T>)c.GetConverter(DataFormat.Text)),
configure);
// Lives outside to prevent capture of T.
void AddProviderStructType(Type type, Type nullableType, string dataTypeName, TypeInfoFactory createInfo, bool pgTypeIdClassified,
Func<TypeInfoMapping, PgProviderTypeInfo, PgConcreteTypeInfoProvider> nullableProviderConverter,
Func<TypeInfoMapping, PgConcreteTypeInfo, PgConverter> nullableConcreteBinaryWrap,
Func<TypeInfoMapping, PgConcreteTypeInfo, PgConverter> nullableConcreteTextWrap,
Func<TypeInfoMapping, TypeInfoMapping>? configure)
{
var factory = pgTypeIdClassified ? WrapForErasure(createInfo) : createInfo;
var mapping = new TypeInfoMapping(type, dataTypeName, factory);
mapping = configure?.Invoke(mapping) ?? mapping;
if (type != typeof(object) && mapping.MatchRequirement is MatchRequirement.DataTypeName or MatchRequirement.Single && !TryGetMapping(typeof(object), mapping.DataTypeName, out _))
_items.Add(new TypeInfoMapping(typeof(object), dataTypeName,
CreateComposedFactory(type, mapping,
static (_, info) => PgProviderTypeInfo.GetProvider(info),
concreteBinaryWrap: static (_, c) => c.GetConverter(DataFormat.Binary),
concreteTextWrap: static (_, c) => c.GetConverter(DataFormat.Text),
copyPreferredFormat: true))
{
MatchRequirement = mapping.MatchRequirement
});
_items.Add(mapping);
_items.Add(new TypeInfoMapping(nullableType, dataTypeName,
CreateComposedFactory(nullableType, mapping, nullableProviderConverter,
concreteBinaryWrap: nullableConcreteBinaryWrap,
concreteTextWrap: nullableConcreteTextWrap,
copyPreferredFormat: true))
{
MatchRequirement = mapping.MatchRequirement,
TypeMatchPredicate = mapping.TypeMatchPredicate is not null
? matchType => matchType is null
? mapping.TypeMatchPredicate(null)
: matchType == nullableType && mapping.TypeMatchPredicate(type)
: null
});
}
public void AddProviderStructArrayType<TElement>(string elementDataTypeName) where TElement : struct
=> AddProviderStructArrayType<TElement>(GetMapping(typeof(TElement), elementDataTypeName), GetMapping(typeof(TElement?), elementDataTypeName), suppressObjectMapping: false);
public void AddProviderStructArrayType<TElement>(string elementDataTypeName, bool suppressObjectMapping) where TElement : struct
=> AddProviderStructArrayType<TElement>(GetMapping(typeof(TElement), elementDataTypeName), GetMapping(typeof(TElement?), elementDataTypeName), suppressObjectMapping);
public void AddProviderStructArrayType<TElement>(TypeInfoMapping elementMapping, TypeInfoMapping nullableElementMapping) where TElement : struct
=> AddProviderStructArrayType<TElement>(elementMapping, nullableElementMapping, suppressObjectMapping: false);
public void AddProviderStructArrayType<TElement>(TypeInfoMapping elementMapping, TypeInfoMapping nullableElementMapping, bool suppressObjectMapping) where TElement : struct
{
// Always use a predicate to match all dimensions.
var arrayTypeMatchPredicate = GetArrayTypeMatchPredicate(elementMapping.TypeMatchPredicate ?? (static type => type is null || type == typeof(TElement)));
var nullableArrayTypeMatchPredicate = GetArrayTypeMatchPredicate(nullableElementMapping.TypeMatchPredicate ?? (static type =>
type is null || type == typeof(TElement?)));
var listTypeMatchPredicate = GetListTypeMatchPredicate<TElement>(elementMapping.TypeMatchPredicate ?? (static type => type is null || type == typeof(TElement)));
var nullableListTypeMatchPredicate = GetListTypeMatchPredicate<TElement?>(nullableElementMapping.TypeMatchPredicate ?? (static type =>
type is null || type == typeof(TElement?)));
var arrayDataTypeName = GetArrayDataTypeName(elementMapping.DataTypeName);
AddProviderStructArrayType(elementMapping, nullableElementMapping, typeof(TElement[]), typeof(TElement?[]),
CreateArrayBasedTypeInfoProvider<TElement>, CreateArrayBasedConverter<TElement>,
CreateArrayBasedTypeInfoProvider<TElement?>, CreateArrayBasedConverter<TElement?>,
suppressObjectMapping: suppressObjectMapping || TryGetMapping(typeof(object), arrayDataTypeName, out _), arrayTypeMatchPredicate, nullableArrayTypeMatchPredicate);
// Don't add the object converter for the list based converter.
AddProviderStructArrayType(elementMapping, nullableElementMapping, typeof(IList<TElement>), typeof(IList<TElement?>),
CreateListBasedTypeInfoProvider<TElement>, CreateListBasedConverter<TElement>,
CreateListBasedTypeInfoProvider<TElement?>, CreateListBasedConverter<TElement?>,
suppressObjectMapping: true, listTypeMatchPredicate, nullableListTypeMatchPredicate);
}
// Lives outside to prevent capture of TElement.
void AddProviderStructArrayType(TypeInfoMapping elementMapping, TypeInfoMapping nullableElementMapping, Type type, Type nullableType,
Func<TypeInfoMapping, PgProviderTypeInfo, PgConcreteTypeInfoProvider> providerConverter,
Func<TypeInfoMapping, PgConcreteTypeInfo, PgConverter> concreteConverter,
Func<TypeInfoMapping, PgProviderTypeInfo, PgConcreteTypeInfoProvider> nullableProviderConverter,
Func<TypeInfoMapping, PgConcreteTypeInfo, PgConverter> nullableConcreteConverter,
bool suppressObjectMapping, Func<Type?, bool>? typeMatchPredicate, Func<Type?, bool>? nullableTypeMatchPredicate)
{
var arrayDataTypeName = GetArrayDataTypeName(elementMapping.DataTypeName);
var arrayMapping = new TypeInfoMapping(type, arrayDataTypeName, CreateComposedFactory(type, elementMapping,
providerConverter, concreteBinaryWrap: concreteConverter, supportsReading: true))
{
MatchRequirement = elementMapping.MatchRequirement,
TypeMatchPredicate = typeMatchPredicate
};
var nullableArrayMapping = new TypeInfoMapping(nullableType, arrayDataTypeName, CreateComposedFactory(nullableType, nullableElementMapping,
nullableProviderConverter, concreteBinaryWrap: nullableConcreteConverter, supportsReading: true))
{
MatchRequirement = elementMapping.MatchRequirement,
TypeMatchPredicate = nullableTypeMatchPredicate
};
_items.Add(arrayMapping);
_items.Add(nullableArrayMapping);
suppressObjectMapping = suppressObjectMapping || arrayMapping.TypeEquals(typeof(object));
if (!suppressObjectMapping && arrayMapping.MatchRequirement is MatchRequirement.DataTypeName or MatchRequirement.Single)
_items.Add(new TypeInfoMapping(typeof(object), arrayDataTypeName, (options, mapping, requiresDataTypeName) => options.ArrayNullabilityMode switch
{
_ when !requiresDataTypeName => throw new InvalidOperationException("Should not happen, please file a bug."),
ArrayNullabilityMode.Never => arrayMapping.Factory(options, mapping, requiresDataTypeName),
ArrayNullabilityMode.Always => nullableArrayMapping.Factory(options, mapping, requiresDataTypeName),
ArrayNullabilityMode.PerInstance => CreateComposedPerInstance(
arrayMapping.Factory(options, mapping, requiresDataTypeName),
nullableArrayMapping.Factory(options, mapping, requiresDataTypeName),
mapping.DataTypeName
),
_ => throw new ArgumentOutOfRangeException()
}) { MatchRequirement = MatchRequirement.DataTypeName });
PgTypeInfo CreateComposedPerInstance(PgTypeInfo innerInfo, PgTypeInfo nullableInnerInfo, string dataTypeName)
{
// When both inner array typeinfos were erased to concretes (pgTypeIdClassified element provider
// with a decided pgTypeId), polymorphic dispatch is just between two concrete array converters —
// build the PolymorphicArrayConverter directly without wrapping back into a provider.
if (innerInfo is PgConcreteTypeInfo innerConcrete && nullableInnerInfo is PgConcreteTypeInfo nullableInnerConcrete)
{
var concreteConverter = new PolymorphicArrayConverter<Array>(
(PgConverter<Array>)innerConcrete.GetConverter(DataFormat.Binary), (PgConverter<Array>)nullableInnerConcrete.GetConverter(DataFormat.Binary));
return PgConcreteTypeInfo.Create(innerInfo.Options, concreteConverter,
innerInfo.Options.GetCanonicalTypeId(new DataTypeName(dataTypeName)), requestedType: typeof(object), supportsWriting: false);
}
var provider =
new PolymorphicArrayTypeInfoProvider<Array>((PgProviderTypeInfo)innerInfo,
(PgProviderTypeInfo)nullableInnerInfo, isCompositionalUnit: true);
return PgProviderTypeInfo.Create(innerInfo.Options, provider,
innerInfo.Options.GetCanonicalTypeId(new DataTypeName(dataTypeName)), requestedType: typeof(object));
}
}
internal void AddPolymorphicProviderArrayType(string elementDataTypeName, Func<PgSerializerOptions, Func<PgConcreteTypeInfo, PgConverter>> elementToArrayConverterFactory)
=> AddPolymorphicProviderArrayType(GetMapping(typeof(object), elementDataTypeName), elementToArrayConverterFactory);
internal void AddPolymorphicProviderArrayType(TypeInfoMapping elementMapping, Func<PgSerializerOptions, Func<PgConcreteTypeInfo, PgConverter>> elementToArrayConverterFactory)
{
AddPolymorphicProviderArrayType(elementMapping, typeof(object),
(mapping, elementInfo) => new PolymorphicArrayTypeInfoProvider(
elementInfo.Options.GetCanonicalTypeId(new DataTypeName(mapping.DataTypeName)), elementInfo, elementToArrayConverterFactory(elementInfo.Options), isCompositionalUnit: true)
, null);
void AddPolymorphicProviderArrayType(TypeInfoMapping elementMapping, Type type, Func<TypeInfoMapping, PgProviderTypeInfo, PgConcreteTypeInfoProvider> converter, Func<Type?, bool>? typeMatchPredicate)
{
var arrayDataTypeName = GetArrayDataTypeName(elementMapping.DataTypeName);
var mapping = new TypeInfoMapping(type, arrayDataTypeName,
CreateComposedFactory(typeof(Array), elementMapping,
converter,
// Polymorphism only makes sense over a provider element; if the element provider was erased
// to a concrete (pgTypeIdClassified), there's no polymorphism left to express. Today's
// polymorphic elements are unclassified object-shape providers (e.g. LateBindingTypeInfoProvider),
// so this path isn't reached.
static (_, _) => throw new InvalidOperationException("Polymorphic provider arrays do not support pgTypeIdClassified element providers."),
supportsReading: true, supportsWriting: false))
{
MatchRequirement = elementMapping.MatchRequirement,
TypeMatchPredicate = typeMatchPredicate
};
_items.Add(mapping);
}
}
/// Returns whether type matches any of the types we register pg arrays as.
[UnconditionalSuppressMessage("Trimming", "IL2070",
Justification = "Checking for IList<T> implementing types requires interface list enumeration which isn't compatible with trimming. " +
"However as long as a concrete IList<T> is rooted somewhere in the app, for instance through an `AddArrayType<T>(...)` mapping, every implementation must keep it.")]
// We care about IList<T> implementations if the instantiation is actually rooted by us through an Array mapping.
// Dynamic resolvers are a notable counterexample, but they are all correctly marked with RequiresUnreferencedCode.
public static bool IsArrayLikeType(Type type, [NotNullWhen(true)] out Type? elementType)
{
if (type.GetElementType() is { } t)
{
elementType = t;
return true;
}
if (type.IsConstructedGenericType && type.GetGenericTypeDefinition() is var def && (def == typeof(List<>) || def == typeof(IList<>)))
{
elementType = type.GetGenericArguments()[0];
return true;
}
foreach (var inf in type.GetInterfaces())
{
if (inf.IsConstructedGenericType && inf.GetGenericTypeDefinition() == typeof(IList<>))
{
elementType = inf.GetGenericArguments()[0];
return true;
}
}
elementType = null;
return false;
}
static string GetArrayDataTypeName(string dataTypeName)
=> DataTypeName.IsFullyQualified(dataTypeName.AsSpan())
? DataTypeName.ValidatedName(dataTypeName).ToArrayName().Value
: "_" + DataTypeName.FromDisplayName(dataTypeName).UnqualifiedName;
static ArrayConverter<Array> CreateArrayBasedConverter<TElement>(TypeInfoMapping mapping, PgTypeInfo elemInfo)
{
if (!elemInfo.HasExactType)
ThrowRequiresExactType(provider: false);
return ArrayConverter<Array>.CreateArrayBased<TElement>((PgConcreteTypeInfo)elemInfo, mapping.Type);
}
static ArrayConverter<IList<TElement>> CreateListBasedConverter<TElement>(TypeInfoMapping mapping, PgTypeInfo elemInfo)
{
if (!elemInfo.HasExactType)
ThrowRequiresExactType(provider: false);
return ArrayConverter<IList<TElement>>.CreateListBased<TElement>((PgConcreteTypeInfo)elemInfo);
}
static ArrayTypeInfoProvider<Array, TElement> CreateArrayBasedTypeInfoProvider<TElement>(TypeInfoMapping mapping, PgProviderTypeInfo elemInfo)
{
if (!elemInfo.HasExactType)
ThrowRequiresExactType(provider: true);
return new ArrayTypeInfoProvider<Array, TElement>(elemInfo, mapping.Type);
}
static ArrayTypeInfoProvider<IList<TElement>, TElement> CreateListBasedTypeInfoProvider<TElement>(TypeInfoMapping mapping, PgProviderTypeInfo elemInfo)
{
if (!elemInfo.HasExactType)
ThrowRequiresExactType(provider: true);
return new ArrayTypeInfoProvider<IList<TElement>, TElement>(elemInfo, mapping.Type);
}
[DoesNotReturn]
static void ThrowRequiresExactType(bool provider)
=> throw new InvalidOperationException($"An exact-type info is required here; manually construct a mapping over a casting converter{(provider ? " type info provider" : "")} instead.");
}
[Experimental(NpgsqlDiagnostics.ConvertersExperimental)]
public static class TypeInfoMappingHelpers
{
internal static bool TryResolveFullyQualifiedName(PgSerializerOptions options, string dataTypeName, out DataTypeName fqDataTypeName)
{
if (DataTypeName.IsFullyQualified(dataTypeName.AsSpan()))
{
fqDataTypeName = new DataTypeName(dataTypeName);
return true;
}
if (options.DatabaseInfo.TryGetPostgresTypeByName(dataTypeName, out var pgType))
{
fqDataTypeName = pgType.DataTypeName;
return true;
}
fqDataTypeName = default;
return false;
}
internal static PostgresType GetPgType(this TypeInfoMapping mapping, PgSerializerOptions options)
=> options.DatabaseInfo.GetPostgresType(new DataTypeName(mapping.DataTypeName));
// NOTE: This method exists since 9.0 to be able to deprecate the method below that has optional arguments in 10.0 (potentially removing it directly or in 11.0).
// It reduces how binary breaking that change will be if this method would not be there to be picked for the most common invocations.
/// <summary>
/// Creates a PgTypeInfo from a mapping, optins, and a converter.
/// </summary>
/// <param name="mapping">The mapping to create an info for.</param>
/// <param name="options">The options to use.</param>
/// <param name="converter">The converter to create a PgTypeInfo for.</param>
/// <returns>The created info instance.</returns>
public static PgTypeInfo CreateInfo(this TypeInfoMapping mapping, PgSerializerOptions options, PgConverter converter)
=> PgConcreteTypeInfo.Create(options, converter, new DataTypeName(mapping.DataTypeName));
/// <summary>
/// Creates a PgTypeInfo from a mapping, options, and a converter.
/// </summary>
/// <param name="mapping">The mapping to create an info for.</param>
/// <param name="options">The options to use.</param>
/// <param name="converter">The converter to create a PgTypeInfo for.</param>
/// <param name="preferredFormat">Whether to prefer a specific data format for this info, when null it defaults to the most suitable format.</param>
/// <param name="supportsWriting">Whether the converters returned from the given provider support writing.</param>
/// <returns>The created info instance.</returns>
public static PgTypeInfo CreateInfo(this TypeInfoMapping mapping, PgSerializerOptions options, PgConverter converter, DataFormat? preferredFormat = null, bool supportsWriting = true)
=> PgConcreteTypeInfo.Create(options, converter, new DataTypeName(mapping.DataTypeName),
preferredFormat: preferredFormat, supportsWriting: supportsWriting);
// NOTE: This method exists since 11.0 to be able to deprecate the method below that has optional arguments in 12.0 (potentially removing it directly or in 13.0).
/// <summary>
/// Creates a PgTypeInfo from a mapping, options, and explicit per-format converters.
/// </summary>
/// <param name="mapping">The mapping to create an info for.</param>
/// <param name="options">The options to use.</param>
/// <param name="binary">The converter handling the binary wire format.</param>
/// <param name="text">The converter handling the text wire format.</param>
/// <returns>The created info instance.</returns>
public static PgTypeInfo CreateInfo(this TypeInfoMapping mapping, PgSerializerOptions options, PgConverter binary, PgConverter text)
=> PgConcreteTypeInfo.Create(options, binary, text, new DataTypeName(mapping.DataTypeName));
/// <summary>
/// Creates a PgTypeInfo from a mapping, options, and explicit per-format converters.
/// </summary>
/// <param name="mapping">The mapping to create an info for.</param>
/// <param name="options">The options to use.</param>
/// <param name="binary">The converter handling the binary wire format.</param>
/// <param name="text">The converter handling the text wire format.</param>
/// <param name="preferredFormat">Whether to prefer a specific data format for this info, when null it defaults to the most suitable format.</param>
/// <param name="supportsWriting">Whether the converters returned from the given provider support writing.</param>
/// <returns>The created info instance.</returns>
public static PgTypeInfo CreateInfo(this TypeInfoMapping mapping, PgSerializerOptions options, PgConverter binary, PgConverter text, DataFormat? preferredFormat = null, bool supportsWriting = true)
=> PgConcreteTypeInfo.Create(options, binary, text, new DataTypeName(mapping.DataTypeName),
preferredFormat: preferredFormat, supportsWriting: supportsWriting);
// NOTE: This method exists since 9.0 to be able to deprecate the method below that has optional arguments in 10.0 (potentially removing it directly or in 11.0).
// It reduces how binary breaking that change will be if this method would not be there to be picked for the most common invocations.
/// <summary>
/// Creates a PgProviderTypeInfo from a mapping, options, and a provider.
/// </summary>
/// <param name="mapping">The mapping to create an info for.</param>
/// <param name="options">The options to use.</param>
/// <param name="provider">The provider to create a PgProviderTypeInfo for.</param>
/// <param name="includeDataTypeName">Whether to pass mapping.DataTypeName to the PgProviderTypeInfo constructor, mandatory when TypeInfoFactory(..., requiresDataTypeName: true).</param>
/// <returns>The created info instance.</returns>
public static PgTypeInfo CreateInfo(this TypeInfoMapping mapping, PgSerializerOptions options, PgConcreteTypeInfoProvider provider, bool includeDataTypeName)
{
PgTypeId? pgTypeId = includeDataTypeName ? new PgTypeId(new DataTypeName(mapping.DataTypeName)) : null;
return PgProviderTypeInfo.Create(options, provider, pgTypeId);
}
}