forked from npgsql/npgsql
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNpgsqlConnection.cs
More file actions
1457 lines (1284 loc) · 60.3 KB
/
NpgsqlConnection.cs
File metadata and controls
1457 lines (1284 loc) · 60.3 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
#region License
// The PostgreSQL License
//
// Copyright (C) 2017 The Npgsql Development Team
//
// Permission to use, copy, modify, and distribute this software and its
// documentation for any purpose, without fee, and without a written
// agreement is hereby granted, provided that the above copyright notice
// and this paragraph and the following two paragraphs appear in all copies.
//
// IN NO EVENT SHALL THE NPGSQL DEVELOPMENT TEAM BE LIABLE TO ANY PARTY
// FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
// INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS
// DOCUMENTATION, EVEN IF THE NPGSQL DEVELOPMENT TEAM HAS BEEN ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
// THE NPGSQL DEVELOPMENT TEAM SPECIFICALLY DISCLAIMS ANY WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
// ON AN "AS IS" BASIS, AND THE NPGSQL DEVELOPMENT TEAM HAS NO OBLIGATIONS
// TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
#endregion
using System;
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.Reflection;
using System.Security.Cryptography;
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 IsolationLevel = System.Data.IsolationLevel;
using ThreadState = System.Threading.ThreadState;
#if !NETSTANDARD1_3
using System.Transactions;
#endif
namespace Npgsql
{
/// <summary>
/// This class represents a connection to a PostgreSQL server.
/// </summary>
#if NETSTANDARD1_3
public sealed class NpgsqlConnection : DbConnection
#else
// ReSharper disable once RedundantNameQualifier
[System.ComponentModel.DesignerCategory("")]
public sealed class NpgsqlConnection : DbConnection, ICloneable
#endif
{
#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;
/// <summary>
/// The original connection string provided by the user, including the password.
/// </summary>
string _connectionString;
internal string OriginalConnectionString => _connectionString;
/// <summary>
/// The connector object connected to the backend.
/// </summary>
[CanBeNull]
internal NpgsqlConnector Connector { get; set; }
/// <summary>
/// The parsed connection string set by the user
/// </summary>
internal NpgsqlConnectionStringBuilder Settings { get; private set; }
[CanBeNull]
ConnectorPool _pool;
bool _wasBroken;
#if !NETSTANDARD1_3
[CanBeNull]
internal Transaction EnlistedTransaction { get; set; }
#endif
/// <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
{
get
{
CheckConnectionOpen();
return Connector.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;
#endregion Fields
#region Constructors / Init / Open
/// <summary>
/// Initializes a new instance of the
/// <see cref="NpgsqlConnection">NpgsqlConnection</see> class.
/// </summary>
public NpgsqlConnection() : 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)
{
GC.SuppressFinalize(this);
ConnectionString = connectionString;
#if !NETSTANDARD1_3
// Fix authentication problems. See https://bugzilla.novell.com/show_bug.cgi?id=MONO77559 and
// http://pgfoundry.org/forum/message.php?msg_id=1002377 for more info.
RSACryptoServiceProvider.UseMachineKeyStore = true;
#endif
}
/// <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)
=> SynchronizationContextSwitcher.NoContext(async () => await Open(true, cancellationToken));
void GetPoolAndSettings()
{
var pools = PoolManager.Pools;
lock (pools)
{
if (pools.TryGetValue(_connectionString, out _pool))
Settings = _pool.Settings; // Great, we already have a pool
else
{
// Connection string hasn't been seen before. Parse it.
Settings = new NpgsqlConnectionStringBuilder(_connectionString);
if (!_countersInitialized)
{
_countersInitialized = true;
Counters.Initialize(Settings.UsePerfCounters);
}
// Maybe pooling is off
if (Settings.Pooling)
{
// Connstring 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 (pools.TryGetValue(canonical, out _pool))
pools[_connectionString] = _pool;
else
{
// Really unseen, need to create a new pool
_pool = pools[_connectionString] = new ConnectorPool(Settings, canonical);
if (_connectionString != canonical)
pools[canonical] = _pool;
}
}
}
}
}
async Task Open(bool async, CancellationToken cancellationToken)
{
CheckConnectionClosed();
Log.Trace("Opening connection...");
_wasBroken = false;
try
{
Debug.Assert(Settings != null);
var timeout = new NpgsqlTimeout(TimeSpan.FromSeconds(ConnectionTimeout));
if (_pool == null) // Unpooled connection
{
if (!Settings.PersistSecurityInfo)
_userFacingConnectionString = Settings.ToStringWithoutPassword();
Connector = new NpgsqlConnector(this);
await Connector.Open(timeout, async, cancellationToken);
Counters.NumberOfNonPooledConnections.Increment();
}
else
{
_userFacingConnectionString = _pool.UserFacingConnectionString;
#if !NETSTANDARD1_3
if (Settings.Enlist)
{
if (Transaction.Current != 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)
EnlistedTransaction = Transaction.Current;
}
if (Connector == null)
Connector = await _pool.Allocate(this, timeout, async, cancellationToken);
}
else // No enlist
#endif
Connector = await _pool.Allocate(this, timeout, async, cancellationToken);
Counters.SoftConnectsPerSecond.Increment();
// Since this pooled connector was opened, global mappings may have
// changed. Bring this up to date if needed.
var mapper = Connector.TypeMapper;
if (mapper.IsModified ||
mapper.ChangeCounter != TypeMapping.GlobalTypeMapper.Instance.ChangeCounter)
{
mapper.Reset();
}
}
#if !NETSTANDARD1_3
// We may have gotten an already enlisted pending connector above, no need to enlist in that case
if (Settings.Enlist && Transaction.Current != null && EnlistedTransaction == null)
EnlistTransaction(Transaction.Current);
#endif
}
catch
{
Connector = null;
throw;
}
Log.Debug("Connection opened", Connector.Id);
OnStateChange(new StateChangeEventArgs(ConnectionState.Closed, ConnectionState.Open));
}
#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>
[CanBeNull]
public override string ConnectionString
{
get => _userFacingConnectionString;
set
{
CheckConnectionClosed();
if (value == null)
value = string.Empty;
_userFacingConnectionString = _connectionString = value;
GetPoolAndSettings();
}
}
#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>
[CanBeNull]
public override string Database => Settings.Database ?? Settings.Username;
/// <summary>
/// Gets the string identifying the database server (host and port)
/// </summary>
public override string DataSource => $"tcp://{Host}:{Port}";
/// <summary>
/// Whether to use Windows integrated security to log in.
/// </summary>
[PublicAPI]
public bool IntegratedSecurity => Settings.IntegratedSecurity;
/// <summary>
/// User name.
/// </summary>
[PublicAPI]
[CanBeNull]
public string UserName => Settings.Username;
[CanBeNull]
internal string Password => Settings.Password;
// The following two lines are here for backwards compatibility with the EF6 provider
internal string EntityTemplateDatabase => Settings.EntityTemplateDatabase;
internal string EntityAdminDatabase => Settings.EntityAdminDatabase;
#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 NotSupportedException("Nested/Concurrent transactions aren't supported.");
return new NpgsqlTransaction(this, level);
}
}
#if !NETSTANDARD1_3
/// <summary>
/// Enlist transation.
/// </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.
}
}
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);
}
#endif
#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;
CloseOngoingOperations();
if (!Settings.Pooling)
Connector.Close();
else
{
#if NETSTANDARD1_3
_pool.Release(Connector);
#else
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;
}
#endif
}
Log.Debug("Connection closed", connectorId);
Connector = null;
OnStateChange(new StateChangeEventArgs(ConnectionState.Open, ConnectionState.Closed));
}
/// <summary>
/// Closes ongoing operations, i.e. an open reader exists or a COPY operation still in progress, as
/// part of a connection close.
/// Does nothing if the thread has been aborted - the connector will be closed immediately.
/// </summary>
void CloseOngoingOperations()
{
if ((Thread.CurrentThread.ThreadState & (ThreadState.Aborted | ThreadState.AbortRequested)) != 0)
return;
Debug.Assert(Connector != null);
Connector.CurrentReader?.Close(true, false);
var currentCopyOperation = Connector.CurrentCopyOperation;
if (currentCopyOperation != null)
{
// TODO: There's probably a race condition as the COPY operation may finish on its own during the next few lines
// Note: we only want to cancel import operations, since in these cases cancel is safe.
// Export cancellations go through the PostgreSQL "asynchronous" cancel mechanism and are
// therefore vulnerable to the race condition in #615.
if (currentCopyOperation is NpgsqlBinaryImporter ||
currentCopyOperation is NpgsqlCopyTextWriter ||
(currentCopyOperation is NpgsqlRawCopyStream && ((NpgsqlRawCopyStream)currentCopyOperation).CanWrite))
{
try
{
currentCopyOperation.Cancel();
}
catch (Exception e)
{
Log.Warn("Error while cancelling COPY on connector close", e, Connector.Id);
}
}
try
{
currentCopyOperation.Dispose();
}
catch (Exception e)
{
Log.Warn("Error while disposing cancelled COPY on connector close", e, Connector.Id);
}
}
}
/// <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
/// <summary>
/// Occurs on NoticeResponses from the PostgreSQL backend.
/// </summary>
public event NoticeEventHandler Notice;
/// <summary>
/// Occurs on NotificationResponses from the PostgreSQL backend.
/// </summary>
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
#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>
[CanBeNull]
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>
[CanBeNull]
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.ServerVersion;
}
}
/// <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.IntegerDateTimes;
}
}
/// <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;
}
}
#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(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(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;
return stream;
}
catch
{
connector.EndUserAction();
throw;
}
}
#endregion
#region Enum mapping
/// <summary>
/// Maps a CLR enum to a PostgreSQL enum type for use with this connection.
/// </summary>
/// <remarks>
/// CLR enum labels are mapped by name to PostgreSQL enum labels.