forked from pingcap/tidb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtxn_context_test.go
830 lines (695 loc) · 28.3 KB
/
txn_context_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
// Copyright 2021 PingCAP, Inc.
//
// 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 sessiontxn_test
import (
"context"
"fmt"
"strings"
"testing"
"time"
"github.com/pingcap/failpoint"
"github.com/pingcap/tidb/domain"
"github.com/pingcap/tidb/kv"
"github.com/pingcap/tidb/parser/ast"
"github.com/pingcap/tidb/planner/core"
"github.com/pingcap/tidb/sessionctx"
"github.com/pingcap/tidb/sessiontxn"
"github.com/pingcap/tidb/testkit"
"github.com/pingcap/tidb/testkit/testsetup"
"github.com/stretchr/testify/require"
"go.uber.org/goleak"
)
func TestMain(m *testing.M) {
testsetup.SetupForCommonTest()
opts := []goleak.Option{
goleak.IgnoreTopFunction("github.com/golang/glog.(*loggingT).flushDaemon"),
goleak.IgnoreTopFunction("go.etcd.io/etcd/client/pkg/v3/logutil.(*MergeLogger).outputLoop"),
goleak.IgnoreTopFunction("go.opencensus.io/stats/view.(*worker).start"),
}
goleak.VerifyTestMain(m, opts...)
}
func setupTxnContextTest(t *testing.T) (kv.Storage, *domain.Domain, func()) {
require.NoError(t, failpoint.Enable("github.com/pingcap/tidb/executor/assertTxnManagerInCompile", "return"))
require.NoError(t, failpoint.Enable("github.com/pingcap/tidb/executor/assertTxnManagerInRebuildPlan", "return"))
require.NoError(t, failpoint.Enable("github.com/pingcap/tidb/executor/assertTxnManagerAfterBuildExecutor", "return"))
require.NoError(t, failpoint.Enable("github.com/pingcap/tidb/executor/assertTxnManagerAfterPessimisticLockErrorRetry", "return"))
require.NoError(t, failpoint.Enable("github.com/pingcap/tidb/executor/assertTxnManagerInShortPointGetPlan", "return"))
require.NoError(t, failpoint.Enable("github.com/pingcap/tidb/executor/assertStaleReadValuesSameWithExecuteAndBuilder", "return"))
require.NoError(t, failpoint.Enable("github.com/pingcap/tidb/executor/assertNotStaleReadForExecutorGetReadTS", "return"))
require.NoError(t, failpoint.Enable("github.com/pingcap/tidb/executor/hookBeforeFirstRunExecutor", "return"))
require.NoError(t, failpoint.Enable("github.com/pingcap/tidb/executor/hookAfterOnStmtRetryWithLockError", "return"))
require.NoError(t, failpoint.Enable("github.com/pingcap/tidb/session/assertTxnManagerInRunStmt", "return"))
require.NoError(t, failpoint.Enable("github.com/pingcap/tidb/session/assertTxnManagerInPreparedStmtExec", "return"))
require.NoError(t, failpoint.Enable("github.com/pingcap/tidb/session/assertTxnManagerInCachedPlanExec", "return"))
require.NoError(t, failpoint.Enable("github.com/pingcap/tidb/session/assertTxnManagerForUpdateTSEqual", "return"))
require.NoError(t, failpoint.Enable("github.com/pingcap/tidb/planner/core/assertStaleReadForOptimizePreparedPlan", "return"))
store, do, clean := testkit.CreateMockStoreAndDomain(t)
tk := testkit.NewTestKit(t, store)
tk.Session().SetValue(sessiontxn.AssertRecordsKey, nil)
tk.Session().SetValue(sessiontxn.AssertTxnInfoSchemaKey, nil)
tk.MustExec("use test")
tk.MustExec("drop table if exists t1,t2")
tk.MustExec("create table t1 (id int primary key, v int)")
tk.MustExec("insert into t1 values(1, 10)")
tk.MustExec("create table t2 (id int)")
tk.MustExec("create temporary table tmp (id int)")
tk.MustExec("insert into tmp values(10)")
return store, do, func() {
require.NoError(t, failpoint.Disable("github.com/pingcap/tidb/executor/assertTxnManagerInCompile"))
require.NoError(t, failpoint.Disable("github.com/pingcap/tidb/executor/assertTxnManagerInRebuildPlan"))
require.NoError(t, failpoint.Disable("github.com/pingcap/tidb/executor/assertTxnManagerAfterBuildExecutor"))
require.NoError(t, failpoint.Disable("github.com/pingcap/tidb/executor/assertTxnManagerAfterPessimisticLockErrorRetry"))
require.NoError(t, failpoint.Disable("github.com/pingcap/tidb/executor/assertTxnManagerInShortPointGetPlan"))
require.NoError(t, failpoint.Disable("github.com/pingcap/tidb/executor/assertStaleReadValuesSameWithExecuteAndBuilder"))
require.NoError(t, failpoint.Disable("github.com/pingcap/tidb/executor/assertNotStaleReadForExecutorGetReadTS"))
require.NoError(t, failpoint.Disable("github.com/pingcap/tidb/executor/hookBeforeFirstRunExecutor"))
require.NoError(t, failpoint.Disable("github.com/pingcap/tidb/executor/hookAfterOnStmtRetryWithLockError"))
require.NoError(t, failpoint.Disable("github.com/pingcap/tidb/session/assertTxnManagerInRunStmt"))
require.NoError(t, failpoint.Disable("github.com/pingcap/tidb/session/assertTxnManagerInPreparedStmtExec"))
require.NoError(t, failpoint.Disable("github.com/pingcap/tidb/session/assertTxnManagerInCachedPlanExec"))
require.NoError(t, failpoint.Disable("github.com/pingcap/tidb/session/assertTxnManagerForUpdateTSEqual"))
require.NoError(t, failpoint.Disable("github.com/pingcap/tidb/planner/core/assertStaleReadForOptimizePreparedPlan"))
tk.Session().SetValue(sessiontxn.AssertRecordsKey, nil)
tk.Session().SetValue(sessiontxn.AssertTxnInfoSchemaKey, nil)
tk.Session().SetValue(sessiontxn.AssertTxnInfoSchemaAfterRetryKey, nil)
clean()
}
}
func checkAssertRecordExits(t *testing.T, se sessionctx.Context, name string) {
records, ok := se.Value(sessiontxn.AssertRecordsKey).(map[string]interface{})
require.True(t, ok, fmt.Sprintf("'%s' not in record, maybe failpoint not enabled?", name))
_, ok = records[name]
require.True(t, ok, fmt.Sprintf("'%s' not in record", name))
}
func doWithCheckPath(t *testing.T, se sessionctx.Context, names []string, do func()) {
se.SetValue(sessiontxn.AssertRecordsKey, nil)
do()
for _, name := range names {
checkAssertRecordExits(t, se, name)
}
}
var normalPathRecords = []string{
"assertTxnManagerInCompile",
"assertTxnManagerInRunStmt",
"assertTxnManagerAfterBuildExecutor",
}
func TestTxnContextForSimpleCases(t *testing.T) {
store, do, deferFunc := setupTxnContextTest(t)
defer deferFunc()
tk := testkit.NewTestKit(t, store)
tk.MustExec("use test")
se := tk.Session()
tk2 := testkit.NewTestKit(t, store)
tk2.MustExec("use test")
is1 := do.InfoSchema()
se.SetValue(sessiontxn.AssertTxnInfoSchemaKey, is1)
// test for write
doWithCheckPath(t, se, normalPathRecords, func() {
tk.MustExec("insert into t2 (id) values(3)")
})
// test for select
doWithCheckPath(t, se, normalPathRecords, func() {
tk.MustQuery("select * from t1 where id=1").Check(testkit.Rows("1 10"))
})
// test for select for update
doWithCheckPath(t, se, normalPathRecords, func() {
tk.MustQuery("select * from t1 where id=1 for update").Check(testkit.Rows("1 10"))
})
tk2.MustExec("alter table t2 add column(c1 int)")
is2 := do.InfoSchema()
require.True(t, is2.SchemaMetaVersion() > is1.SchemaMetaVersion())
se.SetValue(sessiontxn.AssertTxnInfoSchemaKey, is2)
doWithCheckPath(t, se, normalPathRecords, func() {
tk.MustQuery("select * from t1 where id=1").Check(testkit.Rows("1 10"))
})
}
func TestTxnContextInExplicitTxn(t *testing.T) {
store, do, deferFunc := setupTxnContextTest(t)
defer deferFunc()
tk := testkit.NewTestKit(t, store)
tk.MustExec("use test")
se := tk.Session()
tk2 := testkit.NewTestKit(t, store)
tk2.MustExec("use test")
is1 := do.InfoSchema()
se.SetValue(sessiontxn.AssertTxnInfoSchemaKey, is1)
tk.MustExec("begin")
// test for write
doWithCheckPath(t, se, normalPathRecords, func() {
tk.MustExec("insert into t2 (id) values(2)")
})
// test for select
doWithCheckPath(t, se, normalPathRecords, func() {
tk.MustQuery("select * from t1 where id=1").Check(testkit.Rows("1 10"))
})
// test for select for update
doWithCheckPath(t, se, normalPathRecords, func() {
tk.MustQuery("select * from t1 where id=1 for update").Check(testkit.Rows("1 10"))
})
// info schema changed when txn not finish, the info schema in old txn should not change
tk2.MustExec("alter table t2 add column(c1 int)")
is2 := do.InfoSchema()
require.True(t, is2.SchemaMetaVersion() > is1.SchemaMetaVersion())
// test for write
doWithCheckPath(t, se, normalPathRecords, func() {
tk.MustExec("insert into t2 (id) values(2)")
})
// test for select
doWithCheckPath(t, se, normalPathRecords, func() {
tk.MustQuery("select * from t1 where id=1").Check(testkit.Rows("1 10"))
})
// test for select for update
doWithCheckPath(t, se, normalPathRecords, func() {
tk.MustQuery("select * from t1 where id=1 for update").Check(testkit.Rows("1 10"))
})
doWithCheckPath(t, se, normalPathRecords, func() {
tk.MustExec("commit")
})
// the info schema in new txn should use the newest one
se.SetValue(sessiontxn.AssertTxnInfoSchemaKey, is2)
tk.MustExec("begin")
// test for write
doWithCheckPath(t, se, normalPathRecords, func() {
tk.MustExec("insert into t2 (id) values(2)")
})
// test for select
doWithCheckPath(t, se, normalPathRecords, func() {
tk.MustQuery("select * from t1 where id=1").Check(testkit.Rows("1 10"))
})
// test for select for update
doWithCheckPath(t, se, normalPathRecords, func() {
tk.MustQuery("select * from t1 where id=1 for update").Check(testkit.Rows("1 10"))
})
}
func TestTxnContextBeginInUnfinishedTxn(t *testing.T) {
store, do, deferFunc := setupTxnContextTest(t)
defer deferFunc()
tk := testkit.NewTestKit(t, store)
tk.MustExec("use test")
se := tk.Session()
tk2 := testkit.NewTestKit(t, store)
tk2.MustExec("use test")
is1 := do.InfoSchema()
se.SetValue(sessiontxn.AssertTxnInfoSchemaKey, is1)
tk.MustExec("begin")
doWithCheckPath(t, se, normalPathRecords, func() {
tk.MustQuery("select * from t1 where id=1").Check(testkit.Rows("1 10"))
})
tk2.MustExec("alter table t2 add column(c1 int)")
is2 := do.InfoSchema()
require.True(t, is2.SchemaMetaVersion() > is1.SchemaMetaVersion())
doWithCheckPath(t, se, normalPathRecords, func() {
tk.MustQuery("select * from t1 where id=1").Check(testkit.Rows("1 10"))
})
tk.MustExec("begin")
se.SetValue(sessiontxn.AssertTxnInfoSchemaKey, is2)
doWithCheckPath(t, se, normalPathRecords, func() {
tk.MustQuery("select * from t1 where id=1").Check(testkit.Rows("1 10"))
})
tk.MustExec("rollback")
}
func TestTxnContextWithAutocommitFalse(t *testing.T) {
store, do, deferFunc := setupTxnContextTest(t)
defer deferFunc()
tk := testkit.NewTestKit(t, store)
tk.MustExec("use test")
se := tk.Session()
tk2 := testkit.NewTestKit(t, store)
tk2.MustExec("use test")
is1 := do.InfoSchema()
se.SetValue(sessiontxn.AssertTxnInfoSchemaKey, is1)
tk.MustExec("begin")
tk.MustExec("set autocommit=0")
se.SetValue(sessiontxn.AssertTxnInfoSchemaKey, do.InfoSchema())
// test for write
doWithCheckPath(t, se, normalPathRecords, func() {
tk.MustExec("insert into t2 (id) values(2)")
})
// schema change should not affect because it is in txn
tk2.MustExec("alter table t2 add column(c1 int)")
// test for select
doWithCheckPath(t, se, normalPathRecords, func() {
tk.MustQuery("select * from t1 where id=1").Check(testkit.Rows("1 10"))
})
// test for select for update
doWithCheckPath(t, se, normalPathRecords, func() {
tk.MustQuery("select * from t1 where id=1 for update").Check(testkit.Rows("1 10"))
})
tk.MustExec("rollback")
}
func TestTxnContextInRC(t *testing.T) {
store, do, deferFunc := setupTxnContextTest(t)
defer deferFunc()
tk := testkit.NewTestKit(t, store)
tk.MustExec("use test")
se := tk.Session()
tk2 := testkit.NewTestKit(t, store)
tk2.MustExec("use test")
is1 := do.InfoSchema()
tk.MustExec("set tx_isolation = 'READ-COMMITTED'")
se.SetValue(sessiontxn.AssertTxnInfoSchemaKey, is1)
doWithCheckPath(t, se, normalPathRecords, func() {
tk.MustQuery("select * from t1 where id=1").Check(testkit.Rows("1 10"))
})
tk.MustExec("begin pessimistic")
// schema change should not affect even in rc isolation
se.SetValue(sessiontxn.AssertTxnInfoSchemaKey, nil)
tk2.MustExec("alter table t2 add column(c1 int)")
se.SetValue(sessiontxn.AssertTxnInfoSchemaKey, is1)
// test for write
doWithCheckPath(t, se, normalPathRecords, func() {
tk.MustExec("insert into t2 (id) values(2)")
})
// test for select
doWithCheckPath(t, se, normalPathRecords, func() {
tk.MustQuery("select * from t1 where id=1").Check(testkit.Rows("1 10"))
})
tk2.MustExec("update t1 set v=11 where id=1")
// test for select
doWithCheckPath(t, se, normalPathRecords, func() {
tk.MustQuery("select * from t1 where id=1").Check(testkit.Rows("1 11"))
})
// test for select for update
doWithCheckPath(t, se, normalPathRecords, func() {
tk.MustQuery("select * from t1 where id=1 for update").Check(testkit.Rows("1 11"))
})
tk.MustExec("rollback")
}
func TestTxnContextInPessimisticKeyConflict(t *testing.T) {
store, do, deferFunc := setupTxnContextTest(t)
defer deferFunc()
tk := testkit.NewTestKit(t, store)
tk.MustExec("use test")
se := tk.Session()
is1 := do.InfoSchema()
tk.MustExec("begin pessimistic")
// trigger retry
tk2 := testkit.NewTestKit(t, store)
tk2.MustExec("use test")
tk2.MustExec("update t1 set v=11 where id=1")
tk2.MustExec("alter table t2 add column(c1 int)")
se.SetValue(sessiontxn.AssertTxnInfoSchemaKey, is1)
path := append([]string{"assertTxnManagerAfterPessimisticLockErrorRetry"}, normalPathRecords...)
doWithCheckPath(t, se, path, func() {
tk.MustExec("update t1 set v=12 where id=1")
})
tk.MustExec("rollback")
}
func TestTxnContextInOptimisticRetry(t *testing.T) {
store, do, deferFunc := setupTxnContextTest(t)
defer deferFunc()
tk := testkit.NewTestKit(t, store)
tk.MustExec("use test")
tk.MustExec("set @@tidb_disable_txn_auto_retry=0")
se := tk.Session()
is1 := do.InfoSchema()
tk.MustExec("begin optimistic")
// trigger retry
tk2 := testkit.NewTestKit(t, store)
tk2.MustExec("use test")
tk2.MustExec("update t1 set v=11 where id=1")
tk2.MustExec("alter table t2 add column(c1 int)")
tk.MustExec("update t1 set v=12 where id=1")
// check retry context
path := append([]string{"assertTxnManagerInRebuildPlan"}, normalPathRecords...)
se.SetValue(sessiontxn.AssertTxnInfoSchemaKey, is1)
se.SetValue(sessiontxn.AssertTxnInfoSchemaAfterRetryKey, do.InfoSchema())
doWithCheckPath(t, se, path, func() {
tk.MustExec("commit")
})
tk.MustQuery("select * from t1 where id=1").Check(testkit.Rows("1 12"))
}
func TestTxnContextForHistoricalRead(t *testing.T) {
store, do, deferFunc := setupTxnContextTest(t)
defer deferFunc()
tk := testkit.NewTestKit(t, store)
tk.MustExec("use test")
se := tk.Session()
safePoint := "20160102-15:04:05 -0700"
tk.MustExec(fmt.Sprintf(`INSERT INTO mysql.tidb VALUES ('tikv_gc_safe_point', '%s', '') ON DUPLICATE KEY UPDATE variable_value = '%s', comment=''`, safePoint, safePoint))
is1 := do.InfoSchema()
tk.MustExec("do sleep(0.1)")
tk.MustExec("set @a=now(6)")
// change schema
tk.MustExec("alter table t2 add column(c1 int)")
tk.MustExec("update t1 set v=11 where id=1")
tk.MustExec("set @@tidb_snapshot=@a")
se.SetValue(sessiontxn.AssertTxnInfoSchemaKey, is1)
doWithCheckPath(t, se, normalPathRecords, func() {
tk.MustQuery("select * from t1 where id=1").Check(testkit.Rows("1 10"))
})
doWithCheckPath(t, se, normalPathRecords, func() {
tk.MustQuery("select * from t1 where id=1 for update").Check(testkit.Rows("1 10"))
})
se.SetValue(sessiontxn.AssertTxnInfoSchemaKey, nil)
tk.MustExec("set @@tidb_snapshot=''")
tk.MustExec("begin")
se.SetValue(sessiontxn.AssertTxnInfoSchemaKey, do.InfoSchema())
doWithCheckPath(t, se, normalPathRecords, func() {
tk.MustQuery("select * from t1 where id=1").Check(testkit.Rows("1 11"))
})
doWithCheckPath(t, se, normalPathRecords, func() {
tk.MustQuery("select * from t1 where id=1 for update").Check(testkit.Rows("1 11"))
})
se.SetValue(sessiontxn.AssertTxnInfoSchemaKey, nil)
tk.MustExec("set @@tidb_snapshot=@a")
se.SetValue(sessiontxn.AssertTxnInfoSchemaKey, is1)
doWithCheckPath(t, se, normalPathRecords, func() {
tk.MustQuery("select * from t1 where id=1").Check(testkit.Rows("1 10"))
})
doWithCheckPath(t, se, normalPathRecords, func() {
tk.MustQuery("select * from t1 where id=1 for update").Check(testkit.Rows("1 11"))
})
tk.MustExec("rollback")
}
func TestTxnContextForStaleRead(t *testing.T) {
store, do, deferFunc := setupTxnContextTest(t)
defer deferFunc()
tk := testkit.NewTestKit(t, store)
tk.MustExec("use test")
se := tk.Session()
safePoint := "20160102-15:04:05 -0700"
tk.MustExec(fmt.Sprintf(`INSERT INTO mysql.tidb VALUES ('tikv_gc_safe_point', '%s', '') ON DUPLICATE KEY UPDATE variable_value = '%s', comment=''`, safePoint, safePoint))
is1 := do.InfoSchema()
tk.MustExec("do sleep(0.1)")
tk.MustExec("set @a=now(6)")
time.Sleep(time.Millisecond * 1200)
// change schema
tk.MustExec("alter table t2 add column(c1 int)")
tk.MustExec("update t1 set v=11 where id=1")
// @@tidb_read_staleness
tk.MustExec("set @@tidb_read_staleness=-1")
se.SetValue(sessiontxn.AssertTxnInfoSchemaKey, is1)
doWithCheckPath(t, se, normalPathRecords, func() {
tk.MustQuery("select * from t1 as of timestamp @a").Check(testkit.Rows("1 10"))
})
se.SetValue(sessiontxn.AssertTxnInfoSchemaKey, nil)
tk.MustExec("set @@tidb_read_staleness=''")
// select ... as of ...
se.SetValue(sessiontxn.AssertTxnInfoSchemaKey, is1)
doWithCheckPath(t, se, normalPathRecords, func() {
tk.MustQuery("select * from t1 as of timestamp @a").Check(testkit.Rows("1 10"))
})
// @@tx_read_ts
se.SetValue(sessiontxn.AssertTxnInfoSchemaKey, nil)
tk.MustExec("set @@tx_read_ts=@a")
se.SetValue(sessiontxn.AssertTxnInfoSchemaKey, is1)
doWithCheckPath(t, se, normalPathRecords, func() {
tk.MustQuery("select * from t1 where id=1").Check(testkit.Rows("1 10"))
})
se.SetValue(sessiontxn.AssertTxnInfoSchemaKey, do.InfoSchema())
doWithCheckPath(t, se, normalPathRecords, func() {
tk.MustQuery("select * from t1 where id=1").Check(testkit.Rows("1 11"))
})
// txn begin with @tx_read_ts
se.SetValue(sessiontxn.AssertTxnInfoSchemaKey, nil)
tk.MustExec("set @@tx_read_ts=@a")
tk.MustExec("begin")
se.SetValue(sessiontxn.AssertTxnInfoSchemaKey, is1)
doWithCheckPath(t, se, normalPathRecords, func() {
tk.MustQuery("select * from t1 where id=1").Check(testkit.Rows("1 10"))
})
tk.MustExec("rollback")
se.SetValue(sessiontxn.AssertTxnInfoSchemaKey, do.InfoSchema())
doWithCheckPath(t, se, normalPathRecords, func() {
tk.MustQuery("select * from t1 where id=1").Check(testkit.Rows("1 11"))
})
// txn begin ... as of ...
se.SetValue(sessiontxn.AssertTxnInfoSchemaKey, nil)
tk.MustExec("start transaction read only as of timestamp @a")
se.SetValue(sessiontxn.AssertTxnInfoSchemaKey, is1)
doWithCheckPath(t, se, normalPathRecords, func() {
tk.MustQuery("select * from t1 where id=1").Check(testkit.Rows("1 10"))
})
tk.MustExec("rollback")
se.SetValue(sessiontxn.AssertTxnInfoSchemaKey, do.InfoSchema())
doWithCheckPath(t, se, normalPathRecords, func() {
tk.MustQuery("select * from t1 where id=1").Check(testkit.Rows("1 11"))
})
}
func TestTxnContextForPrepareExecute(t *testing.T) {
store, do, deferFunc := setupTxnContextTest(t)
defer deferFunc()
orgEnable := core.PreparedPlanCacheEnabled()
defer core.SetPreparedPlanCache(orgEnable)
core.SetPreparedPlanCache(true)
tk := testkit.NewTestKit(t, store)
tk.MustExec("use test")
se := tk.Session()
stmtID, _, _, err := se.PrepareStmt("select * from t1 where id=1")
require.NoError(t, err)
is1 := do.InfoSchema()
se.SetValue(sessiontxn.AssertTxnInfoSchemaKey, is1)
// Test prepare/execute in SQL
doWithCheckPath(t, se, normalPathRecords, func() {
tk.MustExec("prepare s from 'select * from t1 where id=1'")
})
doWithCheckPath(t, se, normalPathRecords, func() {
tk.MustQuery("execute s").Check(testkit.Rows("1 10"))
})
// Test ExecutePreparedStmt
path := append([]string{"assertTxnManagerInPreparedStmtExec"}, normalPathRecords...)
doWithCheckPath(t, se, path, func() {
rs, err := se.ExecutePreparedStmt(context.TODO(), stmtID, nil)
require.NoError(t, err)
tk.ResultSetToResult(rs, fmt.Sprintf("%v", rs)).Check(testkit.Rows("1 10"))
})
// Test PlanCache
doWithCheckPath(t, se, nil, func() {
rs, err := se.ExecutePreparedStmt(context.TODO(), stmtID, nil)
require.NoError(t, err)
tk.ResultSetToResult(rs, fmt.Sprintf("%v", rs)).Check(testkit.Rows("1 10"))
})
// In txn
se.SetValue(sessiontxn.AssertTxnInfoSchemaKey, nil)
tk.MustExec("begin")
//change schema
tk2 := testkit.NewTestKit(t, store)
tk2.MustExec("use test")
tk2.MustExec("alter table t2 add column(c1 int)")
tk2.MustExec("update t1 set v=11 where id=1")
se.SetValue(sessiontxn.AssertTxnInfoSchemaKey, is1)
doWithCheckPath(t, se, normalPathRecords, func() {
tk.MustExec("prepare s from 'select * from t1 where id=1'")
})
doWithCheckPath(t, se, normalPathRecords, func() {
tk.MustQuery("execute s").Check(testkit.Rows("1 10"))
})
path = append([]string{"assertTxnManagerInPreparedStmtExec"}, normalPathRecords...)
doWithCheckPath(t, se, path, func() {
rs, err := se.ExecutePreparedStmt(context.TODO(), stmtID, nil)
require.NoError(t, err)
tk.ResultSetToResult(rs, fmt.Sprintf("%v", rs)).Check(testkit.Rows("1 10"))
})
tk.MustExec("rollback")
}
func TestTxnContextForStaleReadInPrepare(t *testing.T) {
store, do, deferFunc := setupTxnContextTest(t)
defer deferFunc()
tk := testkit.NewTestKit(t, store)
tk.MustExec("use test")
se := tk.Session()
is1 := do.InfoSchema()
tk.MustExec("do sleep(0.1)")
tk.MustExec("set @a=now(6)")
tk.MustExec("prepare s1 from 'select * from t1 where id=1'")
tk.MustExec("prepare s2 from 'select * from t1 as of timestamp @a where id=1 '")
stmtID1, _, _, err := se.PrepareStmt("select * from t1 where id=1")
require.NoError(t, err)
stmtID2, _, _, err := se.PrepareStmt("select * from t1 as of timestamp @a where id=1 ")
require.NoError(t, err)
//change schema
tk.MustExec("use test")
tk.MustExec("alter table t2 add column(c1 int)")
tk.MustExec("update t1 set v=11 where id=1")
tk.MustExec("set @@tx_read_ts=@a")
stmtID3, _, _, err := se.PrepareStmt("select * from t1 where id=1 ")
require.NoError(t, err)
tk.MustExec("set @@tx_read_ts=''")
tk.MustExec("set @@tx_read_ts=@a")
tk.MustExec("prepare s3 from 'select * from t1 where id=1 '")
tk.MustExec("set @@tx_read_ts=''")
// tx_read_ts
tk.MustExec("set @@tx_read_ts=@a")
se.SetValue(sessiontxn.AssertTxnInfoSchemaKey, is1)
path := append([]string{"assertTxnManagerInPreparedStmtExec"}, normalPathRecords...)
doWithCheckPath(t, se, path, func() {
rs, err := se.ExecutePreparedStmt(context.TODO(), stmtID1, nil)
require.NoError(t, err)
tk.ResultSetToResult(rs, fmt.Sprintf("%v", rs)).Check(testkit.Rows("1 10"))
})
se.SetValue(sessiontxn.AssertTxnInfoSchemaKey, nil)
tk.MustExec("set @@tx_read_ts=''")
tk.MustExec("set @@tx_read_ts=@a")
se.SetValue(sessiontxn.AssertTxnInfoSchemaKey, is1)
doWithCheckPath(t, se, normalPathRecords, func() {
tk.MustExec("execute s1")
})
se.SetValue(sessiontxn.AssertTxnInfoSchemaKey, nil)
tk.MustExec("set @@tx_read_ts=''")
// select ... as of ...
se.SetValue(sessiontxn.AssertTxnInfoSchemaKey, is1)
doWithCheckPath(t, se, path, func() {
rs, err := se.ExecutePreparedStmt(context.TODO(), stmtID2, nil)
require.NoError(t, err)
tk.ResultSetToResult(rs, fmt.Sprintf("%v", rs)).Check(testkit.Rows("1 10"))
})
doWithCheckPath(t, se, normalPathRecords, func() {
tk.MustExec("execute s2")
})
// tx_read_ts in prepare
se.SetValue(sessiontxn.AssertTxnInfoSchemaKey, is1)
doWithCheckPath(t, se, path, func() {
rs, err := se.ExecutePreparedStmt(context.TODO(), stmtID3, nil)
require.NoError(t, err)
tk.ResultSetToResult(rs, fmt.Sprintf("%v", rs)).Check(testkit.Rows("1 10"))
})
doWithCheckPath(t, se, normalPathRecords, func() {
tk.MustExec("execute s3")
})
}
func TestTxnContextPreparedStmtWithForUpdate(t *testing.T) {
store, do, deferFunc := setupTxnContextTest(t)
defer deferFunc()
tk := testkit.NewTestKit(t, store)
tk.MustExec("use test")
se := tk.Session()
is1 := do.InfoSchema()
stmtID1, _, _, err := se.PrepareStmt("select * from t1 where id=1 for update")
require.NoError(t, err)
tk.MustExec("prepare s from 'select * from t1 where id=1 for update'")
tk.MustExec("begin pessimistic")
//change schema
tk2 := testkit.NewTestKit(t, store)
tk2.MustExec("use test")
tk2.MustExec("alter table t1 add column(c int default 100)")
tk2.MustExec("update t1 set v=11 where id=1")
se.SetValue(sessiontxn.AssertTxnInfoSchemaKey, is1)
doWithCheckPath(t, se, normalPathRecords, func() {
tk.MustQuery("select * from t1 where id=1 for update").Check(testkit.Rows("1 11"))
})
path := append([]string{"assertTxnManagerInPreparedStmtExec"}, normalPathRecords...)
doWithCheckPath(t, se, path, func() {
rs, err := se.ExecutePreparedStmt(context.TODO(), stmtID1, nil)
require.NoError(t, err)
tk.ResultSetToResult(rs, fmt.Sprintf("%v", rs)).Check(testkit.Rows("1 11"))
})
doWithCheckPath(t, se, normalPathRecords, func() {
tk.MustQuery("execute s").Check(testkit.Rows("1 11"))
})
se.SetValue(sessiontxn.AssertTxnInfoSchemaKey, nil)
tk.MustExec("rollback")
}
// See issue: https://github.com/pingcap/tidb/issues/35459
func TestStillWriteConflictAfterRetry(t *testing.T) {
store, _, deferFunc := setupTxnContextTest(t)
defer deferFunc()
queries := []string{
"select * from t1 for update",
"select * from t1 where id=1 for update",
"select * from t1 where id in (1, 2, 3) for update",
"select * from t1 where id=1 and v>0 for update",
"select * from t1 where id=1 for update union select * from t1 where id=1 for update",
"update t1 set v=v+1",
"update t1 set v=v+1 where id=1",
"update t1 set v=v+1 where id=1 and v>0",
"update t1 set v=v+1 where id in (1, 2, 3)",
"update t1 set v=v+1 where id in (1, 2, 3) and v>0",
}
for _, isolation := range []string{ast.RepeatableRead, ast.ReadCommitted} {
for _, query := range queries {
for _, autocommit := range []bool{true, false} {
t.Run(fmt.Sprintf("%s,%s,autocommit=%v", isolation, query, autocommit), func(t *testing.T) {
testStillWriteConflictAfterRetry(t, store, isolation, query, autocommit)
})
}
}
}
}
func testStillWriteConflictAfterRetry(t *testing.T, store kv.Storage, isolation string, query string, autocommit bool) {
tk := testkit.NewTestKit(t, store)
defer tk.MustExec("rollback")
tk.MustExec("use test")
tk.MustExec(fmt.Sprintf("set tx_isolation = '%s'", isolation))
tk.MustExec("set autocommit=1")
tk.MustExec("set @@tidb_txn_mode = 'pessimistic'")
tk.MustExec("truncate table t1")
tk.MustExec("insert into t1 values(1, 10)")
se := tk.Session()
chanBeforeRunStmt := make(chan func(), 1)
chanAfterOnStmtRetry := make(chan func(), 1)
c2 := make(chan string, 1)
c3 := make(chan string, 1)
wait := func(ch chan string, expect string) {
select {
case got := <-ch:
if got != expect {
panic(fmt.Sprintf("expect '%s', got '%s'", expect, got))
}
case <-time.After(time.Second * 10):
panic("wait2 timeout")
}
}
if autocommit {
tk.MustExec("begin")
} else {
tk.MustExec("set @@autocommit=0")
}
se.SetValue(sessiontxn.HookBeforeFirstRunExecutorKey, chanBeforeRunStmt)
se.SetValue(sessiontxn.HookAfterOnStmtRetryWithLockErrorKey, chanAfterOnStmtRetry)
defer func() {
se.SetValue(sessiontxn.HookBeforeFirstRunExecutorKey, nil)
se.SetValue(sessiontxn.HookAfterOnStmtRetryWithLockErrorKey, nil)
}()
chanBeforeRunStmt <- func() {
c2 <- "now before session1 runStmt"
wait(c3, "session2 updated v=v+1 done")
}
chanAfterOnStmtRetry <- func() {
c2 <- "now after OnStmtRetry before rebuild executor"
wait(c3, "session2 updated v=v+1 again done")
}
go func() {
tk2 := testkit.NewTestKit(t, store)
tk2.MustExec("use test")
// first conflict
wait(c2, "now before session1 runStmt")
tk2.MustExec("update t1 set v=v+1 where id=1")
c3 <- "session2 updated v=v+1 done"
// second conflict
wait(c2, "now after OnStmtRetry before rebuild executor")
tk2.MustExec("update t1 set v=v+1 where id=1")
c3 <- "session2 updated v=v+1 again done"
chanAfterOnStmtRetry <- func() {}
c3 <- "done"
}()
isSelect := false
if strings.HasPrefix(query, "update ") {
tk.MustExec(query)
} else if strings.HasPrefix(query, "select ") {
isSelect = true
tk.MustQuery(query).Check(testkit.Rows("1 12"))
} else {
require.FailNowf(t, "invalid query: %s", query)
}
wait(c3, "done")
se.SetValue(sessiontxn.HookBeforeFirstRunExecutorKey, nil)
se.SetValue(sessiontxn.HookAfterOnStmtRetryWithLockErrorKey, nil)
if isSelect {
tk.MustExec("update t1 set v=v+1")
}
tk.MustExec("commit")
tk.MustQuery("select * from t1").Check(testkit.Rows("1 13"))
tk.MustExec("rollback")
}