forked from npgsql/npgsql
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathSystemTransactionTests.cs
More file actions
500 lines (437 loc) · 18.9 KB
/
SystemTransactionTests.cs
File metadata and controls
500 lines (437 loc) · 18.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
using System;
using System.Data;
using System.Threading;
using System.Transactions;
using NUnit.Framework;
using static Npgsql.Tests.TestUtil;
namespace Npgsql.Tests;
// This test suite contains ambient transaction tests, except those involving distributed transactions which are only
// supported on .NET Framework / Windows. Distributed transaction tests are in DistributedTransactionTests.
public class SystemTransactionTests : TestBase
{
[Test, Description("Single connection enlisting explicitly, committing")]
public void Explicit_enlist()
{
var dataSource = EnlistOffDataSource;
var tableName = CreateTempTable(dataSource, "name TEXT");
using var conn = dataSource.OpenConnection();
using (var scope = new TransactionScope())
{
conn.EnlistTransaction(Transaction.Current);
Assert.That(conn.ExecuteNonQuery(@$"INSERT INTO {tableName} (name) VALUES ('test')"), Is.EqualTo(1), "Unexpected insert rowcount");
AssertNoDistributedIdentifier();
AssertNoPreparedTransactions();
scope.Complete();
}
AssertNoDistributedIdentifier();
AssertNoPreparedTransactions();
using (var tx = conn.BeginTransaction())
{
Assert.That(conn.ExecuteScalar(@$"SELECT COUNT(*) FROM {tableName}"), Is.EqualTo(1), "Unexpected data count");
tx.Rollback();
}
}
[Test, Description("Single connection enlisting implicitly, committing")]
public void Implicit_enlist()
{
var dataSource = EnlistOnDataSource;
var tableName = CreateTempTable(dataSource, "name TEXT");
using var conn = dataSource.CreateConnection();
using (var scope = new TransactionScope())
{
conn.Open();
Assert.That(conn.ExecuteNonQuery(@$"INSERT INTO {tableName} (name) VALUES ('test')"), Is.EqualTo(1), "Unexpected insert rowcount");
AssertNoDistributedIdentifier();
AssertNoPreparedTransactions();
scope.Complete();
}
using (var tx = conn.BeginTransaction())
{
Assert.That(conn.ExecuteScalar(@$"SELECT COUNT(*) FROM {tableName}"), Is.EqualTo(1), "Unexpected data count");
tx.Rollback();
}
}
[Test]
public void Enlist_Off()
{
var dataSource = EnlistOffDataSource;
var tableName = CreateTempTable(dataSource, "name TEXT");
using (new TransactionScope())
using (var conn1 = dataSource.OpenConnection())
using (var conn2 = dataSource.OpenConnection())
{
Assert.That(conn1.EnlistedTransaction, Is.Null);
Assert.That(conn1.ExecuteNonQuery(@$"INSERT INTO {tableName} (name) VALUES ('test')"), Is.EqualTo(1), "Unexpected insert rowcount");
Assert.That(conn2.ExecuteScalar($"SELECT COUNT(*) FROM {tableName}"), Is.EqualTo(1), "Unexpected data count");
}
// Scope disposed and not completed => rollback, but no enlistment, so changes should still be there.
using (var conn3 = dataSource.OpenConnection())
{
Assert.That(conn3.ExecuteScalar($"SELECT COUNT(*) FROM {tableName}"), Is.EqualTo(1), "Insert unexpectedly rollback-ed");
}
}
[Test, Description("Single connection enlisting explicitly, rollback")]
public void Rollback_explicit_enlist()
{
using var dataSource = CreateDataSource();
var tableName = CreateTempTable(dataSource, "name TEXT");
using var conn = dataSource.OpenConnection();
using (new TransactionScope())
{
conn.EnlistTransaction(Transaction.Current);
Assert.That(conn.ExecuteNonQuery(@$"INSERT INTO {tableName} (name) VALUES ('test')"), Is.EqualTo(1), "Unexpected insert rowcount");
// No commit
}
AssertNoDistributedIdentifier();
AssertNoPreparedTransactions();
using (var tx = conn.BeginTransaction())
{
Assert.That(conn.ExecuteScalar(@$"SELECT COUNT(*) FROM {tableName}"), Is.EqualTo(0), "Unexpected data count");
tx.Rollback();
}
}
[Test, Description("Single connection enlisting implicitly, rollback")]
[IssueLink("https://github.com/npgsql/npgsql/issues/2408")]
public void Rollback_implicit_enlist([Values(true, false)] bool pooling)
{
using var dataSource = CreateDataSource(csb => csb.Pooling = pooling);
var tableName = CreateTempTable(dataSource, "name TEXT");
using (new TransactionScope())
using (var conn = dataSource.OpenConnection())
{
Assert.That(conn.ExecuteNonQuery(@$"INSERT INTO {tableName} (name) VALUES ('test')"), Is.EqualTo(1), "Unexpected insert rowcount");
AssertNoDistributedIdentifier();
AssertNoPreparedTransactions();
// No commit
}
AssertNumberOfRows(0, tableName);
}
[Test]
public void Two_consecutive_connections()
{
var dataSource = EnlistOnDataSource;
var tableName = CreateTempTable(dataSource, "name TEXT");
using (var scope = new TransactionScope())
{
using (var conn1 = dataSource.OpenConnection())
{
Assert.That(conn1.ExecuteNonQuery(@$"INSERT INTO {tableName} (name) VALUES ('test1')"), Is.EqualTo(1), "Unexpected first insert rowcount");
}
using (var conn2 = dataSource.OpenConnection())
{
Assert.That(conn2.ExecuteNonQuery(@$"INSERT INTO {tableName} (name) VALUES ('test2')"), Is.EqualTo(1), "Unexpected second insert rowcount");
}
// Consecutive connections used in same scope should not promote the transaction to distributed.
AssertNoDistributedIdentifier();
AssertNoPreparedTransactions();
scope.Complete();
}
AssertNumberOfRows(2, tableName);
}
[Test]
public void Close_connection()
{
// We assert the number of idle connections below
using var dataSource = CreateDataSource(csb => csb.Enlist = true);
var tableName = CreateTempTable(dataSource, "name TEXT");
using (var scope = new TransactionScope())
using (var conn = dataSource.OpenConnection())
{
Assert.That(conn.ExecuteNonQuery(@$"INSERT INTO {tableName} (name) VALUES ('test')"), Is.EqualTo(1), "Unexpected insert rowcount");
conn.Close();
AssertNoDistributedIdentifier();
AssertNoPreparedTransactions();
scope.Complete();
}
AssertNumberOfRows(1, tableName);
Assert.That(dataSource.Statistics.Idle, Is.EqualTo(1));
}
[Test]
public void Enlist_to_two_transactions()
{
var dataSource = EnlistOffDataSource;
var tableName = CreateTempTable(dataSource, "name TEXT");
using var conn = dataSource.OpenConnection();
var ctx = new CommittableTransaction();
conn.EnlistTransaction(ctx);
Assert.That(() => conn.EnlistTransaction(new CommittableTransaction()), Throws.Exception.TypeOf<InvalidOperationException>());
ctx.Rollback();
using var tx = conn.BeginTransaction();
Assert.That(conn.ExecuteScalar(@$"SELECT COUNT(*) FROM {tableName}"), Is.EqualTo(0));
tx.Rollback();
}
[Test]
public void Enlist_twice_to_same_transaction()
{
var dataSource = EnlistOffDataSource;
var tableName = CreateTempTable(dataSource, "name TEXT");
using var conn = dataSource.OpenConnection();
var ctx = new CommittableTransaction();
conn.EnlistTransaction(ctx);
conn.EnlistTransaction(ctx);
ctx.Rollback();
using var tx = conn.BeginTransaction();
Assert.That(conn.ExecuteScalar(@$"SELECT COUNT(*) FROM {tableName}"), Is.EqualTo(0));
tx.Rollback();
}
[Test]
public void Scope_after_scope()
{
var dataSource = EnlistOffDataSource;
var tableName = CreateTempTable(dataSource, "name TEXT");
using var conn = dataSource.OpenConnection();
using (new TransactionScope())
conn.EnlistTransaction(Transaction.Current);
using (new TransactionScope())
conn.EnlistTransaction(Transaction.Current);
using (var tx = conn.BeginTransaction())
{
Assert.That(conn.ExecuteScalar(@$"SELECT COUNT(*) FROM {tableName}"), Is.EqualTo(0));
tx.Rollback();
}
}
[Test]
public void Reuse_connection()
{
// We check the ProcessID below
using var dataSource = CreateDataSource(csb => csb.Enlist = true);
var tableName = CreateTempTable(dataSource, "name TEXT");
using (var scope = new TransactionScope())
using (var conn = dataSource.CreateConnection())
{
conn.Open();
var processId = conn.ProcessID;
conn.ExecuteNonQuery(@$"INSERT INTO {tableName} (name) VALUES ('test1')");
conn.Close();
conn.Open();
Assert.That(conn.ProcessID, Is.EqualTo(processId));
conn.ExecuteNonQuery(@$"INSERT INTO {tableName} (name) VALUES ('test2')");
conn.Close();
scope.Complete();
}
AssertNumberOfRows(2, tableName);
}
[Test]
public void Reuse_connection_rollback()
{
// We check the ProcessID below
using var dataSource = CreateDataSource(csb => csb.Enlist = true);
var tableName = CreateTempTable(dataSource, "name TEXT");
using (new TransactionScope())
using (var conn = dataSource.CreateConnection())
{
conn.Open();
var processId = conn.ProcessID;
conn.ExecuteNonQuery(@$"INSERT INTO {tableName} (name) VALUES ('test1')");
conn.Close();
conn.Open();
Assert.That(conn.ProcessID, Is.EqualTo(processId));
conn.ExecuteNonQuery(@$"INSERT INTO {tableName} (name) VALUES ('test2')");
conn.Close();
// No commit
}
AssertNumberOfRows(0, tableName);
}
[Test, IssueLink("https://github.com/npgsql/npgsql/issues/3735")]
public void Reuse_connection_resets_temp_tables()
{
// When a connection is closed inside a TransactionScope and then reopened,
// temp tables should be discarded.
using var dataSource = CreateDataSource(csb => csb.Enlist = true);
using (new TransactionScope())
using (var conn = dataSource.CreateConnection())
{
conn.Open();
var processId = conn.ProcessID;
// Create a temp table
conn.ExecuteNonQuery("CREATE TEMP TABLE temp_test (id INT)");
conn.Close();
// Reopen - should get the same physical connection but with reset state
conn.Open();
Assert.That(conn.ProcessID, Is.EqualTo(processId), "Should reuse the same physical connection");
// The temp table should have been discarded
Assert.That(() => conn.ExecuteScalar("SELECT COUNT(*) FROM temp_test"),
Throws.Exception.TypeOf<PostgresException>()
.With.Property(nameof(PostgresException.SqlState)).EqualTo(PostgresErrorCodes.UndefinedTable));
}
}
[Test, Ignore("Timeout doesn't seem to fire on .NET Core / Linux")]
public void Timeout_triggers_rollback_while_busy()
{
var dataSource = EnlistOffDataSource;
var tableName = CreateTempTable(dataSource, "name TEXT");
using (var conn = dataSource.OpenConnection())
{
using (new TransactionScope(TransactionScopeOption.Required, TimeSpan.FromSeconds(1)))
{
conn.EnlistTransaction(Transaction.Current);
Assert.That(() => CreateSleepCommand(conn, 5).ExecuteNonQuery(),
Throws.Exception.TypeOf<PostgresException>()
.With.Property(nameof(PostgresException.SqlState))
.EqualTo(PostgresErrorCodes.QueryCanceled));
}
}
AssertNumberOfRows(0, tableName);
}
[Test, IssueLink("https://github.com/npgsql/npgsql/issues/1579")]
public void Schema_connection_should_not_enlist()
{
var dataSource = EnlistOnDataSource;
var tableName = CreateTempTable(dataSource, "name TEXT");
using var tran = new TransactionScope();
using var conn = dataSource.OpenConnection();
using var cmd = new NpgsqlCommand($"SELECT * FROM {tableName}", conn);
using var reader = cmd.ExecuteReader(CommandBehavior.KeyInfo);
reader.GetColumnSchema();
AssertNoDistributedIdentifier();
AssertNoPreparedTransactions();
tran.Complete();
}
[Test, IssueLink("https://github.com/npgsql/npgsql/issues/1737")]
public void Single_unpooled_connection()
{
using var dataSource = CreateDataSource(csb =>
{
csb.Pooling = false;
csb.Enlist = true;
});
using var scope = new TransactionScope();
using (var conn = dataSource.OpenConnection())
using (var cmd = new NpgsqlCommand("SELECT 1", conn))
cmd.ExecuteNonQuery();
scope.Complete();
}
[Test]
[IssueLink("https://github.com/npgsql/npgsql/issues/4963"), IssueLink("https://github.com/npgsql/npgsql/issues/5783")]
public void Single_closed_connection_in_transaction_scope([Values] bool pooling, [Values] bool multipleHosts)
{
using var dataSource = CreateDataSource(csb =>
{
csb.Pooling = pooling;
csb.Enlist = true;
csb.Host = multipleHosts ? "localhost,127.0.0.1" : csb.Host;
});
using (var scope = new TransactionScope())
using (var conn = dataSource.OpenConnection())
using (var cmd = new NpgsqlCommand("SELECT 1", conn))
{
cmd.ExecuteNonQuery();
conn.Close();
Assert.That(pooling ? dataSource.Statistics.Busy : dataSource.Statistics.Total, Is.EqualTo(1));
scope.Complete();
}
Assert.That(pooling ? dataSource.Statistics.Busy : dataSource.Statistics.Total, Is.EqualTo(0));
}
[Test]
[IssueLink("https://github.com/npgsql/npgsql/issues/3863")]
public void Break_connector_while_in_transaction_scope_with_rollback([Values] bool pooling)
{
using var dataSource = CreateDataSource(csb => csb.Pooling = pooling);
using var scope = new TransactionScope();
var conn = dataSource.OpenConnection();
conn.ExecuteNonQuery("SELECT 1");
conn.Connector!.Break(new Exception(nameof(Break_connector_while_in_transaction_scope_with_rollback)));
}
[Test]
[IssueLink("https://github.com/npgsql/npgsql/issues/3863")]
public void Break_connector_while_in_transaction_scope_with_commit([Values] bool pooling)
{
using var dataSource = CreateDataSource(csb => csb.Pooling = pooling);
var ex = Assert.Throws<TransactionInDoubtException>(() =>
{
using var scope = new TransactionScope();
var conn = dataSource.OpenConnection();
conn.ExecuteNonQuery("SELECT 1");
conn.Connector!.Break(new Exception(nameof(Break_connector_while_in_transaction_scope_with_commit)));
scope.Complete();
})!;
Assert.That(ex.InnerException, Is.TypeOf<ObjectDisposedException>());
Assert.That(ex.InnerException!.InnerException, Is.TypeOf<Exception>());
Assert.That(ex.InnerException!.InnerException!.Message, Is.EqualTo(nameof(Break_connector_while_in_transaction_scope_with_commit)));
}
[Test]
[IssueLink("https://github.com/npgsql/npgsql/issues/4085")]
public void Open_connection_with_enlist_and_aborted_TransactionScope()
{
var dataSource = EnlistOnDataSource;
for (var i = 0; i < 2; i++)
{
using var outerScope = new TransactionScope();
try
{
using var innerScope = new TransactionScope();
throw new Exception("Random exception to abort the transaction scope");
}
catch (Exception)
{
}
var ex = Assert.Throws<TransactionException>(() => dataSource.OpenConnection())!;
Assert.That(ex.Message, Is.EqualTo("The operation is not valid for the state of the transaction."));
}
}
[Test, IssueLink("https://github.com/npgsql/npgsql/issues/1594")]
public void Bug1594()
{
var dataSource = EnlistOnDataSource;
var tableName = CreateTempTable(dataSource, "name TEXT");
using var outerScope = new TransactionScope();
using (var conn = dataSource.OpenConnection())
using (var innerScope1 = new TransactionScope())
{
conn.ExecuteNonQuery(@$"INSERT INTO {tableName} (name) VALUES ('test1')");
innerScope1.Complete();
}
using (dataSource.OpenConnection())
using (new TransactionScope())
{
// Don't complete, triggering rollback
}
}
#region Utilities
void AssertNoPreparedTransactions()
=> Assert.That(GetNumberOfPreparedTransactions(), Is.EqualTo(0), "Prepared transactions found");
int GetNumberOfPreparedTransactions()
{
var dataSource = EnlistOffDataSource;
using var conn = dataSource.OpenConnection();
using var cmd = new NpgsqlCommand("SELECT COUNT(*) FROM pg_prepared_xacts WHERE database = @database", conn);
cmd.Parameters.Add(new NpgsqlParameter("database", conn.Database));
return (int)(long)cmd.ExecuteScalar()!;
}
void AssertNumberOfRows(int expected, string tableName)
{
using var conn = OpenConnection();
Assert.That(conn.ExecuteScalar(@$"SELECT COUNT(*) FROM {tableName}"), Is.EqualTo(expected), "Unexpected data count");
}
static void AssertNoDistributedIdentifier()
=> Assert.That(Transaction.Current?.TransactionInformation.DistributedIdentifier ?? Guid.Empty, Is.EqualTo(Guid.Empty), "Distributed identifier found");
#endregion Utilities
#region Setup
NpgsqlDataSource EnlistOnDataSource { get; set; } = default!;
NpgsqlDataSource EnlistOffDataSource { get; set; } = default!;
[OneTimeSetUp]
public void OneTimeSetUp()
{
EnlistOnDataSource = CreateDataSource(csb => csb.Enlist = true);
EnlistOffDataSource = CreateDataSource(csb => csb.Enlist = false);
}
[OneTimeTearDown]
public void OnTimeTearDown()
{
EnlistOnDataSource?.Dispose();
EnlistOnDataSource = null!;
EnlistOffDataSource?.Dispose();
EnlistOffDataSource = null!;
}
internal static string CreateTempTable(NpgsqlDataSource dataSource, string columns)
{
var tableName = "temp_table" + Interlocked.Increment(ref _tempTableCounter);
dataSource.ExecuteNonQuery(@$"
START TRANSACTION; SELECT pg_advisory_xact_lock(0);
DROP TABLE IF EXISTS {tableName} CASCADE;
COMMIT;
CREATE TABLE {tableName} ({columns})");
return tableName;
}
#endregion
}