-
Notifications
You must be signed in to change notification settings - Fork 818
/
NpgsqlConnectionStringBuilder.cs
1702 lines (1536 loc) · 62.9 KB
/
NpgsqlConnectionStringBuilder.cs
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
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.Common;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using System.Text;
namespace Npgsql
{
/// <summary>
/// Provides a simple way to create and manage the contents of connection strings used by
/// the <see cref="NpgsqlConnection"/> class.
/// </summary>
public sealed class NpgsqlConnectionStringBuilder : DbConnectionStringBuilder, IDictionary<string, object?>
{
#region Fields
/// <summary>
/// Makes all valid keywords for a property to that property (e.g. User Name -> Username, UserId -> Username...)
/// </summary>
static readonly Dictionary<string, PropertyInfo> PropertiesByKeyword;
/// <summary>
/// Maps CLR property names (e.g. BufferSize) to their canonical keyword name, which is the
/// property's [DisplayName] (e.g. Buffer Size)
/// </summary>
static readonly Dictionary<string, string> PropertyNameToCanonicalKeyword;
/// <summary>
/// Maps each property to its [DefaultValue]
/// </summary>
static readonly Dictionary<PropertyInfo, object?> PropertyDefaults;
/// <summary>
/// Cached DataSource value to reduce allocations on NpgsqlConnection.DataSource.get
/// </summary>
string? _dataSourceCached;
internal string DataSourceCached
=> _dataSourceCached ??= _host is null
? string.Empty
: Path.IsPathRooted(_host)
? Path.Combine(_host, $".s.PGSQL.{_port}")
: $"tcp://{_host}:{_port}";
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the NpgsqlConnectionStringBuilder class.
/// </summary>
public NpgsqlConnectionStringBuilder() { Init(); }
/// <summary>
/// Initializes a new instance of the NpgsqlConnectionStringBuilder class, optionally using ODBC rules for quoting values.
/// </summary>
/// <param name="useOdbcRules">true to use {} to delimit fields; false to use quotation marks.</param>
public NpgsqlConnectionStringBuilder(bool useOdbcRules) : base(useOdbcRules) { Init(); }
/// <summary>
/// Initializes a new instance of the NpgsqlConnectionStringBuilder class and sets its <see cref="DbConnectionStringBuilder.ConnectionString"/>.
/// </summary>
public NpgsqlConnectionStringBuilder(string? connectionString)
{
Init();
ConnectionString = connectionString;
}
void Init()
{
// Set the strongly-typed properties to their default values
foreach (var kv in PropertyDefaults)
kv.Key.SetValue(this, kv.Value);
// Setting the strongly-typed properties here also set the string-based properties in the base class.
// Clear them (default settings = empty connection string)
base.Clear();
}
#endregion
#region Static initialization
static NpgsqlConnectionStringBuilder()
{
var properties = typeof(NpgsqlConnectionStringBuilder)
.GetProperties()
.Where(p => p.GetCustomAttribute<NpgsqlConnectionStringPropertyAttribute>() != null)
.ToArray();
Debug.Assert(properties.All(p => p.CanRead && p.CanWrite));
Debug.Assert(properties.All(p => p.GetCustomAttribute<DisplayNameAttribute>() != null));
PropertiesByKeyword = (
from p in properties
let displayName = p.GetCustomAttribute<DisplayNameAttribute>()!.DisplayName.ToUpperInvariant()
let propertyName = p.Name.ToUpperInvariant()
from k in new[] { displayName }
.Concat(propertyName != displayName ? new[] { propertyName } : EmptyStringArray )
.Concat(p.GetCustomAttribute<NpgsqlConnectionStringPropertyAttribute>()!.Synonyms
.Select(a => a.ToUpperInvariant())
)
.Select(k => new { Property = p, Keyword = k })
select k
).ToDictionary(t => t.Keyword, t => t.Property);
PropertyNameToCanonicalKeyword = properties.ToDictionary(
p => p.Name,
p => p.GetCustomAttribute<DisplayNameAttribute>()!.DisplayName
);
PropertyDefaults = properties
.Where(p => p.GetCustomAttribute<ObsoleteAttribute>() == null)
.ToDictionary(
p => p,
p => p.GetCustomAttribute<DefaultValueAttribute>() != null
? p.GetCustomAttribute<DefaultValueAttribute>()!.Value
: (p.PropertyType.GetTypeInfo().IsValueType ? Activator.CreateInstance(p.PropertyType) : null)
);
}
#endregion
#region Non-static property handling
/// <summary>
/// Gets or sets the value associated with the specified key.
/// </summary>
/// <param name="keyword">The key of the item to get or set.</param>
/// <returns>The value associated with the specified key.</returns>
[AllowNull]
public override object this[string keyword]
{
get
{
if (!TryGetValue(keyword, out var value))
throw new ArgumentException("Keyword not supported: " + keyword, nameof(keyword));
return value;
}
set
{
if (value is null)
{
Remove(keyword);
return;
}
var p = GetProperty(keyword);
try
{
var convertedValue = p.PropertyType.GetTypeInfo().IsEnum && value is string str
? Enum.Parse(p.PropertyType, str)
: Convert.ChangeType(value, p.PropertyType);
p.SetValue(this, convertedValue);
}
catch (Exception e)
{
throw new ArgumentException("Couldn't set " + keyword, keyword, e);
}
}
}
object? IDictionary<string, object?>.this[string keyword]
{
get => this[keyword];
set => this[keyword] = value!;
}
/// <summary>
/// Adds an item to the <see cref="NpgsqlConnectionStringBuilder"/>.
/// </summary>
/// <param name="item">The key-value pair to be added.</param>
public void Add(KeyValuePair<string, object?> item)
=> this[item.Key] = item.Value!;
void IDictionary<string, object?>.Add(string keyword, object? value)
=> this[keyword] = value;
/// <summary>
/// Removes the entry with the specified key from the DbConnectionStringBuilder instance.
/// </summary>
/// <param name="keyword">The key of the key/value pair to be removed from the connection string in this DbConnectionStringBuilder.</param>
/// <returns><b>true</b> if the key existed within the connection string and was removed; <b>false</b> if the key did not exist.</returns>
public override bool Remove(string keyword)
{
var p = GetProperty(keyword);
var canonicalName = PropertyNameToCanonicalKeyword[p.Name];
var removed = base.ContainsKey(canonicalName);
// Note that string property setters call SetValue, which itself calls base.Remove().
p.SetValue(this, PropertyDefaults[p]);
base.Remove(canonicalName);
return removed;
}
/// <summary>
/// Removes the entry from the DbConnectionStringBuilder instance.
/// </summary>
/// <param name="item">The key/value pair to be removed from the connection string in this DbConnectionStringBuilder.</param>
/// <returns><b>true</b> if the key existed within the connection string and was removed; <b>false</b> if the key did not exist.</returns>
public bool Remove(KeyValuePair<string, object?> item)
=> Remove(item.Key);
/// <summary>
/// Clears the contents of the <see cref="NpgsqlConnectionStringBuilder"/> instance.
/// </summary>
public override void Clear()
{
Debug.Assert(Keys != null);
foreach (var k in Keys.ToArray()) {
Remove(k);
}
}
/// <summary>
/// Determines whether the <see cref="NpgsqlConnectionStringBuilder"/> contains a specific key.
/// </summary>
/// <param name="keyword">The key to locate in the <see cref="NpgsqlConnectionStringBuilder"/>.</param>
/// <returns><b>true</b> if the <see cref="NpgsqlConnectionStringBuilder"/> contains an entry with the specified key; otherwise <b>false</b>.</returns>
public override bool ContainsKey(string keyword)
=> keyword is null
? throw new ArgumentNullException(nameof(keyword))
: PropertiesByKeyword.ContainsKey(keyword.ToUpperInvariant());
/// <summary>
/// Determines whether the <see cref="NpgsqlConnectionStringBuilder"/> contains a specific key-value pair.
/// </summary>
/// <param name="item">The item to locate in the <see cref="NpgsqlConnectionStringBuilder"/>.</param>
/// <returns><b>true</b> if the <see cref="NpgsqlConnectionStringBuilder"/> contains the entry; otherwise <b>false</b>.</returns>
public bool Contains(KeyValuePair<string, object?> item)
=> TryGetValue(item.Key, out var value) &&
((value == null && item.Value == null) || (value != null && value.Equals(item.Value)));
PropertyInfo GetProperty(string keyword)
=> PropertiesByKeyword.TryGetValue(keyword.ToUpperInvariant(), out var p)
? p
: throw new ArgumentException("Keyword not supported: " + keyword, nameof(keyword));
/// <summary>
/// Retrieves a value corresponding to the supplied key from this <see cref="NpgsqlConnectionStringBuilder"/>.
/// </summary>
/// <param name="keyword">The key of the item to retrieve.</param>
/// <param name="value">The value corresponding to the key.</param>
/// <returns><b>true</b> if keyword was found within the connection string, <b>false</b> otherwise.</returns>
public override bool TryGetValue(string keyword, [NotNullWhen(true)] out object? value)
{
if (keyword == null)
throw new ArgumentNullException(nameof(keyword));
if (!PropertiesByKeyword.ContainsKey(keyword.ToUpperInvariant()))
{
value = null;
return false;
}
value = GetProperty(keyword).GetValue(this) ?? "";
return true;
}
void SetValue(string propertyName, object? value)
{
var canonicalKeyword = PropertyNameToCanonicalKeyword[propertyName];
if (value == null)
base.Remove(canonicalKeyword);
else
base[canonicalKeyword] = value;
}
#endregion
#region Properties - Connection
/// <summary>
/// The hostname or IP address of the PostgreSQL server to connect to.
/// </summary>
[Category("Connection")]
[Description("The hostname or IP address of the PostgreSQL server to connect to.")]
[DisplayName("Host")]
[NpgsqlConnectionStringProperty("Server")]
public string? Host
{
get => _host;
set
{
_host = value;
SetValue(nameof(Host), value);
_dataSourceCached = null;
}
}
string? _host;
/// <summary>
/// The TCP/IP port of the PostgreSQL server.
/// </summary>
[Category("Connection")]
[Description("The TCP port of the PostgreSQL server.")]
[DisplayName("Port")]
[NpgsqlConnectionStringProperty]
[DefaultValue(NpgsqlConnection.DefaultPort)]
public int Port
{
get => _port;
set
{
if (value <= 0)
throw new ArgumentOutOfRangeException(nameof(value), value, "Invalid port: " + value);
_port = value;
SetValue(nameof(Port), value);
_dataSourceCached = null;
}
}
int _port;
///<summary>
/// The PostgreSQL database to connect to.
/// </summary>
[Category("Connection")]
[Description("The PostgreSQL database to connect to.")]
[DisplayName("Database")]
[NpgsqlConnectionStringProperty("DB")]
public string? Database
{
get => _database;
set
{
_database = value;
SetValue(nameof(Database), value);
}
}
string? _database;
/// <summary>
/// The username to connect with. Not required if using IntegratedSecurity.
/// </summary>
[Category("Connection")]
[Description("The username to connect with. Not required if using IntegratedSecurity.")]
[DisplayName("Username")]
[NpgsqlConnectionStringProperty("User Name", "UserId", "User Id", "UID")]
public string? Username
{
get => _username;
set
{
_username = value;
SetValue(nameof(Username), value);
}
}
string? _username;
/// <summary>
/// The password to connect with. Not required if using IntegratedSecurity.
/// </summary>
[Category("Connection")]
[Description("The password to connect with. Not required if using IntegratedSecurity.")]
[PasswordPropertyText(true)]
[DisplayName("Password")]
[NpgsqlConnectionStringProperty("PSW", "PWD")]
public string? Password
{
get => _password;
set
{
_password = value;
SetValue(nameof(Password), value);
}
}
string? _password;
/// <summary>
/// Path to a PostgreSQL password file (PGPASSFILE), from which the password would be taken.
/// </summary>
[Category("Connection")]
[Description("Path to a PostgreSQL password file (PGPASSFILE), from which the password would be taken.")]
[DisplayName("Passfile")]
[NpgsqlConnectionStringProperty]
public string? Passfile
{
get => _passfile;
set
{
_passfile = value;
SetValue(nameof(Passfile), value);
}
}
string? _passfile;
/// <summary>
/// The optional application name parameter to be sent to the backend during connection initiation.
/// </summary>
[Category("Connection")]
[Description("The optional application name parameter to be sent to the backend during connection initiation")]
[DisplayName("Application Name")]
[NpgsqlConnectionStringProperty]
public string? ApplicationName
{
get => _applicationName;
set
{
_applicationName = value;
SetValue(nameof(ApplicationName), value);
}
}
string? _applicationName;
/// <summary>
/// Whether to enlist in an ambient TransactionScope.
/// </summary>
[Category("Connection")]
[Description("Whether to enlist in an ambient TransactionScope.")]
[DisplayName("Enlist")]
[DefaultValue(true)]
[NpgsqlConnectionStringProperty]
public bool Enlist
{
get => _enlist;
set
{
_enlist = value;
SetValue(nameof(Enlist), value);
}
}
bool _enlist;
/// <summary>
/// Gets or sets the schema search path.
/// </summary>
[Category("Connection")]
[Description("Gets or sets the schema search path.")]
[DisplayName("Search Path")]
[NpgsqlConnectionStringProperty]
public string? SearchPath
{
get => _searchPath;
set
{
_searchPath = value;
SetValue(nameof(SearchPath), value);
}
}
string? _searchPath;
/// <summary>
/// Gets or sets the client_encoding parameter.
/// </summary>
[Category("Connection")]
[Description("Gets or sets the client_encoding parameter.")]
[DisplayName("Client Encoding")]
[NpgsqlConnectionStringProperty]
public string? ClientEncoding
{
get => _clientEncoding;
set
{
_clientEncoding = value;
SetValue(nameof(ClientEncoding), value);
}
}
string? _clientEncoding;
/// <summary>
/// Gets or sets the .NET encoding that will be used to encode/decode PostgreSQL string data.
/// </summary>
[Category("Connection")]
[Description("Gets or sets the .NET encoding that will be used to encode/decode PostgreSQL string data.")]
[DisplayName("Encoding")]
[DefaultValue("UTF8")]
[NpgsqlConnectionStringProperty]
public string Encoding
{
get => _encoding;
set
{
_encoding = value;
SetValue(nameof(Encoding), value);
}
}
string _encoding = "UTF8";
/// <summary>
/// Gets or sets the PostgreSQL session timezone, in Olson/IANA database format.
/// </summary>
[Category("Connection")]
[Description("Gets or sets the PostgreSQL session timezone, in Olson/IANA database format.")]
[DisplayName("Timezone")]
[NpgsqlConnectionStringProperty]
public string? Timezone
{
get => _timezone;
set
{
_timezone = value;
SetValue(nameof(Timezone), value);
}
}
string? _timezone;
#endregion
#region Properties - Security
/// <summary>
/// Controls whether SSL is required, disabled or preferred, depending on server support.
/// </summary>
[Category("Security")]
[Description("Controls whether SSL is required, disabled or preferred, depending on server support.")]
[DisplayName("SSL Mode")]
[NpgsqlConnectionStringProperty]
public SslMode SslMode
{
get => _sslMode;
set
{
_sslMode = value;
SetValue(nameof(SslMode), value);
}
}
SslMode _sslMode;
/// <summary>
/// Whether to trust the server certificate without validating it.
/// </summary>
[Category("Security")]
[Description("Whether to trust the server certificate without validating it.")]
[DisplayName("Trust Server Certificate")]
[NpgsqlConnectionStringProperty]
public bool TrustServerCertificate
{
get => _trustServerCertificate;
set
{
_trustServerCertificate = value;
SetValue(nameof(TrustServerCertificate), value);
}
}
bool _trustServerCertificate;
/// <summary>
/// Location of a client certificate to be sent to the server.
/// </summary>
[Category("Security")]
[Description("Location of a client certificate to be sent to the server.")]
[DisplayName("Client Certificate")]
[NpgsqlConnectionStringProperty]
public string? ClientCertificate
{
get => _clientCertificate;
set
{
_clientCertificate = value;
SetValue(nameof(ClientCertificate), value);
}
}
string? _clientCertificate;
/// <summary>
/// Key for a client certificate to be sent to the server.
/// </summary>
[Category("Security")]
[Description("Key for a client certificate to be sent to the server.")]
[DisplayName("Client Certificate Key")]
[NpgsqlConnectionStringProperty]
public string? ClientCertificateKey
{
get => _clientCertificateKey;
set
{
_clientCertificateKey = value;
SetValue(nameof(ClientCertificateKey), value);
}
}
string? _clientCertificateKey;
/// <summary>
/// Location of a CA certificate used to validate the server certificate.
/// </summary>
[Category("Security")]
[Description("Location of a CA certificate used to validate the server certificate.")]
[DisplayName("Root Certificate")]
[NpgsqlConnectionStringProperty]
public string? RootCertificate
{
get => _rootCertificate;
set
{
_rootCertificate = value;
SetValue(nameof(RootCertificate), value);
}
}
string? _rootCertificate;
/// <summary>
/// Whether to check the certificate revocation list during authentication.
/// False by default.
/// </summary>
[Category("Security")]
[Description("Whether to check the certificate revocation list during authentication.")]
[DisplayName("Check Certificate Revocation")]
[NpgsqlConnectionStringProperty]
public bool CheckCertificateRevocation
{
get => _checkCertificateRevocation;
set
{
_checkCertificateRevocation = value;
SetValue(nameof(CheckCertificateRevocation), value);
}
}
bool _checkCertificateRevocation;
/// <summary>
/// Whether to use Windows integrated security to log in.
/// </summary>
[Category("Security")]
[Description("Whether to use Windows integrated security to log in.")]
[DisplayName("Integrated Security")]
[NpgsqlConnectionStringProperty]
public bool IntegratedSecurity
{
get => _integratedSecurity;
set
{
// No integrated security if we're on mono and .NET 4.5 because of ClaimsIdentity,
// see https://github.com/npgsql/Npgsql/issues/133
if (value && Type.GetType("Mono.Runtime") != null)
throw new NotSupportedException("IntegratedSecurity is currently unsupported on mono and .NET 4.5 (see https://github.com/npgsql/Npgsql/issues/133)");
_integratedSecurity = value;
SetValue(nameof(IntegratedSecurity), value);
}
}
bool _integratedSecurity;
/// <summary>
/// The Kerberos service name to be used for authentication.
/// </summary>
[Category("Security")]
[Description("The Kerberos service name to be used for authentication.")]
[DisplayName("Kerberos Service Name")]
[NpgsqlConnectionStringProperty("Krbsrvname")]
[DefaultValue("postgres")]
public string KerberosServiceName
{
get => _kerberosServiceName;
set
{
_kerberosServiceName = value;
SetValue(nameof(KerberosServiceName), value);
}
}
string _kerberosServiceName = "postgres";
/// <summary>
/// The Kerberos realm to be used for authentication.
/// </summary>
[Category("Security")]
[Description("The Kerberos realm to be used for authentication.")]
[DisplayName("Include Realm")]
[NpgsqlConnectionStringProperty]
public bool IncludeRealm
{
get => _includeRealm;
set
{
_includeRealm = value;
SetValue(nameof(IncludeRealm), value);
}
}
bool _includeRealm;
/// <summary>
/// Gets or sets a Boolean value that indicates if security-sensitive information, such as the password, is not returned as part of the connection if the connection is open or has ever been in an open state.
/// </summary>
[Category("Security")]
[Description("Gets or sets a Boolean value that indicates if security-sensitive information, such as the password, is not returned as part of the connection if the connection is open or has ever been in an open state.")]
[DisplayName("Persist Security Info")]
[NpgsqlConnectionStringProperty]
public bool PersistSecurityInfo
{
get => _persistSecurityInfo;
set
{
_persistSecurityInfo = value;
SetValue(nameof(PersistSecurityInfo), value);
}
}
bool _persistSecurityInfo;
/// <summary>
/// When enabled, parameter values are logged when commands are executed. Defaults to false.
/// </summary>
[Category("Security")]
[Description("When enabled, parameter values are logged when commands are executed. Defaults to false.")]
[DisplayName("Log Parameters")]
[NpgsqlConnectionStringProperty]
public bool LogParameters
{
get => _logParameters;
set
{
_logParameters = value;
SetValue(nameof(LogParameters), value);
}
}
bool _logParameters;
internal const string IncludeExceptionDetailDisplayName = "Include Error Detail";
/// <summary>
/// When enabled, PostgreSQL error details are included on <see cref="PostgresException.Detail" /> and
/// <see cref="PostgresNotice.Detail" />. These can contain sensitive data.
/// </summary>
[Category("Security")]
[Description("When enabled, PostgreSQL error and notice details are included on PostgresException.Detail and PostgresNotice.Detail. These can contain sensitive data.")]
[DisplayName(IncludeExceptionDetailDisplayName)]
[NpgsqlConnectionStringProperty]
public bool IncludeErrorDetails
{
get => _includeErrorDetails;
set
{
_includeErrorDetails = value;
SetValue(nameof(IncludeErrorDetails), value);
}
}
bool _includeErrorDetails;
#endregion
#region Properties - Pooling
/// <summary>
/// Whether connection pooling should be used.
/// </summary>
[Category("Pooling")]
[Description("Whether connection pooling should be used.")]
[DisplayName("Pooling")]
[NpgsqlConnectionStringProperty]
[DefaultValue(true)]
public bool Pooling
{
get => _pooling;
set
{
_pooling = value;
SetValue(nameof(Pooling), value);
}
}
bool _pooling;
/// <summary>
/// The minimum connection pool size.
/// </summary>
[Category("Pooling")]
[Description("The minimum connection pool size.")]
[DisplayName("Minimum Pool Size")]
[NpgsqlConnectionStringProperty]
[DefaultValue(0)]
public int MinPoolSize
{
get => _minPoolSize;
set
{
if (value < 0)
throw new ArgumentOutOfRangeException(nameof(value), value, "MinPoolSize can't be negative");
_minPoolSize = value;
SetValue(nameof(MinPoolSize), value);
}
}
int _minPoolSize;
/// <summary>
/// The maximum connection pool size.
/// </summary>
[Category("Pooling")]
[Description("The maximum connection pool size.")]
[DisplayName("Maximum Pool Size")]
[NpgsqlConnectionStringProperty]
[DefaultValue(100)]
public int MaxPoolSize
{
get => _maxPoolSize;
set
{
if (value < 0)
throw new ArgumentOutOfRangeException(nameof(value), value, "MaxPoolSize can't be negative");
_maxPoolSize = value;
SetValue(nameof(MaxPoolSize), value);
}
}
int _maxPoolSize;
/// <summary>
/// The time to wait before closing idle connections in the pool if the count
/// of all connections exceeds MinPoolSize.
/// </summary>
/// <value>The time (in seconds) to wait. The default value is 300.</value>
[Category("Pooling")]
[Description("The time to wait before closing unused connections in the pool if the count of all connections exceeds MinPoolSize.")]
[DisplayName("Connection Idle Lifetime")]
[NpgsqlConnectionStringProperty]
[DefaultValue(300)]
public int ConnectionIdleLifetime
{
get => _connectionIdleLifetime;
set
{
_connectionIdleLifetime = value;
SetValue(nameof(ConnectionIdleLifetime), value);
}
}
int _connectionIdleLifetime;
/// <summary>
/// How many seconds the pool waits before attempting to prune idle connections that are beyond
/// idle lifetime (<see cref="ConnectionIdleLifetime"/>.
/// </summary>
/// <value>The interval (in seconds). The default value is 10.</value>
[Category("Pooling")]
[Description("How many seconds the pool waits before attempting to prune idle connections that are beyond idle lifetime.")]
[DisplayName("Connection Pruning Interval")]
[NpgsqlConnectionStringProperty]
[DefaultValue(10)]
public int ConnectionPruningInterval
{
get => _connectionPruningInterval;
set
{
_connectionPruningInterval = value;
SetValue(nameof(ConnectionPruningInterval), value);
}
}
int _connectionPruningInterval;
/// <summary>
/// The total maximum lifetime of connections (in seconds). Connections which have exceeded this value will be
/// destroyed instead of returned from the pool. This is useful in clustered configurations to force load
/// balancing between a running server and a server just brought online.
/// </summary>
/// <value>The time (in seconds) to wait, or 0 to to make connections last indefinitely (the default).</value>
[Category("Pooling")]
[Description("The total maximum lifetime of connections (in seconds).")]
[DisplayName("Connection Lifetime")]
[NpgsqlConnectionStringProperty("Load Balance Timeout")]
[DefaultValue(0)]
public int ConnectionLifetime
{
get => _connectionLifetime;
set
{
_connectionLifetime = value;
SetValue(nameof(ConnectionLifetime), value);
}
}
int _connectionLifetime;
#endregion
#region Properties - Timeouts
/// <summary>
/// The time to wait (in seconds) while trying to establish a connection before terminating the attempt and generating an error.
/// Defaults to 15 seconds.
/// </summary>
[Category("Timeouts")]
[Description("The time to wait (in seconds) while trying to establish a connection before terminating the attempt and generating an error.")]
[DisplayName("Timeout")]
[NpgsqlConnectionStringProperty]
[DefaultValue(DefaultTimeout)]
public int Timeout
{
get => _timeout;
set
{
if (value < 0 || value > NpgsqlConnection.TimeoutLimit)
throw new ArgumentOutOfRangeException(nameof(value), value, "Timeout must be between 0 and " + NpgsqlConnection.TimeoutLimit);
_timeout = value;
SetValue(nameof(Timeout), value);
}
}
int _timeout;
internal const int DefaultTimeout = 15;
/// <summary>
/// The time to wait (in seconds) while trying to execute a command before terminating the attempt and generating an error.
/// Defaults to 30 seconds.
/// </summary>
[Category("Timeouts")]
[Description("The time to wait (in seconds) while trying to execute a command before terminating the attempt and generating an error. Set to zero for infinity.")]
[DisplayName("Command Timeout")]
[NpgsqlConnectionStringProperty]
[DefaultValue(NpgsqlCommand.DefaultTimeout)]
public int CommandTimeout
{
get => _commandTimeout;
set
{
if (value < 0)
throw new ArgumentOutOfRangeException(nameof(value), value, "CommandTimeout can't be negative");
_commandTimeout = value;
SetValue(nameof(CommandTimeout), value);
}
}
int _commandTimeout;
/// <summary>
/// The time to wait (in seconds) while trying to execute a an internal command before terminating the attempt and generating an error.
/// </summary>
[Category("Timeouts")]
[Description("The time to wait (in seconds) while trying to execute a an internal command before terminating the attempt and generating an error. -1 uses CommandTimeout, 0 means no timeout.")]
[DisplayName("Internal Command Timeout")]
[NpgsqlConnectionStringProperty]
[DefaultValue(-1)]
public int InternalCommandTimeout
{
get => _internalCommandTimeout;
set
{
if (value != 0 && value != -1 && value < NpgsqlConnector.MinimumInternalCommandTimeout)
throw new ArgumentOutOfRangeException(nameof(value), value,
$"InternalCommandTimeout must be >= {NpgsqlConnector.MinimumInternalCommandTimeout}, 0 (infinite) or -1 (use CommandTimeout)");
_internalCommandTimeout = value;
SetValue(nameof(InternalCommandTimeout), value);
}
}
int _internalCommandTimeout;
/// <summary>
/// The time to wait (in seconds) while trying to read a response for a cancellation request for a timed out or cancelled query, before terminating the attempt and generating an error.
/// Defaults to 2 seconds.
/// </summary>
[Category("Timeouts")]
[Description("After Command Timeout is reached (or user supplied cancellation token is cancelled) and command cancellation is attempted, Npgsql waits for this additional timeout (in seconds) before breaking the connection. Defaults to 2, set to zero for infinity.")]
[DisplayName("Cancellation Timeout")]
[NpgsqlConnectionStringProperty]
[DefaultValue(2)]
public int CancellationTimeout
{
get => _cancellationTimeout;
set
{
if (value < 0)
throw new ArgumentOutOfRangeException(nameof(value), value, $"{nameof(CancellationTimeout)} can't be negative");
_cancellationTimeout = value;
SetValue(nameof(CancellationTimeout), value);
}
}
int _cancellationTimeout;
#endregion
#region Properties - Entity Framework
/// <summary>
/// The database template to specify when creating a database in Entity Framework. If not specified,
/// PostgreSQL defaults to "template1".
/// </summary>
/// <remarks>
/// https://www.postgresql.org/docs/current/static/manage-ag-templatedbs.html
/// </remarks>
[Category("Entity Framework")]
[Description("The database template to specify when creating a database in Entity Framework. If not specified, PostgreSQL defaults to \"template1\".")]
[DisplayName("EF Template Database")]
[NpgsqlConnectionStringProperty]
public string? EntityTemplateDatabase
{
get => _entityTemplateDatabase;
set
{
_entityTemplateDatabase = value;
SetValue(nameof(EntityTemplateDatabase), value);
}
}
string? _entityTemplateDatabase;
/// <summary>
/// The database admin to specify when creating and dropping a database in Entity Framework. This is needed because
/// Npgsql needs to connect to a database in order to send the create/drop database command.
/// If not specified, defaults to "template1". Check NpgsqlServices.UsingPostgresDBConnection for more information.
/// </summary>
[Category("Entity Framework")]
[Description("The database admin to specify when creating and dropping a database in Entity Framework. If not specified, defaults to \"template1\".")]
[DisplayName("EF Admin Database")]
[NpgsqlConnectionStringProperty]
public string? EntityAdminDatabase
{
get => _entityAdminDatabase;