-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathaborted_transactions_test.go
980 lines (897 loc) · 37.4 KB
/
aborted_transactions_test.go
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
// Copyright 2021 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
//
// https://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 spannerdriver
import (
"context"
"database/sql"
"reflect"
"testing"
"time"
"cloud.google.com/go/spanner"
sppb "cloud.google.com/go/spanner/apiv1/spannerpb"
"github.com/google/go-cmp/cmp"
"github.com/googleapis/go-sql-spanner/testutil"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
func TestCommitAborted(t *testing.T) {
t.Parallel()
db, server, teardown := setupTestDBConnectionWithParams(t, "minSessions=1;maxSessions=1")
defer teardown()
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
tx, err := db.BeginTx(ctx, &sql.TxOptions{})
if err != nil {
t.Fatalf("begin failed: %v", err)
}
server.TestSpanner.PutExecutionTime(testutil.MethodCommitTransaction, testutil.SimulatedExecutionTime{
Errors: []error{status.Error(codes.Aborted, "Aborted")},
})
err = tx.Commit()
if err != nil {
t.Fatalf("commit failed: %v", err)
}
reqs := drainRequestsFromServer(server.TestSpanner)
commitReqs := requestsOfType(reqs, reflect.TypeOf(&sppb.CommitRequest{}))
if g, w := len(commitReqs), 2; g != w {
t.Fatalf("commit request count mismatch\nGot: %v\nWant: %v", g, w)
}
}
func TestCommitAbortedWithInternalRetriesDisabled(t *testing.T) {
t.Parallel()
db, server, teardown := setupTestDBConnectionWithParams(t, "retryAbortsInternally=false;minSessions=1;maxSessions=1")
defer teardown()
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
tx, err := db.BeginTx(ctx, &sql.TxOptions{})
if err != nil {
t.Fatalf("begin failed: %v", err)
}
server.TestSpanner.PutExecutionTime(testutil.MethodCommitTransaction, testutil.SimulatedExecutionTime{
Errors: []error{status.Error(codes.Aborted, "Aborted")},
})
err = tx.Commit()
// The aborted error should be propagated to the caller when internal retries have been disabled.
if g, w := spanner.ErrCode(err), codes.Aborted; g != w {
t.Fatalf("commit error code mismatch\nGot: %v\nWant: %v", g, w)
}
reqs := drainRequestsFromServer(server.TestSpanner)
commitReqs := requestsOfType(reqs, reflect.TypeOf(&sppb.CommitRequest{}))
if g, w := len(commitReqs), 1; g != w {
t.Fatalf("commit request count mismatch\nGot: %v\nWant: %v", g, w)
}
}
func TestUpdateAborted(t *testing.T) {
t.Parallel()
db, server, teardown := setupTestDBConnectionWithParams(t, "minSessions=1;maxSessions=1")
defer teardown()
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
tx, err := db.BeginTx(ctx, &sql.TxOptions{})
if err != nil {
t.Fatalf("begin failed: %v", err)
}
server.TestSpanner.PutExecutionTime(testutil.MethodExecuteSql, testutil.SimulatedExecutionTime{
Errors: []error{status.Error(codes.Aborted, "Aborted")},
})
res, err := tx.ExecContext(ctx, testutil.UpdateBarSetFoo)
if err != nil {
t.Fatalf("update failed: %v", err)
}
affected, err := res.RowsAffected()
if err != nil {
t.Fatalf("get affected rows failed: %v", err)
}
if affected != testutil.UpdateBarSetFooRowCount {
t.Fatalf("affected rows mismatch\nGot: %v\nWant: %v", affected, testutil.UpdateBarSetFooRowCount)
}
err = tx.Commit()
if err != nil {
t.Fatalf("commit failed: %v", err)
}
reqs := drainRequestsFromServer(server.TestSpanner)
execReqs := requestsOfType(reqs, reflect.TypeOf(&sppb.ExecuteSqlRequest{}))
if g, w := len(execReqs), 2; g != w {
t.Fatalf("execute request count mismatch\nGot: %v\nWant: %v", g, w)
}
commitReqs := requestsOfType(reqs, reflect.TypeOf(&sppb.CommitRequest{}))
if g, w := len(commitReqs), 1; g != w {
t.Fatalf("commit request count mismatch\nGot: %v\nWant: %v", g, w)
}
}
func TestBatchUpdateAborted(t *testing.T) {
t.Parallel()
db, server, teardown := setupTestDBConnectionWithParams(t, "minSessions=1;maxSessions=1")
defer teardown()
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
tx, err := db.BeginTx(ctx, &sql.TxOptions{})
if err != nil {
t.Fatalf("begin failed: %v", err)
}
server.TestSpanner.PutExecutionTime(testutil.MethodExecuteBatchDml, testutil.SimulatedExecutionTime{
Errors: []error{status.Error(codes.Aborted, "Aborted")},
})
if _, err := tx.ExecContext(ctx, "START BATCH DML"); err != nil {
t.Fatalf("start batch failed: %v", err)
}
if _, err := tx.ExecContext(ctx, testutil.UpdateBarSetFoo); err != nil {
t.Fatalf("update failed: %v", err)
}
if _, err := tx.ExecContext(ctx, "RUN BATCH"); err != nil {
t.Fatalf("run batch failed: %v", err)
}
err = tx.Commit()
if err != nil {
t.Fatalf("commit failed: %v", err)
}
reqs := drainRequestsFromServer(server.TestSpanner)
execReqs := requestsOfType(reqs, reflect.TypeOf(&sppb.ExecuteBatchDmlRequest{}))
if g, w := len(execReqs), 2; g != w {
t.Fatalf("batch request count mismatch\nGot: %v\nWant: %v", g, w)
}
commitReqs := requestsOfType(reqs, reflect.TypeOf(&sppb.CommitRequest{}))
if g, w := len(commitReqs), 1; g != w {
t.Fatalf("commit request count mismatch\nGot: %v\nWant: %v", g, w)
}
}
func TestQueryAborted(t *testing.T) {
testRetryReadWriteTransactionWithQueryWithRetrySuccess(t, func(server testutil.InMemSpannerServer) {
server.PutExecutionTime(testutil.MethodExecuteStreamingSql, testutil.SimulatedExecutionTime{
Errors: []error{status.Error(codes.Aborted, "Aborted")},
})
}, codes.OK, 0, 2, 1)
}
func TestEmptyQueryAbortedTwice(t *testing.T) {
testRetryReadWriteTransactionWithQueryWithRetrySuccess(t, func(server testutil.InMemSpannerServer) {
server.PutStatementResult(testutil.SelectFooFromBar, &testutil.StatementResult{
Type: testutil.StatementResultResultSet,
ResultSet: testutil.CreateSingleColumnResultSet([]int64{}, "FOO"),
})
server.PutExecutionTime(testutil.MethodExecuteStreamingSql, testutil.SimulatedExecutionTime{
Errors: []error{status.Error(codes.Aborted, "Aborted"), status.Error(codes.Aborted, "Aborted")},
})
}, codes.OK, -1, 3, 1)
}
func TestQueryAbortedHalfway(t *testing.T) {
testRetryReadWriteTransactionWithQueryWithRetrySuccess(t, func(server testutil.InMemSpannerServer) {
server.AddPartialResultSetError(testutil.SelectFooFromBar, testutil.PartialResultSetExecutionTime{
ResumeToken: testutil.EncodeResumeToken(2),
Err: status.Error(codes.Aborted, "Aborted"),
})
}, codes.OK, 0, 2, 1)
}
func TestQueryAbortedTwice(t *testing.T) {
testRetryReadWriteTransactionWithQueryWithRetrySuccess(t, func(server testutil.InMemSpannerServer) {
server.AddPartialResultSetError(testutil.SelectFooFromBar, testutil.PartialResultSetExecutionTime{
ResumeToken: testutil.EncodeResumeToken(1),
Err: status.Error(codes.Aborted, "Aborted"),
})
server.AddPartialResultSetError(testutil.SelectFooFromBar, testutil.PartialResultSetExecutionTime{
ResumeToken: testutil.EncodeResumeToken(2),
Err: status.Error(codes.Aborted, "Aborted"),
})
}, codes.OK, 0, 3, 1)
}
func TestQuery_CommitAborted(t *testing.T) {
testRetryReadWriteTransactionWithQueryWithRetrySuccess(t, func(server testutil.InMemSpannerServer) {
server.PutExecutionTime(testutil.MethodCommitTransaction, testutil.SimulatedExecutionTime{
Errors: []error{status.Error(codes.Aborted, "Aborted")},
})
}, codes.OK, 0, 2, 2)
}
func TestQuery_CommitAbortedTwice(t *testing.T) {
testRetryReadWriteTransactionWithQueryWithRetrySuccess(t, func(server testutil.InMemSpannerServer) {
server.PutExecutionTime(testutil.MethodCommitTransaction, testutil.SimulatedExecutionTime{
Errors: []error{status.Error(codes.Aborted, "Aborted"), status.Error(codes.Aborted, "Aborted")},
})
}, codes.OK, 0, 3, 3)
}
func TestQueryConsumedHalfway_CommitAborted(t *testing.T) {
testRetryReadWriteTransactionWithQueryWithRetrySuccess(t, func(server testutil.InMemSpannerServer) {
server.PutExecutionTime(testutil.MethodCommitTransaction, testutil.SimulatedExecutionTime{
Errors: []error{status.Error(codes.Aborted, "Aborted")},
})
}, codes.OK, 1, 2, 2)
}
// TestQueryConsumedHalfway_RetryContainsMoreResults_CommitAborted tests the
// following scenario:
// 1. The initial attempt returns 2 rows. The application fetches the 2 rows,
// but does not try to fetch a 3 row. It therefore does not know that the
// iterator only contains 2 rows and not more.
// 2. The retry attempt returns 3 rows. The retry will also only fetch the 2
// first rows, and as the initial attempt did not know what was after these
// 2 rows the retry should succeed.
func TestQueryConsumedHalfway_RetryContainsMoreResults_CommitAborted(t *testing.T) {
testRetryReadWriteTransactionWithQuery(t, func(server testutil.InMemSpannerServer) {
server.PutExecutionTime(testutil.MethodCommitTransaction, testutil.SimulatedExecutionTime{
Errors: []error{status.Error(codes.Aborted, "Aborted")},
})
}, codes.OK, 2, 2, 2,
func(server testutil.InMemSpannerServer) {
server.PutStatementResult(testutil.SelectFooFromBar, &testutil.StatementResult{
Type: testutil.StatementResultResultSet,
ResultSet: testutil.CreateSingleColumnResultSet([]int64{1, 2, 3}, "FOO"),
})
}, nil)
}
func TestQueryWithError_CommitAborted(t *testing.T) {
testRetryReadWriteTransactionWithQueryWithRetrySuccess(t, func(server testutil.InMemSpannerServer) {
// Let the query return a Table not found error.
server.PutStatementResult(testutil.SelectFooFromBar, &testutil.StatementResult{
Type: testutil.StatementResultError,
Err: status.Errorf(codes.NotFound, "Table not found"),
})
server.PutExecutionTime(testutil.MethodCommitTransaction, testutil.SimulatedExecutionTime{
Errors: []error{status.Error(codes.Aborted, "Aborted")},
})
}, codes.NotFound, 0, 2, 2)
}
func TestQueryWithErrorHalfway_CommitAborted(t *testing.T) {
testRetryReadWriteTransactionWithQueryWithRetrySuccess(t, func(server testutil.InMemSpannerServer) {
// Let the query return an internal error halfway through the stream.
// Add the error twice so it is also returned during the retry.
for n := 0; n < 2; n++ {
server.AddPartialResultSetError(testutil.SelectFooFromBar, testutil.PartialResultSetExecutionTime{
ResumeToken: testutil.EncodeResumeToken(2),
Err: status.Errorf(codes.Internal, "broken stream"),
})
}
server.PutExecutionTime(testutil.MethodCommitTransaction, testutil.SimulatedExecutionTime{
Errors: []error{status.Errorf(codes.Aborted, "Aborted")},
})
}, codes.Internal, 0, 2, 2)
}
func TestQueryAbortedWithMoreResultsDuringRetry(t *testing.T) {
testRetryReadWriteTransactionWithQuery(t, nil, codes.OK, 0, 2, 1,
func(server testutil.InMemSpannerServer) {
server.PutExecutionTime(testutil.MethodCommitTransaction, testutil.SimulatedExecutionTime{
Errors: []error{status.Errorf(codes.Aborted, "Aborted")},
})
// Replace the original query result with a new one with an additional row
// before the transaction is committed. This will cause the retry to fail.
server.PutStatementResult(testutil.SelectFooFromBar, &testutil.StatementResult{
Type: testutil.StatementResultResultSet,
ResultSet: testutil.CreateSingleColumnResultSet([]int64{1, 2, 3}, "FOO"),
})
}, ErrAbortedDueToConcurrentModification)
}
// Tests that receiving less results during the retry will cause a failed retry.
func TestQueryAbortedWithLessResultsDuringRetry(t *testing.T) {
testRetryReadWriteTransactionWithQuery(t, nil, codes.OK, 0, 2, 1,
func(server testutil.InMemSpannerServer) {
server.PutExecutionTime(testutil.MethodCommitTransaction, testutil.SimulatedExecutionTime{
Errors: []error{status.Errorf(codes.Aborted, "Aborted")},
})
// Replace the original query result with a new one with an additional row
// before the transaction is committed. This will cause the retry to fail.
server.PutStatementResult(testutil.SelectFooFromBar, &testutil.StatementResult{
Type: testutil.StatementResultResultSet,
ResultSet: testutil.CreateSingleColumnResultSet([]int64{1}, "FOO"),
})
}, ErrAbortedDueToConcurrentModification)
}
// TestQueryWithEmptyResult_CommitAborted tests the scenario where a query returns
// the same empty result set during the initial attempt and a retry.
func TestQueryWithEmptyResult_CommitAborted(t *testing.T) {
testRetryReadWriteTransactionWithQueryWithRetrySuccess(t, func(server testutil.InMemSpannerServer) {
// Let the query return an empty result set with only one column.
server.PutStatementResult(testutil.SelectFooFromBar, &testutil.StatementResult{
Type: testutil.StatementResultResultSet,
ResultSet: testutil.CreateSingleColumnResultSet([]int64{}, "FOO"),
})
server.PutExecutionTime(testutil.MethodCommitTransaction, testutil.SimulatedExecutionTime{
Errors: []error{status.Error(codes.Aborted, "Aborted")},
})
}, codes.OK, -1, 2, 2)
}
// TestQueryWithNewColumn_CommitAborted tests the scenario where a query returns
// the same empty result set during a retry, but with a new column.
func TestQueryWithNewColumn_CommitAborted(t *testing.T) {
testRetryReadWriteTransactionWithQuery(t, func(server testutil.InMemSpannerServer) {
// Let the query return an empty result set with only one column.
server.PutStatementResult(testutil.SelectFooFromBar, &testutil.StatementResult{
Type: testutil.StatementResultResultSet,
ResultSet: testutil.CreateSingleColumnResultSet([]int64{}, "FOO"),
})
server.PutExecutionTime(testutil.MethodCommitTransaction, testutil.SimulatedExecutionTime{
Errors: []error{status.Error(codes.Aborted, "Aborted")},
})
}, codes.OK, -1, 2, 1,
func(server testutil.InMemSpannerServer) {
// Let the query return an empty result set with two columns during the retry.
// This should cause a retry failure.
server.PutStatementResult(testutil.SelectFooFromBar, &testutil.StatementResult{
Type: testutil.StatementResultResultSet,
ResultSet: testutil.CreateTwoColumnResultSet([][2]int64{}, [2]string{"FOO", "BAR"}),
})
}, ErrAbortedDueToConcurrentModification)
}
// testRetryReadWriteTransactionWithQueryWithRetrySuccess tests a scenario where a
// transaction with a query is retried and the retry should succeed.
func testRetryReadWriteTransactionWithQueryWithRetrySuccess(t *testing.T, setupServer func(server testutil.InMemSpannerServer),
wantErrCode codes.Code, numRowsToConsume int, wantSqlExecuteCount int, wantCommitCount int) {
testRetryReadWriteTransactionWithQuery(t, setupServer, wantErrCode, numRowsToConsume, wantSqlExecuteCount, wantCommitCount, nil, nil)
}
// testRetryReadWriteTransactionWithQuery tests a scenario where a transaction with
// a query is retried. The retry should fail with the given wantCommitErr error, or
// succeed if wantCommitErr is nil.
func testRetryReadWriteTransactionWithQuery(t *testing.T, setupServer func(server testutil.InMemSpannerServer),
wantErrCode codes.Code, numRowsToConsume int, wantSqlExecuteCount int, wantCommitCount int,
beforeCommit func(server testutil.InMemSpannerServer), wantCommitErr error) {
t.Parallel()
db, server, teardown := setupTestDBConnectionWithParams(t, "minSessions=1;maxSessions=1")
defer teardown()
if setupServer != nil {
setupServer(server.TestSpanner)
}
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
tx, err := db.BeginTx(ctx, &sql.TxOptions{})
if err != nil {
t.Fatalf("begin failed: %v", err)
}
rows, err := tx.QueryContext(ctx, testutil.SelectFooFromBar)
if err != nil {
t.Fatalf("query failed: %v", err)
}
values := make([]int64, 0)
for rows.Next() {
err = rows.Err()
if err != nil {
t.Fatalf("next failed: %v", err)
}
var val int64
err = rows.Scan(&val)
if err != nil {
t.Fatalf("scan failed: %v", err)
}
values = append(values, val)
if len(values) == numRowsToConsume {
break
}
}
err = rows.Err()
if g, w := spanner.ErrCode(err), wantErrCode; g != w {
t.Fatalf("next error mismatch\nGot: %v\nWant: %v", g, w)
}
if wantErrCode == codes.OK {
if numRowsToConsume > -1 {
if g, w := len(values), firstNonZero(numRowsToConsume, 2); g != w {
t.Fatalf("row count mismatch\nGot: %v\nWant: %v", g, w)
}
wantValues := ([]int64{1, 2})[:firstNonZero(numRowsToConsume, 2)]
if !cmp.Equal(wantValues, values) {
t.Fatalf("values mismatch\nGot: %v\nWant: %v", values, wantValues)
}
}
}
err = rows.Close()
if err != nil {
t.Fatalf("closing iterator failed: %v", err)
}
if beforeCommit != nil {
beforeCommit(server.TestSpanner)
}
err = tx.Commit()
if err != wantCommitErr {
t.Fatalf("commit error mismatch\nGot: %v\nWant: %v", err, wantCommitErr)
}
reqs := drainRequestsFromServer(server.TestSpanner)
execReqs := requestsOfType(reqs, reflect.TypeOf(&sppb.ExecuteSqlRequest{}))
if g, w := len(execReqs), wantSqlExecuteCount; g != w {
t.Fatalf("execute request count mismatch\nGot: %v\nWant: %v", g, w)
}
commitReqs := requestsOfType(reqs, reflect.TypeOf(&sppb.CommitRequest{}))
if g, w := len(commitReqs), wantCommitCount; g != w {
t.Fatalf("commit request count mismatch\nGot: %v\nWant: %v", g, w)
}
}
// Tests that a query that is aborted halfway the stream will be retried,
// but that the retry will fail if the results in the part of the result
// set that has already been seen will fail the retry.
func TestQueryAbortedHalfway_WithDifferentResultsInFirstHalf(t *testing.T) {
t.Parallel()
db, server, teardown := setupTestDBConnection(t)
defer teardown()
// Ensure that the second call to Next() will fail with an Aborted error.
server.TestSpanner.AddPartialResultSetError(testutil.SelectFooFromBar, testutil.PartialResultSetExecutionTime{
ResumeToken: testutil.EncodeResumeToken(2),
Err: status.Error(codes.Aborted, "Aborted"),
})
ctx := context.Background()
tx, err := db.BeginTx(ctx, &sql.TxOptions{})
if err != nil {
t.Fatalf("begin failed: %v", err)
}
rows, err := tx.QueryContext(ctx, testutil.SelectFooFromBar)
if err != nil {
t.Fatalf("query failed: %v", err)
}
// The first row should succeed.
next := rows.Next()
if !next {
t.Fatalf("next result mismatch\nGot: %v\nWant: %v", next, true)
}
err = rows.Err()
if err != nil {
t.Fatalf("next failed: %v", err)
}
var val int64
err = rows.Scan(&val)
if err != nil {
t.Fatalf("scan failed: %v", err)
}
if g, w := val, int64(1); g != w {
t.Fatalf("value mismatch\nGot: %v\nWant: %v", g, w)
}
// Replace the original query result with a new one with a different value
// for the first row. This should cause the transaction to fail with an
// ErrAbortedDueToConcurrentModification error.
server.TestSpanner.PutStatementResult(testutil.SelectFooFromBar, &testutil.StatementResult{
Type: testutil.StatementResultResultSet,
ResultSet: testutil.CreateSingleColumnResultSet([]int64{2, 2}, "FOO"),
})
// This should now fail with an ErrAbortedDueToConcurrentModification error.
next = rows.Next()
if next {
t.Fatalf("next result mismatch\nGot: %v\nWant: %v", next, false)
}
if g, w := rows.Err(), ErrAbortedDueToConcurrentModification; g != w {
t.Fatalf("next error mismatch\nGot: %v\nWant: %v", g, w)
}
reqs := drainRequestsFromServer(server.TestSpanner)
execReqs := requestsOfType(reqs, reflect.TypeOf(&sppb.ExecuteSqlRequest{}))
if g, w := len(execReqs), 2; g != w {
t.Fatalf("execute request count mismatch\nGot: %v\nWant: %v", g, w)
}
}
// Tests that a change in the results of a result set that has not yet been seen
// by the user does not cause a retry failure.
func TestQueryAbortedHalfway_WithDifferentResultsInSecondHalf(t *testing.T) {
t.Parallel()
db, server, teardown := setupTestDBConnection(t)
defer teardown()
// Ensure that the second call to Next() will fail with an Aborted error.
server.TestSpanner.AddPartialResultSetError(testutil.SelectFooFromBar, testutil.PartialResultSetExecutionTime{
ResumeToken: testutil.EncodeResumeToken(2),
Err: status.Error(codes.Aborted, "Aborted"),
})
ctx := context.Background()
tx, err := db.BeginTx(ctx, &sql.TxOptions{})
if err != nil {
t.Fatalf("begin failed: %v", err)
}
rows, err := tx.QueryContext(ctx, testutil.SelectFooFromBar)
if err != nil {
t.Fatalf("query failed: %v", err)
}
// The first row should succeed.
next := rows.Next()
if !next {
t.Fatalf("next result mismatch\nGot: %v\nWant: %v", next, true)
}
err = rows.Err()
if err != nil {
t.Fatalf("next failed: %v", err)
}
var val int64
err = rows.Scan(&val)
if err != nil {
t.Fatalf("scan failed: %v", err)
}
if g, w := val, int64(1); g != w {
t.Fatalf("value mismatch\nGot: %v\nWant: %v", g, w)
}
// Replace the original query result with a new one with a different value
// for the second row. This should not cause the transaction to fail with an
// ErrAbortedDueToConcurrentModification error as the result has not yet
// been seen by the user.
server.TestSpanner.PutStatementResult(testutil.SelectFooFromBar, &testutil.StatementResult{
Type: testutil.StatementResultResultSet,
ResultSet: testutil.CreateSingleColumnResultSet([]int64{1, 3}, "FOO"),
})
// This should succeed and return the new result.
next = rows.Next()
if !next {
t.Fatalf("next result mismatch\nGot: %v\nWant: %v", next, true)
}
err = rows.Err()
if err != nil {
t.Fatalf("next failed: %v", err)
}
err = rows.Scan(&val)
if err != nil {
t.Fatalf("scan failed: %v", err)
}
if g, w := val, int64(3); g != w {
t.Fatalf("value mismatch\nGot: %v\nWant: %v", g, w)
}
reqs := drainRequestsFromServer(server.TestSpanner)
execReqs := requestsOfType(reqs, reflect.TypeOf(&sppb.ExecuteSqlRequest{}))
if g, w := len(execReqs), 2; g != w {
t.Fatalf("execute request count mismatch\nGot: %v\nWant: %v", g, w)
}
}
func TestSecondUpdateAborted(t *testing.T) {
t.Parallel()
db, server, teardown := setupTestDBConnection(t)
defer teardown()
ctx := context.Background()
tx, err := db.BeginTx(ctx, &sql.TxOptions{})
if err != nil {
t.Fatalf("begin failed: %v", err)
}
// This statement should succeed and is not aborted.
_, err = tx.ExecContext(ctx, testutil.UpdateSingersSetLastName)
if err != nil {
t.Fatalf("update singers failed: %v", err)
}
server.TestSpanner.PutExecutionTime(testutil.MethodExecuteSql, testutil.SimulatedExecutionTime{
Errors: []error{status.Error(codes.Aborted, "Aborted")},
})
// This statement will return Aborted, the transaction will be retried internally and the statement is
// then executed once more and should return the correct value.
res, err := tx.ExecContext(ctx, testutil.UpdateBarSetFoo)
if err != nil {
t.Fatalf("update bar failed: %v", err)
}
affected, err := res.RowsAffected()
if err != nil {
t.Fatalf("get affected rows failed: %v", err)
}
if affected != testutil.UpdateBarSetFooRowCount {
t.Fatalf("affected rows mismatch\nGot: %v\nWant: %v", affected, testutil.UpdateBarSetFooRowCount)
}
err = tx.Commit()
if err != nil {
t.Fatalf("commit failed: %v", err)
}
reqs := drainRequestsFromServer(server.TestSpanner)
execReqs := requestsOfType(reqs, reflect.TypeOf(&sppb.ExecuteSqlRequest{}))
// The server should receive 4 execute statements, as each update statement should
// be executed twice.
if g, w := len(execReqs), 4; g != w {
t.Fatalf("execute request count mismatch\nGot: %v\nWant: %v", g, w)
}
commitReqs := requestsOfType(reqs, reflect.TypeOf(&sppb.CommitRequest{}))
if g, w := len(commitReqs), 1; g != w {
t.Fatalf("commit request count mismatch\nGot: %v\nWant: %v", g, w)
}
}
func TestSecondBatchUpdateAborted(t *testing.T) {
t.Parallel()
db, server, teardown := setupTestDBConnection(t)
defer teardown()
ctx := context.Background()
tx, err := db.BeginTx(ctx, &sql.TxOptions{})
if err != nil {
t.Fatalf("begin failed: %v", err)
}
if _, err := tx.ExecContext(ctx, "START BATCH DML"); err != nil {
t.Fatalf("failed to start batch: %v", err)
}
if _, err := tx.ExecContext(ctx, testutil.UpdateSingersSetLastName); err != nil {
t.Fatalf("update singers failed: %v", err)
}
if _, err := tx.ExecContext(ctx, "RUN BATCH"); err != nil {
t.Fatalf("failed to run batch: %v", err)
}
server.TestSpanner.PutExecutionTime(testutil.MethodExecuteBatchDml, testutil.SimulatedExecutionTime{
Errors: []error{status.Error(codes.Aborted, "Aborted")},
})
if _, err := tx.ExecContext(ctx, "START BATCH DML"); err != nil {
t.Fatalf("failed to start batch: %v", err)
}
if _, err := tx.ExecContext(ctx, testutil.UpdateBarSetFoo); err != nil {
t.Fatalf("update bar failed: %v", err)
}
// This statement will return Aborted, the transaction will be retried internally and the statement is
// then executed once more and should return the correct value.
if _, err := tx.ExecContext(ctx, "RUN BATCH"); err != nil {
t.Fatalf("failed to run batch: %v", err)
}
if err := tx.Commit(); err != nil {
t.Fatalf("commit failed: %v", err)
}
reqs := drainRequestsFromServer(server.TestSpanner)
execReqs := requestsOfType(reqs, reflect.TypeOf(&sppb.ExecuteBatchDmlRequest{}))
// The server should receive 4 batch statements, as each update statement should
// be executed twice.
if g, w := len(execReqs), 4; g != w {
t.Fatalf("batch request count mismatch\nGot: %v\nWant: %v", g, w)
}
commitReqs := requestsOfType(reqs, reflect.TypeOf(&sppb.CommitRequest{}))
if g, w := len(commitReqs), 1; g != w {
t.Fatalf("commit request count mismatch\nGot: %v\nWant: %v", g, w)
}
}
func TestSecondUpdateAborted_FirstStatementWithSameError(t *testing.T) {
t.Parallel()
db, server, teardown := setupTestDBConnection(t)
defer teardown()
ctx := context.Background()
tx, err := db.BeginTx(ctx, &sql.TxOptions{})
if err != nil {
t.Fatalf("begin failed: %v", err)
}
server.TestSpanner.PutStatementResult(testutil.UpdateSingersSetLastName, &testutil.StatementResult{
Type: testutil.StatementResultError,
Err: status.Error(codes.NotFound, "Table not found"),
})
// This statement should fail with NotFound. That will also be the result
// during the retry.
_, err = tx.ExecContext(ctx, testutil.UpdateSingersSetLastName)
if spanner.ErrCode(err) != codes.NotFound {
t.Fatalf("error code mismatch\nGot: %v\nWant: %v", spanner.ErrCode(err), codes.NotFound)
}
server.TestSpanner.PutExecutionTime(testutil.MethodExecuteSql, testutil.SimulatedExecutionTime{
Errors: []error{status.Error(codes.Aborted, "Aborted")},
})
// This statement will return Aborted, the transaction will be retried internally and the statement is
// then executed once more and should return the correct value.
res, err := tx.ExecContext(ctx, testutil.UpdateBarSetFoo)
if err != nil {
t.Fatalf("update bar failed: %v", err)
}
affected, err := res.RowsAffected()
if err != nil {
t.Fatalf("get affected rows failed: %v", err)
}
if affected != testutil.UpdateBarSetFooRowCount {
t.Fatalf("affected rows mismatch\nGot: %v\nWant: %v", affected, testutil.UpdateBarSetFooRowCount)
}
err = tx.Commit()
if err != nil {
t.Fatalf("commit failed: %v", err)
}
reqs := drainRequestsFromServer(server.TestSpanner)
execReqs := requestsOfType(reqs, reflect.TypeOf(&sppb.ExecuteSqlRequest{}))
// The server should receive 4 execute statements, as each update statement should
// be executed twice.
if g, w := len(execReqs), 4; g != w {
t.Fatalf("execute request count mismatch\nGot: %v\nWant: %v", g, w)
}
commitReqs := requestsOfType(reqs, reflect.TypeOf(&sppb.CommitRequest{}))
if g, w := len(commitReqs), 1; g != w {
t.Fatalf("commit request count mismatch\nGot: %v\nWant: %v", g, w)
}
}
func TestSecondUpdateAborted_FirstResultUpdateCountChanged(t *testing.T) {
testSecondUpdateAborted_FirstResultChanged(t, nil, &testutil.StatementResult{
Type: testutil.StatementResultUpdateCount,
UpdateCount: 0,
})
}
func TestSecondUpdateAborted_FirstResultFromSuccessToError(t *testing.T) {
// Simulate that the table has been deleted after the first attempt.
testSecondUpdateAborted_FirstResultChanged(t, nil, &testutil.StatementResult{
Type: testutil.StatementResultError,
Err: status.Error(codes.NotFound, "Table not found"),
})
}
func TestSecondUpdateAborted_FirstResultFromErrorToSuccess(t *testing.T) {
// Simulate that the table has been created after the first attempt.
testSecondUpdateAborted_FirstResultChanged(t, &testutil.StatementResult{
Type: testutil.StatementResultError,
Err: status.Error(codes.NotFound, "Table not found"),
}, &testutil.StatementResult{
Type: testutil.StatementResultUpdateCount,
UpdateCount: 1,
})
}
func TestSecondUpdateAborted_FirstResultFromErrorToOtherError(t *testing.T) {
// Simulate that the table has been created after the first attempt, but that
// the user has no permission for the table.
testSecondUpdateAborted_FirstResultChanged(t, &testutil.StatementResult{
Type: testutil.StatementResultError,
Err: status.Error(codes.NotFound, "Table not found"),
}, &testutil.StatementResult{
Type: testutil.StatementResultError,
Err: status.Error(codes.PermissionDenied, "No permission for table"),
})
}
func testSecondUpdateAborted_FirstResultChanged(t *testing.T, firstResult *testutil.StatementResult, secondResult *testutil.StatementResult) {
t.Parallel()
db, server, teardown := setupTestDBConnection(t)
defer teardown()
if firstResult != nil {
server.TestSpanner.PutStatementResult(testutil.UpdateSingersSetLastName, firstResult)
}
ctx := context.Background()
tx, err := db.BeginTx(ctx, &sql.TxOptions{})
if err != nil {
t.Fatalf("begin failed: %v", err)
}
// Ignore the result, as all we care about is whether the retry fails because
// the result is different during the retry.
_, _ = tx.ExecContext(ctx, testutil.UpdateSingersSetLastName)
// Update the result to simulate a different result during the retry.
server.TestSpanner.PutStatementResult(testutil.UpdateSingersSetLastName, secondResult)
server.TestSpanner.PutExecutionTime(testutil.MethodExecuteSql, testutil.SimulatedExecutionTime{
Errors: []error{status.Error(codes.Aborted, "Aborted")},
})
// This statement will return Aborted and the transaction will be retried internally. That
// retry will fail because the result of the first statement is different during the retry.
_, err = tx.ExecContext(ctx, testutil.UpdateBarSetFoo)
if err != ErrAbortedDueToConcurrentModification {
t.Fatalf("update error mismatch\nGot: %v\nWant: %v", err, ErrAbortedDueToConcurrentModification)
}
reqs := drainRequestsFromServer(server.TestSpanner)
execReqs := requestsOfType(reqs, reflect.TypeOf(&sppb.ExecuteSqlRequest{}))
// The server should receive 3 execute statements, as only the first statement is retried.
if g, w := len(execReqs), 3; g != w {
t.Fatalf("execute request count mismatch\nGot: %v\nWant: %v", g, w)
}
}
func TestBatchUpdateAbortedWithError(t *testing.T) {
t.Parallel()
db, server, teardown := setupTestDBConnection(t)
defer teardown()
// Make sure that one of the DML statements will return an error.
server.TestSpanner.PutStatementResult(testutil.UpdateSingersSetLastName, &testutil.StatementResult{
Type: testutil.StatementResultError,
Err: status.Error(codes.NotFound, "Table not found"),
})
ctx := context.Background()
tx, err := db.BeginTx(ctx, &sql.TxOptions{})
if err != nil {
t.Fatalf("begin failed: %v", err)
}
if _, err := tx.ExecContext(ctx, "START BATCH DML"); err != nil {
t.Fatalf("failed to start batch: %v", err)
}
if _, err := tx.ExecContext(ctx, testutil.UpdateBarSetFoo); err != nil {
t.Fatalf("dml statement failed: %v", err)
}
// This statement should fail with NotFound when the batch is executed.
// That will also be the result during the retry. Note that the error
// will not be returned now, but when the batch is executed.
if _, err = tx.ExecContext(ctx, testutil.UpdateSingersSetLastName); err != nil {
t.Fatalf("dml statement failed: %v", err)
}
// Note that even though Spanner returns the row count for a Batch DML that
// fails halfway, go/sql does not do that, so result will be nil for batch
// statements that fail. Internally, the driver still keeps track of the row
// counts that were returned, and uses that in the retry strategy.
if _, err := tx.ExecContext(ctx, "RUN BATCH"); spanner.ErrCode(err) != codes.NotFound {
t.Fatalf("error code mismatch\nGot: %v\nWant: %v", spanner.ErrCode(err), codes.NotFound)
}
// Abort the transaction. The internal retry should succeed as teh same error
// and the same row count is returned during the retry.
server.TestSpanner.PutExecutionTime(testutil.MethodCommitTransaction, testutil.SimulatedExecutionTime{
Errors: []error{status.Error(codes.Aborted, "Aborted")},
})
err = tx.Commit()
if err != nil {
t.Fatalf("commit failed: %v", err)
}
reqs := drainRequestsFromServer(server.TestSpanner)
execReqs := requestsOfType(reqs, reflect.TypeOf(&sppb.ExecuteBatchDmlRequest{}))
if g, w := len(execReqs), 2; g != w {
t.Fatalf("batch request count mismatch\nGot: %v\nWant: %v", g, w)
}
commitReqs := requestsOfType(reqs, reflect.TypeOf(&sppb.CommitRequest{}))
if g, w := len(commitReqs), 2; g != w {
t.Fatalf("commit request count mismatch\nGot: %v\nWant: %v", g, w)
}
}
func TestBatchUpdateAbortedWithError_DifferentRowCountDuringRetry(t *testing.T) {
t.Parallel()
db, server, teardown := setupTestDBConnection(t)
defer teardown()
// Make sure that one of the DML statements will return an error.
server.TestSpanner.PutStatementResult(testutil.UpdateSingersSetLastName, &testutil.StatementResult{
Type: testutil.StatementResultError,
Err: status.Error(codes.NotFound, "Table not found"),
})
ctx := context.Background()
tx, err := db.BeginTx(ctx, &sql.TxOptions{})
if err != nil {
t.Fatalf("begin failed: %v", err)
}
if _, err := tx.ExecContext(ctx, "START BATCH DML"); err != nil {
t.Fatalf("failed to start batch: %v", err)
}
if _, err := tx.ExecContext(ctx, testutil.UpdateBarSetFoo); err != nil {
t.Fatalf("dml statement failed: %v", err)
}
// This statement should fail with NotFound when the batch is executed.
// That will also be the result during the retry. Note that the error
// will not be returned now, but when the batch is executed.
if _, err = tx.ExecContext(ctx, testutil.UpdateSingersSetLastName); err != nil {
t.Fatalf("dml statement failed: %v", err)
}
if _, err := tx.ExecContext(ctx, "RUN BATCH"); spanner.ErrCode(err) != codes.NotFound {
t.Fatalf("error code mismatch\nGot: %v\nWant: %v", spanner.ErrCode(err), codes.NotFound)
}
// Change the returned row count of the first DML statement. This will cause
// the retry to fail.
server.TestSpanner.PutStatementResult(testutil.UpdateBarSetFoo, &testutil.StatementResult{
Type: testutil.StatementResultUpdateCount,
UpdateCount: testutil.UpdateBarSetFooRowCount + 1,
})
server.TestSpanner.PutExecutionTime(testutil.MethodCommitTransaction, testutil.SimulatedExecutionTime{
Errors: []error{status.Error(codes.Aborted, "Aborted")},
})
err = tx.Commit()
if err != ErrAbortedDueToConcurrentModification {
t.Fatalf("commit error mismatch\nGot: %v\nWant: %v", err, ErrAbortedDueToConcurrentModification)
}
reqs := drainRequestsFromServer(server.TestSpanner)
execReqs := requestsOfType(reqs, reflect.TypeOf(&sppb.ExecuteBatchDmlRequest{}))
if g, w := len(execReqs), 2; g != w {
t.Fatalf("batch request count mismatch\nGot: %v\nWant: %v", g, w)
}
commitReqs := requestsOfType(reqs, reflect.TypeOf(&sppb.CommitRequest{}))
// The commit should be attempted only once.
if g, w := len(commitReqs), 1; g != w {
t.Fatalf("commit request count mismatch\nGot: %v\nWant: %v", g, w)
}
}
func TestBatchUpdateAbortedWithError_DifferentErrorDuringRetry(t *testing.T) {
t.Parallel()
db, server, teardown := setupTestDBConnection(t)
defer teardown()
// Make sure that one of the DML statements will return an error.
server.TestSpanner.PutStatementResult(testutil.UpdateSingersSetLastName, &testutil.StatementResult{
Type: testutil.StatementResultError,
Err: status.Error(codes.NotFound, "Table not found"),
})
ctx := context.Background()
tx, err := db.BeginTx(ctx, &sql.TxOptions{})
if err != nil {
t.Fatalf("begin failed: %v", err)
}
if _, err := tx.ExecContext(ctx, "START BATCH DML"); err != nil {
t.Fatalf("failed to start batch: %v", err)
}
if _, err = tx.ExecContext(ctx, testutil.UpdateSingersSetLastName); err != nil {
t.Fatalf("dml statement failed: %v", err)
}
if _, err := tx.ExecContext(ctx, "RUN BATCH"); spanner.ErrCode(err) != codes.NotFound {
t.Fatalf("error code mismatch\nGot: %v\nWant: %v", spanner.ErrCode(err), codes.NotFound)
}
// Remove the error for the DML statement and cause a retry. The missing
// error for the DML statement should fail the retry.
server.TestSpanner.PutStatementResult(testutil.UpdateSingersSetLastName, &testutil.StatementResult{
Type: testutil.StatementResultUpdateCount,
UpdateCount: testutil.UpdateSingersSetLastNameRowCount,
})
server.TestSpanner.PutExecutionTime(testutil.MethodCommitTransaction, testutil.SimulatedExecutionTime{
Errors: []error{status.Error(codes.Aborted, "Aborted")},
})
err = tx.Commit()
if err != ErrAbortedDueToConcurrentModification {
t.Fatalf("commit error mismatch\nGot: %v\nWant: %v", err, ErrAbortedDueToConcurrentModification)
}
reqs := drainRequestsFromServer(server.TestSpanner)
execReqs := requestsOfType(reqs, reflect.TypeOf(&sppb.ExecuteBatchDmlRequest{}))
if g, w := len(execReqs), 2; g != w {
t.Fatalf("batch request count mismatch\nGot: %v\nWant: %v", g, w)
}
commitReqs := requestsOfType(reqs, reflect.TypeOf(&sppb.CommitRequest{}))
// The commit should be attempted only once.
if g, w := len(commitReqs), 1; g != w {
t.Fatalf("commit request count mismatch\nGot: %v\nWant: %v", g, w)
}
}
func firstNonZero(values ...int) int {
for _, v := range values {
if v > 0 {
return v
}
}
return 0
}