-
Notifications
You must be signed in to change notification settings - Fork 874
Expand file tree
/
Copy pathNpgsqlParameter.cs
More file actions
904 lines (785 loc) · 34 KB
/
NpgsqlParameter.cs
File metadata and controls
904 lines (785 loc) · 34 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
using System;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using Npgsql.Internal;
using Npgsql.Internal.Postgres;
using Npgsql.PostgresTypes;
using Npgsql.TypeMapping;
using Npgsql.Util;
using NpgsqlTypes;
namespace Npgsql;
///<summary>
/// This class represents a parameter to a command that will be sent to server
///</summary>
public class NpgsqlParameter : DbParameter, IDbDataParameter, ICloneable
{
#region Fields and Properties
private protected byte _precision;
private protected byte _scale;
private protected int _size;
internal NpgsqlDbType? _npgsqlDbType;
internal string? _dataTypeName;
internal DbType? _dbType;
private protected string _name = string.Empty;
object? _value;
private protected bool _useSubStream;
private protected SubReadStream? _subStream;
private protected string _sourceColumn;
internal string TrimmedName { get; private protected set; } = PositionalName;
internal const string PositionalName = "";
IDbTypeResolver? _dbTypeResolver;
private protected PgTypeInfo? TypeInfo { get; private set; }
internal PgTypeId PgTypeId { get; private set; }
private protected PgConverter? Converter { get; private set; }
internal DataFormat Format { get; private protected set; }
private protected Size? WriteSize { get; set; }
private protected object? _writeState;
private protected Size _bufferRequirement;
private protected bool _asObject;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="NpgsqlParameter"/> class.
/// </summary>
public NpgsqlParameter()
{
_sourceColumn = string.Empty;
Direction = ParameterDirection.Input;
SourceVersion = DataRowVersion.Current;
}
/// <summary>
/// Initializes a new instance of the <see cref="NpgsqlParameter"/> class with the parameter name and a value.
/// </summary>
/// <param name="parameterName">The name of the parameter to map.</param>
/// <param name="value">The value of the <see cref="NpgsqlParameter"/>.</param>
/// <remarks>
/// <p>
/// When you specify an <see cref="object"/> in the value parameter, the <see cref="System.Data.DbType"/> is
/// inferred from the CLR type.
/// </p>
/// <p>
/// When using this constructor, you must be aware of a possible misuse of the constructor which takes a <see cref="DbType"/>
/// parameter. This happens when calling this constructor passing an int 0 and the compiler thinks you are passing a value of
/// <see cref="DbType"/>. Use <see cref="Convert.ToInt32(object)"/> for example to have compiler calling the correct constructor.
/// </p>
/// </remarks>
public NpgsqlParameter(string? parameterName, object? value)
: this()
{
ParameterName = parameterName;
// ReSharper disable once VirtualMemberCallInConstructor
Value = value;
}
/// <summary>
/// Initializes a new instance of the <see cref="NpgsqlParameter"/> class with the parameter name and the data type.
/// </summary>
/// <param name="parameterName">The name of the parameter to map.</param>
/// <param name="parameterType">One of the <see cref="NpgsqlTypes.NpgsqlDbType"/> values.</param>
public NpgsqlParameter(string? parameterName, NpgsqlDbType parameterType)
: this(parameterName, parameterType, 0, string.Empty)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="NpgsqlParameter"/>.
/// </summary>
/// <param name="parameterName">The name of the parameter to map.</param>
/// <param name="parameterType">One of the <see cref="System.Data.DbType"/> values.</param>
public NpgsqlParameter(string? parameterName, DbType parameterType)
: this(parameterName, parameterType, 0, string.Empty)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="NpgsqlParameter"/>.
/// </summary>
/// <param name="parameterName">The name of the parameter to map.</param>
/// <param name="parameterType">One of the <see cref="NpgsqlTypes.NpgsqlDbType"/> values.</param>
/// <param name="size">The length of the parameter.</param>
public NpgsqlParameter(string? parameterName, NpgsqlDbType parameterType, int size)
: this(parameterName, parameterType, size, string.Empty)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="NpgsqlParameter"/>.
/// </summary>
/// <param name="parameterName">The name of the parameter to map.</param>
/// <param name="parameterType">One of the <see cref="System.Data.DbType"/> values.</param>
/// <param name="size">The length of the parameter.</param>
public NpgsqlParameter(string? parameterName, DbType parameterType, int size)
: this(parameterName, parameterType, size, string.Empty)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="NpgsqlParameter"/>
/// </summary>
/// <param name="parameterName">The name of the parameter to map.</param>
/// <param name="parameterType">One of the <see cref="NpgsqlTypes.NpgsqlDbType"/> values.</param>
/// <param name="size">The length of the parameter.</param>
/// <param name="sourceColumn">The name of the source column.</param>
public NpgsqlParameter(string? parameterName, NpgsqlDbType parameterType, int size, string? sourceColumn)
{
ParameterName = parameterName;
NpgsqlDbType = parameterType;
_size = size;
_sourceColumn = sourceColumn ?? string.Empty;
Direction = ParameterDirection.Input;
SourceVersion = DataRowVersion.Current;
}
/// <summary>
/// Initializes a new instance of the <see cref="NpgsqlParameter"/>.
/// </summary>
/// <param name="parameterName">The name of the parameter to map.</param>
/// <param name="parameterType">One of the <see cref="System.Data.DbType"/> values.</param>
/// <param name="size">The length of the parameter.</param>
/// <param name="sourceColumn">The name of the source column.</param>
public NpgsqlParameter(string? parameterName, DbType parameterType, int size, string? sourceColumn)
{
ParameterName = parameterName;
DbType = parameterType;
_size = size;
_sourceColumn = sourceColumn ?? string.Empty;
Direction = ParameterDirection.Input;
SourceVersion = DataRowVersion.Current;
}
/// <summary>
/// Initializes a new instance of the <see cref="NpgsqlParameter"/>.
/// </summary>
/// <param name="parameterName">The name of the parameter to map.</param>
/// <param name="parameterType">One of the <see cref="NpgsqlTypes.NpgsqlDbType"/> values.</param>
/// <param name="size">The length of the parameter.</param>
/// <param name="sourceColumn">The name of the source column.</param>
/// <param name="direction">One of the <see cref="System.Data.ParameterDirection"/> values.</param>
/// <param name="isNullable">
/// <see langword="true"/> if the value of the field can be <see langword="null"/>, otherwise <see langword="false"/>.
/// </param>
/// <param name="precision">
/// The total number of digits to the left and right of the decimal point to which <see cref="Value"/> is resolved.
/// </param>
/// <param name="scale">The total number of decimal places to which <see cref="Value"/> is resolved.</param>
/// <param name="sourceVersion">One of the <see cref="System.Data.DataRowVersion"/> values.</param>
/// <param name="value">An <see cref="object"/> that is the value of the <see cref="NpgsqlParameter"/>.</param>
public NpgsqlParameter(string parameterName, NpgsqlDbType parameterType, int size, string? sourceColumn,
ParameterDirection direction, bool isNullable, byte precision, byte scale,
DataRowVersion sourceVersion, object value)
{
ParameterName = parameterName;
Size = size;
_sourceColumn = sourceColumn ?? string.Empty;
Direction = direction;
IsNullable = isNullable;
Precision = precision;
Scale = scale;
SourceVersion = sourceVersion;
// ReSharper disable once VirtualMemberCallInConstructor
Value = value;
NpgsqlDbType = parameterType;
}
/// <summary>
/// Initializes a new instance of the <see cref="NpgsqlParameter"/>.
/// </summary>
/// <param name="parameterName">The name of the parameter to map.</param>
/// <param name="parameterType">One of the <see cref="System.Data.DbType"/> values.</param>
/// <param name="size">The length of the parameter.</param>
/// <param name="sourceColumn">The name of the source column.</param>
/// <param name="direction">One of the <see cref="System.Data.ParameterDirection"/> values.</param>
/// <param name="isNullable">
/// <see langword="true"/> if the value of the field can be <see langword="null"/>, otherwise <see langword="false"/>.
/// </param>
/// <param name="precision">
/// The total number of digits to the left and right of the decimal point to which <see cref="Value"/> is resolved.
/// </param>
/// <param name="scale">The total number of decimal places to which <see cref="Value"/> is resolved.</param>
/// <param name="sourceVersion">One of the <see cref="System.Data.DataRowVersion"/> values.</param>
/// <param name="value">An <see cref="object"/> that is the value of the <see cref="NpgsqlParameter"/>.</param>
public NpgsqlParameter(string parameterName, DbType parameterType, int size, string? sourceColumn,
ParameterDirection direction, bool isNullable, byte precision, byte scale,
DataRowVersion sourceVersion, object value)
{
ParameterName = parameterName;
Size = size;
_sourceColumn = sourceColumn ?? string.Empty;
Direction = direction;
IsNullable = isNullable;
Precision = precision;
Scale = scale;
SourceVersion = sourceVersion;
// ReSharper disable once VirtualMemberCallInConstructor
Value = value;
DbType = parameterType;
}
#endregion
#region Name
/// <summary>
/// Gets or sets The name of the <see cref="NpgsqlParameter"/>.
/// </summary>
/// <value>The name of the <see cref="NpgsqlParameter"/>.
/// The default is an empty string.</value>
[AllowNull, DefaultValue("")]
public sealed override string ParameterName
{
get => _name;
set
{
if (Collection is not null)
Collection.ChangeParameterName(this, value);
else
ChangeParameterName(value);
}
}
internal void ChangeParameterName(string? value)
{
if (value is null)
_name = TrimmedName = PositionalName;
else if (value.Length > 0 && (value[0] == ':' || value[0] == '@'))
TrimmedName = (_name = value).Substring(1);
else
_name = TrimmedName = value;
}
internal bool IsPositional => ParameterName.Length == 0;
#endregion Name
#region Value
/// <inheritdoc />
[TypeConverter(typeof(StringConverter)), Category("Data")]
public override object? Value
{
get => _value;
set
{
if (ShouldResetObjectTypeInfo(value))
ResetTypeInfo();
else
ResetBindingInfo();
_value = value;
}
}
/// <summary>
/// Gets or sets the value of the parameter.
/// </summary>
/// <value>
/// An <see cref="object" /> that is the value of the parameter.
/// The default value is <see langword="null" />.
/// </value>
[Category("Data")]
[TypeConverter(typeof(StringConverter))]
public object? NpgsqlValue
{
get => Value;
set => Value = value;
}
#endregion Value
#region Type
/// <summary>
/// Gets or sets the <see cref="System.Data.DbType"/> of the parameter.
/// </summary>
/// <value>One of the <see cref="System.Data.DbType"/> values. The default is <see cref="object"/>.</value>
[DefaultValue(DbType.Object)]
[Category("Data"), RefreshProperties(RefreshProperties.All)]
public sealed override DbType DbType
{
get
{
if (_dbType is { } dbType)
return dbType;
if (_dataTypeName is not null)
{
var dataTypeName = Internal.Postgres.DataTypeName.FromDisplayName(_dataTypeName);
if (TryResolveDbType(dataTypeName, out var resolvedDbType))
return resolvedDbType;
return dataTypeName.ToNpgsqlDbType()?.ToDbType() ?? DbType.Object;
}
if (_npgsqlDbType is { } npgsqlDbType)
return npgsqlDbType.ToDbType();
// Infer from value but don't cache
// We pass ValueType here for the generic derived type, where we should respect T and not the runtime type.
if (GetValueType(StaticValueType) is { } valueType)
return GlobalTypeMapper.Instance.FindDataTypeName(valueType, Value)?.ToNpgsqlDbType()?.ToDbType() ?? DbType.Object;
return DbType.Object;
}
set
{
ResetTypeInfo();
_dbType = value;
}
}
/// <summary>
/// Gets or sets the <see cref="NpgsqlTypes.NpgsqlDbType"/> of the parameter.
/// </summary>
/// <value>One of the <see cref="NpgsqlTypes.NpgsqlDbType"/> values. The default is <see cref="NpgsqlTypes.NpgsqlDbType"/>.</value>
[DefaultValue(NpgsqlDbType.Unknown)]
[Category("Data"), RefreshProperties(RefreshProperties.All)]
[DbProviderSpecificTypeProperty(true)]
public NpgsqlDbType NpgsqlDbType
{
get
{
if (_npgsqlDbType.HasValue)
return _npgsqlDbType.Value;
if (_dataTypeName is not null)
return Internal.Postgres.DataTypeName.FromDisplayName(_dataTypeName).ToNpgsqlDbType() ?? NpgsqlDbType.Unknown;
var valueType = GetValueType(StaticValueType);
if (_dbType is { } dbType)
{
if (TryResolveDbTypeDataTypeName(dbType, valueType, out var dataTypeName))
return NpgsqlDbTypeExtensions.ToNpgsqlDbType(dataTypeName) ?? NpgsqlDbType.Unknown;
return dbType.ToNpgsqlDbType() ?? NpgsqlDbType.Unknown;
}
// Infer from value but don't cache
// We pass ValueType here for the generic derived type, where we should respect T and not the runtime type.
if (valueType is not null)
return GlobalTypeMapper.Instance.FindDataTypeName(valueType, Value)?.ToNpgsqlDbType() ?? NpgsqlDbType.Unknown;
return NpgsqlDbType.Unknown;
}
set
{
if (value == NpgsqlDbType.Array)
ThrowHelper.ThrowArgumentOutOfRangeException(nameof(value), "Cannot set NpgsqlDbType to just Array, Binary-Or with the element type (e.g. Array of Box is NpgsqlDbType.Array | NpgsqlDbType.Box).");
if (value == NpgsqlDbType.Range)
ThrowHelper.ThrowArgumentOutOfRangeException(nameof(value), "Cannot set NpgsqlDbType to just Range, Binary-Or with the element type (e.g. Range of integer is NpgsqlDbType.Range | NpgsqlDbType.Integer)");
ResetTypeInfo();
_npgsqlDbType = value;
}
}
/// <summary>
/// Used to specify which PostgreSQL type will be sent to the database for this parameter.
/// </summary>
public string? DataTypeName
{
get
{
if (_dataTypeName != null)
return _dataTypeName;
// Map it to a display name.
if (_npgsqlDbType is { } npgsqlDbType)
{
var unqualifiedName = npgsqlDbType.ToUnqualifiedDataTypeName();
return unqualifiedName is null ? null : Internal.Postgres.DataTypeName.ValidatedName(
"pg_catalog." + unqualifiedName).UnqualifiedDisplayName;
}
var valueType = GetValueType(StaticValueType);
if (_dbType is { } dbType)
{
if (TryResolveDbTypeDataTypeName(dbType, valueType, out var dataTypeName))
return dataTypeName;
var unqualifiedName = dbType.ToNpgsqlDbType()?.ToUnqualifiedDataTypeName();
return unqualifiedName is null ? null : Internal.Postgres.DataTypeName.ValidatedName(
"pg_catalog." + unqualifiedName).UnqualifiedDisplayName;
}
// Infer from value but don't cache
// We pass ValueType here for the generic derived type, where we should respect T and not the runtime type.
if (valueType is not null)
return GlobalTypeMapper.Instance.FindDataTypeName(valueType, Value)?.DisplayName;
return null;
}
set
{
ResetTypeInfo();
_dataTypeName = value;
}
}
#endregion Type
#region Other Properties
/// <inheritdoc />
public sealed override bool IsNullable { get; set; }
/// <inheritdoc />
[DefaultValue(ParameterDirection.Input)]
[Category("Data")]
public sealed override ParameterDirection Direction { get; set; }
/// <summary>
/// Gets or sets the maximum number of digits used to represent the <see cref="Value"/> property.
/// </summary>
/// <value>
/// The maximum number of digits used to represent the <see cref="Value"/> property.
/// The default value is 0, which indicates that the data provider sets the precision for <see cref="Value"/>.</value>
[DefaultValue((byte)0)]
[Category("Data")]
public new byte Precision
{
get => _precision;
set => _precision = value;
}
/// <summary>
/// Gets or sets the number of decimal places to which <see cref="Value"/> is resolved.
/// </summary>
/// <value>The number of decimal places to which <see cref="Value"/> is resolved. The default is 0.</value>
[DefaultValue((byte)0)]
[Category("Data")]
public new byte Scale
{
get => _scale;
set => _scale = value;
}
/// <inheritdoc />
[DefaultValue(0)]
[Category("Data")]
public sealed override int Size
{
get => _size;
set
{
if (value < -1)
ThrowHelper.ThrowArgumentException($"Invalid parameter Size value '{value}'. The value must be greater than or equal to 0.");
ResetBindingInfo();
_size = value;
}
}
/// <inheritdoc />
[AllowNull, DefaultValue("")]
[Category("Data")]
public sealed override string SourceColumn
{
get => _sourceColumn;
set => _sourceColumn = value ?? string.Empty;
}
/// <inheritdoc />
[Category("Data"), DefaultValue(DataRowVersion.Current)]
public sealed override DataRowVersion SourceVersion { get; set; }
/// <inheritdoc />
public sealed override bool SourceColumnNullMapping { get; set; }
/// <summary>
/// The collection to which this parameter belongs, if any.
/// </summary>
public NpgsqlParameterCollection? Collection { get; set; }
/// <summary>
/// The PostgreSQL data type, such as int4 or text, as discovered from pg_type.
/// This property is automatically set if parameters have been derived via
/// <see cref="NpgsqlCommandBuilder.DeriveParameters"/> and can be used to
/// acquire additional information about the parameters' data type.
/// </summary>
public PostgresType? PostgresType { get; internal set; }
#endregion Other Properties
#region Internals
private protected virtual Type StaticValueType => typeof(object);
Type? GetValueType(Type staticValueType) => staticValueType != typeof(object) ? staticValueType : Value?.GetType();
bool TryResolveDbType(DataTypeName dataTypeName, out DbType dbType)
{
if (_dbTypeResolver?.GetDbType(dataTypeName) is { } result)
{
dbType = result;
return true;
}
dbType = default;
return false;
}
bool TryResolveDbTypeDataTypeName(DbType dbType, Type? type, [NotNullWhen(true)]out string? normalizedDataTypeName)
{
if (_dbTypeResolver?.GetDataTypeName(dbType, type) is { } result)
{
normalizedDataTypeName = Internal.Postgres.DataTypeName.NormalizeName(result);
return true;
}
normalizedDataTypeName = null;
return false;
}
internal void SetOutputValue(NpgsqlDataReader reader, int ordinal)
{
if (GetType() == typeof(NpgsqlParameter))
Value = reader.GetValue(ordinal);
else
SetOutputValueCore(reader, ordinal);
}
private protected virtual void SetOutputValueCore(NpgsqlDataReader reader, int ordinal) {}
internal bool ShouldResetObjectTypeInfo(object? value)
{
var currentType = TypeInfo?.Type;
if (currentType is null || value is null)
return false;
var valueType = value.GetType();
// We don't want to reset the type info when the value is a DBNull, we're able to write it out with any type info.
return valueType != typeof(DBNull) && currentType != valueType;
}
internal void GetResolutionInfo(out PgTypeInfo? typeInfo, out PgConverter? converter, out PgTypeId pgTypeId)
{
typeInfo = TypeInfo;
converter = Converter;
pgTypeId = PgTypeId;
}
internal void SetResolutionInfo(PgTypeInfo typeInfo, PgConverter converter, PgTypeId pgTypeId)
{
if (WriteSize is not null)
ResetBindingInfo();
TypeInfo = typeInfo;
Converter = converter;
PgTypeId = pgTypeId;
}
/// Attempt to resolve a type info based on available (postgres) type information on the parameter.
internal void ResolveTypeInfo(PgSerializerOptions options, IDbTypeResolver? dbTypeResolver)
{
var typeInfo = TypeInfo;
var previouslyResolved = ReferenceEquals(typeInfo?.Options, options);
if (!previouslyResolved)
{
var staticValueType = StaticValueType;
var valueType = GetValueType(staticValueType);
string? dataTypeName = null;
if (_dataTypeName is not null)
{
dataTypeName = Internal.Postgres.DataTypeName.NormalizeName(_dataTypeName);
}
else if (_npgsqlDbType is { } npgsqlDbType)
{
dataTypeName = npgsqlDbType.ToDataTypeName() ?? npgsqlDbType.ToUnqualifiedDataTypeNameOrThrow();
}
else if (_dbType is { } dbType)
{
if (dbTypeResolver is not null)
{
_dbTypeResolver = dbTypeResolver;
if (dbTypeResolver.GetDataTypeName(dbType, valueType) is { } result)
{
dataTypeName = Internal.Postgres.DataTypeName.NormalizeName(result);
}
}
// Fall back to builtin mappings if there was no resolver, or it didn't produce a result.
if (dataTypeName is null)
{
dataTypeName = dbType.ToNpgsqlDbType()?.ToDataTypeName();
// If DbType.Object was specified we will only throw (see ThrowNoTypeInfo) if valueType is also null.
if (dataTypeName is null && dbType is not DbType.Object)
ThrowDbTypeNotSupported();
}
}
PgTypeId? pgTypeId = null;
if (dataTypeName is not null)
{
if (!options.DatabaseInfo.TryGetPostgresTypeByName(dataTypeName, out var pgType))
{
ThrowNotSupported(dataTypeName);
return;
}
pgTypeId = options.ToCanonicalTypeId(pgType.GetRepresentationalType());
}
if (pgTypeId is null && valueType is null)
{
ThrowNoTypeInfo();
return;
}
// We treat object typed DBNull values as default info (we don't supply a type).
// Unless we don't have a pgTypeId either, at which point we'll use an 'unspecified' PgTypeInfo to help us write a NULL.
if (valueType == typeof(DBNull) && staticValueType == typeof(object))
{
TypeInfo = typeInfo = pgTypeId is null
? options.UnspecifiedDBNullTypeInfo
: AdoSerializerHelpers.GetTypeInfoForWriting(type: null, pgTypeId, options, _npgsqlDbType);
}
else
{
TypeInfo = typeInfo = AdoSerializerHelpers.GetTypeInfoForWriting(valueType, pgTypeId, options, _npgsqlDbType);
}
}
// This step isn't part of BindValue because we need to know the PgTypeId beforehand for things like SchemaOnly with null values.
// We never reuse resolutions for resolvers across executions as a mutable value itself may influence the result.
// TODO we could expose a property on a Converter/TypeInfo to indicate whether it's immutable, at that point we can reuse.
if (!previouslyResolved || typeInfo!.IsResolverInfo)
{
ResetBindingInfo();
var resolution = ResolveConverter(typeInfo!);
Converter = resolution.Converter;
PgTypeId = resolution.PgTypeId;
}
void ThrowNoTypeInfo()
=> ThrowHelper.ThrowInvalidOperationException(
$"Parameter '{(!string.IsNullOrEmpty(ParameterName) ? ParameterName : $"${Collection?.IndexOf(this) + 1}")}' must have either its DbType, NpgsqlDbType, DataTypeName or its Value set.");
void ThrowDbTypeNotSupported()
=> ThrowHelper.ThrowNotSupportedException(
$"The DbType '{_dbType}' isn't supported by Npgsql. There might be an Npgsql plugin with support for this DbType.");
void ThrowNotSupported(string dataTypeName)
=> ThrowHelper.ThrowNotSupportedException(
$"The data type name '{dataTypeName}'{(_npgsqlDbType is not null ? $", provided as NpgsqlDbType '{_npgsqlDbType}'," : null)} could not be found in the types that were loaded by Npgsql. " +
$"Your database details or Npgsql type loading configuration may be incorrect. Alternatively your PostgreSQL installation might need to be upgraded, or an extension adding the missing data type might not have been installed.");
}
// Pull from Value so we also support object typed generic params.
private protected virtual PgConverterResolution ResolveConverter(PgTypeInfo typeInfo)
{
_asObject = true;
return typeInfo.GetObjectResolution(Value);
}
/// Bind the current value to the type info, truncate (if applicable), take its size, and do any final validation before writing.
internal void Bind(out DataFormat format, out Size size, DataFormat? requiredFormat = null)
{
if (TypeInfo is null)
ThrowHelper.ThrowInvalidOperationException($"Missing type info, {nameof(ResolveTypeInfo)} needs to be called before {nameof(Bind)}.");
// We might call this twice, once during validation and once during WriteBind, only compute things once.
if (WriteSize is null)
{
if (_size > 0)
HandleSizeTruncation();
BindCore(requiredFormat);
}
format = Format;
size = WriteSize!.Value;
if (requiredFormat is not null && format != requiredFormat)
ThrowHelper.ThrowNotSupportedException($"Parameter '{ParameterName}' must be written in {requiredFormat} format, but does not support this format.");
// Handle Size truncate behavior for a predetermined set of types and pg types.
// Doesn't matter if we 'box' Value, all supported types are reference types.
[MethodImpl(MethodImplOptions.NoInlining)]
void HandleSizeTruncation()
{
var type = Converter!.TypeToConvert;
if ((type != typeof(string) && type != typeof(char[]) && type != typeof(byte[]) && type != typeof(Stream)) || Value is not { } value)
return;
var dataTypeName = TypeInfo!.Options.GetDataTypeName(PgTypeId);
if (dataTypeName == DataTypeNames.Text || dataTypeName == DataTypeNames.Varchar || dataTypeName == DataTypeNames.Bpchar)
{
if (value is string s && s.Length > _size)
Value = s.Substring(0, _size);
else if (value is char[] chars && chars.Length > _size)
{
var truncated = new char[_size];
Array.Copy(chars, truncated, _size);
Value = truncated;
}
}
else if (dataTypeName == DataTypeNames.Bytea)
{
if (value is byte[] bytes && bytes.Length > _size)
{
var truncated = new byte[_size];
Array.Copy(bytes, truncated, _size);
Value = truncated;
}
else if (value is Stream)
{
_asObject = true;
_useSubStream = true;
}
}
}
}
private protected virtual void BindCore(DataFormat? formatPreference, bool allowNullReference = false)
{
// Pull from Value so we also support object typed generic params.
var value = Value;
if (value is null && !allowNullReference)
ThrowHelper.ThrowInvalidOperationException($"Parameter '{ParameterName}' cannot be null, DBNull.Value should be used instead.");
if (_useSubStream && value is not null)
value = _subStream = new SubReadStream((Stream)value, _size);
if (TypeInfo!.BindObject(Converter!, value, out var size, out _writeState, out var dataFormat, formatPreference) is { } info)
{
WriteSize = size;
_bufferRequirement = info.BufferRequirement;
}
else
{
WriteSize = -1;
_bufferRequirement = default;
}
Format = dataFormat;
}
internal async ValueTask Write(bool async, PgWriter writer, CancellationToken cancellationToken)
{
if (WriteSize is not { } writeSize)
{
ThrowHelper.ThrowInvalidOperationException("Missing type info or binding info.");
return;
}
try
{
if (writer.ShouldFlush(sizeof(int)))
await writer.Flush(async, cancellationToken).ConfigureAwait(false);
writer.WriteInt32(writeSize.Value);
if (writeSize.Value is -1)
{
writer.Commit(sizeof(int));
return;
}
var current = new ValueMetadata
{
Format = Format,
BufferRequirement = _bufferRequirement,
Size = writeSize,
WriteState = _writeState
};
await writer.BeginWrite(async, current, cancellationToken).ConfigureAwait(false);
await WriteValue(async, writer, cancellationToken).ConfigureAwait(false);
writer.Commit(writeSize.Value + sizeof(int));
}
finally
{
ResetBindingInfo();
}
}
private protected virtual ValueTask WriteValue(bool async, PgWriter writer, CancellationToken cancellationToken)
{
// Pull from Value so we also support base calls from generic parameters.
var value = (_useSubStream ? _subStream : Value)!;
if (async)
return Converter!.WriteAsObjectAsync(writer, value, cancellationToken);
Converter!.WriteAsObject(writer, value);
return new();
}
/// <inheritdoc />
public override void ResetDbType()
{
_dbType = null;
_npgsqlDbType = null;
_dataTypeName = null;
ResetTypeInfo();
}
private protected void ResetTypeInfo()
{
TypeInfo = null;
_asObject = false;
Converter = null;
PgTypeId = default;
ResetBindingInfo();
}
private protected void ResetBindingInfo()
{
if (WriteSize is null)
{
Debug.Assert(_writeState == default && _useSubStream == default && Format == default && _bufferRequirement == default);
return;
}
if (_writeState is not null)
{
TypeInfo?.DisposeWriteState(_writeState);
_writeState = null;
}
if (_useSubStream)
{
_useSubStream = false;
_subStream?.Dispose();
_subStream = null;
}
WriteSize = null;
Format = default;
_bufferRequirement = default;
}
internal bool IsInputDirection => Direction == ParameterDirection.InputOutput || Direction == ParameterDirection.Input;
internal bool IsOutputDirection => Direction == ParameterDirection.InputOutput || Direction == ParameterDirection.Output;
#endregion
#region Clone
/// <summary>
/// Creates a new <see cref="NpgsqlParameter"/> that is a copy of the current instance.
/// </summary>
/// <returns>A new <see cref="NpgsqlParameter"/> that is a copy of this instance.</returns>
public NpgsqlParameter Clone() => CloneCore();
private protected virtual NpgsqlParameter CloneCore() =>
// use fields instead of properties
// to avoid auto-initializing something like type_info
new()
{
_precision = _precision,
_scale = _scale,
_size = _size,
_dbType = _dbType,
_npgsqlDbType = _npgsqlDbType,
_dataTypeName = _dataTypeName,
Direction = Direction,
IsNullable = IsNullable,
_name = _name,
TrimmedName = TrimmedName,
SourceColumn = SourceColumn,
SourceVersion = SourceVersion,
_value = _value,
SourceColumnNullMapping = SourceColumnNullMapping,
};
object ICloneable.Clone() => Clone();
#endregion
}