-
Notifications
You must be signed in to change notification settings - Fork 875
Expand file tree
/
Copy pathNpgsqlConnection.cs
More file actions
1822 lines (1576 loc) · 73.9 KB
/
NpgsqlConnection.cs
File metadata and controls
1822 lines (1576 loc) · 73.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
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.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Net.Security;
using System.Net.Sockets;
using System.Runtime.CompilerServices;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Threading.Tasks;
using System.Transactions;
using Microsoft.Extensions.Logging;
using Npgsql.Internal;
using Npgsql.TypeMapping;
using Npgsql.Util;
using IsolationLevel = System.Data.IsolationLevel;
namespace Npgsql;
/// <summary>
/// This class represents a connection to a PostgreSQL server.
/// </summary>
// ReSharper disable once RedundantNameQualifier
[System.ComponentModel.DesignerCategory("")]
public sealed class NpgsqlConnection : DbConnection, ICloneable, IComponent
{
#region Fields
// Set this when disposed is called.
bool _disposed;
/// <summary>
/// The connection string, without the password after open (unless Persist Security Info=true)
/// </summary>
string _userFacingConnectionString = string.Empty;
/// <summary>
/// The original connection string provided by the user, including the password.
/// </summary>
string _connectionString = string.Empty;
ConnectionState _fullState;
/// <summary>
/// The physical connection to the database. This is <see langword="null"/> when the connection is closed.
/// </summary>
internal NpgsqlConnector? Connector { get; set; }
/// <summary>
/// The parsed connection string. Set only after the connection is opened.
/// </summary>
internal NpgsqlConnectionStringBuilder Settings { get; private set; } = DefaultSettings;
static readonly NpgsqlConnectionStringBuilder DefaultSettings = new();
NpgsqlDataSource? _dataSource;
internal NpgsqlDataSource NpgsqlDataSource
{
get
{
Debug.Assert(_dataSource is not null);
return _dataSource;
}
}
/// <summary>
/// Flag used to make sure we never double-close a connection, returning it twice to the pool.
/// </summary>
int _closing;
internal Transaction? EnlistedTransaction { get; set; }
/// <summary>
/// The global type mapper, which contains defaults used by all new connections.
/// Modify mappings on this mapper to affect your entire application.
/// </summary>
[Obsolete("Global-level type mapping has been replaced with data source mapping, see the 7.0 release notes.")]
public static INpgsqlTypeMapper GlobalTypeMapper => TypeMapping.GlobalTypeMapper.Instance;
/// <summary>
/// Connection-level type mapping is no longer supported. See the 7.0 release notes for configuring type mapping on NpgsqlDataSource.
/// </summary>
[Obsolete("Connection-level type mapping is no longer supported. See the 7.0 release notes for configuring type mapping on NpgsqlDataSource.", true)]
public INpgsqlTypeMapper TypeMapper
=> throw new NotSupportedException();
static Func<string, NpgsqlConnection>? _cloningInstantiator;
/// <summary>
/// The default TCP/IP port for PostgreSQL.
/// </summary>
public const int DefaultPort = 5432;
/// <summary>
/// Maximum value for connection timeout.
/// </summary>
internal const int TimeoutLimit = 1024;
ILogger _connectionLogger = default!; // Initialized in Open, shouldn't be used otherwise
static readonly StateChangeEventArgs ClosedToOpenEventArgs = new(ConnectionState.Closed, ConnectionState.Open);
static readonly StateChangeEventArgs OpenToClosedEventArgs = new(ConnectionState.Open, ConnectionState.Closed);
#endregion Fields
#region Constructors / Init / Open
/// <summary>
/// Initializes a new instance of the <see cref="NpgsqlConnection"/> class.
/// </summary>
public NpgsqlConnection()
=> GC.SuppressFinalize(this);
/// <summary>
/// Initializes a new instance of <see cref="NpgsqlConnection"/> with the given connection string.
/// </summary>
/// <param name="connectionString">The connection used to open the PostgreSQL database.</param>
public NpgsqlConnection(string? connectionString) : this()
=> ConnectionString = connectionString;
internal NpgsqlConnection(NpgsqlDataSource dataSource, NpgsqlConnector connector) : this()
{
_dataSource = dataSource;
Settings = dataSource.Settings;
_userFacingConnectionString = dataSource.ConnectionString;
Connector = connector;
connector.Connection = this;
FullState = ConnectionState.Open;
}
internal static NpgsqlConnection FromDataSource(NpgsqlDataSource dataSource)
=> new()
{
_dataSource = dataSource,
Settings = dataSource.Settings,
_userFacingConnectionString = dataSource.ConnectionString,
};
/// <summary>
/// Opens a database connection with the property settings specified by the <see cref="ConnectionString"/>.
/// </summary>
public override void Open() => Open(false, CancellationToken.None).GetAwaiter().GetResult();
/// <summary>
/// This is the asynchronous version of <see cref="Open()"/>.
/// </summary>
/// <remarks>
/// Do not invoke other methods and properties of the <see cref="NpgsqlConnection"/> object until the returned Task is complete.
/// </remarks>
/// <param name="cancellationToken">
/// An optional token to cancel the asynchronous operation. The default value is <see cref="CancellationToken.None"/>.
/// </param>
/// <returns>A task representing the asynchronous operation.</returns>
public override Task OpenAsync(CancellationToken cancellationToken) => Open(async: true, cancellationToken);
void SetupDataSource()
{
// Fast path: a pool already corresponds to this exact version of the connection string.
if (PoolManager.Pools.TryGetValue(_connectionString, out _dataSource))
{
Settings = _dataSource.Settings; // Great, we already have a pool
return;
}
// Connection string hasn't been seen before. Check for empty and parse (slow one-time path).
if (_connectionString == string.Empty)
{
Settings = DefaultSettings;
_dataSource = null;
return;
}
var settings = new NpgsqlConnectionStringBuilder(_connectionString);
settings.PostProcessAndValidate();
Settings = settings;
// The connection string may be equivalent to one that has already been seen though (e.g. different
// ordering). Have NpgsqlConnectionStringBuilder produce a canonical string representation
// and recheck.
// Note that we remove TargetSessionAttributes to make all connection strings that are otherwise identical point to the same pool.
var canonical = settings.ConnectionStringForMultipleHosts;
if (PoolManager.Pools.TryGetValue(canonical, out _dataSource))
{
// If this is a multi-host data source and the user specified a TargetSessionAttributes, create a wrapper in front of the
// MultiHostDataSource with that TargetSessionAttributes.
if (_dataSource is NpgsqlMultiHostDataSource multiHostDataSource && settings.TargetSessionAttributesParsed.HasValue)
_dataSource = multiHostDataSource.WithTargetSession(settings.TargetSessionAttributesParsed.Value);
// The pool was found, but only under the canonical key - we're using a different version
// for the first time. Map it via our own key for next time.
_dataSource = PoolManager.Pools.GetOrAdd(_connectionString, _dataSource);
return;
}
// Really unseen, need to create a new pool
// The canonical pool is the 'base' pool so we need to set that up first. If someone beats us to it use what they put.
// The connection string pool can either be added here or above, if it's added above we should just use that.
var dataSourceBuilder = new NpgsqlDataSourceBuilder(canonical);
dataSourceBuilder.UseLoggerFactory(NpgsqlLoggingConfiguration.GlobalLoggerFactory);
dataSourceBuilder.EnableParameterLogging(NpgsqlLoggingConfiguration.GlobalIsParameterLoggingEnabled);
var newDataSource = dataSourceBuilder.Build();
// See Clone() on the following line:
_cloningInstantiator = s => new NpgsqlConnection(s);
_dataSource = PoolManager.Pools.GetOrAdd(canonical, newDataSource);
if (_dataSource != newDataSource)
newDataSource.Dispose();
// If this is a multi-host data source and the user specified a TargetSessionAttributes, create a wrapper in front of the
// MultiHostDataSource with that TargetSessionAttributes.
if (_dataSource is NpgsqlMultiHostDataSource multiHostDataSource2 && settings.TargetSessionAttributesParsed.HasValue)
_dataSource = multiHostDataSource2.WithTargetSession(settings.TargetSessionAttributesParsed.Value);
_dataSource = PoolManager.Pools.GetOrAdd(_connectionString, _dataSource);
}
internal Task Open(bool async, CancellationToken cancellationToken)
{
CheckClosed();
Debug.Assert(Connector == null);
if (_dataSource is null)
{
Debug.Assert(string.IsNullOrEmpty(_connectionString));
ThrowHelper.ThrowInvalidOperationException("The ConnectionString property has not been initialized.");
}
_userFacingConnectionString = _dataSource.ConnectionString;
_connectionLogger = _dataSource.LoggingConfiguration.ConnectionLogger;
if (_connectionLogger.IsEnabled(LogLevel.Trace))
LogMessages.OpeningConnection(_connectionLogger, Settings.Host!, Settings.Port, Settings.Database!, _userFacingConnectionString);
return OpenAsync(async, cancellationToken);
async Task OpenAsync(bool async, CancellationToken cancellationToken)
{
FullState = ConnectionState.Connecting;
NpgsqlConnector? connector = null;
try
{
var connectionTimeout = TimeSpan.FromSeconds(ConnectionTimeout);
var timeout = new NpgsqlTimeout(connectionTimeout);
var enlistToTransaction = Settings.Enlist ? Transaction.Current : null;
// First, check to see if we there's an ambient transaction, and we have a connection enlisted
// to this transaction which has been closed. If so, return that as an optimization rather than
// opening a new one and triggering escalation to a distributed transaction.
// Otherwise just get a new connector and enlist below.
if (enlistToTransaction is not null && _dataSource.TryRentEnlistedPending(enlistToTransaction, this, out connector))
{
EnlistedTransaction = enlistToTransaction;
enlistToTransaction = null;
}
else
connector = await _dataSource.Get(this, timeout, async, cancellationToken).ConfigureAwait(false);
Debug.Assert(connector.Connection is null,
$"Connection for opened connector '{Connector?.Id.ToString() ?? "???"}' is bound to another connection");
connector.Connection = this;
Connector = connector;
if (enlistToTransaction is not null)
EnlistTransaction(enlistToTransaction);
LogMessages.OpenedConnection(_connectionLogger, Host!, Port, Database, _userFacingConnectionString, connector.Id);
FullState = ConnectionState.Open;
}
catch
{
FullState = ConnectionState.Closed;
Connector = null;
EnlistedTransaction = null;
if (connector is not null)
{
connector.Connection = null;
connector.Return();
}
throw;
}
}
}
#endregion Open / Init
#region Connection string management
/// <summary>
/// Gets or sets the string used to connect to a PostgreSQL database. See the manual for details.
/// </summary>
/// <value>The connection string that includes the server name,
/// the database name, and other parameters needed to establish
/// the initial connection. The default value is an empty string.
/// </value>
[AllowNull]
public override string ConnectionString
{
get => _userFacingConnectionString;
set
{
CheckClosed();
_userFacingConnectionString = _connectionString = value ?? string.Empty;
SetupDataSource();
}
}
/// <summary>
/// Gets or sets the delegate used to generate a password for new database connections.
/// </summary>
/// <remarks>
/// <p>
/// This delegate is executed when a new database connection is opened that requires a password.
/// </p>
/// <p>
/// The <see cref="NpgsqlConnectionStringBuilder.Password"/> and <see cref="NpgsqlConnectionStringBuilder.Passfile"/> connection
/// string properties have precedence over this delegate: it will not be executed if a password is specified, or if the specified or
/// default Passfile contains a valid entry.
/// </p>
/// <p>
/// Due to connection pooling this delegate is only executed when a new physical connection is opened, not when reusing a connection
/// that was previously opened from the pool.
/// </p>
/// </remarks>
[Obsolete("Use NpgsqlDataSourceBuilder.UsePeriodicPasswordProvider or inject passwords directly into NpgsqlDataSource.Password")]
public ProvidePasswordCallback? ProvidePasswordCallback { get; set; }
#endregion Connection string management
#region Configuration settings
/// <summary>
/// Backend server host name.
/// </summary>
[Browsable(true)]
public string? Host => Connector?.Host;
/// <summary>
/// Backend server port.
/// </summary>
[Browsable(true)]
public int Port => Connector?.Port ?? 0;
/// <summary>
/// Gets the time (in seconds) to wait while trying to establish a connection
/// before terminating the attempt and generating an error.
/// </summary>
/// <value>The time (in seconds) to wait for a connection to open. The default value is 15 seconds.</value>
public override int ConnectionTimeout => Settings.Timeout;
/// <summary>
/// Gets the time (in seconds) to wait while trying to execute a command
/// before terminating the attempt and generating an error.
/// </summary>
/// <value>The time (in seconds) to wait for a command to complete. The default value is 30 seconds.</value>
public int CommandTimeout => Settings.CommandTimeout;
///<summary>
/// Gets the name of the current database or the database to be used after a connection is opened.
/// </summary>
/// <value>The name of the current database or the name of the database to be
/// used after a connection is opened. The default value is the empty string.</value>
public override string Database => Settings.Database ?? Settings.Username ?? "";
/// <summary>
/// Gets the string identifying the database server (host and port)
/// </summary>
/// <value>
/// The name of the database server (host and port). If the connection uses a Unix-domain socket,
/// the path to that socket is returned. The default value is the empty string.
/// </value>
public override string DataSource => Connector?.Settings.DataSourceCached ?? _dataSource?.Settings.DataSourceCached ?? string.Empty;
/// <summary>
/// User name.
/// </summary>
public string? UserName => Settings.Username;
#endregion Configuration settings
#region State management
/// <summary>
/// Gets the current state of the connection.
/// </summary>
/// <value>A bitwise combination of the <see cref="System.Data.ConnectionState"/> values. The default is <b>Closed</b>.</value>
[Browsable(false)]
public ConnectionState FullState
{
// Note: we allow accessing the state after dispose, #164
get
{
if (_fullState != ConnectionState.Open)
return _fullState;
if (Connector is null)
return ConnectionState.Open; // When unbound, we only know we're open
switch (Connector.State)
{
case ConnectorState.Ready:
return ConnectionState.Open;
case ConnectorState.Executing:
return ConnectionState.Open | ConnectionState.Executing;
case ConnectorState.Fetching:
case ConnectorState.Copy:
case ConnectorState.Replication:
case ConnectorState.Waiting:
return ConnectionState.Open | ConnectionState.Fetching;
case ConnectorState.Connecting:
return ConnectionState.Connecting;
case ConnectorState.Broken:
return ConnectionState.Broken;
case ConnectorState.Closed:
ThrowHelper.ThrowInvalidOperationException("Internal Npgsql bug: connection is in state Open but connector is in state Closed");
return ConnectionState.Broken;
default:
ThrowHelper.ThrowInvalidOperationException($"Internal Npgsql bug: unexpected value {{0}} of enum {nameof(ConnectorState)}. Please file a bug.", Connector.State);
return ConnectionState.Broken;
}
}
internal set
{
if (value is < 0 or > ConnectionState.Broken)
ThrowHelper.ThrowArgumentOutOfRangeException(nameof(value), "Unknown connection state", value);
var originalOpen = _fullState.HasFlag(ConnectionState.Open);
_fullState = value;
var currentOpen = _fullState.HasFlag(ConnectionState.Open);
if (currentOpen != originalOpen)
{
OnStateChange(currentOpen
? ClosedToOpenEventArgs
: OpenToClosedEventArgs);
}
}
}
/// <summary>
/// Gets whether the current state of the connection is Open or Closed
/// </summary>
/// <value>ConnectionState.Open, ConnectionState.Closed or ConnectionState.Connecting</value>
[Browsable(false)]
public override ConnectionState State
{
get
{
var fullState = FullState;
if (fullState.HasFlag(ConnectionState.Connecting))
return ConnectionState.Connecting;
if (fullState.HasFlag(ConnectionState.Open))
return ConnectionState.Open;
return ConnectionState.Closed;
}
}
#endregion State management
#region Command / Batch creation
/// <summary>
/// A cached command handed out by <see cref="CreateCommand" />, which is returned when disposed. Useful for reducing allocations.
/// </summary>
internal NpgsqlCommand? CachedCommand { get; set; }
/// <summary>
/// Creates and returns a <see cref="System.Data.Common.DbCommand"/>
/// object associated with the <see cref="System.Data.Common.DbConnection"/>.
/// </summary>
/// <returns>A <see cref="System.Data.Common.DbCommand"/> object.</returns>
protected override DbCommand CreateDbCommand() => CreateCommand();
/// <summary>
/// Creates and returns a <see cref="NpgsqlCommand"/> object associated with the <see cref="NpgsqlConnection"/>.
/// </summary>
/// <returns>A <see cref="NpgsqlCommand"/> object.</returns>
public new NpgsqlCommand CreateCommand()
{
CheckDisposed();
var cachedCommand = CachedCommand;
if (cachedCommand is not null)
{
CachedCommand = null;
cachedCommand.State = CommandState.Idle;
return cachedCommand;
}
return NpgsqlCommand.CreateCachedCommand(this);
}
/// <summary>
/// A cached batch handed out by <see cref="CreateBatch" />, which is returned when disposed. Useful for reducing allocations.
/// </summary>
internal NpgsqlBatch? CachedBatch { get; set; }
/// <inheritdoc/>
public override bool CanCreateBatch => true;
/// <inheritdoc/>
protected override DbBatch CreateDbBatch() => CreateBatch();
/// <inheritdoc cref="DbConnection.CreateBatch"/>
public new NpgsqlBatch CreateBatch()
{
CheckDisposed();
var cachedBatch = CachedBatch;
if (cachedBatch is not null)
{
CachedBatch = null;
return cachedBatch;
}
return NpgsqlBatch.CreateCachedBatch(this);
}
#endregion Command / Batch creation
#region Transactions
/// <summary>
/// Begins a database transaction with the specified isolation level.
/// </summary>
/// <param name="isolationLevel">The isolation level under which the transaction should run.</param>
/// <returns>A <see cref="System.Data.Common.DbTransaction"/> object representing the new transaction.</returns>
/// <remarks>Nested transactions are not supported.</remarks>
protected override DbTransaction BeginDbTransaction(IsolationLevel isolationLevel) => BeginTransaction(isolationLevel);
/// <summary>
/// Begins a database transaction.
/// </summary>
/// <returns>A <see cref="NpgsqlTransaction"/> object representing the new transaction.</returns>
/// <remarks>
/// Nested transactions are not supported.
/// Transactions created by this method will have the <see cref="IsolationLevel.ReadCommitted"/> isolation level.
/// </remarks>
public new NpgsqlTransaction BeginTransaction()
=> BeginTransaction(IsolationLevel.Unspecified);
/// <summary>
/// Begins a database transaction with the specified isolation level.
/// </summary>
/// <param name="level">The isolation level under which the transaction should run.</param>
/// <returns>A <see cref="NpgsqlTransaction"/> object representing the new transaction.</returns>
/// <remarks>Nested transactions are not supported.</remarks>
public new NpgsqlTransaction BeginTransaction(IsolationLevel level)
=> BeginTransaction(async: false, level, CancellationToken.None).GetAwaiter().GetResult();
async ValueTask<NpgsqlTransaction> BeginTransaction(bool async, IsolationLevel level, CancellationToken cancellationToken)
{
if (level == IsolationLevel.Chaos)
ThrowHelper.ThrowNotSupportedException($"Unsupported IsolationLevel: {nameof(IsolationLevel.Chaos)}");
CheckReady();
var connector = Connector;
if (connector is { InTransaction: true })
ThrowHelper.ThrowInvalidOperationException("A transaction is already in progress; nested/concurrent transactions aren't supported.");
// There was a committed/rolled back transaction, but it was not disposed
Debug.Assert(connector != null);
// Note that beginning a transaction doesn't actually send anything to the backend (only prepends).
// But we start a user action to check the cancellation token and generate exceptions
using var _ = connector.StartUserAction(cancellationToken);
connector.Transaction ??= new NpgsqlTransaction(connector);
connector.Transaction.Init(level);
return connector.Transaction;
}
/// <summary>
/// Asynchronously begins a database transaction.
/// </summary>
/// <param name="isolationLevel">The isolation level under which the transaction should run.</param>
/// <param name="cancellationToken">
/// An optional token to cancel the asynchronous operation. The default value is <see cref="CancellationToken.None"/>.
/// </param>
/// <returns>A task whose <see cref="ValueTask{T}.Result"/> property is an object representing the new transaction.</returns>
/// <remarks>
/// Nested transactions are not supported.
/// </remarks>
protected override async ValueTask<DbTransaction> BeginDbTransactionAsync(IsolationLevel isolationLevel, CancellationToken cancellationToken)
=> await BeginTransactionAsync(isolationLevel, cancellationToken).ConfigureAwait(false);
/// <summary>
/// Asynchronously begins a database transaction.
/// </summary>
/// <param name="cancellationToken">
/// An optional token to cancel the asynchronous operation. The default value is <see cref="CancellationToken.None"/>.
/// </param>
/// <returns>A task whose Result property is an object representing the new transaction.</returns>
/// <remarks>
/// Nested transactions are not supported.
/// Transactions created by this method will have the <see cref="IsolationLevel.ReadCommitted"/> isolation level.
/// </remarks>
public new ValueTask<NpgsqlTransaction> BeginTransactionAsync(CancellationToken cancellationToken = default)
=> BeginTransactionAsync(IsolationLevel.Unspecified, cancellationToken);
/// <summary>
/// Asynchronously begins a database transaction.
/// </summary>
/// <param name="level">The isolation level under which the transaction should run.</param>
/// <param name="cancellationToken">
/// An optional token to cancel the asynchronous operation. The default value is <see cref="CancellationToken.None"/>.
/// </param>
/// <returns>A task whose <see cref="ValueTask{T}.Result"/> property is an object representing the new transaction.</returns>
/// <remarks>
/// Nested transactions are not supported.
/// </remarks>
public new ValueTask<NpgsqlTransaction> BeginTransactionAsync(IsolationLevel level, CancellationToken cancellationToken = default)
=> BeginTransaction(async: true, level, cancellationToken);
/// <summary>
/// Enlist transaction.
/// </summary>
public override void EnlistTransaction(Transaction? transaction)
{
if (EnlistedTransaction != null)
{
if (EnlistedTransaction.Equals(transaction))
return;
try
{
if (EnlistedTransaction.TransactionInformation.Status == System.Transactions.TransactionStatus.Active)
throw new InvalidOperationException($"Already enlisted to transaction (localid={EnlistedTransaction.TransactionInformation.LocalIdentifier})");
}
catch (ObjectDisposedException)
{
// The MSDTC 2nd phase is asynchronous, so we may end up checking the TransactionInformation on
// a disposed transaction. To be extra safe we catch that, and understand that the transaction
// has ended - no problem for reenlisting.
}
}
CheckReady();
var connector = Connector!;
EnlistedTransaction = transaction;
if (transaction == null)
return;
// Until #1378 is implemented, we have no recovery, and so no need to enlist as a durable resource manager
// (or as promotable single phase).
// Note that even when #1378 is implemented in some way, we should check for mono and go volatile in any case -
// distributed transactions aren't supported.
var volatileResourceManager = new VolatileResourceManager(this, transaction);
transaction.EnlistVolatile(volatileResourceManager, EnlistmentOptions.None);
volatileResourceManager.Init();
EnlistedTransaction = transaction;
LogMessages.EnlistedVolatileResourceManager(
connector.LoggingConfiguration.TransactionLogger,
transaction.TransactionInformation.LocalIdentifier,
connector.Id);
}
#endregion
#region Close
/// <summary>
/// Releases the connection. If the connection is pooled, it will be returned to the pool and made available for re-use.
/// If it is non-pooled, the physical connection will be closed.
/// </summary>
public override void Close() => Close(async: false).GetAwaiter().GetResult();
/// <summary>
/// Releases the connection. If the connection is pooled, it will be returned to the pool and made available for re-use.
/// If it is non-pooled, the physical connection will be closed.
/// </summary>
public override Task CloseAsync()
=> Close(async: true);
internal bool TakeCloseLock() => Interlocked.Exchange(ref _closing, 1) == 0;
internal void ReleaseCloseLock() => Volatile.Write(ref _closing, 0);
internal Task Close(bool async)
{
// Even though NpgsqlConnection isn't thread safe we'll make sure this part is.
// Because we really don't want double returns to the pool.
if (!TakeCloseLock())
return Task.CompletedTask;
switch (FullState)
{
case ConnectionState.Open:
case ConnectionState.Open | ConnectionState.Executing:
case ConnectionState.Open | ConnectionState.Fetching:
break;
case ConnectionState.Broken:
FullState = ConnectionState.Closed;
goto case ConnectionState.Closed;
case ConnectionState.Closed:
ReleaseCloseLock();
return Task.CompletedTask;
case ConnectionState.Connecting:
ReleaseCloseLock();
throw new InvalidOperationException("Can't close, connection is in state " + FullState);
default:
ReleaseCloseLock();
throw new ArgumentOutOfRangeException("Unknown connection state: " + FullState);
}
return CloseAsync(async);
}
async Task CloseAsync(bool async)
{
Debug.Assert(Connector != null);
try
{
var connector = Connector;
LogMessages.ClosingConnection(_connectionLogger, Settings.Host!, Settings.Port, Settings.Database!, _userFacingConnectionString, connector.Id);
if (connector.CurrentReader != null || connector.CurrentCopyOperation != null)
{
// This method could re-enter connection.Close() due to an underlying connection failure.
await connector.CloseOngoingOperations(async).ConfigureAwait(false);
}
Debug.Assert(connector.IsReady || connector.IsBroken, $"Connector is not ready or broken during close, it's {connector.State}");
Debug.Assert(connector.CurrentReader == null);
Debug.Assert(connector.CurrentCopyOperation == null);
if (EnlistedTransaction != null)
{
// A System.Transactions transaction is still in progress.
// Close the connection and disconnect it from the resource manager and reset the connector, but leave the
// connector in an enlisted pending list in the data source. If another connection is opened within
// the same transaction scope, we will reuse this connector to avoid escalating to a distributed
// transaction.
connector.ResetWithinEnlistedTransaction();
connector.Connection = null;
_dataSource?.AddPendingEnlistedConnector(connector, EnlistedTransaction);
EnlistedTransaction = null;
}
else
{
if (Settings.Pooling)
{
// Clear the buffer, roll back any pending transaction and prepend a reset message if needed
// Note that we're doing this only for pooled connections
await connector.Reset(async).ConfigureAwait(false);
}
else
{
// We're already doing the same in the NpgsqlConnector.Reset for pooled connections
// TODO: move reset logic to ConnectorSource.Return
connector.Transaction?.UnbindIfNecessary();
}
connector.Connection = null;
connector.Return();
}
LogMessages.ClosedConnection(_connectionLogger, Settings.Host!, Settings.Port, Settings.Database!, _userFacingConnectionString, connector.Id);
Connector = null;
FullState = ConnectionState.Closed;
}
finally
{
ReleaseCloseLock();
}
}
/// <summary>
/// Releases all resources used by the <see cref="NpgsqlConnection"/>.
/// </summary>
/// <param name="disposing"><see langword="true"/> when called from <see cref="Dispose"/>;
/// <see langword="false"/> when being called from the finalizer.</param>
protected override void Dispose(bool disposing)
{
if (_disposed)
return;
if (disposing)
Close();
_disposed = true;
}
/// <summary>
/// Releases all resources used by the <see cref="NpgsqlConnection"/>.
/// </summary>
public override async ValueTask DisposeAsync()
{
if (_disposed)
return;
await CloseAsync().ConfigureAwait(false);
_disposed = true;
}
internal void MakeDisposed()
=> _disposed = true;
#endregion
#region Notifications and Notices
/// <summary>
/// Fires when PostgreSQL notices are received from PostgreSQL.
/// </summary>
/// <remarks>
/// PostgreSQL notices are non-critical messages generated by PostgreSQL, either as a result of a user query
/// (e.g. as a warning or informational notice), or due to outside activity (e.g. if the database administrator
/// initiates a "fast" database shutdown).
///
/// Note that notices are very different from notifications (see the <see cref="Notification"/> event).
/// </remarks>
public event NoticeEventHandler? Notice;
/// <summary>
/// Fires when PostgreSQL notifications are received from PostgreSQL.
/// </summary>
/// <remarks>
/// PostgreSQL notifications are sent when your connection has registered for notifications on a specific channel via the
/// LISTEN command. NOTIFY can be used to generate such notifications, allowing for an inter-connection communication channel.
///
/// Note that notifications are very different from notices (see the <see cref="Notice"/> event).
/// </remarks>
public event NotificationEventHandler? Notification;
internal void OnNotice(PostgresNotice e)
{
try
{
Notice?.Invoke(this, new NpgsqlNoticeEventArgs(e));
}
catch (Exception ex)
{
// Block all exceptions bubbling up from the user's event handler
LogMessages.CaughtUserExceptionInNoticeEventHandler(_connectionLogger, ex);
}
}
internal void OnNotification(NpgsqlNotificationEventArgs e)
{
try
{
Notification?.Invoke(this, e);
}
catch (Exception ex)
{
// Block all exceptions bubbling up from the user's event handler
LogMessages.CaughtUserExceptionInNotificationEventHandler(_connectionLogger, ex);
}
}
#endregion Notifications and Notices
#region SSL
/// <summary>
/// Returns whether SSL is being used for the connection.
/// </summary>
internal bool IsSslEncrypted
{
get
{
CheckOpen();
return Connector!.IsSslEncrypted;
}
}
/// <summary>
/// Returns whether GSS encryption is being used for the connection.
/// </summary>
internal bool IsGssEncrypted
{
get
{
CheckOpen();
return Connector!.IsGssEncrypted;
}
}
/// <summary>
/// Returns whether SCRAM-SHA256 is being user for the connection
/// </summary>
internal bool IsScram
{
get
{
CheckOpen();
return Connector!.IsScram;
}
}
/// <summary>
/// Returns whether SCRAM-SHA256-PLUS is being user for the connection
/// </summary>
internal bool IsScramPlus
{
get
{
CheckOpen();
return Connector!.IsScramPlus;
}
}
/// <summary>
/// Selects the local Secure Sockets Layer (SSL) certificate used for authentication.
/// </summary>
/// <remarks>
/// See <see href="https://msdn.microsoft.com/en-us/library/system.net.security.localcertificateselectioncallback(v=vs.110).aspx"/>
/// </remarks>
[Obsolete("Use UseSslClientAuthenticationOptionsCallback")]
public ProvideClientCertificatesCallback? ProvideClientCertificatesCallback { get; set; }
/// <summary>
/// When using SSL/TLS, this is a callback that allows customizing how the PostgreSQL-provided certificate is verified. This is an
/// advanced API, consider using <see cref="SslMode.VerifyFull" /> or <see cref="SslMode.VerifyCA" /> instead.
/// </summary>
/// <remarks>
/// <para>
/// Cannot be used in conjunction with <see cref="SslMode.Disable" />, <see cref="SslMode.VerifyCA" /> and
/// <see cref="SslMode.VerifyFull" />.
/// </para>
/// <para>
/// See <see href="https://msdn.microsoft.com/en-us/library/system.net.security.remotecertificatevalidationcallback(v=vs.110).aspx"/>.
/// </para>
/// </remarks>
[Obsolete("Use UseSslClientAuthenticationOptionsCallback")]
public RemoteCertificateValidationCallback? UserCertificateValidationCallback { get; set; }
/// <summary>
/// When using SSL/TLS, this is a callback that allows customizing SslStream's authentication options.
/// </summary>
/// <remarks>
/// <para>
/// See <see href="https://learn.microsoft.com/en-us/dotnet/api/system.net.security.sslclientauthenticationoptions"/>.
/// </para>
/// </remarks>
public Action<SslClientAuthenticationOptions>? SslClientAuthenticationOptionsCallback { get; set; }
#endregion SSL
#region Backend version, capabilities, settings
// TODO: We should probably move DatabaseInfo from each connector to the pool (but remember unpooled)
/// <summary>
/// The version of the PostgreSQL server we're connected to.
/// <remarks>
/// <p>
/// This can only be called when the connection is open.
/// </p>
/// <p>
/// In case of a development or pre-release version this field will contain
/// the version of the next version to be released from this branch.
/// </p>
/// </remarks>
/// </summary>
[Browsable(false)]
public Version PostgreSqlVersion
{
get
{
CheckOpen();
return Connector!.DatabaseInfo.Version;
}
}
/// <summary>
/// The PostgreSQL server version as returned by the server_version option.
/// <remarks>
/// This can only be called when the connection is open.
/// </remarks>
/// </summary>
public override string ServerVersion
{
get
{
CheckOpen();
return Connector!.DatabaseInfo.ServerVersion;
}
}
/// <summary>