/
NpgsqlConnection.cs
1443 lines (1256 loc) · 61.9 KB
/
NpgsqlConnection.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.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Diagnostics;
using System.IO;
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 JetBrains.Annotations;
using Npgsql.Logging;
using Npgsql.NameTranslation;
using Npgsql.TypeMapping;
using NpgsqlTypes;
using System.Transactions;
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
{
#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;
internal string OriginalConnectionString => _connectionString;
/// <summary>
/// The connector object connected to the backend.
/// </summary>
internal NpgsqlConnector? Connector;
/// <summary>
/// The parsed connection string set by the user
/// </summary>
internal NpgsqlConnectionStringBuilder Settings { get; private set; } = DefaultSettings;
static readonly NpgsqlConnectionStringBuilder DefaultSettings = new NpgsqlConnectionStringBuilder();
ConnectorPool? _pool;
bool _wasBroken;
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>
public static INpgsqlTypeMapper GlobalTypeMapper => TypeMapping.GlobalTypeMapper.Instance;
/// <summary>
/// The connection-specific type mapper - all modifications affect this connection only,
/// and are lost when it is closed.
/// </summary>
public INpgsqlTypeMapper TypeMapper => CheckReadyAndGetConnector().TypeMapper;
///
/// <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;
static readonly NpgsqlLogger Log = NpgsqlLogManager.GetCurrentClassLogger();
static bool _countersInitialized;
static readonly StateChangeEventArgs ClosedToOpenEventArgs = new StateChangeEventArgs(ConnectionState.Closed, ConnectionState.Open);
static readonly StateChangeEventArgs OpenToClosedEventArgs = new StateChangeEventArgs(ConnectionState.Open, ConnectionState.Closed);
#endregion Fields
#region Constructors / Init / Open
/// <summary>
/// Initializes a new instance of the
/// <see cref="NpgsqlConnection">NpgsqlConnection</see> 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;
/// <summary>
/// Opens a database connection with the property settings specified by the
/// <see cref="ConnectionString">ConnectionString</see>.
/// </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">The cancellation instruction.</param>
/// <returns>A task representing the asynchronous operation.</returns>
public override Task OpenAsync(CancellationToken cancellationToken)
{
using (NoSynchronizationContextScope.Enter())
return Open(true, cancellationToken);
}
void GetPoolAndSettings()
{
if (PoolManager.TryGetValue(_connectionString, out _pool))
{
Settings = _pool.Settings; // Great, we already have a pool
return;
}
// Connection string hasn't been seen before. Parse it.
Settings = new NpgsqlConnectionStringBuilder(_connectionString);
if (!_countersInitialized)
{
Counters.Initialize(Settings.UsePerfCounters);
_countersInitialized = true;
}
// Maybe pooling is off
if (!Settings.Pooling)
return;
// 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.
var canonical = Settings.ConnectionString;
if (PoolManager.TryGetValue(canonical, out _pool))
{
// 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.
_pool = PoolManager.GetOrAdd(_connectionString, _pool);
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 newPool = new ConnectorPool(Settings, canonical);
_pool = PoolManager.GetOrAdd(canonical, newPool);
if (_pool == newPool)
{
// If the pool we created was the one that ended up being stored we need to increment the appropriate counter.
// Avoids a race condition where multiple threads will create a pool but only one will be stored.
Counters.NumberOfActiveConnectionPools.Increment();
}
_pool = PoolManager.GetOrAdd(_connectionString, _pool);
}
Task Open(bool async, CancellationToken cancellationToken)
{
// This is an optimized path for when a connection can be taken from the pool
// with no waiting or I/O
CheckConnectionClosed();
Log.Trace("Opening connection...");
if (_pool == null || Settings.Enlist || !_pool.TryAllocateFast(this, out Connector))
return OpenLong();
_userFacingConnectionString = _pool.UserFacingConnectionString;
Counters.SoftConnectsPerSecond.Increment();
// Since this pooled connector was opened, types may have been added (and ReloadTypes() called),
// or global mappings may have changed. Bring this up to date if needed.
var mapper = Connector.TypeMapper;
if (mapper.ChangeCounter != TypeMapping.GlobalTypeMapper.Instance.ChangeCounter)
{
// We always do this synchronously which isn't amazing but not very important, because
// it's supposed to be a pretty rare event and the whole point is to keep this method
// non-async
Connector.LoadDatabaseInfo(NpgsqlTimeout.Infinite, false).GetAwaiter().GetResult();
}
Debug.Assert(Connector.Connection != null, "Open done but connector not set on Connection");
Log.Debug("Connection opened", Connector.Id);
OnStateChange(new StateChangeEventArgs(ConnectionState.Closed, ConnectionState.Open));
return Task.CompletedTask;
async Task OpenLong()
{
CheckConnectionClosed();
Log.Trace("Opening connection...");
_wasBroken = false;
try
{
Debug.Assert(Settings != null);
var timeout = new NpgsqlTimeout(TimeSpan.FromSeconds(ConnectionTimeout));
Transaction? transaction = null;
if (_pool == null) // Un-pooled connection (or user forgot to set connection string)
{
if (string.IsNullOrEmpty(_connectionString))
throw new InvalidOperationException("The ConnectionString property has not been initialized.");
if (!Settings.PersistSecurityInfo)
_userFacingConnectionString = Settings.ToStringWithoutPassword();
Connector = new NpgsqlConnector(this);
await Connector.Open(timeout, async, cancellationToken);
Counters.NumberOfNonPooledConnections.Increment();
}
else
{
_userFacingConnectionString = _pool.UserFacingConnectionString;
if (Settings.Enlist)
{
transaction = Transaction.Current;
if (transaction != null)
{
// First, check to see if 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.
Connector = _pool.TryAllocateEnlistedPending(Transaction.Current);
if (Connector != null)
{
Connector.Connection = this;
EnlistedTransaction = transaction;
}
}
if (Connector == null)
{
// If Enlist is true, we skipped the fast path above, try it here first,
// before going to the long path.
// TODO: Maybe find a more elegant way to factor this code...
if (!_pool.TryAllocateFast(this, out Connector))
Connector = await _pool.AllocateLong(this, timeout, async, cancellationToken);
}
}
else // No enlist
Connector = await _pool.AllocateLong(this, timeout, async, cancellationToken);
// Since this pooled connector was opened, types may have been added (and ReloadTypes() called),
// or global mappings may have changed. Bring this up to date if needed.
mapper = Connector.TypeMapper;
if (mapper.ChangeCounter != TypeMapping.GlobalTypeMapper.Instance.ChangeCounter)
await Connector.LoadDatabaseInfo(NpgsqlTimeout.Infinite, async);
}
// We may have gotten an already enlisted pending connector above, no need to enlist in that case
if (transaction != null && EnlistedTransaction == null)
EnlistTransaction(Transaction.Current);
}
catch
{
if (Connector != null)
{
if (_pool == null)
Connector.Close();
else
_pool.Release(Connector);
Connector = null;
}
throw;
}
Debug.Assert(Connector.Connection != null, "Open done but connector not set on Connection");
Log.Debug("Connection opened", Connector.Id);
OnStateChange(ClosedToOpenEventArgs);
}
}
#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>
#nullable disable
public override string ConnectionString
#nullable enable
{
get => _userFacingConnectionString;
set
{
CheckConnectionClosed();
if (value == null)
value = string.Empty;
_userFacingConnectionString = _connectionString = value;
GetPoolAndSettings();
}
}
/// <summary>
/// Gets or sets the delegate used to generate a password for new database connections.
/// </summary>
/// <remarks>
/// This delegate is executed when a new database connection is opened that requires a password.
/// <see cref="NpgsqlConnectionStringBuilder.Password">Password</see> and
/// <see cref="NpgsqlConnectionStringBuilder.Passfile">Passfile</see> connection string
/// properties have precedence over this delegate. It will not be executed if a password is
/// specified, or the specified or default Passfile contains a valid entry.
/// 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.
/// </remarks>
public ProvidePasswordCallback? ProvidePasswordCallback { get; set; }
#endregion Connection string management
#region Configuration settings
/// <summary>
/// Backend server host name.
/// </summary>
[Browsable(true)]
[PublicAPI]
public string? Host => Settings.Host;
/// <summary>
/// Backend server port.
/// </summary>
[Browsable(true)]
[PublicAPI]
public int Port => Settings.Port;
/// <summary>
/// Gets the time 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 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 20 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>
public override string DataSource => Settings.DataSourceCached;
/// <summary>
/// Whether to use Windows integrated security to log in.
/// </summary>
[PublicAPI]
public bool IntegratedSecurity => Settings.IntegratedSecurity;
/// <summary>
/// User name.
/// </summary>
[PublicAPI]
public string? UserName => Settings.Username;
internal string? Password => Settings.Password;
// The following two lines are here for backwards compatibility with the EF6 provider
// ReSharper disable UnusedMember.Global
internal string? EntityTemplateDatabase => Settings.EntityTemplateDatabase;
internal string? EntityAdminDatabase => Settings.EntityAdminDatabase;
// ReSharper restore UnusedMember.Global
#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">ConnectionState</see> values. The default is <b>Closed</b>.</value>
[Browsable(false)]
public ConnectionState FullState
{
get
{
if (Connector == null || _disposed)
{
return _wasBroken ? ConnectionState.Broken : ConnectionState.Closed;
}
switch (Connector.State)
{
case ConnectorState.Closed:
return ConnectionState.Closed;
case ConnectorState.Connecting:
return ConnectionState.Connecting;
case ConnectorState.Ready:
return ConnectionState.Open;
case ConnectorState.Executing:
return ConnectionState.Open | ConnectionState.Executing;
case ConnectorState.Copy:
case ConnectorState.Fetching:
case ConnectorState.Waiting:
return ConnectionState.Open | ConnectionState.Fetching;
case ConnectorState.Broken:
return ConnectionState.Broken;
default:
throw new InvalidOperationException($"Internal Npgsql bug: unexpected value {Connector.State} of enum {nameof(ConnectorState)}. Please file a bug.");
}
}
}
/// <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 s = FullState;
if ((s & ConnectionState.Open) != 0)
return ConnectionState.Open;
if ((s & ConnectionState.Connecting) != 0)
return ConnectionState.Connecting;
return ConnectionState.Closed;
}
}
#endregion State management
#region Commands
/// <summary>
/// Creates and returns a <see cref="System.Data.Common.DbCommand">DbCommand</see>
/// object associated with the <see cref="System.Data.Common.DbConnection">IDbConnection</see>.
/// </summary>
/// <returns>A <see cref="System.Data.Common.DbCommand">DbCommand</see> object.</returns>
protected override DbCommand CreateDbCommand()
{
return CreateCommand();
}
/// <summary>
/// Creates and returns a <see cref="NpgsqlCommand">NpgsqlCommand</see>
/// object associated with the <see cref="NpgsqlConnection">NpgsqlConnection</see>.
/// </summary>
/// <returns>A <see cref="NpgsqlCommand">NpgsqlCommand</see> object.</returns>
public new NpgsqlCommand CreateCommand()
{
CheckDisposed();
return new NpgsqlCommand("", this);
}
#endregion Commands
#region Transactions
/// <summary>
/// Begins a database transaction with the specified isolation level.
/// </summary>
/// <param name="isolationLevel">The <see cref="System.Data.IsolationLevel">isolation level</see> under which the transaction should run.</param>
/// <returns>An <see cref="System.Data.Common.DbTransaction">DbTransaction</see>
/// object representing the new transaction.</returns>
/// <remarks>
/// Currently the IsolationLevel ReadCommitted and Serializable are supported by the PostgreSQL backend.
/// There's no support for nested transactions.
/// </remarks>
protected override DbTransaction BeginDbTransaction(IsolationLevel isolationLevel)
{
return BeginTransaction(isolationLevel);
}
/// <summary>
/// Begins a database transaction.
/// </summary>
/// <returns>A <see cref="NpgsqlTransaction">NpgsqlTransaction</see>
/// object representing the new transaction.</returns>
/// <remarks>
/// Currently there's no support for nested transactions. Transactions created by this method will have Read Committed 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 <see cref="System.Data.IsolationLevel">isolation level</see> under which the transaction should run.</param>
/// <returns>A <see cref="NpgsqlTransaction">NpgsqlTransaction</see>
/// object representing the new transaction.</returns>
/// <remarks>
/// Currently the IsolationLevel ReadCommitted and Serializable are supported by the PostgreSQL backend.
/// There's no support for nested transactions.
/// </remarks>
public new NpgsqlTransaction BeginTransaction(IsolationLevel level)
{
if (level == IsolationLevel.Chaos)
throw new NotSupportedException("Unsupported IsolationLevel: " + level);
var connector = CheckReadyAndGetConnector();
Debug.Assert(Connector != null);
// Note that beginning a transaction doesn't actually send anything to the backend
// (only prepends), so strictly speaking we don't have to start a user action.
// However, we do this for consistency as if we did (for the checks and exceptions)
using (connector.StartUserAction())
{
if (connector.InTransaction)
throw new InvalidOperationException("A transaction is already in progress; nested/concurrent transactions aren't supported.");
connector.Transaction.Init(level);
return connector.Transaction;
}
}
/// <summary>
/// Enlist transaction.
/// </summary>
#nullable disable
public override void EnlistTransaction(Transaction transaction)
#nullable enable
{
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.
}
}
var connector = CheckReadyAndGetConnector();
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.
transaction.EnlistVolatile(new VolatileResourceManager(this, transaction), EnlistmentOptions.None);
Log.Debug($"Enlisted volatile resource manager (localid={transaction.TransactionInformation.LocalIdentifier})", connector.Id);
}
#endregion
#region Close
/// <summary>
/// releases the connection to the database. If the connection is pooled, it will be
/// made available for re-use. If it is non-pooled, the actual connection will be shutdown.
/// </summary>
public override void Close() => Close(false);
internal void Close(bool wasBroken)
{
if (Connector == null)
return;
var connectorId = Connector.Id;
Log.Trace("Closing connection...", connectorId);
_wasBroken = wasBroken;
Connector.CloseOngoingOperations();
if (Settings.Pooling)
{
if (EnlistedTransaction == null)
_pool!.Release(Connector);
else
{
// A System.Transactions transaction is still in progress, we need to wait for it to complete.
// Close the connection and disconnect it from the resource manager but leave the connector
// in a enlisted pending list in the pool.
_pool!.AddPendingEnlistedConnector(Connector, EnlistedTransaction);
Connector.Connection = null;
EnlistedTransaction = null;
}
}
else // Non-pooled connection
{
if (EnlistedTransaction == null)
Connector.Close();
// If a non-pooled connection is being closed but is enlisted in an ongoing
// TransactionScope, simply detach the connector from the connection and leave
// it open. It will be closed when the TransactionScope is disposed.
Connector.Connection = null;
EnlistedTransaction = null;
}
Log.Debug("Connection closed", connectorId);
Connector = null;
OnStateChange(OpenToClosedEventArgs);
}
/// <summary>
/// Releases all resources used by the
/// <see cref="NpgsqlConnection">NpgsqlConnection</see>.
/// </summary>
/// <param name="disposing"><b>true</b> when called from Dispose();
/// <b>false</b> when being called from the finalizer.</param>
protected override void Dispose(bool disposing)
{
if (_disposed)
return;
if (disposing)
Close();
base.Dispose(disposing);
_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
Log.Error("User exception caught when emitting notice event", 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
Log.Error("User exception caught when emitting notification event", ex);
}
}
#endregion Notifications and Notices
#region SSL
/// <summary>
/// Returns whether SSL is being used for the connection.
/// </summary>
internal bool IsSecure
{
get
{
CheckConnectionOpen();
Debug.Assert(Connector != null);
return Connector.IsSecure;
}
}
/// <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>
public ProvideClientCertificatesCallback? ProvideClientCertificatesCallback { get; set; }
/// <summary>
/// Verifies the remote Secure Sockets Layer (SSL) certificate used for authentication.
/// Ignored if <see cref="NpgsqlConnectionStringBuilder.TrustServerCertificate"/> is set.
/// </summary>
/// <remarks>
/// See <see href="https://msdn.microsoft.com/en-us/library/system.net.security.remotecertificatevalidationcallback(v=vs.110).aspx"/>
/// </remarks>
public RemoteCertificateValidationCallback? UserCertificateValidationCallback { get; set; }
#endregion SSL
#region Backend version, capabilities, settings
/// <summary>
/// Version of the PostgreSQL backend.
/// This can only be called when there is an active connection.
/// </summary>
[Browsable(false)]
public Version PostgreSqlVersion
{
get
{
CheckConnectionOpen();
Debug.Assert(Connector != null);
return Connector.DatabaseInfo.Version;
}
}
/// <summary>
/// PostgreSQL server version.
/// </summary>
public override string ServerVersion => PostgreSqlVersion.ToString();
/// <summary>
/// Process id of backend server.
/// This can only be called when there is an active connection.
/// </summary>
[Browsable(false)]
// ReSharper disable once InconsistentNaming
public int ProcessID
{
get
{
CheckConnectionOpen();
Debug.Assert(Connector != null);
return Connector.BackendProcessId;
}
}
/// <summary>
/// Reports whether the backend uses the newer integer timestamp representation.
/// Note that the old floating point representation is not supported.
/// Meant for use by type plugins (e.g. NodaTime)
/// </summary>
[Browsable(false)]
[PublicAPI]
public bool HasIntegerDateTimes
{
get
{
CheckConnectionOpen();
Debug.Assert(Connector != null);
return Connector.DatabaseInfo.HasIntegerDateTimes;
}
}
/// <summary>
/// The connection's timezone as reported by PostgreSQL, in the IANA/Olson database format.
/// </summary>
[Browsable(false)]
[PublicAPI]
public string Timezone
{
get
{
CheckConnectionOpen();
Debug.Assert(Connector != null);
return Connector.Timezone;
}
}
/// <summary>
/// Holds all PostgreSQL parameters received for this connection. Is updated if the values change
/// (e.g. as a result of a SET command).
/// </summary>
[Browsable(false)]
[PublicAPI]
public IReadOnlyDictionary<string, string> PostgresParameters
{
get
{
CheckConnectionOpen();
Debug.Assert(Connector != null);
return Connector.PostgresParameters;
}
}
#endregion Backend version, capabilities, settings
#region Copy
/// <summary>
/// Begins a binary COPY FROM STDIN operation, a high-performance data import mechanism to a PostgreSQL table.
/// </summary>
/// <param name="copyFromCommand">A COPY FROM STDIN SQL command</param>
/// <returns>A <see cref="NpgsqlBinaryImporter"/> which can be used to write rows and columns</returns>
/// <remarks>
/// See http://www.postgresql.org/docs/current/static/sql-copy.html.
/// </remarks>
public NpgsqlBinaryImporter BeginBinaryImport(string copyFromCommand)
{
if (copyFromCommand == null)
throw new ArgumentNullException(nameof(copyFromCommand));
if (!copyFromCommand.TrimStart().ToUpper().StartsWith("COPY"))
throw new ArgumentException("Must contain a COPY FROM STDIN command!", nameof(copyFromCommand));
var connector = CheckReadyAndGetConnector();
Log.Debug("Starting binary import", connector.Id);
connector.StartUserAction(ConnectorState.Copy);
try
{
var importer = new NpgsqlBinaryImporter(connector, copyFromCommand);
connector.CurrentCopyOperation = importer;
return importer;
}
catch
{
connector.EndUserAction();
throw;
}
}
/// <summary>
/// Begins a binary COPY TO STDOUT operation, a high-performance data export mechanism from a PostgreSQL table.
/// </summary>
/// <param name="copyToCommand">A COPY TO STDOUT SQL command</param>
/// <returns>A <see cref="NpgsqlBinaryExporter"/> which can be used to read rows and columns</returns>
/// <remarks>
/// See http://www.postgresql.org/docs/current/static/sql-copy.html.
/// </remarks>
public NpgsqlBinaryExporter BeginBinaryExport(string copyToCommand)
{
if (copyToCommand == null)
throw new ArgumentNullException(nameof(copyToCommand));
if (!copyToCommand.TrimStart().ToUpper().StartsWith("COPY"))
throw new ArgumentException("Must contain a COPY TO STDOUT command!", nameof(copyToCommand));
var connector = CheckReadyAndGetConnector();
Log.Debug("Starting binary export", connector.Id);
connector.StartUserAction(ConnectorState.Copy);
try
{
var exporter = new NpgsqlBinaryExporter(connector, copyToCommand);
connector.CurrentCopyOperation = exporter;
return exporter;
}
catch
{
connector.EndUserAction();
throw;
}
}
/// <summary>
/// Begins a textual COPY FROM STDIN operation, a data import mechanism to a PostgreSQL table.
/// It is the user's responsibility to send the textual input according to the format specified
/// in <paramref name="copyFromCommand"/>.
/// </summary>
/// <param name="copyFromCommand">A COPY FROM STDIN SQL command</param>
/// <returns>
/// A TextWriter that can be used to send textual data.</returns>
/// <remarks>
/// See http://www.postgresql.org/docs/current/static/sql-copy.html.
/// </remarks>
public TextWriter BeginTextImport(string copyFromCommand)
{
if (copyFromCommand == null)
throw new ArgumentNullException(nameof(copyFromCommand));
if (!copyFromCommand.TrimStart().ToUpper().StartsWith("COPY"))
throw new ArgumentException("Must contain a COPY FROM STDIN command!", nameof(copyFromCommand));
var connector = CheckReadyAndGetConnector();
Log.Debug("Starting text import", connector.Id);
connector.StartUserAction(ConnectorState.Copy);
try
{
var writer = new NpgsqlCopyTextWriter(connector, new NpgsqlRawCopyStream(connector, copyFromCommand));
connector.CurrentCopyOperation = writer;
return writer;
}
catch
{
connector.EndUserAction();
throw;
}
}
/// <summary>
/// Begins a textual COPY TO STDOUT operation, a data export mechanism from a PostgreSQL table.
/// It is the user's responsibility to parse the textual input according to the format specified
/// in <paramref name="copyToCommand"/>.
/// </summary>
/// <param name="copyToCommand">A COPY TO STDOUT SQL command</param>
/// <returns>
/// A TextReader that can be used to read textual data.</returns>
/// <remarks>
/// See http://www.postgresql.org/docs/current/static/sql-copy.html.
/// </remarks>
public TextReader BeginTextExport(string copyToCommand)
{
if (copyToCommand == null)
throw new ArgumentNullException(nameof(copyToCommand));
if (!copyToCommand.TrimStart().ToUpper().StartsWith("COPY"))
throw new ArgumentException("Must contain a COPY TO STDOUT command!", nameof(copyToCommand));
var connector = CheckReadyAndGetConnector();
Log.Debug("Starting text export", connector.Id);
connector.StartUserAction(ConnectorState.Copy);
try
{
var reader = new NpgsqlCopyTextReader(connector, new NpgsqlRawCopyStream(connector, copyToCommand));
connector.CurrentCopyOperation = reader;
return reader;
}
catch
{
connector.EndUserAction();
throw;
}
}
/// <summary>
/// Begins a raw binary COPY operation (TO STDOUT or FROM STDIN), a high-performance data export/import mechanism to a PostgreSQL table.
/// Note that unlike the other COPY API methods, <see cref="BeginRawBinaryCopy"/> doesn't implement any encoding/decoding
/// and is unsuitable for structured import/export operation. It is useful mainly for exporting a table as an opaque
/// blob, for the purpose of importing it back later.
/// </summary>
/// <param name="copyCommand">A COPY TO STDOUT or COPY FROM STDIN SQL command</param>
/// <returns>A <see cref="NpgsqlRawCopyStream"/> that can be used to read or write raw binary data.</returns>
/// <remarks>
/// See http://www.postgresql.org/docs/current/static/sql-copy.html.
/// </remarks>
public NpgsqlRawCopyStream BeginRawBinaryCopy(string copyCommand)
{
if (copyCommand == null)
throw new ArgumentNullException(nameof(copyCommand));
if (!copyCommand.TrimStart().ToUpper().StartsWith("COPY"))
throw new ArgumentException("Must contain a COPY TO STDOUT OR COPY FROM STDIN command!", nameof(copyCommand));
var connector = CheckReadyAndGetConnector();
Log.Debug("Starting raw COPY operation", connector.Id);
connector.StartUserAction(ConnectorState.Copy);
try
{
var stream = new NpgsqlRawCopyStream(connector, copyCommand);
if (!stream.IsBinary)
{
// TODO: Stop the COPY operation gracefully, no breaking
connector.Break();
throw new ArgumentException("copyToCommand triggered a text transfer, only binary is allowed", nameof(copyCommand));
}
connector.CurrentCopyOperation = stream;