-
Notifications
You must be signed in to change notification settings - Fork 45
Expand file tree
/
Copy pathtransaction_test.dart
More file actions
840 lines (716 loc) · 23.8 KB
/
Copy pathtransaction_test.dart
File metadata and controls
840 lines (716 loc) · 23.8 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
// ignore_for_file: unawaited_futures
import 'dart:async';
import 'package:postgres/postgres.dart';
import 'package:test/test.dart';
import 'docker.dart';
void main() {
withPostgresServer('Transaction behavior', (server) {
late Connection conn;
setUp(() async {
conn = await server.newConnection();
await conn.execute('CREATE TEMPORARY TABLE t (id INT UNIQUE)');
});
tearDown(() async {
await conn.close();
});
test('Rows are Lists of column values', () async {
await conn.execute('INSERT INTO t (id) VALUES (1)');
final outValue = await conn.runTx((ctx) async {
return await ctx.execute(
Sql.named('SELECT * FROM t WHERE id = @id:int4 LIMIT 1'),
parameters: {'id': 1},
);
});
expect(outValue, [
[1],
]);
});
test(
'Send successful transaction succeeds, returns returned value',
() async {
final outResult = await conn.runTx((c) async {
await c.execute('INSERT INTO t (id) VALUES (1)');
return await c.execute('SELECT id FROM t');
});
expect(outResult, [
[1],
]);
final result = await conn.execute('SELECT id FROM t');
expect(result, [
[1],
]);
},
);
test('Connection query during transaction will throw exception.', () async {
try {
await conn.runTx((ctx) async {
await conn.execute('SELECT 1');
await ctx.execute('INSERT INTO t (id) VALUES (1)');
});
fail('unreachable');
} on PgException catch (e) {
expect(e.message, contains('runTx'));
// ignore
}
expect(await conn.execute('SELECT * from t'), hasLength(0));
});
test(
'Make sure two simultaneous transactions cannot be interwoven',
() async {
final orderEnsurer = [];
final firstTransactionFuture = conn.runTx((c) async {
orderEnsurer.add(11);
await c.execute('INSERT INTO t (id) VALUES (1)');
orderEnsurer.add(12);
final result = await c.execute('SELECT id FROM t');
orderEnsurer.add(13);
return result;
});
final secondTransactionFuture = conn.runTx((c) async {
orderEnsurer.add(21);
await c.execute('INSERT INTO t (id) VALUES (2)');
orderEnsurer.add(22);
final result = await c.execute('SELECT id FROM t');
orderEnsurer.add(23);
return result;
});
final firstResults = await firstTransactionFuture;
final secondResults = await secondTransactionFuture;
expect(orderEnsurer, [11, 12, 13, 21, 22, 23]);
expect(firstResults, [
[1],
]);
expect(secondResults, [
[1],
[2],
]);
},
);
test('May intentionally rollback transaction', () async {
final rollback = Exception();
await expectLater(
conn.runTx((c) async {
await c.execute('INSERT INTO t (id) VALUES (1)');
throw rollback;
}),
throwsA(rollback),
);
final result = await conn.execute('SELECT id FROM t');
expect(result, []);
});
test('A transaction does not preempt pending queries', () async {
// Add a few insert queries but don't await, then do a transaction that does a fetch,
// make sure that transaction contains all of the elements.
// This makes use of the implementation detail that simple executes
// (no result rows, no parameters) are locking the connection directly.
conn.execute('INSERT INTO t (id) VALUES (1)', ignoreRows: true);
conn.execute('INSERT INTO t (id) VALUES (2)', ignoreRows: true);
conn.execute('INSERT INTO t (id) VALUES (3)', ignoreRows: true);
final results = await conn.runTx((ctx) async {
return await ctx.execute('SELECT id FROM t');
});
expect(results, [
[1],
[2],
[3],
]);
});
test("A transaction doesn't have to await on simple queries", () async {
conn.runTx((ctx) async {
ctx.execute(
'INSERT INTO t (id) VALUES (1)',
queryMode: QueryMode.simple,
);
ctx.execute(
'INSERT INTO t (id) VALUES (2)',
queryMode: QueryMode.simple,
);
ctx.execute(
'INSERT INTO t (id) VALUES (3)',
queryMode: QueryMode.simple,
);
});
final total = await conn.execute('SELECT id FROM t');
expect(total, [
[1],
[2],
[3],
]);
});
test('A transaction has to await extended queries', () async {
await conn.runTx((session) async {
expect(
session.execute('select 1;'),
throwsA(
isA<PgException>().having(
(e) => e.message,
'message',
contains('did you forget to await a statement?'),
),
),
);
});
});
test(
"A transaction doesn't have to await on simple queries, when the last query fails, it still emits an error from the transaction",
() async {
dynamic transactionError;
final rs = await conn.execute('SELECT 1');
await conn
.runTx<void>((ctx) async {
ctx.execute(
'INSERT INTO t (id) VALUES (1)',
queryMode: QueryMode.simple,
);
ctx.execute(
'INSERT INTO t (id) VALUES (2)',
queryMode: QueryMode.simple,
);
ctx
.execute(
"INSERT INTO t (id) VALUES ('foo')",
queryMode: QueryMode.simple,
)
.catchError((e) => rs);
})
.catchError((e) => transactionError = e);
expect(transactionError, isNotNull);
final total = await conn.execute('SELECT id FROM t');
expect(total, []);
},
);
test(
"A transaction doesn't have to await on simple queries, when the non-last query fails, it still emits an error from the transaction",
() async {
dynamic failingQueryError;
dynamic pendingQueryError;
dynamic transactionError;
final rs = await conn.execute('SELECT 1');
await conn
.runTx<void>((ctx) async {
ctx.execute(
'INSERT INTO t (id) VALUES (1)',
queryMode: QueryMode.simple,
);
ctx
.execute(
"INSERT INTO t (id) VALUES ('foo')",
queryMode: QueryMode.simple,
)
.catchError((e) {
failingQueryError = e;
return rs;
});
ctx
.execute(
'INSERT INTO t (id) VALUES (2)',
queryMode: QueryMode.simple,
)
.catchError((e) {
pendingQueryError = e;
return rs;
});
})
.catchError((e) => transactionError = e);
expect(transactionError, isNotNull);
expect(failingQueryError.toString(), contains('invalid input'));
expect(
pendingQueryError.toString(),
contains('current transaction is aborted'),
);
final total = await conn.execute('SELECT id FROM t');
expect(total, []);
},
);
test(
'A transaction with a rollback and non-await queries rolls back transaction',
() async {
final rs = await conn.execute('select 1');
final rollback = Exception();
final errs = [];
await expectLater(
conn.runTx((ctx) async {
Result errsAdd(e) {
errs.add(e);
return rs;
}
ctx.execute('INSERT INTO t (id) VALUES (1)').catchError(errsAdd);
ctx.execute('INSERT INTO t (id) VALUES (2)').catchError(errsAdd);
throw rollback;
}),
throwsA(rollback),
);
final total = await conn.execute('SELECT id FROM t');
expect(total, []);
expect(errs.length, 2);
},
);
test(
'A transaction that mixes awaiting and non-awaiting queries fails gracefully when an awaited query fails',
() async {
final rs = await conn.execute('select 1');
dynamic transactionError;
await conn
.runTx<void>((ctx) async {
unawaited(
ctx.execute(
'INSERT INTO t (id) VALUES (1)',
queryMode: QueryMode.simple,
),
);
try {
await ctx.execute("INSERT INTO t (id) VALUES ('foo')");
} on PgException {
// expected
}
unawaited(
ctx
.execute(
'INSERT INTO t (id) VALUES (2)',
queryMode: QueryMode.simple,
)
.catchError((_) => rs),
);
})
.catchError((e) => transactionError = e);
expect(transactionError, isNotNull);
final total = await conn.execute('SELECT id FROM t');
expect(total, []);
},
);
test(
'A transaction that mixes awaiting and non-awaiting queries fails gracefully when an unawaited query fails',
() async {
dynamic transactionError;
final rs = conn.execute('SELECT 1');
await conn
.runTx<void>((ctx) async {
await ctx.execute('INSERT INTO t (id) VALUES (1)');
ctx
.execute(
"INSERT INTO t (id) VALUES ('foo')",
queryMode: QueryMode.simple,
)
.catchError((_) => rs);
try {
await ctx.execute('INSERT INTO t (id) VALUES (2)');
} on PgException {
// expected
}
})
.catchError((e) => transactionError = e);
expect(transactionError, isNotNull);
final total = await conn.execute('SELECT id FROM t');
expect(total, []);
},
);
test('isOpen and closed', () async {
late Session leakedTransaction;
var afterTransaction = false;
await conn.runTx(
expectAsync1((session) async {
leakedTransaction = session;
expect(session.isOpen, isTrue);
// .closed should complete before the runTx future
expectLater(
session.closed.then((_) => afterTransaction),
completion(isFalse),
);
}),
);
afterTransaction = true;
expect(leakedTransaction.isOpen, isFalse);
});
});
// A transaction can fail for three reasons: query error, exception in code, or a rollback.
// After a transaction fails, the changes must be rolled back, it should continue with pending queries, pending transactions, later queries, later transactions
withPostgresServer('Transaction:Query recovery', (server) {
late Connection conn;
setUp(() async {
conn = await server.newConnection();
await conn.execute('CREATE TEMPORARY TABLE t (id INT UNIQUE)');
});
tearDown(() async {
await conn.close();
});
test('Is rolled back/executes later query', () async {
try {
await conn.runTx((c) async {
await c.execute('INSERT INTO t (id) VALUES (1)');
final oneRow = await c.execute('SELECT id FROM t');
expect(oneRow, [
[1],
]);
// This will error
await c.execute('INSERT INTO t (id) VALUES (1)');
});
fail('Should have thrown an exception');
} on PgException catch (e) {
expect(e.message, contains('unique constraint'));
}
final noRows = await conn.execute('SELECT id FROM t');
expect(noRows, []);
});
test('Executes pending query', () async {
final orderEnsurer = [];
conn
.runTx((c) async {
orderEnsurer.add(1);
await c.execute('INSERT INTO t (id) VALUES (1)');
orderEnsurer.add(2);
// This will error
await c.execute('INSERT INTO t (id) VALUES (1)');
})
.catchError((e) => null);
orderEnsurer.add(11);
final result = await conn.execute('SELECT id FROM t');
orderEnsurer.add(12);
expect(orderEnsurer, [11, 1, 2, 12]);
expect(result, []);
});
test('Executes pending transaction', () async {
final orderEnsurer = [];
conn
.runTx((c) async {
orderEnsurer.add(1);
await c.execute('INSERT INTO t (id) VALUES (1)');
orderEnsurer.add(2);
// This will error
await c.execute('INSERT INTO t (id) VALUES (1)');
})
.catchError((e) => null);
final result = await conn.runTx((ctx) async {
orderEnsurer.add(11);
return await ctx.execute('SELECT id FROM t');
});
orderEnsurer.add(12);
expect(orderEnsurer, [1, 2, 11, 12]);
expect(result, []);
});
test('Executes later transaction', () async {
try {
await conn.runTx((c) async {
await c.execute('INSERT INTO t (id) VALUES (1)');
final oneRow = await c.execute('SELECT id FROM t');
expect(oneRow, [
[1],
]);
// This will error
await c.execute('INSERT INTO t (id) VALUES (1)');
});
expect(true, false);
} on PgException {
// ignore
}
final result = await conn.runTx((ctx) async {
return await ctx.execute('SELECT id FROM t');
});
expect(result, []);
});
});
withPostgresServer('Transaction:Exception recovery', (server) {
late Connection conn;
setUp(() async {
conn = await server.newConnection();
await conn.execute('CREATE TEMPORARY TABLE t (id INT UNIQUE)');
});
tearDown(() async {
await conn.close();
});
test('Is rolled back/executes later query', () async {
final exception = Exception('rollback');
await expectLater(
conn.runTx((c) async {
await c.execute('INSERT INTO t (id) VALUES (1)');
throw exception;
}),
throwsA(exception),
);
final noRows = await conn.execute('SELECT id FROM t');
expect(noRows, []);
});
test('Executes pending query', () async {
final orderEnsurer = [];
conn
.runTx<void>((c) async {
orderEnsurer.add(1);
await c.execute('INSERT INTO t (id) VALUES (1)');
orderEnsurer.add(2);
throw Exception('foo');
})
.catchError((e) => null);
orderEnsurer.add(11);
final result = await conn.execute('SELECT id FROM t');
orderEnsurer.add(12);
expect(orderEnsurer, [11, 1, 2, 12]);
expect(result, []);
});
test('Executes pending transaction', () async {
final orderEnsurer = [];
conn
.runTx<void>((c) async {
orderEnsurer.add(1);
await c.execute('INSERT INTO t (id) VALUES (1)');
orderEnsurer.add(2);
throw Exception('foo');
})
.catchError((e) => null);
final result = await conn.runTx((ctx) async {
orderEnsurer.add(11);
return await ctx.execute('SELECT id FROM t');
});
orderEnsurer.add(12);
expect(orderEnsurer, [1, 2, 11, 12]);
expect(result, []);
});
test('Executes later transaction', () async {
await expectLater(
conn.runTx((c) async {
await c.execute('INSERT INTO t (id) VALUES (1)');
throw Exception('foo');
}),
throwsA(isException),
);
final result = await conn.runTx((ctx) async {
return await ctx.execute('SELECT id FROM t');
});
expect(result, []);
});
test("Caught Dart errors don't roll back transactions", () async {
await conn.runTx((c) async {
await c.execute('INSERT INTO t (id) VALUES (1)');
// The mismatched type is caught in Dart, but unawaited here
expect(
c.execute(
Sql.named('INSERT INTO t (id) VALUES (@id:int4)'),
parameters: {'id': 'foobar'},
),
throwsA(isA<FormatException>()),
);
await c.execute('INSERT INTO t (id) VALUES (2)');
});
final rows = await conn.execute('SELECT id FROM t');
expect(rows, [
[1],
[2],
]);
});
test('Async query failure prevents closure from continuing', () async {
var reached = false;
try {
await conn.runTx((c) async {
await c.execute('INSERT INTO t (id) VALUES (1)');
await c.execute("INSERT INTO t (id) VALUE ('foo') RETURNING id");
reached = true;
await c.execute('INSERT INTO t (id) VALUES (2)');
});
fail('unreachable');
} on PgException {
// ignore
}
expect(reached, false);
final res = await conn.execute('SELECT * FROM t');
expect(res, []);
});
test(
'When exception thrown in unawaited on future, transaction is rolled back',
() async {
try {
final rs = conn.execute('SELECT 1');
await conn.runTx((c) async {
await c.execute('INSERT INTO t (id) VALUES (1)');
c
.execute(
"INSERT INTO t (id) VALUE ('foo') RETURNING id",
queryMode: QueryMode.simple,
)
.catchError((_) => rs);
await c.execute('INSERT INTO t (id) VALUES (2)');
});
fail('unreachable');
} on PgException {
// ignore
}
final res = await conn.execute('SELECT * FROM t');
expect(res, []);
},
);
});
withPostgresServer('Transaction:Rollback recovery', (server) {
late Connection conn;
setUp(() async {
conn = await server.newConnection();
await conn.execute('CREATE TEMPORARY TABLE t (id INT UNIQUE)');
});
tearDown(() async {
await conn.close();
});
test('Is rolled back/executes later query after exception', () async {
expect(
conn.runTx((c) async {
await c.execute('INSERT INTO t (id) VALUES (1)');
throw Exception();
}),
throwsA(isException),
);
final noRows = await conn.execute('SELECT id FROM t');
expect(noRows, []);
});
test(
'Is rolled back/executes later query after calling `rollback()`.',
() async {
final rs = await conn.runTx((c) async {
await c.execute('INSERT INTO t (id) VALUES (1)');
final stm = await c.prepare('SELECT 1');
expect(await stm.run([]), hasLength(1));
await c.rollback();
await expectLater(() => c.execute('SELECT 1'), throwsException);
await expectLater(() => stm.run([]), throwsException);
return 123;
});
expect(rs, 123);
final noRows = await conn.execute('SELECT id FROM t');
expect(noRows, []);
},
);
test('Executes pending query', () async {
final orderEnsurer = [];
conn
.runTx<void>((c) async {
orderEnsurer.add(1);
await c.execute('INSERT INTO t (id) VALUES (1)');
orderEnsurer.add(2);
throw Exception();
})
.catchError((_) => {});
orderEnsurer.add(11);
final result = await conn.execute('SELECT id FROM t');
orderEnsurer.add(12);
expect(orderEnsurer, [11, 1, 2, 12]);
expect(result, []);
});
test('Executes pending transaction', () async {
final orderEnsurer = [];
expect(
conn.runTx((c) async {
orderEnsurer.add(1);
await c.execute('INSERT INTO t (id) VALUES (1)');
orderEnsurer.add(2);
throw Exception();
}),
throwsA(isException),
);
final result = await conn.runTx((ctx) async {
orderEnsurer.add(11);
return await ctx.execute('SELECT id FROM t');
});
orderEnsurer.add(12);
expect(orderEnsurer, [1, 2, 11, 12]);
expect(result, []);
});
test('Executes later transaction', () async {
await expectLater(
conn.runTx((c) async {
await c.execute('INSERT INTO t (id) VALUES (1)');
throw Exception();
}),
throwsA(isException),
);
final result = await conn.runTx((ctx) async {
return await ctx.execute('SELECT id FROM t');
});
expect(result, []);
});
test('can start transactions manually', () async {
await conn.execute('BEGIN');
await conn.execute(
Sql.named('INSERT INTO t VALUES (@a:int4)'),
parameters: {'a': 123},
);
await conn.execute('ROLLBACK');
await expectLater(conn.execute('SELECT * FROM t'), completion(isEmpty));
});
});
withPostgresServer('exception inside transaction', (server) {
late Connection conn;
setUp(() async {
conn = await server.newConnection();
await conn.execute('CREATE TEMPORARY TABLE t (id INT UNIQUE)');
});
tearDown(() async {
await conn.close();
});
test('exception thrown in transaction is propagated out', () async {
final expectedException = Exception('my custom exception');
dynamic actualException;
dynamic thrownException;
await conn
.runTx((session) async {
await session.execute('INSERT INTO t (id) VALUES (1)');
try {
await session.execute('INSERT INTO t (id) VALUES (1)');
} on PgException catch (e) {
thrownException = e;
throw expectedException;
}
})
.catchError((error) {
actualException = error;
});
expect(actualException, expectedException);
// testing the same exception without the try-catch block inside the transaction:
dynamic uncaughtException;
await conn
.runTx((session) async {
await session.execute('INSERT INTO t (id) VALUES (1)');
await session.execute('INSERT INTO t (id) VALUES (1)');
})
.catchError((error) {
uncaughtException = error;
});
expect(uncaughtException.toString(), thrownException.toString());
});
// TODO: decide if this is the desired outcome.
test('exception caught in transaction is propagated out', () async {
await expectLater(
() => conn.runTx((c) async {
await c.execute('INSERT INTO t (id) VALUES (1)');
try {
await c.execute('INSERT INTO t (id) VALUES (1)');
} catch (_) {
// ignore
}
}),
throwsA(isA<UniqueViolationException>()),
);
});
test(
'prepared statement created outside transaction can be used inside it',
() async {
await conn.execute('INSERT INTO t (id) VALUES (1), (2), (3)');
// Prepare outside the transaction.
final stmt = await conn.prepare(
Sql(r'SELECT id FROM t WHERE id = $1', types: [Type.integer]),
);
try {
final result = await conn.runTx((tx) async {
// Use the pre-prepared statement inside the transaction.
// Before the fix this would hang indefinitely because stmt tried to
// acquire the connection's _operationLock, which runTx already holds.
return await stmt.run([2]);
});
expect(result, [
[2],
]);
// Statement still works after the transaction.
final afterTx = await stmt.run([3]);
expect(afterTx, [
[3],
]);
} finally {
await stmt.dispose();
}
},
);
});
}