forked from danzel/Npgsql
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNpgsqlConnection.cs
More file actions
1257 lines (1093 loc) · 44.7 KB
/
NpgsqlConnection.cs
File metadata and controls
1257 lines (1093 loc) · 44.7 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
// created on 10/5/2002 at 23:01
// Npgsql.NpgsqlConnection.cs
//
// Author:
// Francisco Jr. (fxjrlists@yahoo.com.br)
//
// Copyright (C) 2002 The Npgsql Development Team
// npgsql-general@gborg.postgresql.org
// http://gborg.postgresql.org/project/npgsql/projdisplay.php
//
//
// 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.
using System;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Net.Security;
using System.Reflection;
using System.Resources;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Transactions;
using Mono.Security.Protocol.Tls;
using IsolationLevel = System.Data.IsolationLevel;
#if WITHDESIGN
#endif
namespace Npgsql
{
/// <summary>
/// Represents the method that handles the <see cref="Npgsql.NpgsqlConnection.Notification">Notice</see> events.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">A <see cref="Npgsql.NpgsqlNoticeEventArgs">NpgsqlNoticeEventArgs</see> that contains the event data.</param>
public delegate void NoticeEventHandler(Object sender, NpgsqlNoticeEventArgs e);
/// <summary>
/// Represents the method that handles the <see cref="Npgsql.NpgsqlConnection.Notification">Notification</see> events.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">A <see cref="Npgsql.NpgsqlNotificationEventArgs">NpgsqlNotificationEventArgs</see> that contains the event data.</param>
public delegate void NotificationEventHandler(Object sender, NpgsqlNotificationEventArgs e);
/// <summary>
/// This class represents a connection to a
/// PostgreSQL server.
/// </summary>
#if WITHDESIGN
[System.Drawing.ToolboxBitmapAttribute(typeof(NpgsqlConnection))]
#endif
public sealed class NpgsqlConnection : DbConnection, ICloneable
{
// Logging related values
private static readonly String CLASSNAME = MethodBase.GetCurrentMethod().DeclaringType.Name;
private static readonly ResourceManager resman = new ResourceManager(MethodBase.GetCurrentMethod().DeclaringType);
// Parsed connection string cache
private static readonly Cache<NpgsqlConnectionStringBuilder> cache = new Cache<NpgsqlConnectionStringBuilder>();
/// <summary>
/// Occurs on NoticeResponses from the PostgreSQL backend.
/// </summary>
public event NoticeEventHandler Notice;
internal NoticeEventHandler NoticeDelegate;
/// <summary>
/// Occurs on NotificationResponses from the PostgreSQL backend.
/// </summary>
public event NotificationEventHandler Notification;
internal NotificationEventHandler NotificationDelegate;
/// <summary>
/// Called to provide client certificates for SSL handshake.
/// </summary>
public event ProvideClientCertificatesCallback ProvideClientCertificatesCallback;
internal ProvideClientCertificatesCallback ProvideClientCertificatesCallbackDelegate;
/// <summary>
/// Mono.Security.Protocol.Tls.CertificateSelectionCallback delegate.
/// </summary>
[Obsolete("CertificateSelectionCallback, CertificateValidationCallback and PrivateKeySelectionCallback have been replaced with ValidateRemoteCertificateCallback.")]
public event CertificateSelectionCallback CertificateSelectionCallback;
internal CertificateSelectionCallback CertificateSelectionCallbackDelegate;
/// <summary>
/// Mono.Security.Protocol.Tls.CertificateValidationCallback delegate.
/// </summary>
[Obsolete("CertificateSelectionCallback, CertificateValidationCallback and PrivateKeySelectionCallback have been replaced with ValidateRemoteCertificateCallback.")]
public event CertificateValidationCallback CertificateValidationCallback;
internal CertificateValidationCallback CertificateValidationCallbackDelegate;
/// <summary>
/// Mono.Security.Protocol.Tls.PrivateKeySelectionCallback delegate.
/// </summary>
[Obsolete("CertificateSelectionCallback, CertificateValidationCallback and PrivateKeySelectionCallback have been replaced with ValidateRemoteCertificateCallback.")]
public event PrivateKeySelectionCallback PrivateKeySelectionCallback;
internal PrivateKeySelectionCallback PrivateKeySelectionCallbackDelegate;
/// <summary>
/// Called to validate server's certificate during SSL handshake
/// </summary>
public event ValidateRemoteCertificateCallback ValidateRemoteCertificateCallback;
internal ValidateRemoteCertificateCallback ValidateRemoteCertificateCallbackDelegate;
// Set this when disposed is called.
private bool disposed = false;
// Used when we closed the connector due to an error, but are pretending it's open.
private bool _fakingOpen;
// Used when the connection is closed but an TransactionScope is still active
// (the actual close is postponed until the scope ends)
private bool _postponingClose;
private bool _postponingDispose;
// Strong-typed ConnectionString values
private NpgsqlConnectionStringBuilder settings;
// Connector being used for the active connection.
private NpgsqlConnector connector = null;
private NpgsqlPromotableSinglePhaseNotification promotable = null;
// A cached copy of the result of `settings.ConnectionString`
private string _connectionString;
/// <summary>
/// Initializes a new instance of the
/// <see cref="Npgsql.NpgsqlConnection">NpgsqlConnection</see> class.
/// </summary>
public NpgsqlConnection()
: this(String.Empty)
{
}
private void Init()
{
NoticeDelegate = new NoticeEventHandler(OnNotice);
NotificationDelegate = new NotificationEventHandler(OnNotification);
ProvideClientCertificatesCallbackDelegate = new ProvideClientCertificatesCallback(DefaultProvideClientCertificatesCallback);
CertificateValidationCallbackDelegate = new CertificateValidationCallback(DefaultCertificateValidationCallback);
CertificateSelectionCallbackDelegate = new CertificateSelectionCallback(DefaultCertificateSelectionCallback);
PrivateKeySelectionCallbackDelegate = new PrivateKeySelectionCallback(DefaultPrivateKeySelectionCallback);
ValidateRemoteCertificateCallbackDelegate = new ValidateRemoteCertificateCallback(DefaultValidateRemoteCertificateCallback);
// 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;
promotable = new NpgsqlPromotableSinglePhaseNotification(this);
}
/// <summary>
/// Initializes a new instance of the
/// <see cref="Npgsql.NpgsqlConnection">NpgsqlConnection</see> class
/// and sets the <see cref="Npgsql.NpgsqlConnection.ConnectionString">ConnectionString</see>.
/// </summary>
/// <param name="ConnectionString">The connection used to open the PostgreSQL database.</param>
public NpgsqlConnection(String ConnectionString)
{
NpgsqlEventLog.LogMethodEnter(LogLevel.Debug, CLASSNAME, CLASSNAME, "NpgsqlConnection()");
LoadConnectionStringBuilder(ConnectionString);
Init();
}
/// <summary>
/// Initializes a new instance of the
/// <see cref="Npgsql.NpgsqlConnection">NpgsqlConnection</see> class
/// and sets the <see cref="Npgsql.NpgsqlConnection.ConnectionString">ConnectionString</see>.
/// </summary>
/// <param name="ConnectionString">The connection used to open the PostgreSQL database.</param>
public NpgsqlConnection(NpgsqlConnectionStringBuilder ConnectionString)
{
NpgsqlEventLog.LogMethodEnter(LogLevel.Debug, CLASSNAME, CLASSNAME, "NpgsqlConnection()");
LoadConnectionStringBuilder(ConnectionString);
Init();
}
/// <summary>
/// Gets or sets the string used to connect to a PostgreSQL database.
/// Valid values are:
/// <ul>
/// <li>
/// Server: Address/Name of Postgresql Server;
/// </li>
/// <li>
/// Port: Port to connect to;
/// </li>
/// <li>
/// Protocol: Protocol version to use, instead of automatic; Integer 2 or 3;
/// </li>
/// <li>
/// Database: Database name. Defaults to user name if not specified;
/// </li>
/// <li>
/// User Id: User name;
/// </li>
/// <li>
/// Password: Password for clear text authentication;
/// </li>
/// <li>
/// SSL: True or False. Controls whether to attempt a secure connection. Default = False;
/// </li>
/// <li>
/// Pooling: True or False. Controls whether connection pooling is used. Default = True;
/// </li>
/// <li>
/// MinPoolSize: Min size of connection pool;
/// </li>
/// <li>
/// MaxPoolSize: Max size of connection pool;
/// </li>
/// <li>
/// Timeout: Time to wait for connection open in seconds. Default is 15.
/// </li>
/// <li>
/// CommandTimeout: Time to wait for command to finish execution before throw an exception. In seconds. Default is 20.
/// </li>
/// <li>
/// Sslmode: Mode for ssl connection control. Can be Prefer, Require, Allow or Disable. Default is Disable. Check user manual for explanation of values.
/// </li>
/// <li>
/// ConnectionLifeTime: Time to wait before closing unused connections in the pool in seconds. Default is 15.
/// </li>
/// <li>
/// SyncNotification: Specifies if Npgsql should use synchronous notifications.
/// </li>
/// <li>
/// SearchPath: Changes search path to specified and public schemas.
/// </li>
/// </ul>
/// </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>
#if WITHDESIGN
[RefreshProperties(RefreshProperties.All), DefaultValue(""), RecommendedAsConfigurable(true)]
[NpgsqlSysDescription("Description_ConnectionString", typeof(NpgsqlConnection)), Category("Data")]
[Editor(typeof(ConnectionStringEditor), typeof(System.Drawing.Design.UITypeEditor))]
#endif
public override String ConnectionString
{
get
{
if (string.IsNullOrEmpty(_connectionString))
RefreshConnectionString();
return settings.ConnectionString;
}
set
{
// Connection string is used as the key to the connector. Because of this,
// we cannot change it while we own a connector.
CheckConnectionClosed();
NpgsqlEventLog.LogPropertySet(LogLevel.Debug, CLASSNAME, "ConnectionString", value);
NpgsqlConnectionStringBuilder builder = cache[value];
if (builder == null)
{
settings = new NpgsqlConnectionStringBuilder(value);
}
else
{
settings = builder.Clone();
}
LoadConnectionStringBuilder(value);
}
}
/// <summary>
/// Backend server host name.
/// </summary>
[Browsable(true)]
public String Host
{
get { return settings.Host; }
}
/// <summary>
/// Backend server port.
/// </summary>
[Browsable(true)]
public Int32 Port
{
get { return settings.Port; }
}
/// <summary>
/// If true, the connection will attempt to use SSL.
/// </summary>
[Browsable(true)]
public Boolean SSL
{
get { return settings.SSL; }
}
public Boolean UseSslStream
{
get { return NpgsqlConnector.UseSslStream; }
set { NpgsqlConnector.UseSslStream = value; }
}
/// <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>
#if WITHDESIGN
[NpgsqlSysDescription("Description_ConnectionTimeout", typeof(NpgsqlConnection))]
#endif
public override Int32 ConnectionTimeout
{
get { return 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 Int32 CommandTimeout
{
get { return settings.CommandTimeout; }
}
/// <summary>
/// Gets the time to wait before closing unused connections in the pool if the count
/// of all connections exeeds MinPoolSize.
/// </summary>
/// <remarks>
/// If connection pool contains unused connections for ConnectionLifeTime seconds,
/// the half of them will be closed. If there will be unused connections in a second
/// later then again the half of them will be closed and so on.
/// This strategy provide smooth change of connection count in the pool.
/// </remarks>
/// <value>The time (in seconds) to wait. The default value is 15 seconds.</value>
public Int32 ConnectionLifeTime
{
get { return settings.ConnectionLifeTime; }
}
///<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>
#if WITHDESIGN
[NpgsqlSysDescription("Description_Database", typeof(NpgsqlConnection))]
#endif
public override String Database
{
get { return settings.Database; }
}
/// <summary>
/// Whether datareaders are loaded in their entirety (for compatibility with earlier code).
/// </summary>
public bool PreloadReader
{
get { return settings.PreloadReader; }
}
/// <summary>
/// Gets the database server name.
/// </summary>
public override string DataSource
{
get { return settings.Host; }
}
/// <summary>
/// Gets flag indicating if we are using Synchronous notification or not.
/// The default value is false.
/// </summary>
public Boolean SyncNotification
{
get { return settings.SyncNotification; }
}
/// <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
{
//CheckNotDisposed();
if (connector != null && !disposed)
{
return connector.State;
}
else
{
return ConnectionState.Closed;
}
}
}
/// <summary>
/// Gets whether the current state of the connection is Open or Closed
/// </summary>
/// <value>ConnectionState.Open or ConnectionState.Closed</value>
[Browsable(false)]
public override ConnectionState State
{
get
{
return (FullState & ConnectionState.Open) == ConnectionState.Open ? ConnectionState.Open : ConnectionState.Closed;
}
}
/// <summary>
/// Compatibility version.
/// </summary>
public Version NpgsqlCompatibilityVersion
{
get
{
return settings.Compatible;
}
}
/// <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();
return connector.ServerVersion;
}
}
/// <summary>
/// PostgreSQL server version.
/// </summary>
public override string ServerVersion
{
get { return PostgreSqlVersion.ToString(); }
}
/// <summary>
/// Protocol version in use.
/// This can only be called when there is an active connection.
/// Always retuna Version3
/// </summary>
[Browsable(false)]
public ProtocolVersion BackendProtocolVersion
{
get
{
CheckConnectionOpen();
return ProtocolVersion.Version3;
}
}
/// <summary>
/// Process id of backend server.
/// This can only be called when there is an active connection.
/// </summary>
[Browsable(false)]
public Int32 ProcessID
{
get
{
CheckConnectionOpen();
return connector.BackEndKeyData.ProcessID;
}
}
/// <summary>
/// Report whether the backend is expecting standard conformant strings.
/// In version 8.1, Postgres began reporting this value (false), but did not actually support standard conformant strings.
/// In version 8.2, Postgres began supporting standard conformant strings, but defaulted this flag to false.
/// As of version 9.1, this flag defaults to true.
/// </summary>
[Browsable(false)]
public Boolean UseConformantStrings
{
get
{
CheckConnectionOpen();
return connector.NativeToBackendTypeConverterOptions.UseConformantStrings;
}
}
/// <summary>
/// Report whether the backend understands the string literal E prefix (>= 8.1).
/// </summary>
[Browsable(false)]
public Boolean Supports_E_StringPrefix
{
get
{
CheckConnectionOpen();
return connector.NativeToBackendTypeConverterOptions.Supports_E_StringPrefix;
}
}
/// <summary>
/// Report whether the backend understands the hex byte format (>= 9.0).
/// </summary>
[Browsable(false)]
public Boolean SupportsHexByteFormat
{
get
{
CheckConnectionOpen();
return connector.NativeToBackendTypeConverterOptions.SupportsHexByteFormat;
}
}
/// <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)
{
NpgsqlEventLog.LogMethodEnter(LogLevel.Debug, CLASSNAME, "BeginDbTransaction", isolationLevel);
return BeginTransaction(isolationLevel);
}
/// <summary>
/// Begins a database transaction.
/// </summary>
/// <returns>A <see cref="Npgsql.NpgsqlTransaction">NpgsqlTransaction</see>
/// object representing the new transaction.</returns>
/// <remarks>
/// Currently there's no support for nested transactions.
/// </remarks>
public new NpgsqlTransaction BeginTransaction()
{
NpgsqlEventLog.LogMethodEnter(LogLevel.Debug, CLASSNAME, "BeginTransaction");
return this.BeginTransaction(IsolationLevel.ReadCommitted);
}
/// <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="Npgsql.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)
{
NpgsqlEventLog.LogMethodEnter(LogLevel.Debug, CLASSNAME, "BeginTransaction", level);
CheckConnectionOpen();
if (connector.Transaction != null)
{
throw new InvalidOperationException(resman.GetString("Exception_NoNestedTransactions"));
}
return new NpgsqlTransaction(this, level);
}
/// <summary>
/// Opens a database connection with the property settings specified by the
/// <see cref="Npgsql.NpgsqlConnection.ConnectionString">ConnectionString</see>.
/// </summary>
public override void Open()
{
// If we're postponing a close (see doc on this variable), the connection is already
// open and can be silently reused
if (_postponingClose)
return;
CheckConnectionClosed();
NpgsqlEventLog.LogMethodEnter(LogLevel.Debug, CLASSNAME, "Open");
// Check if there is any missing argument.
if (!settings.ContainsKey(Keywords.Host))
{
throw new ArgumentException(resman.GetString("Exception_MissingConnStrArg"),
NpgsqlConnectionStringBuilder.GetKeyName(Keywords.Host));
}
if (!settings.ContainsKey(Keywords.UserName) && !settings.ContainsKey(Keywords.IntegratedSecurity))
{
throw new ArgumentException(resman.GetString("Exception_MissingConnStrArg"),
NpgsqlConnectionStringBuilder.GetKeyName(Keywords.UserName));
}
// Get a Connector, either from the pool or creating one ourselves.
if (Pooling)
{
connector = NpgsqlConnectorPool.ConnectorPoolMgr.RequestConnector(this);
}
else
{
connector = new NpgsqlConnector(this);
connector.ProvideClientCertificatesCallback += ProvideClientCertificatesCallbackDelegate;
connector.CertificateSelectionCallback += CertificateSelectionCallbackDelegate;
connector.CertificateValidationCallback += CertificateValidationCallbackDelegate;
connector.PrivateKeySelectionCallback += PrivateKeySelectionCallbackDelegate;
connector.ValidateRemoteCertificateCallback += ValidateRemoteCertificateCallbackDelegate;
connector.Open();
}
connector.Notice += NoticeDelegate;
connector.Notification += NotificationDelegate;
if (SyncNotification)
{
connector.AddNotificationThread();
}
if (Enlist)
{
Promotable.Enlist(Transaction.Current);
}
this.OnStateChange (new StateChangeEventArgs(ConnectionState.Closed, ConnectionState.Open));
}
/// <summary>
/// This method changes the current database by disconnecting from the actual
/// database and connecting to the specified.
/// </summary>
/// <param name="dbName">The name of the database to use in place of the current database.</param>
public override void ChangeDatabase(String dbName)
{
CheckNotDisposed();
NpgsqlEventLog.LogMethodEnter(LogLevel.Debug, CLASSNAME, "ChangeDatabase", dbName);
if (dbName == null)
{
throw new ArgumentNullException("dbName");
}
if (string.IsNullOrEmpty(dbName))
{
throw new ArgumentOutOfRangeException("dbName", dbName, String.Format(resman.GetString("Exception_InvalidDbName")));
}
String oldDatabaseName = Database;
Close();
// Mutating the current `settings` object would invalidate the cached instance, so work on a copy instead.
settings = settings.Clone();
settings[Keywords.Database] = dbName;
_connectionString = null;
Open();
}
internal void EmergencyClose()
{
_fakingOpen = true;
}
/// <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()
{
NpgsqlEventLog.LogMethodEnter(LogLevel.Debug, CLASSNAME, "Close");
if (connector == null)
return;
if (promotable != null && promotable.InLocalTransaction)
{
_postponingClose = true;
return;
}
ReallyClose();
}
private void ReallyClose()
{
NpgsqlEventLog.LogMethodEnter(LogLevel.Debug, CLASSNAME, "ReallyClose");
_postponingClose = false;
// clear the way for another promotable transaction
promotable = null;
connector.Notification -= NotificationDelegate;
connector.Notice -= NoticeDelegate;
if (SyncNotification)
{
connector.RemoveNotificationThread();
}
if (Pooling)
{
NpgsqlConnectorPool.ConnectorPoolMgr.ReleaseConnector(this, connector);
}
else
{
Connector.ProvideClientCertificatesCallback -= ProvideClientCertificatesCallbackDelegate;
Connector.CertificateSelectionCallback -= CertificateSelectionCallbackDelegate;
Connector.CertificateValidationCallback -= CertificateValidationCallbackDelegate;
Connector.PrivateKeySelectionCallback -= PrivateKeySelectionCallbackDelegate;
Connector.ValidateRemoteCertificateCallback -= ValidateRemoteCertificateCallbackDelegate;
if (Connector.Transaction != null)
{
Connector.Transaction.Cancel();
}
Connector.Close();
}
connector = null;
this.OnStateChange (new StateChangeEventArgs(ConnectionState.Open, ConnectionState.Closed));
}
/// <summary>
/// When a connection is closed within an enclosing TransactionScope and the transaction
/// hasn't been promoted, we defer the actual closing until the scope ends.
/// </summary>
internal void PromotableLocalTransactionEnded()
{
NpgsqlEventLog.LogMethodEnter(LogLevel.Debug, CLASSNAME, "PromotableLocalTransactionEnded");
if (_postponingDispose)
Dispose(true);
else if (_postponingClose)
ReallyClose();
}
/// <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()
{
NpgsqlEventLog.LogMethodEnter(LogLevel.Debug, CLASSNAME, "CreateDbCommand");
return CreateCommand();
}
/// <summary>
/// Creates and returns a <see cref="Npgsql.NpgsqlCommand">NpgsqlCommand</see>
/// object associated with the <see cref="Npgsql.NpgsqlConnection">NpgsqlConnection</see>.
/// </summary>
/// <returns>A <see cref="Npgsql.NpgsqlCommand">NpgsqlCommand</see> object.</returns>
public new NpgsqlCommand CreateCommand()
{
CheckNotDisposed();
NpgsqlEventLog.LogMethodEnter(LogLevel.Debug, CLASSNAME, "CreateCommand");
return new NpgsqlCommand("", this);
}
/// <summary>
/// Releases all resources used by the
/// <see cref="Npgsql.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;
_postponingDispose = false;
if (disposing)
{
NpgsqlEventLog.LogMethodEnter(LogLevel.Debug, CLASSNAME, "Dispose");
Close();
if (_postponingClose)
{
_postponingDispose = true;
return;
}
}
base.Dispose(disposing);
disposed = true;
}
/// <summary>
/// Create a new connection based on this one.
/// </summary>
/// <returns>A new NpgsqlConnection object.</returns>
Object ICloneable.Clone()
{
return Clone();
}
/// <summary>
/// Create a new connection based on this one.
/// </summary>
/// <returns>A new NpgsqlConnection object.</returns>
public NpgsqlConnection Clone()
{
CheckNotDisposed();
NpgsqlConnection C = new NpgsqlConnection(ConnectionString);
C.Notice += this.Notice;
if (connector != null)
{
C.Open();
}
return C;
}
//
// Internal methods and properties
//
internal void OnNotice(object O, NpgsqlNoticeEventArgs E)
{
if (Notice != null)
{
Notice(this, E);
}
}
internal void OnNotification(object O, NpgsqlNotificationEventArgs E)
{
if (Notification != null)
{
Notification(this, E);
}
}
/// <summary>
/// Returns a copy of the NpgsqlConnectionStringBuilder that contains the parsed connection string values.
/// </summary>
internal NpgsqlConnectionStringBuilder CopyConnectionStringBuilder()
{
return settings.Clone();
}
/// <summary>
/// The connector object connected to the backend.
/// </summary>
internal NpgsqlConnector Connector
{
get { return connector; }
}
/// <summary>
/// Gets the NpgsqlConnectionStringBuilder containing the parsed connection string values.
/// </summary>
internal NpgsqlConnectionStringBuilder ConnectionStringValues
{
get { return settings; }
}
/// <summary>
/// User name.
/// </summary>
internal String UserName
{
get { return settings.UserName; }
}
/// <summary>
/// Use extended types.
/// </summary>
public bool UseExtendedTypes
{
get
{
bool ext = settings.UseExtendedTypes;
return ext;
}
}
/// <summary>
/// Password.
/// </summary>
internal byte[] Password
{
get { return settings.PasswordAsByteArray; }
}
/// <summary>
/// Determine if connection pooling will be used for this connection.
/// </summary>
internal Boolean Pooling
{
get { return (settings.Pooling && (settings.MaxPoolSize > 0)); }
}
internal Int32 MinPoolSize
{
get { return settings.MinPoolSize; }
}
internal Int32 MaxPoolSize
{
get { return settings.MaxPoolSize; }
}
internal Int32 Timeout
{
get { return settings.Timeout; }
}
internal Boolean Enlist
{
get { return settings.Enlist; }
}
//
// Event handlers
//
/// <summary>
/// Default SSL CertificateSelectionCallback implementation.
/// </summary>
internal X509Certificate DefaultCertificateSelectionCallback(X509CertificateCollection clientCertificates,
X509Certificate serverCertificate, string targetHost,
X509CertificateCollection serverRequestedCertificates)
{
if (CertificateSelectionCallback != null)
{
return CertificateSelectionCallback(clientCertificates, serverCertificate, targetHost, serverRequestedCertificates);
}
else
{
return null;
}
}
/// <summary>
/// Default SSL CertificateValidationCallback implementation.
/// </summary>
internal bool DefaultCertificateValidationCallback(X509Certificate certificate, int[] certificateErrors)
{
if (CertificateValidationCallback != null)
{
return CertificateValidationCallback(certificate, certificateErrors);
}
else
{
return true;
}
}
/// <summary>
/// Default SSL PrivateKeySelectionCallback implementation.
/// </summary>