/
ITTransactionRetryTest.java
1588 lines (1529 loc) · 67.5 KB
/
ITTransactionRetryTest.java
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
/*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.spanner.connection.it;
import static com.google.cloud.spanner.testing.EmulatorSpannerHelper.isUsingEmulator;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assume.assumeFalse;
import com.google.cloud.Timestamp;
import com.google.cloud.spanner.AbortedDueToConcurrentModificationException;
import com.google.cloud.spanner.AbortedException;
import com.google.cloud.spanner.KeySet;
import com.google.cloud.spanner.Mutation;
import com.google.cloud.spanner.ParallelIntegrationTest;
import com.google.cloud.spanner.ResultSet;
import com.google.cloud.spanner.SpannerException;
import com.google.cloud.spanner.Statement;
import com.google.cloud.spanner.connection.ITAbstractSpannerTest;
import com.google.cloud.spanner.connection.TransactionRetryListener;
import java.sql.Connection;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.rules.TestName;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* This integration test tests the different scenarios for automatically retrying read/write
* transactions, both when possible and when the transaction must abort because of a concurrent
* update.
*/
@Category(ParallelIntegrationTest.class)
@RunWith(JUnit4.class)
public class ITTransactionRetryTest extends ITAbstractSpannerTest {
private static final Logger logger = Logger.getLogger(ITTransactionRetryTest.class.getName());
@Rule public TestName testName = new TestName();
@Override
protected void appendConnectionUri(StringBuilder uri) {
uri.append(";autocommit=false;retryAbortsInternally=true");
}
@Override
public boolean doCreateDefaultTestTable() {
return true;
}
/** Clear the test table before each test run */
@Before
public void clearTable() {
try (ITConnection connection = createConnection()) {
connection.bufferedWrite(Mutation.delete("TEST", KeySet.all()));
connection.commit();
}
}
@Before
public void clearStatistics() {
RETRY_STATISTICS.clear();
}
@Before
public void logStart() {
logger.fine(
"--------------------------------------------------------------\n"
+ testName.getMethodName()
+ " started");
}
@After
public void logFinished() {
logger.fine(
"--------------------------------------------------------------\n"
+ testName.getMethodName()
+ " finished");
}
/** Simple data structure to keep track of retry statistics */
private static class RetryStatistics {
private int totalRetryAttemptsStarted;
private int totalRetryAttemptsFinished;
private int totalSuccessfulRetries;
private int totalErroredRetries;
private int totalNestedAborts;
private int totalMaxAttemptsExceeded;
private int totalConcurrentModifications;
private void clear() {
totalRetryAttemptsStarted = 0;
totalRetryAttemptsFinished = 0;
totalSuccessfulRetries = 0;
totalErroredRetries = 0;
totalNestedAborts = 0;
totalMaxAttemptsExceeded = 0;
totalConcurrentModifications = 0;
}
}
/**
* Static to allow access from the {@link CountTransactionRetryListener}. Statistics are
* automatically cleared before each test case.
*/
public static final RetryStatistics RETRY_STATISTICS = new RetryStatistics();
/**
* Simple {@link TransactionRetryListener} that keeps track of the total count of the different
* transaction retry events of a {@link Connection}. Note that as {@link
* TransactionRetryListener}s are instantiated once per connection, the listener keeps track of
* the total statistics of a connection and not only of the last transaction.
*/
public static class CountTransactionRetryListener implements TransactionRetryListener {
@Override
public void retryStarting(Timestamp transactionStarted, long transactionId, int retryAttempt) {
RETRY_STATISTICS.totalRetryAttemptsStarted++;
}
@Override
public void retryFinished(
Timestamp transactionStarted, long transactionId, int retryAttempt, RetryResult result) {
RETRY_STATISTICS.totalRetryAttemptsFinished++;
switch (result) {
case RETRY_ABORTED_AND_MAX_ATTEMPTS_EXCEEDED:
RETRY_STATISTICS.totalMaxAttemptsExceeded++;
break;
case RETRY_ABORTED_AND_RESTARTING:
RETRY_STATISTICS.totalNestedAborts++;
break;
case RETRY_ABORTED_DUE_TO_CONCURRENT_MODIFICATION:
RETRY_STATISTICS.totalConcurrentModifications++;
break;
case RETRY_ERROR:
RETRY_STATISTICS.totalErroredRetries++;
break;
case RETRY_SUCCESSFUL:
RETRY_STATISTICS.totalSuccessfulRetries++;
break;
default:
break;
}
}
}
/** Test successful retry when the commit aborts */
@Test
public void testCommitAborted() {
AbortInterceptor interceptor = new AbortInterceptor(0);
try (ITConnection connection =
createConnection(interceptor, new CountTransactionRetryListener())) {
// verify that the there is no test record
try (ResultSet rs =
connection.executeQuery(Statement.of("SELECT COUNT(*) AS C FROM TEST WHERE ID=1"))) {
assertThat(rs.next(), is(true));
assertThat(rs.getLong("C"), is(equalTo(0L)));
assertThat(rs.next(), is(false));
}
// do an insert
connection.executeUpdate(
Statement.of("INSERT INTO TEST (ID, NAME) VALUES (1, 'test aborted')"));
// indicate that the next statement should abort
interceptor.setProbability(1.0);
interceptor.setOnlyInjectOnce(true);
// do a commit that will first abort, and then on retry will succeed
connection.commit();
assertThat(RETRY_STATISTICS.totalRetryAttemptsStarted >= 1, is(true));
assertThat(RETRY_STATISTICS.totalRetryAttemptsFinished >= 1, is(true));
assertThat(RETRY_STATISTICS.totalSuccessfulRetries >= 1, is(true));
assertThat(RETRY_STATISTICS.totalErroredRetries, is(equalTo(0)));
assertThat(RETRY_STATISTICS.totalConcurrentModifications, is(equalTo(0)));
assertThat(RETRY_STATISTICS.totalMaxAttemptsExceeded, is(equalTo(0)));
// verify that the insert succeeded
try (ResultSet rs =
connection.executeQuery(Statement.of("SELECT COUNT(*) AS C FROM TEST WHERE ID=1"))) {
assertThat(rs.next(), is(true));
assertThat(rs.getLong("C"), is(equalTo(1L)));
assertThat(rs.next(), is(false));
}
}
}
/** Test successful retry when an insert statement aborts */
@Test
public void testInsertAborted() {
AbortInterceptor interceptor = new AbortInterceptor(0);
try (ITConnection connection =
createConnection(interceptor, new CountTransactionRetryListener())) {
// verify that the there is no test record
try (ResultSet rs =
connection.executeQuery(Statement.of("SELECT COUNT(*) AS C FROM TEST WHERE ID=1"))) {
assertThat(rs.next(), is(true));
assertThat(rs.getLong("C"), is(equalTo(0L)));
assertThat(rs.next(), is(false));
}
// indicate that the next statement should abort
interceptor.setProbability(1.0);
interceptor.setOnlyInjectOnce(true);
// do an insert that will abort
connection.executeUpdate(
Statement.of("INSERT INTO TEST (ID, NAME) VALUES (1, 'test aborted')"));
// do a commit
connection.commit();
assertThat(RETRY_STATISTICS.totalSuccessfulRetries >= 1, is(true));
// verify that the insert succeeded
try (ResultSet rs =
connection.executeQuery(Statement.of("SELECT COUNT(*) AS C FROM TEST WHERE ID=1"))) {
assertThat(rs.next(), is(true));
assertThat(rs.getLong("C"), is(equalTo(1L)));
assertThat(rs.next(), is(false));
}
}
}
/** Test successful retry when an update statement aborts */
@Test
public void testUpdateAborted() {
AbortInterceptor interceptor = new AbortInterceptor(0);
try (ITConnection connection =
createConnection(interceptor, new CountTransactionRetryListener())) {
// verify that the there is no test record
try (ResultSet rs =
connection.executeQuery(Statement.of("SELECT COUNT(*) AS C FROM TEST WHERE ID=1"))) {
assertThat(rs.next(), is(true));
assertThat(rs.getLong("C"), is(equalTo(0L)));
assertThat(rs.next(), is(false));
}
// insert a test record
connection.executeUpdate(
Statement.of("INSERT INTO TEST (ID, NAME) VALUES (1, 'test aborted')"));
// indicate that the next statement should abort
interceptor.setProbability(1.0);
interceptor.setOnlyInjectOnce(true);
// do an update that will abort
connection.executeUpdate(Statement.of("UPDATE TEST SET NAME='update aborted' WHERE ID=1"));
// do a commit
connection.commit();
assertThat(RETRY_STATISTICS.totalSuccessfulRetries >= 1, is(true));
// verify that the update succeeded
try (ResultSet rs =
connection.executeQuery(
Statement.of(
"SELECT COUNT(*) AS C FROM TEST WHERE ID=1 AND NAME='update aborted'"))) {
assertThat(rs.next(), is(true));
assertThat(rs.getLong("C"), is(equalTo(1L)));
assertThat(rs.next(), is(false));
}
}
}
/** Test successful retry when a query aborts */
@Test
public void testQueryAborted() {
AbortInterceptor interceptor = new AbortInterceptor(0);
try (ITConnection connection =
createConnection(interceptor, new CountTransactionRetryListener())) {
// verify that the there is no test record
try (ResultSet rs =
connection.executeQuery(Statement.of("SELECT COUNT(*) AS C FROM TEST WHERE ID=1"))) {
assertThat(rs.next(), is(true));
assertThat(rs.getLong("C"), is(equalTo(0L)));
assertThat(rs.next(), is(false));
}
// insert a test record
connection.executeUpdate(
Statement.of("INSERT INTO TEST (ID, NAME) VALUES (1, 'test aborted')"));
// indicate that the next statement should abort
interceptor.setProbability(1.0);
interceptor.setOnlyInjectOnce(true);
// do a query that will abort
try (ResultSet rs =
connection.executeQuery(Statement.of("SELECT COUNT(*) AS C FROM TEST WHERE ID=1"))) {
assertThat(rs.next(), is(true));
assertThat(rs.getLong("C"), is(equalTo(1L)));
assertThat(rs.next(), is(false));
}
// do a commit
connection.commit();
assertThat(RETRY_STATISTICS.totalSuccessfulRetries >= 1, is(true));
// verify that the update succeeded
try (ResultSet rs =
connection.executeQuery(Statement.of("SELECT COUNT(*) AS C FROM TEST WHERE ID=1"))) {
assertThat(rs.next(), is(true));
assertThat(rs.getLong("C"), is(equalTo(1L)));
assertThat(rs.next(), is(false));
}
}
}
/** Test successful retry when a call to {@link ResultSet#next()} aborts */
@Test
public void testNextCallAborted() {
AbortInterceptor interceptor = new AbortInterceptor(0);
try (ITConnection connection =
createConnection(interceptor, new CountTransactionRetryListener())) {
// insert two test records
connection.executeUpdate(Statement.of("INSERT INTO TEST (ID, NAME) VALUES (1, 'test 1')"));
connection.executeUpdate(Statement.of("INSERT INTO TEST (ID, NAME) VALUES (2, 'test 2')"));
// do a query
try (ResultSet rs = connection.executeQuery(Statement.of("SELECT * FROM TEST ORDER BY ID"))) {
// the first record should be accessible without any problems
assertThat(rs.next(), is(true));
assertThat(rs.getLong("ID"), is(equalTo(1L)));
// indicate that the next statement should abort
interceptor.setProbability(1.0);
interceptor.setOnlyInjectOnce(true);
assertThat(rs.next(), is(true));
assertThat(rs.getLong("ID"), is(equalTo(2L)));
assertThat(RETRY_STATISTICS.totalSuccessfulRetries >= 1, is(true));
// there should be only two records
assertThat(rs.next(), is(false));
}
connection.commit();
assertThat(RETRY_STATISTICS.totalSuccessfulRetries >= 1, is(true));
// verify that the transaction succeeded
try (ResultSet rs = connection.executeQuery(Statement.of("SELECT COUNT(*) AS C FROM TEST"))) {
assertThat(rs.next(), is(true));
assertThat(rs.getLong("C"), is(equalTo(2L)));
assertThat(rs.next(), is(false));
}
}
}
/** Test successful retry after multiple aborts */
@Test
public void testMultipleAborts() {
AbortInterceptor interceptor = new AbortInterceptor(0);
try (ITConnection connection =
createConnection(interceptor, new CountTransactionRetryListener())) {
// verify that the there is no test record
try (ResultSet rs =
connection.executeQuery(Statement.of("SELECT COUNT(*) AS C FROM TEST WHERE ID=1"))) {
assertThat(rs.next(), is(true));
assertThat(rs.getLong("C"), is(equalTo(0L)));
assertThat(rs.next(), is(false));
}
// do three inserts which all will abort and retry
interceptor.setProbability(1.0);
interceptor.setOnlyInjectOnce(true);
connection.executeUpdate(Statement.of("INSERT INTO TEST (ID, NAME) VALUES (1, 'test 1')"));
interceptor.setProbability(1.0);
interceptor.setOnlyInjectOnce(true);
connection.executeUpdate(Statement.of("INSERT INTO TEST (ID, NAME) VALUES (2, 'test 2')"));
interceptor.setProbability(1.0);
interceptor.setOnlyInjectOnce(true);
connection.executeUpdate(Statement.of("INSERT INTO TEST (ID, NAME) VALUES (3, 'test 3')"));
connection.commit();
assertThat(RETRY_STATISTICS.totalSuccessfulRetries >= 3, is(true));
// verify that the insert succeeded
try (ResultSet rs = connection.executeQuery(Statement.of("SELECT COUNT(*) AS C FROM TEST"))) {
assertThat(rs.next(), is(true));
assertThat(rs.getLong("C"), is(equalTo(3L)));
assertThat(rs.next(), is(false));
}
}
}
/**
* Tests that a transaction retry can be successful after a select, as long as the select returns
* the same results during the retry
*/
@Test
public void testAbortAfterSelect() {
AbortInterceptor interceptor = new AbortInterceptor(0);
try (ITConnection connection =
createConnection(interceptor, new CountTransactionRetryListener())) {
// verify that the there is no test record
try (ResultSet rs =
connection.executeQuery(Statement.of("SELECT COUNT(*) AS C FROM TEST WHERE ID=1"))) {
assertThat(rs.next(), is(true));
assertThat(rs.getLong("C"), is(equalTo(0L)));
assertThat(rs.next(), is(false));
}
// insert a test record
connection.executeUpdate(Statement.of("INSERT INTO TEST (ID, NAME) VALUES (1, 'test 1')"));
// select the test record
try (ResultSet rs = connection.executeQuery(Statement.of("SELECT * FROM TEST WHERE ID=1"))) {
assertThat(rs.next(), is(true));
assertThat(rs.getLong("ID"), is(equalTo(1L)));
assertThat(rs.getString("NAME"), is(equalTo("test 1")));
assertThat(rs.next(), is(false));
}
// do another insert that will abort and retry
interceptor.setProbability(1.0);
interceptor.setOnlyInjectOnce(true);
connection.executeUpdate(Statement.of("INSERT INTO TEST (ID, NAME) VALUES (2, 'test 2')"));
// select the first test record again
try (ResultSet rs = connection.executeQuery(Statement.of("SELECT * FROM TEST WHERE ID=1"))) {
assertThat(rs.next(), is(true));
assertThat(rs.getLong("ID"), is(equalTo(1L)));
assertThat(rs.getString("NAME"), is(equalTo("test 1")));
assertThat(rs.next(), is(false));
}
connection.commit();
assertThat(RETRY_STATISTICS.totalSuccessfulRetries >= 1, is(true));
}
}
/**
* Test a successful retry when a {@link ResultSet} has been consumed half way. The {@link
* ResultSet} should still be at the same position and still behave as if the original transaction
* did not abort.
*/
@Test
public void testAbortWithResultSetHalfway() {
AbortInterceptor interceptor = new AbortInterceptor(0);
try (ITConnection connection =
createConnection(interceptor, new CountTransactionRetryListener())) {
// insert two test records
connection.executeUpdate(Statement.of("INSERT INTO TEST (ID, NAME) VALUES (1, 'test 1')"));
connection.executeUpdate(Statement.of("INSERT INTO TEST (ID, NAME) VALUES (2, 'test 2')"));
// select the test records
try (ResultSet rs = connection.executeQuery(Statement.of("SELECT * FROM TEST ORDER BY ID"))) {
// iterate one step
assertThat(rs.next(), is(true));
assertThat(rs.getLong("ID"), is(equalTo(1L)));
// do another insert that will abort and retry
interceptor.setProbability(1.0);
interceptor.setOnlyInjectOnce(true);
connection.executeUpdate(Statement.of("INSERT INTO TEST (ID, NAME) VALUES (3, 'test 3')"));
// iterate another step
assertThat(rs.next(), is(true));
assertThat(rs.getLong("ID"), is(equalTo(2L)));
// ensure we are at the end of the result set
assertThat(rs.next(), is(false));
}
connection.commit();
assertThat(RETRY_STATISTICS.totalSuccessfulRetries >= 1, is(true));
// verify that all the inserts succeeded
try (ResultSet rs = connection.executeQuery(Statement.of("SELECT COUNT(*) AS C FROM TEST"))) {
assertThat(rs.next(), is(true));
assertThat(rs.getLong("C"), is(equalTo(3L)));
assertThat(rs.next(), is(false));
}
}
}
/** Test successful retry after a {@link ResultSet} has been fully consumed. */
@Test
public void testAbortWithResultSetFullyConsumed() {
AbortInterceptor interceptor = new AbortInterceptor(0);
try (ITConnection connection =
createConnection(interceptor, new CountTransactionRetryListener())) {
// insert two test records
connection.executeUpdate(Statement.of("INSERT INTO TEST (ID, NAME) VALUES (1, 'test 1')"));
connection.executeUpdate(Statement.of("INSERT INTO TEST (ID, NAME) VALUES (2, 'test 2')"));
// select the test records and iterate over them
try (ResultSet rs = connection.executeQuery(Statement.of("SELECT * FROM TEST ORDER BY ID"))) {
while (rs.next()) {
// do nothing, just consume the result set
}
}
// do another insert that will abort and retry
interceptor.setProbability(1.0);
interceptor.setOnlyInjectOnce(true);
connection.executeUpdate(Statement.of("INSERT INTO TEST (ID, NAME) VALUES (3, 'test 3')"));
connection.commit();
assertThat(RETRY_STATISTICS.totalSuccessfulRetries >= 1, is(true));
// verify that all the inserts succeeded
try (ResultSet rs = connection.executeQuery(Statement.of("SELECT COUNT(*) AS C FROM TEST"))) {
assertThat(rs.next(), is(true));
assertThat(rs.getLong("C"), is(equalTo(3L)));
assertThat(rs.next(), is(false));
}
}
}
@Test
public void testAbortWithConcurrentInsert() {
assumeFalse("concurrent transactions are not supported on the emulator", isUsingEmulator());
AbortInterceptor interceptor = new AbortInterceptor(0);
try (ITConnection connection =
createConnection(interceptor, new CountTransactionRetryListener())) {
// insert two test records
connection.executeUpdate(Statement.of("INSERT INTO TEST (ID, NAME) VALUES (1, 'test 1')"));
connection.executeUpdate(Statement.of("INSERT INTO TEST (ID, NAME) VALUES (2, 'test 2')"));
// select the test records and consume the entire result set
try (ResultSet rs = connection.executeQuery(Statement.of("SELECT * FROM TEST ORDER BY ID"))) {
while (rs.next()) {
// do nothing
}
}
// open a new connection and transaction and do an additional insert
try (ITConnection connection2 = createConnection()) {
connection2.executeUpdate(Statement.of("INSERT INTO TEST (ID, NAME) VALUES (3, 'test 3')"));
connection2.commit();
}
// now try to do an insert that will abort. The retry should now fail as there has been a
// concurrent modification
interceptor.setProbability(1.0);
interceptor.setOnlyInjectOnce(true);
boolean expectedException = false;
try {
connection.executeUpdate(Statement.of("INSERT INTO TEST (ID, NAME) VALUES (4, 'test 4')"));
} catch (AbortedDueToConcurrentModificationException e) {
expectedException = true;
}
assertThat(expectedException, is(true));
assertRetryStatistics(1, 1, 0);
}
}
@Test
public void testAbortWithConcurrentDelete() {
assumeFalse("concurrent transactions are not supported on the emulator", isUsingEmulator());
AbortInterceptor interceptor = new AbortInterceptor(0);
// first insert two test records
try (ITConnection connection = createConnection()) {
connection.executeUpdate(Statement.of("INSERT INTO TEST (ID, NAME) VALUES (1, 'test 1')"));
connection.executeUpdate(Statement.of("INSERT INTO TEST (ID, NAME) VALUES (2, 'test 2')"));
connection.commit();
}
// open a new connection and select the two test records
try (ITConnection connection =
createConnection(interceptor, new CountTransactionRetryListener())) {
// select the test records and consume the entire result set
try (ResultSet rs = connection.executeQuery(Statement.of("SELECT * FROM TEST ORDER BY ID"))) {
while (rs.next()) {
// do nothing
}
}
// open a new connection and transaction and remove one of the test records
try (ITConnection connection2 = createConnection()) {
connection2.executeUpdate(Statement.of("DELETE FROM TEST WHERE ID=1"));
connection2.commit();
}
// now try to do an insert that will abort. The retry should now fail as there has been a
// concurrent modification
interceptor.setProbability(1.0);
interceptor.setOnlyInjectOnce(true);
boolean expectedException = false;
try {
connection.executeUpdate(Statement.of("INSERT INTO TEST (ID, NAME) VALUES (3, 'test 3')"));
} catch (AbortedDueToConcurrentModificationException e) {
expectedException = true;
}
assertThat(expectedException, is(true));
assertRetryStatistics(1, 1, 0);
}
}
@Test
public void testAbortWithConcurrentUpdate() {
assumeFalse("concurrent transactions are not supported on the emulator", isUsingEmulator());
AbortInterceptor interceptor = new AbortInterceptor(0);
// first insert two test records
try (ITConnection connection = createConnection()) {
connection.executeUpdate(Statement.of("INSERT INTO TEST (ID, NAME) VALUES (1, 'test 1')"));
connection.executeUpdate(Statement.of("INSERT INTO TEST (ID, NAME) VALUES (2, 'test 2')"));
connection.commit();
}
// open a new connection and select the two test records
try (ITConnection connection =
createConnection(interceptor, new CountTransactionRetryListener())) {
// select the test records and consume the entire result set
try (ResultSet rs = connection.executeQuery(Statement.of("SELECT * FROM TEST ORDER BY ID"))) {
while (rs.next()) {
// do nothing
}
}
// open a new connection and transaction and update one of the test records
try (ITConnection connection2 = createConnection()) {
connection2.executeUpdate(Statement.of("UPDATE TEST SET NAME='test updated' WHERE ID=2"));
connection2.commit();
}
// now try to do an insert that will abort. The retry should now fail as there has been a
// concurrent modification
interceptor.setProbability(1.0);
interceptor.setOnlyInjectOnce(true);
boolean expectedException = false;
try {
connection.executeUpdate(Statement.of("INSERT INTO TEST (ID, NAME) VALUES (3, 'test 3')"));
} catch (AbortedDueToConcurrentModificationException e) {
expectedException = true;
}
assertThat(expectedException, is(true));
assertRetryStatistics(1, 1, 0);
}
}
/**
* Test that shows that a transaction retry is possible even when there is a concurrent insert
* that has an impact on a query that has been executed, as long as the user hasn't actually seen
* the relevant part of the result of the query
*/
@Test
public void testAbortWithUnseenConcurrentInsert() {
assumeFalse("concurrent transactions are not supported on the emulator", isUsingEmulator());
AbortInterceptor interceptor = new AbortInterceptor(0);
try (ITConnection connection =
createConnection(interceptor, new CountTransactionRetryListener())) {
// insert two test records
connection.executeUpdate(Statement.of("INSERT INTO TEST (ID, NAME) VALUES (1, 'test 1')"));
connection.executeUpdate(Statement.of("INSERT INTO TEST (ID, NAME) VALUES (2, 'test 2')"));
// select the test records and consume part of the result set
ResultSet rs = connection.executeQuery(Statement.of("SELECT * FROM TEST ORDER BY ID"));
assertThat(rs.next(), is(true));
assertThat(rs.next(), is(true));
// Open a new connection and transaction and do an additional insert. This insert will be
// included in a retry of the above query, but this has not yet been 'seen' by the user,
// hence is not a problem for retrying the transaction.
try (ITConnection connection2 = createConnection()) {
connection2.executeUpdate(Statement.of("INSERT INTO TEST (ID, NAME) VALUES (3, 'test 3')"));
connection2.commit();
}
// now try to do an insert that will abort. The retry should still succeed.
interceptor.setProbability(1.0);
interceptor.setOnlyInjectOnce(true);
int currentRetryCount = RETRY_STATISTICS.totalRetryAttemptsStarted;
connection.executeUpdate(Statement.of("INSERT INTO TEST (ID, NAME) VALUES (4, 'test 4')"));
assertThat(RETRY_STATISTICS.totalRetryAttemptsStarted >= currentRetryCount + 1, is(true));
// Consume the rest of the result set. The insert by the other transaction should now be
// included in the result set as the transaction retried. Although this means that the result
// is different after a retry, it is not different as seen by the user, as the user didn't
// know that the result set did not have any more results before the transaction retry.
assertThat(rs.next(), is(true));
assertThat(rs.getLong("ID"), is(equalTo(3L)));
// record with id 4 should not be visible, as it was added to the transaction after the query
// was executed
assertThat(rs.next(), is(false));
rs.close();
connection.commit();
assertThat(RETRY_STATISTICS.totalSuccessfulRetries >= 1, is(true));
}
}
/**
* This test shows what happens when an abort occurs on a call to {@link ResultSet#next()} on a
* {@link ResultSet} that has an concurrent insert. As long as the user hasn't consumed the {@link
* ResultSet} so far that the concurrent insert has been seen, the retry will succeed. When the
* user has consumed the {@link ResultSet} to the point where the concurrent insert is visible,
* the retry will fail.
*/
@Test
public void testAbortWithUnseenConcurrentInsertAbortOnNext() {
assumeFalse("concurrent transactions are not supported on the emulator", isUsingEmulator());
// no calls to next(), this should succeed
assertThat(testAbortWithUnseenConcurrentInsertAbortOnNext(0) >= 1, is(true));
// 1 call to next() should also succeed, as there were 2 records in the original result set
assertThat(testAbortWithUnseenConcurrentInsertAbortOnNext(1) >= 1, is(true));
// 2 calls to next() should also succeed, as there were 2 records in the original result set and
// the user doesn't know yet that the next call to next() will return true instead of false
// after the concurrent insert
assertThat(testAbortWithUnseenConcurrentInsertAbortOnNext(2) >= 1, is(true));
boolean expectedException = false;
try {
// 3 calls to next() should fail, as the user would now see the inserted record
testAbortWithUnseenConcurrentInsertAbortOnNext(3);
} catch (AbortedDueToConcurrentModificationException e) {
expectedException = true;
}
assertThat(expectedException, is(true));
}
private int testAbortWithUnseenConcurrentInsertAbortOnNext(int callsToNext)
throws AbortedDueToConcurrentModificationException {
assumeFalse("concurrent transactions are not supported on the emulator", isUsingEmulator());
int retries = 0;
clearTable();
clearStatistics();
AbortInterceptor interceptor = new AbortInterceptor(0);
try (ITConnection connection =
createConnection(interceptor, new CountTransactionRetryListener())) {
int totalRecordsSeen = 0;
// insert two test records
connection.executeUpdate(Statement.of("INSERT INTO TEST (ID, NAME) VALUES (1, 'test 1')"));
connection.executeUpdate(Statement.of("INSERT INTO TEST (ID, NAME) VALUES (2, 'test 2')"));
// select the test records and consume part or all of the result set
ResultSet rs = connection.executeQuery(Statement.of("SELECT * FROM TEST ORDER BY ID"));
for (int counter = 0; counter < callsToNext; counter++) {
if (rs.next()) {
totalRecordsSeen++;
}
}
// Open a new connection and transaction and do an additional insert. This insert will be
// included in a retry of the above query. Any transaction retry will fail/succeed depending
// on whether the user has consumed enough of the result set to potentially have seen this
// insert.
try (ITConnection connection2 = createConnection()) {
connection2.executeUpdate(Statement.of("INSERT INTO TEST (ID, NAME) VALUES (3, 'test 3')"));
connection2.commit();
}
// Now consume the rest of the result set, but trigger a transaction retry by aborting the
// first next() call. Without a retry, the result set should only contain 2 records. With a
// successful retry, the result set contains 3 results. The retry will only succeed as long
// as the user has not consumed enough of the result set to know whether there should have
// been a record with ID 3 or not.
// First verify that the transaction has not yet retried.
int currentRetryCount = RETRY_STATISTICS.totalRetryAttemptsStarted;
interceptor.setProbability(1.0);
interceptor.setOnlyInjectOnce(true);
// Try to consume the rest of the result set.
// This will fail with an AbortedDueToConcurrentModificationException if the retry fails.
while (rs.next()) {
totalRecordsSeen++;
if (totalRecordsSeen == 3) {
assertThat(rs.getLong("ID"), is(equalTo(3L)));
}
}
// Verify that the transaction retried.
assertThat(RETRY_STATISTICS.totalSuccessfulRetries > currentRetryCount, is(true));
rs.close();
connection.commit();
retries = RETRY_STATISTICS.totalSuccessfulRetries;
}
return retries;
}
/**
* Test that shows that a transaction that has aborted is considered to be rolled back, and new
* statements will be executed in a new transaction
*/
@Test
public void testAbortWithConcurrentInsertAndContinue() {
assumeFalse("concurrent transactions are not supported on the emulator", isUsingEmulator());
AbortInterceptor interceptor = new AbortInterceptor(0);
try (ITConnection connection =
createConnection(interceptor, new CountTransactionRetryListener())) {
// insert two test records
connection.executeUpdate(Statement.of("INSERT INTO TEST (ID, NAME) VALUES (1, 'test 1')"));
connection.executeUpdate(Statement.of("INSERT INTO TEST (ID, NAME) VALUES (2, 'test 2')"));
// Select the test records and consume the entire result set.
try (ResultSet rs = connection.executeQuery(Statement.of("SELECT * FROM TEST ORDER BY ID"))) {
while (rs.next()) {
// do nothing
}
}
// Open a new connection and transaction and do an additional insert
try (ITConnection connection2 = createConnection()) {
connection2.executeUpdate(Statement.of("INSERT INTO TEST (ID, NAME) VALUES (3, 'test 3')"));
connection2.commit();
}
// Now try to do an insert that will abort. The retry should now fail as there has been a
// concurrent modification.
interceptor.setProbability(1.0);
interceptor.setOnlyInjectOnce(true);
boolean expectedException = false;
try {
connection.executeUpdate(Statement.of("INSERT INTO TEST (ID, NAME) VALUES (4, 'test 4')"));
} catch (AbortedDueToConcurrentModificationException e) {
expectedException = true;
}
assertThat(expectedException, is(true));
assertRetryStatistics(1, 1, 0);
// Rollback the aborted transaction to start a new one.
connection.rollback();
try (ResultSet rs = connection.executeQuery(Statement.of("SELECT * FROM TEST"))) {
// there should be one record from the transaction on connection2
assertThat(rs.next(), is(true));
assertThat(rs.next(), is(false));
}
}
}
/**
* Test that shows the following:
*
* <ol>
* <li>The transaction aborts at commit
* <li>A retry starts and succeeds
* <li>The commit is applied again and aborts again
* <li>The retry is started again and then succeeds
* </ol>
*/
@Test
public void testAbortTwiceOnCommit() {
AbortInterceptor interceptor =
new AbortInterceptor(0) {
private int commitCount = 0;
@Override
protected boolean shouldAbort(String statement, ExecutionStep step) {
if ("COMMIT".equalsIgnoreCase(statement)) {
commitCount++;
return commitCount <= 2;
}
return false;
}
};
try (ITConnection connection =
createConnection(interceptor, new CountTransactionRetryListener())) {
connection.executeUpdate(
Statement.of("INSERT INTO TEST (ID, NAME) VALUES (1, 'test aborted')"));
connection.commit();
// Assert that the transaction was retried twice.
assertRetryStatistics(2, 0, 2);
// Verify that the insert succeeded.
try (ResultSet rs =
connection.executeQuery(Statement.of("SELECT COUNT(*) AS C FROM TEST WHERE ID=1"))) {
assertThat(rs.next(), is(true));
assertThat(rs.getLong("C"), is(equalTo(1L)));
assertThat(rs.next(), is(false));
}
}
}
/**
* Test that shows the following:
*
* <ol>
* <li>The transaction aborts at commit
* <li>A retry starts and then aborts at the insert statement
* <li>The retry is restarted and then succeeds
* </ol>
*/
@Test
public void testNestedAbortOnInsert() {
AbortInterceptor interceptor =
new AbortInterceptor(0) {
private int commitCount = 0;
private int insertCount = 0;
@Override
protected boolean shouldAbort(String statement, ExecutionStep step) {
if ("COMMIT".equalsIgnoreCase(statement)) {
commitCount++;
return commitCount == 1;
} else if (statement.startsWith("INSERT INTO TEST")) {
insertCount++;
return insertCount == 2;
}
return false;
}
};
try (ITConnection connection =
createConnection(interceptor, new CountTransactionRetryListener())) {
connection.executeUpdate(
Statement.of("INSERT INTO TEST (ID, NAME) VALUES (1, 'test aborted')"));
connection.commit();
// Assert that the transaction was retried (a restarted retry is counted as one successful
// retry).
assertRetryStatistics(2, 0, 1);
assertThat(RETRY_STATISTICS.totalNestedAborts > 0, is(true));
// Verify that the insert succeeded.
try (ResultSet rs =
connection.executeQuery(Statement.of("SELECT COUNT(*) AS C FROM TEST WHERE ID=1"))) {
assertThat(rs.next(), is(true));
assertThat(rs.getLong("C"), is(equalTo(1L)));
assertThat(rs.next(), is(false));
}
}
}
/**
* Test that shows the following:
*
* <ol>
* <li>The transaction aborts at commit
* <li>A retry starts and then aborts at a next call in a result set
* <li>The retry is restarted and then succeeds
* </ol>
*/
@Test
public void testNestedAbortOnNextCall() {
AbortInterceptor interceptor =
new AbortInterceptor(0) {
private int nextCallsDuringRetry = 0;
private int commitCount = 0;
@Override
protected boolean shouldAbort(String statement, ExecutionStep step) {
if ("COMMIT".equalsIgnoreCase(statement)) {
// Note that commit always has ExecutionStep == EXECUTE_STATEMENT, as a commit can
// never
// really be retried (it is always the last statement in a transaction, and if it
// fails
// because of an aborted exception, the entire transaction is retried, and the commit
// statement is then applied again).
commitCount++;
return commitCount == 1;
} else if (statement.equals("SELECT * FROM TEST ORDER BY ID")
&& step == ExecutionStep.RETRY_NEXT_ON_RESULT_SET) {
nextCallsDuringRetry++;
return nextCallsDuringRetry == 1;
}
return false;
}
};
try (ITConnection connection =
createConnection(interceptor, new CountTransactionRetryListener())) {
// Insert two test records.
connection.executeUpdate(Statement.of("INSERT INTO TEST (ID, NAME) VALUES (1, 'test 1')"));
connection.executeUpdate(Statement.of("INSERT INTO TEST (ID, NAME) VALUES (2, 'test 2')"));
// Select the test records.
try (ResultSet rs = connection.executeQuery(Statement.of("SELECT * FROM TEST ORDER BY ID"))) {
// Iterate one step. This step should abort during the retry the first time.
assertThat(rs.next(), is(true));
assertThat(rs.getLong("ID"), is(equalTo(1L)));
// Do another insert that will not be visible to the result set.
connection.executeUpdate(Statement.of("INSERT INTO TEST (ID, NAME) VALUES (3, 'test 3')"));
// iterate another step
assertThat(rs.next(), is(true));
assertThat(rs.getLong("ID"), is(equalTo(2L)));
// Ensure we are at the end of the result set.
assertThat(rs.next(), is(false));
}
connection.commit();
// Verify that the transaction retried.
assertRetryStatistics(2, 0, 1);
assertThat(RETRY_STATISTICS.totalNestedAborts > 0, is(true));
// Verify that all the inserts succeeded.
try (ResultSet rs = connection.executeQuery(Statement.of("SELECT COUNT(*) AS C FROM TEST"))) {
assertThat(rs.next(), is(true));
assertThat(rs.getLong("C"), is(equalTo(3L)));
assertThat(rs.next(), is(false));
}
}
}
/**
* Test that shows the following:
*
* <ol>
* <li>Transaction 1 does two inserts in table TEST
* <li>Transaction 1 selects all records from table TEST
* <li>Transaction 2 inserts a record into TEST
* <li>Transaction 1 does another insert into TEST that aborts
* <li>Transaction 1 starts a retry that aborts at the SELECT statement (i.e. before the
* concurrent modification has been seen)
* <li>Transaction 1 restarts the retry that now aborts due to a concurrent modification
* exception
* </ol>
*/
@Test
public void testNestedAbortWithConcurrentInsert() {
assumeFalse("concurrent transactions are not supported on the emulator", isUsingEmulator());
AbortInterceptor interceptor =
new AbortInterceptor(0) {
private boolean alreadyAborted = false;
@Override
protected boolean shouldAbort(String statement, ExecutionStep step) {
// Abort during retry on the select statement.
if (!alreadyAborted
&& statement.equals("SELECT * FROM TEST ORDER BY ID")
&& step == ExecutionStep.RETRY_STATEMENT) {
alreadyAborted = true;
return true;
}
return super.shouldAbort(statement, step);
}
};
try (ITConnection connection =
createConnection(interceptor, new CountTransactionRetryListener())) {
// insert two test records
connection.executeUpdate(Statement.of("INSERT INTO TEST (ID, NAME) VALUES (1, 'test 1')"));
connection.executeUpdate(Statement.of("INSERT INTO TEST (ID, NAME) VALUES (2, 'test 2')"));
// select the test records and consume the entire result set
try (ResultSet rs = connection.executeQuery(Statement.of("SELECT * FROM TEST ORDER BY ID"))) {
while (rs.next()) {
// do nothing
}
}
// open a new connection and transaction and do an additional insert
try (ITConnection connection2 = createConnection()) {
connection2.executeUpdate(Statement.of("INSERT INTO TEST (ID, NAME) VALUES (3, 'test 3')"));
connection2.commit();
}
// Now try to do an insert that will abort. The retry should now fail as there has been a
// concurrent modification.
interceptor.setProbability(1.0);
interceptor.setOnlyInjectOnce(true);
boolean expectedException = false;
try {
connection.executeUpdate(Statement.of("INSERT INTO TEST (ID, NAME) VALUES (4, 'test 4')"));
} catch (AbortedDueToConcurrentModificationException e) {
expectedException = true;
}
assertThat(expectedException, is(true));
assertRetryStatistics(2, 1, 0);
assertThat(RETRY_STATISTICS.totalNestedAborts > 0, is(true));
}
}
/**