forked from npgsql/npgsql
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConnectionTests.cs
More file actions
977 lines (877 loc) · 39 KB
/
ConnectionTests.cs
File metadata and controls
977 lines (877 loc) · 39 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
#region License
// The PostgreSQL License
//
// Copyright (C) 2015 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.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
using Npgsql;
using System.Data;
using System.Resources;
using NUnit.Framework;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net.Security;
using System.Text.RegularExpressions;
using NpgsqlTypes;
namespace Npgsql.Tests
{
[TestFixture]
public class ConnectionTests : TestBase
{
public ConnectionTests(string backendVersion) : base(backendVersion) { }
[Test, Description("Makes sure the connection goes through the proper state lifecycle")]
//[Timeout(5000)]
public void BasicLifecycle()
{
using (var conn = new NpgsqlConnection(ConnectionString))
{
bool eventOpen = false, eventClosed = false, eventBroken = false;
conn.StateChange += (s, e) =>
{
if (e.OriginalState == ConnectionState.Closed && e.CurrentState == ConnectionState.Open)
eventOpen = true;
if (e.OriginalState == ConnectionState.Open && e.CurrentState == ConnectionState.Closed)
eventClosed = true;
};
Assert.That(conn.State, Is.EqualTo(ConnectionState.Closed));
Assert.That(conn.FullState, Is.EqualTo(ConnectionState.Closed));
// TODO: Connecting state?
conn.Open();
Assert.That(conn.State, Is.EqualTo(ConnectionState.Open));
Assert.That(conn.FullState, Is.EqualTo(ConnectionState.Open));
Assert.That(conn.Connector.State, Is.EqualTo(ConnectorState.Ready));
Assert.That(eventOpen, Is.True);
using (var cmd = new NpgsqlCommand("SELECT 1", conn))
using (var reader = cmd.ExecuteReader())
{
reader.Read();
Assert.That(conn.FullState, Is.EqualTo(ConnectionState.Open | ConnectionState.Fetching));
Assert.That(conn.State, Is.EqualTo(ConnectionState.Open));
Assert.That(conn.Connector.State, Is.EqualTo(ConnectorState.Fetching));
}
Assert.That(conn.FullState, Is.EqualTo(ConnectionState.Open));
Assert.That(conn.State, Is.EqualTo(ConnectionState.Open));
Assert.That(conn.Connector.State, Is.EqualTo(ConnectorState.Ready));
using (var cmd = CreateSleepCommand(conn, 1))
{
var exitFlag = false;
var pollingTask = Task.Factory.StartNew(() =>
{
while (true)
{
if (exitFlag) {
Assert.Fail("Connection did not reach the Executing state");
}
if (conn.Connector.State == ConnectorState.Executing)
{
Assert.That(conn.FullState & ConnectionState.Executing, Is.Not.EqualTo(0));
Assert.That(conn.State, Is.EqualTo(ConnectionState.Open));
return;
}
}
});
cmd.ExecuteNonQuery();
exitFlag = true;
pollingTask.Wait();
}
conn.Close();
Assert.That(conn.State, Is.EqualTo(ConnectionState.Closed));
Assert.That(conn.FullState, Is.EqualTo(ConnectionState.Closed));
Assert.That(eventClosed, Is.True);
conn.Open();
Assert.That(conn.State, Is.EqualTo(ConnectionState.Open));
Assert.That(conn.FullState, Is.EqualTo(ConnectionState.Open));
Assert.That(conn.Connector.State, Is.EqualTo(ConnectorState.Ready));
// Use another connection to kill our connection
ExecuteNonQuery(string.Format("SELECT pg_terminate_backend({0})", conn.ProcessID));
conn.StateChange += (sender, args) =>
{
if (args.CurrentState == ConnectionState.Closed)
eventBroken = true;
};
Assert.That(() => ExecuteScalar("SELECT 1", conn), Throws.Exception.TypeOf<IOException>());
Assert.That(conn.State, Is.EqualTo(ConnectionState.Closed));
Assert.That(conn.FullState, Is.EqualTo(ConnectionState.Broken));
Assert.That(eventBroken, Is.True);
}
}
#region Connection Errors
[Test]
[TestCase(true, TestName = "Pooled")]
[TestCase(false, TestName = "NonPooled")]
public void ConnectionRefused(bool pooled)
{
var csb = new NpgsqlConnectionStringBuilder(ConnectionString) { Port = 44444, Pooling = pooled };
using (var conn = new NpgsqlConnection(csb)) {
Assert.That(() => conn.Open(), Throws.Exception
.TypeOf<SocketException>()
.With.Property("SocketErrorCode").EqualTo(SocketError.ConnectionRefused)
);
Assert.That(conn.FullState, Is.EqualTo(ConnectionState.Closed));
}
}
[Test]
[TestCase(true, TestName = "Pooled")]
[TestCase(false, TestName = "NonPooled")]
public void ConnectionRefusedAsync(bool pooled)
{
var csb = new NpgsqlConnectionStringBuilder(ConnectionString) { Port = 44444, Pooling = pooled };
using (var conn = new NpgsqlConnection(csb))
{
Assert.That(async () => await conn.OpenAsync(), Throws.Exception
.TypeOf<SocketException>()
.With.Property("SocketErrorCode").EqualTo(SocketError.ConnectionRefused)
);
Assert.That(conn.FullState, Is.EqualTo(ConnectionState.Closed));
}
}
[Test]
[Ignore("Fails in a non-determinstic manner and only on the build server... investigate...")]
public void InvalidUserId()
{
var csb = new NpgsqlConnectionStringBuilder(ConnectionString) { Username = "unknown", Pooling = false };
using (var conn = new NpgsqlConnection(csb))
{
Assert.That(conn.Open, Throws.Exception
.TypeOf<NpgsqlException>()
.With.Property("Code").EqualTo("28P01")
);
Assert.That(conn.FullState, Is.EqualTo(ConnectionState.Closed));
}
}
[Test, Description("Connects with a bad password to ensure the proper error is thrown")]
public void AuthenticationFailure()
{
var csb = new NpgsqlConnectionStringBuilder(ConnectionString) { Password = "bad", Pooling = false };
using (var conn = new NpgsqlConnection(csb))
{
Assert.That(() => conn.Open(), Throws.Exception
.TypeOf<NpgsqlException>()
.With.Property("Code").EqualTo("28P01")
);
Assert.That(conn.FullState, Is.EqualTo(ConnectionState.Closed));
}
}
[Test, Description("Tests that mandatory connection string parameters are indeed mandatory")]
public void MandatoryConnectionStringParams()
{
Assert.That(() => new NpgsqlConnection("User ID=npgsql_tests;Password=npgsql_tests;Database=npgsql_tests").Open(), Throws.Exception.TypeOf<ArgumentException>());
}
[Test, Description("Reuses the same connection instance for a failed connection, then a successful one")]
public void FailConnectThenSucceed()
{
ExecuteNonQuery("DROP DATABASE IF EXISTS foo");
try
{
var csb = new NpgsqlConnectionStringBuilder(ConnectionString) {
Database = "foo",
Pooling = false
};
using (var conn = new NpgsqlConnection(csb))
{
Assert.That(() => conn.Open(),
Throws.Exception.TypeOf<NpgsqlException>()
.With.Property("Code").EqualTo("3D000") // database doesn't exist
);
Assert.That(conn.FullState, Is.EqualTo(ConnectionState.Closed));
// Create the database with the other connection
ExecuteNonQuery("CREATE DATABASE foo TEMPLATE template0");
conn.Open();
conn.Close();
}
}
finally
{
ExecuteNonQuery("DROP DATABASE IF EXISTS foo");
}
}
[Test]
public void NoUsername()
{
var csb = new NpgsqlConnectionStringBuilder(ConnectionString) { Username = null };
using (var conn = new NpgsqlConnection(csb))
Assert.That(() => conn.Open(), Throws.Exception.TypeOf<ArgumentException>());
}
[Test]
[Timeout(10000)]
public void ConnectTimeout()
{
var unknownIp = Environment.GetEnvironmentVariable("NPGSQL_UNKNOWN_IP");
if (unknownIp == null)
TestUtil.IgnoreExceptOnBuildServer("NPGSQL_UNKNOWN_IP isn't defined and is required for connection timeout tests");
var csb = new NpgsqlConnectionStringBuilder(ConnectionString) {
Host = unknownIp,
Pooling = false,
Timeout = 2
};
using (var conn = new NpgsqlConnection(csb))
{
var sw = Stopwatch.StartNew();
Assert.That(() => conn.Open(), Throws.Exception.TypeOf<TimeoutException>());
Assert.That(sw.Elapsed.TotalMilliseconds, Is.GreaterThanOrEqualTo((csb.Timeout * 1000) - 100),
string.Format("Timeout was supposed to happen after {0} seconds, but fired after {1}", csb.Timeout, sw.Elapsed.TotalSeconds));
Assert.That(conn.State, Is.EqualTo(ConnectionState.Closed));
}
}
[Test]
[Timeout(10000)]
public void ConnectTimeoutAsync()
{
var unknownIp = Environment.GetEnvironmentVariable("NPGSQL_UNKNOWN_IP");
if (unknownIp == null)
TestUtil.IgnoreExceptOnBuildServer("NPGSQL_UNKNOWN_IP isn't defined and is required for connection timeout tests");
var csb = new NpgsqlConnectionStringBuilder(ConnectionString)
{
Host = unknownIp,
Pooling = false,
Timeout = 2
};
using (var conn = new NpgsqlConnection(csb))
{
Assert.That(async () => await conn.OpenAsync(), Throws.Exception.TypeOf<TimeoutException>());
Assert.That(conn.State, Is.EqualTo(ConnectionState.Closed));
}
}
[Test]
[Timeout(10000)]
public void ConnectTimeoutCancel()
{
var unknownIp = Environment.GetEnvironmentVariable("NPGSQL_UNKNOWN_IP");
if (unknownIp == null)
TestUtil.IgnoreExceptOnBuildServer("NPGSQL_UNKNOWN_IP isn't defined and is required for connection cancellation tests");
var csb = new NpgsqlConnectionStringBuilder(ConnectionString)
{
Host = unknownIp,
Pooling = false,
Timeout = 30
};
using (var conn = new NpgsqlConnection(csb))
{
var cts = new CancellationTokenSource();
cts.CancelAfter(1000);
Assert.That(async () => await conn.OpenAsync(cts.Token), Throws.Exception.TypeOf<TaskCanceledException>());
Assert.That(conn.State, Is.EqualTo(ConnectionState.Closed));
}
}
#endregion
#region Notification
[Test, Description("Simple synchronous LISTEN/NOTIFY scenario")]
public void NotificationSync()
{
var receivedNotification = false;
ExecuteNonQuery("LISTEN notifytest");
Conn.Notification += (o, e) => receivedNotification = true;
ExecuteNonQuery("NOTIFY notifytest");
Assert.IsTrue(receivedNotification);
}
[Test, Description("An asynchronous LISTEN/NOTIFY scenario")]
[Timeout(10000)]
public void NotificationAsync()
{
var mre = new ManualResetEvent(false);
using (var listeningConn = new NpgsqlConnection(ConnectionString + ";ContinuousProcessing=true"))
{
listeningConn.Open();
ExecuteNonQuery("LISTEN notifytest2", listeningConn);
listeningConn.Notification += (o, e) => mre.Set();
// Send notify via the other connection
ExecuteNonQuery("NOTIFY notifytest2");
mre.WaitOne();
// And again
mre.Reset();
ExecuteNonQuery("NOTIFY notifytest2");
mre.WaitOne();
}
}
[Test, Description("A notification arriving while we have an open Reader")]
public void NotificationDuringReader()
{
var receivedNotification = false;
using (var listeningConn = new NpgsqlConnection(ConnectionString + ";ContinuousProcessing=true"))
{
listeningConn.Open();
ExecuteNonQuery("LISTEN notifytest2", listeningConn);
listeningConn.Notification += (o, e) => receivedNotification = true;
using (var cmd = new NpgsqlCommand("SELECT 1", listeningConn))
using (cmd.ExecuteReader()) {
// Send notify via the other connection
ExecuteNonQuery("NOTIFY notifytest2");
Thread.Sleep(500);
}
}
Assert.That(receivedNotification, Is.True);
}
[Test, Description("Receive an asynchronous notification when a message has already been prepended")]
[Timeout(10000)]
public void NotificationAsyncWithPrepend()
{
var mre = new ManualResetEvent(false);
using (var listeningConn = new NpgsqlConnection(ConnectionString + ";ContinuousProcessing=true"))
{
listeningConn.Open();
ExecuteNonQuery("LISTEN notifytest2", listeningConn);
listeningConn.BeginTransaction();
// Send notify via the other connection
listeningConn.Notification += (o, e) => mre.Set();
ExecuteNonQuery("NOTIFY notifytest2");
mre.WaitOne();
}
}
[Test, Description("Generates a notification that arrives after reader data that is already being read")]
[IssueLink("https://github.com/npgsql/npgsql/issues/252")]
public void NotificationAfterData()
{
var receivedNotification = false;
using (var cmd = Conn.CreateCommand())
{
cmd.CommandText = "LISTEN notifytest1";
cmd.ExecuteNonQuery();
Conn.Notification += (o, e) => receivedNotification = true;
cmd.CommandText = "SELECT generate_series(1,10000)";
using (var reader = cmd.ExecuteReader()) {
//After "notify notifytest1", a notification message will be sent to client,
//And so the notification message will stick with the last response message of "select generate_series(1,10000)" in Npgsql's tcp receiving buffer.
using (var connection = new NpgsqlConnection(ConnectionString)) {
connection.Open();
using (var command = connection.CreateCommand()) {
command.CommandText = "NOTIFY notifytest1";
command.ExecuteNonQuery();
}
}
Assert.IsTrue(reader.Read());
Assert.AreEqual(1, reader.GetValue(0));
}
Assert.That(ExecuteScalar("SELECT 1"), Is.EqualTo(1));
Assert.IsTrue(receivedNotification);
}
}
#endregion
#region Keepalive
[Test, Description("Makes sure that if keepalive is enabled, broken connections are detected")]
[Timeout(10000)]
public void Keepalive()
{
var mre = new ManualResetEvent(false);
using (var conn = new NpgsqlConnection(ConnectionString + ";KeepAlive=1;ContinuousProcessing=true"))
{
conn.Open();
conn.StateChange += (sender, args) =>
{
if (args.CurrentState == ConnectionState.Closed)
mre.Set();
};
// Use another connection to kill our keepalive connection
ExecuteNonQuery(string.Format("SELECT pg_terminate_backend({0})", conn.ProcessID));
mre.WaitOne();
Assert.That(conn.State, Is.EqualTo(ConnectionState.Closed));
Assert.That(conn.FullState, Is.EqualTo(ConnectionState.Broken));
}
}
#endregion
[Test]
[IssueLink("https://github.com/npgsql/npgsql/issues/703")]
public void NoDatabaseDefaultsToUsername()
{
var csb = new NpgsqlConnectionStringBuilder(ConnectionString) { Database = null };
using (var conn = new NpgsqlConnection(csb))
{
conn.Open();
Assert.That(ExecuteScalar("SELECT current_database()"), Is.EqualTo(csb.Username));
}
}
[Test, Description("Breaks a connector while it's in the pool, with a keepalive and without")]
[TestCase(false, TestName = "WithoutKeepAlive")]
[TestCase(false, TestName = "WithKeepAlive")]
public void BreakConnectorInPool(bool keepAlive)
{
using (var conn = new NpgsqlConnection(ConnectionString + ";MaxPoolSize=1" + (keepAlive ? ";KeepAlive=1" : "")))
{
conn.Open();
var connectorId = conn.ProcessID;
conn.Close();
// Use another connection to kill the connector currently in the pool
ExecuteNonQuery(string.Format("SELECT pg_terminate_backend({0})", connectorId));
conn.Open();
Assert.That(conn.ProcessID, Is.EqualTo(connectorId));
Assert.That(conn.FullState, Is.EqualTo(ConnectionState.Open));
if (keepAlive)
Assert.That(ExecuteScalar("SELECT 1", conn), Is.EqualTo(1));
else
Assert.That(() => ExecuteScalar("SELECT 1", conn), Throws.Exception);
}
}
[Test]
public void ChangeDatabase()
{
Conn.ChangeDatabase("template1");
var command = new NpgsqlCommand("select current_database()", Conn);
var result = (String)command.ExecuteScalar();
Assert.AreEqual("template1", result);
}
[Test]
public void ChangeDatabaseTestConnectionCache()
{
using (var conn1 = new NpgsqlConnection(ConnectionString))
using (var conn2 = new NpgsqlConnection(ConnectionString))
{
// connection 1 change database
conn1.Open();
conn1.ChangeDatabase("template1");
var command = new NpgsqlCommand("select current_database()", conn1);
var db1 = (String)command.ExecuteScalar();
Assert.AreEqual("template1", db1);
// connection 2 's database should not changed, so should different from conn1
conn2.Open();
command = new NpgsqlCommand("select current_database()", conn2);
var db2 = (String)command.ExecuteScalar();
Assert.AreNotEqual(db1, db2);
}
}
[Test]
public void NestedTransaction()
{
Conn.BeginTransaction();
Assert.That(() => Conn.BeginTransaction(), Throws.TypeOf<NotSupportedException>());
}
[Test]
public void BeginTransactionBeforeOpen()
{
using (var conn = new NpgsqlConnection())
{
Assert.That(() => conn.BeginTransaction(), Throws.Exception.TypeOf<InvalidOperationException>());
}
}
[Test]
public void SequencialTransaction()
{
Conn.BeginTransaction().Rollback();
Conn.BeginTransaction();
}
[Test, Description("Tests closing a connector while a reader is open")]
[TestCase(true, TestName = "Pooled")]
[TestCase(false, TestName = "NonPooled")]
[Timeout(10000)]
public void CloseDuringRead(bool pooled)
{
var conn = new NpgsqlConnection(ConnectionString + ";" + (pooled ? "MaxPoolSize=1" : "Pooling=false"));
conn.Open();
var connectorId = conn.ProcessID;
using (var cmd = new NpgsqlCommand("SELECT 1", conn))
using (var reader = cmd.ExecuteReader())
{
reader.Read();
conn.Close();
Assert.That(conn.State, Is.EqualTo(ConnectionState.Closed));
Assert.That(reader.IsClosed);
}
conn.Open();
if (pooled) // Make sure we can reuse the pooled connector
Assert.That(conn.ProcessID, Is.EqualTo(connectorId));
Assert.That(conn.FullState, Is.EqualTo(ConnectionState.Open));
Assert.That(ExecuteScalar("SELECT 1"), Is.EqualTo(1));
}
[Test]
public void SearchPath()
{
var connString = new NpgsqlConnectionStringBuilder(ConnectionString) { SearchPath = "foo" };
using (var conn = new NpgsqlConnection(connString))
{
conn.Open();
Assert.That(ExecuteScalar("SHOW search_path", conn), Contains.Substring("foo"));
}
}
[Test]
public void ConnectorNotInitializedException1000581()
{
var command = new NpgsqlCommand();
command.CommandText = @"SELECT 123";
for (var i = 0; i < 2; i++)
{
using (var connection = new NpgsqlConnection(ConnectionString))
{
connection.Open();
command.Connection = connection;
command.Transaction = connection.BeginTransaction();
command.ExecuteScalar();
command.Transaction.Commit();
}
}
}
[Test]
[Ignore]
public void NpgsqlErrorRepro1()
{
throw new NotImplementedException();
#if WHAT_TO_DO_WITH_THIS
using (var connection = new NpgsqlConnection(ConnectionString))
{
connection.Open();
using (var transaction = connection.BeginTransaction())
{
var largeObjectMgr = new LargeObjectManager(connection);
try
{
var largeObject = largeObjectMgr.Open(-1, LargeObjectManager.READWRITE);
transaction.Commit();
}
catch
{
// ignore the LO failure
}
} // *1* sometimes it throws "System.NotSupportedException: This stream does not support seek operations"
using (var command = connection.CreateCommand())
{
command.CommandText = "SELECT * FROM pg_database";
using (var reader = command.ExecuteReader())
{
Assert.IsTrue(reader.Read()); // *2* this fails if the initial connection is used
}
}
} // *3* sometimes it throws "System.NotSupportedException: This stream does not support seek operations"
#endif
}
[Test]
public void Bug1011001()
{
//[#1011001] Bug in NpgsqlConnectionStringBuilder affects on cache and connection pool
var csb1 = new NpgsqlConnectionStringBuilder(@"Server=server;Port=5432;User Id=user;Password=passwor;Database=database;");
var cs1 = csb1.ToString();
var csb2 = new NpgsqlConnectionStringBuilder(cs1);
var cs2 = csb2.ToString();
Assert.IsTrue(cs1 == cs2);
}
[Test]
public void NpgsqlErrorRepro2()
{
#if WHAT_TO_DO_WITH_THIS
var connection = new NpgsqlConnection(ConnectionString);
connection.Open();
var transaction = connection.BeginTransaction();
var largeObjectMgr = new LargeObjectManager(connection);
try
{
var largeObject = largeObjectMgr.Open(-1, LargeObjectManager.READWRITE);
transaction.Commit();
}
catch
{
// ignore the LO failure
try
{
transaction.Dispose();
}
catch
{
// ignore dispose failure
}
try
{
connection.Dispose();
}
catch
{
// ignore dispose failure
}
}
using (connection = new NpgsqlConnection(ConnectionString))
{
connection.Open();
using (var command = connection.CreateCommand())
{
command.CommandText = "SELECT * FROM pg_database";
using (var reader = command.ExecuteReader())
{
Assert.IsTrue(reader.Read());
// *1* this fails if the connection for the pool happens to be the bad one from above
Assert.IsTrue(!String.IsNullOrEmpty((string)reader["datname"]));
}
}
}
#endif
}
[Test]
public void GetSchemaForeignKeys()
{
var dt = Conn.GetSchema("ForeignKeys");
Assert.IsNotNull(dt);
}
[Test]
public void GetSchemaParameterMarkerFormats()
{
ExecuteNonQuery("DROP TABLE IF EXISTS data; CREATE TABLE data (int INTEGER);");
ExecuteNonQuery("INSERT INTO data (int) VALUES (4)");
var dt = Conn.GetSchema("DataSourceInformation");
var parameterMarkerFormat = (string)dt.Rows[0]["ParameterMarkerFormat"];
using (var connection = new NpgsqlConnection(ConnectionString))
{
connection.Open();
using (var command = connection.CreateCommand())
{
const String parameterName = "@p_int";
command.CommandText = "SELECT * FROM data WHERE int=" + String.Format(parameterMarkerFormat, parameterName);
command.Parameters.Add(new NpgsqlParameter(parameterName, 4));
using (var reader = command.ExecuteReader())
{
Assert.IsTrue(reader.Read());
// This is OK, when no exceptions are occurred.
}
}
}
}
[Test]
public void GetConnectionState()
{
// Test created to PR #164
NpgsqlConnection c = new NpgsqlConnection();
c.Dispose();
Assert.AreEqual(ConnectionState.Closed, c.State);
}
[Test]
public void ChangeApplicationNameWithConnectionStringBuilder()
{
// Test for issue #165 on github.
NpgsqlConnectionStringBuilder builder = new NpgsqlConnectionStringBuilder();
builder.ApplicationName = "test";
}
[Test, Description("Makes sure notices are probably received and emitted as events")]
public void Notice()
{
// Make sure messages are in English
ExecuteNonQuery(@"SET lc_messages='English_United States.1252'");
ExecuteNonQuery(@"
CREATE OR REPLACE FUNCTION emit_notice() RETURNS VOID AS
'BEGIN RAISE NOTICE ''testnotice''; END;'
LANGUAGE 'plpgsql';
");
NpgsqlNotice notice = null;
NoticeEventHandler action = (sender, args) => notice = args.Notice;
Conn.Notice += action;
try
{
ExecuteNonQuery("SELECT emit_notice()::TEXT"); // See docs for CreateSleepCommand
Assert.That(notice, Is.Not.Null, "No notice was emitted");
Assert.That(notice.MessageText, Is.EqualTo("testnotice"));
Assert.That(notice.Severity, Is.EqualTo("NOTICE"));
}
finally
{
Conn.Notice -= action;
}
}
[Test, Description("Makes sure that concurrent use of the connection throws an exception")]
public void ConcurrentUse()
{
using (var cmd = new NpgsqlCommand("SELECT 1", Conn))
using (cmd.ExecuteReader())
Assert.That(() => ExecuteScalar("SELECT 1", Conn), Throws.Exception.TypeOf<InvalidOperationException>());
}
[Test]
public void NoContinuousProcessingWithSslStream()
{
using (var conn = new NpgsqlConnection(ConnectionString + ";UseSslStream=true;ContinuousProcessing=true"))
Assert.That(() => conn.Open(), Throws.Exception.TypeOf<ArgumentException>());
}
[Test]
[IssueLink("https://github.com/npgsql/npgsql/issues/783")]
public void PersistSecurityInfoIsOn()
{
var connString = new NpgsqlConnectionStringBuilder(ConnectionString) { PersistSecurityInfo = true };
using (var conn = new NpgsqlConnection(connString))
{
var passwd = new NpgsqlConnectionStringBuilder(conn.ConnectionString).Password;
Assert.That(passwd, Is.Not.Null);
conn.Open();
Assert.That(new NpgsqlConnectionStringBuilder(conn.ConnectionString).Password, Is.EqualTo(passwd));
}
}
[Test]
[IssueLink("https://github.com/npgsql/npgsql/issues/783")]
public void NoPasswordWithoutPersistSecurityInfo()
{
using (var conn = new NpgsqlConnection(ConnectionString))
{
var csb = new NpgsqlConnectionStringBuilder(conn.ConnectionString);
Assert.That(csb.PersistSecurityInfo, Is.False);
Assert.That(csb.Password, Is.Not.Null);
conn.Open();
Assert.That(new NpgsqlConnectionStringBuilder(conn.ConnectionString).Password, Is.Null);
}
}
[Test]
[IssueLink("https://github.com/npgsql/npgsql/issues/743")]
[IssueLink("https://github.com/npgsql/npgsql/issues/783")]
public void Clone()
{
var connString = new NpgsqlConnectionStringBuilder(ConnectionString) { Pooling = false };
using (var conn = new NpgsqlConnection(connString))
{
ProvideClientCertificatesCallback callback1 = certificates => { };
conn.ProvideClientCertificatesCallback = callback1;
RemoteCertificateValidationCallback callback2 = (sender, certificate, chain, errors) => true;
conn.UserCertificateValidationCallback = callback2;
conn.Open();
using (var conn2 = (NpgsqlConnection) ((ICloneable) conn).Clone())
{
Assert.That(conn2.ConnectionString, Is.EqualTo(conn.ConnectionString));
Assert.That(conn2.ProvideClientCertificatesCallback, Is.SameAs(callback1));
Assert.That(conn2.UserCertificateValidationCallback, Is.SameAs(callback2));
conn2.Open();
}
}
}
[Test, IssueLink("https://github.com/npgsql/npgsql/issues/824")]
public void ReloadTypes()
{
using (var conn = new NpgsqlConnection(ConnectionString))
{
conn.Open();
Assert.That(ExecuteScalar("SELECT EXISTS (SELECT * FROM pg_type WHERE typname='reload_types_enum')"), Is.False);
ExecuteNonQuery("CREATE TYPE pg_temp.reload_types_enum AS ENUM ('First', 'Second')");
conn.ReloadTypes();
conn.MapEnum<ReloadTypesEnum>("reload_types_enum");
}
}
enum ReloadTypesEnum { First, Second };
[Test]
[IssueLink("https://github.com/npgsql/npgsql/issues/736")]
public void ManyOpenClose()
{
// The connector's _sentRfqPrependedMessages is a byte, too many open/closes made it overflow
for (var i = 0; i < 255; i++)
{
using (var conn = new NpgsqlConnection(ConnectionString))
{
conn.Open();
}
}
using (var conn = new NpgsqlConnection(ConnectionString))
{
conn.Open();
}
using (var conn = new NpgsqlConnection(ConnectionString))
{
conn.Open();
Assert.That(ExecuteScalar("SELECT 1", conn), Is.EqualTo(1));
}
}
[Test]
[IssueLink("https://github.com/npgsql/npgsql/issues/736")]
public void ManyOpenCloseWithTransaction()
{
// The connector's _sentRfqPrependedMessages is a byte, too many open/closes made it overflow
for (var i = 0; i < 255; i++)
{
using (var conn = new NpgsqlConnection(ConnectionString))
{
conn.Open();
conn.BeginTransaction();
}
}
using (var conn = new NpgsqlConnection(ConnectionString))
{
conn.Open();
Assert.That(ExecuteScalar("SELECT 1", conn), Is.EqualTo(1));
}
}
[Test]
[IssueLink("https://github.com/npgsql/npgsql/issues/736")]
public void RollbackOnCloseThenOpenClose()
{
int processId;
using (var conn = new NpgsqlConnection(ConnectionString))
{
conn.Open();
processId = conn.Connector.BackendProcessId;
conn.BeginTransaction();
ExecuteNonQuery("SELECT 1", conn);
}
// This close prepended a rollback for the next time the connector is used
using (var conn = new NpgsqlConnection(ConnectionString))
{
conn.Open();
Assert.That(conn.Connector.BackendProcessId, Is.EqualTo(processId));
}
// Make sure the prepended rollback is maintained
using (var conn = new NpgsqlConnection(ConnectionString))
{
conn.Open();
Assert.That(conn.Connector.BackendProcessId, Is.EqualTo(processId));
Assert.That(ExecuteScalar("SELECT 1", conn), Is.EqualTo(1));
}
}
[Test, Description("Tests an exception happening when sending the Terminate message while closing a ready connector")]
[IssueLink("https://github.com/npgsql/npgsql/issues/777")]
public void ExceptionDuringClose()
{
var connString = new NpgsqlConnectionStringBuilder(ConnectionString) { Pooling = false };
using (var conn = new NpgsqlConnection(connString))
{
conn.Open();
var connectorId = conn.ProcessID;
// Use another connection to kill our connector
ExecuteNonQuery($"SELECT pg_terminate_backend({connectorId})");
conn.Close();
}
}
#region GetSchema
[Test]
public void GetSchema()
{
using (NpgsqlConnection c = new NpgsqlConnection())
{
DataTable metaDataCollections = c.GetSchema();
Assert.IsTrue(metaDataCollections.Rows.Count > 0, "There should be one or more metadatacollections returned. No connectionstring is required.");
}
}
[Test]
public void GetSchemaWithDbMetaDataCollectionNames()
{
DataTable metaDataCollections = Conn.GetSchema(System.Data.Common.DbMetaDataCollectionNames.MetaDataCollections);
Assert.IsTrue(metaDataCollections.Rows.Count > 0, "There should be one or more metadatacollections returned.");
foreach (DataRow row in metaDataCollections.Rows)
{
var collectionName = (string)row["CollectionName"];
//checking this collection
if (collectionName != System.Data.Common.DbMetaDataCollectionNames.MetaDataCollections)
{
var collection = Conn.GetSchema(collectionName);
Assert.IsNotNull(collection, "Each of the advertised metadata collections should work");
}
}
}
[Test]
public void GetSchemaWithRestrictions()
{
DataTable metaDataCollections = Conn.GetSchema(System.Data.Common.DbMetaDataCollectionNames.Restrictions);
Assert.IsTrue(metaDataCollections.Rows.Count > 0, "There should be one or more Restrictions returned.");
}
[Test]
public void GetSchemaWithReservedWords()
{
DataTable metaDataCollections = Conn.GetSchema(System.Data.Common.DbMetaDataCollectionNames.ReservedWords);
Assert.IsTrue(metaDataCollections.Rows.Count > 0, "There should be one or more ReservedWords returned.");
}
#endregion
}
}