forked from pingcap/tidb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsession_test.go
3292 lines (2814 loc) · 122 KB
/
session_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
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2015 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,
// See the License for the specific language governing permissions and
// limitations under the License.
package session_test
import (
"context"
"flag"
"fmt"
"os"
"path"
"strings"
"sync"
"sync/atomic"
"time"
. "github.com/pingcap/check"
"github.com/pingcap/errors"
"github.com/pingcap/failpoint"
"github.com/pingcap/parser"
"github.com/pingcap/parser/auth"
"github.com/pingcap/parser/model"
"github.com/pingcap/parser/mysql"
"github.com/pingcap/parser/terror"
"github.com/pingcap/tidb/config"
"github.com/pingcap/tidb/domain"
"github.com/pingcap/tidb/executor"
"github.com/pingcap/tidb/kv"
"github.com/pingcap/tidb/meta/autoid"
plannercore "github.com/pingcap/tidb/planner/core"
"github.com/pingcap/tidb/privilege/privileges"
"github.com/pingcap/tidb/session"
"github.com/pingcap/tidb/sessionctx"
"github.com/pingcap/tidb/sessionctx/binloginfo"
"github.com/pingcap/tidb/sessionctx/variable"
"github.com/pingcap/tidb/store/mockstore"
"github.com/pingcap/tidb/store/mockstore/cluster"
"github.com/pingcap/tidb/store/mockstore/mocktikv"
"github.com/pingcap/tidb/store/tikv"
"github.com/pingcap/tidb/table/tables"
"github.com/pingcap/tidb/types"
"github.com/pingcap/tidb/util/sqlexec"
"github.com/pingcap/tidb/util/testkit"
"github.com/pingcap/tidb/util/testleak"
"github.com/pingcap/tidb/util/testutil"
"github.com/pingcap/tipb/go-binlog"
"go.etcd.io/etcd/clientv3"
"google.golang.org/grpc"
)
var (
withTiKV = flag.Bool("with-tikv", false, "run tests with TiKV cluster started. (not use the mock server)")
pdAddrs = flag.String("pd-addrs", "127.0.0.1:2379", "pd addrs")
pdAddrChan chan string
initPdAddrsOnce sync.Once
)
var _ = Suite(&testSessionSuite{})
var _ = Suite(&testSessionSuite2{})
var _ = Suite(&testSessionSuite3{})
var _ = Suite(&testSchemaSuite{})
var _ = Suite(&testIsolationSuite{})
var _ = SerialSuites(&testSchemaSerialSuite{})
var _ = SerialSuites(&testSessionSerialSuite{})
var _ = SerialSuites(&testBackupRestoreSuite{})
type testSessionSuiteBase struct {
cluster cluster.Cluster
store kv.Storage
dom *domain.Domain
pdAddr string
}
type testSessionSuite struct {
testSessionSuiteBase
}
type testSessionSuite2 struct {
testSessionSuiteBase
}
type testSessionSuite3 struct {
testSessionSuiteBase
}
type testSessionSerialSuite struct {
testSessionSuiteBase
}
type testBackupRestoreSuite struct {
testSessionSuiteBase
}
func clearStorage(store kv.Storage) error {
txn, err := store.Begin()
if err != nil {
return errors.Trace(err)
}
iter, err := txn.Iter(nil, nil)
if err != nil {
return errors.Trace(err)
}
for iter.Valid() {
txn.Delete(iter.Key())
if err := iter.Next(); err != nil {
return errors.Trace(err)
}
}
return txn.Commit(context.Background())
}
func clearETCD(ebd tikv.EtcdBackend) error {
cli, err := clientv3.New(clientv3.Config{
Endpoints: ebd.EtcdAddrs(),
AutoSyncInterval: 30 * time.Second,
DialTimeout: 5 * time.Second,
DialOptions: []grpc.DialOption{
grpc.WithBackoffMaxDelay(time.Second * 3),
},
TLS: ebd.TLSConfig(),
})
if err != nil {
return errors.Trace(err)
}
defer cli.Close()
resp, err := cli.Get(context.Background(), "/tidb", clientv3.WithPrefix())
if err != nil {
return errors.Trace(err)
}
for _, kv := range resp.Kvs {
if kv.Lease != 0 {
if _, err := cli.Revoke(context.Background(), clientv3.LeaseID(kv.Lease)); err != nil {
return errors.Trace(err)
}
}
}
_, err = cli.Delete(context.Background(), "/tidb", clientv3.WithPrefix())
if err != nil {
return errors.Trace(err)
}
return nil
}
func initPdAddrs() {
initPdAddrsOnce.Do(func() {
addrs := strings.Split(*pdAddrs, ",")
pdAddrChan = make(chan string, len(addrs))
for _, addr := range addrs {
addr = strings.TrimSpace(addr)
if addr != "" {
pdAddrChan <- addr
}
}
})
}
func (s *testSessionSuiteBase) SetUpSuite(c *C) {
testleak.BeforeTest()
if *withTiKV {
initPdAddrs()
s.pdAddr = <-pdAddrChan
var d tikv.Driver
config.UpdateGlobal(func(conf *config.Config) {
conf.TxnLocalLatches.Enabled = false
})
store, err := d.Open(fmt.Sprintf("tikv://%s", s.pdAddr))
c.Assert(err, IsNil)
err = clearStorage(store)
c.Assert(err, IsNil)
err = clearETCD(store.(tikv.EtcdBackend))
c.Assert(err, IsNil)
session.ResetStoreForWithTiKVTest(store)
s.store = store
} else {
store, err := mockstore.NewMockStore(
mockstore.WithClusterInspector(func(c cluster.Cluster) {
mockstore.BootstrapWithSingleStore(c)
s.cluster = c
}),
)
c.Assert(err, IsNil)
s.store = store
session.DisableStats4Test()
}
var err error
s.dom, err = session.BootstrapSession(s.store)
c.Assert(err, IsNil)
s.dom.GetGlobalVarsCache().Disable()
}
func (s *testSessionSuiteBase) TearDownSuite(c *C) {
s.dom.Close()
s.store.Close()
testleak.AfterTest(c)()
if *withTiKV {
pdAddrChan <- s.pdAddr
}
}
func (s *testSessionSuiteBase) TearDownTest(c *C) {
tk := testkit.NewTestKitWithInit(c, s.store)
r := tk.MustQuery("show full tables")
for _, tb := range r.Rows() {
tableName := tb[0]
tableType := tb[1]
if tableType == "VIEW" {
tk.MustExec(fmt.Sprintf("drop view %v", tableName))
} else if tableType == "BASE TABLE" {
tk.MustExec(fmt.Sprintf("drop table %v", tableName))
} else {
panic(fmt.Sprintf("Unexpected table '%s' with type '%s'.", tableName, tableType))
}
}
}
type mockBinlogPump struct {
}
var _ binlog.PumpClient = &mockBinlogPump{}
func (p *mockBinlogPump) WriteBinlog(ctx context.Context, in *binlog.WriteBinlogReq, opts ...grpc.CallOption) (*binlog.WriteBinlogResp, error) {
return &binlog.WriteBinlogResp{}, nil
}
type mockPumpPullBinlogsClient struct {
grpc.ClientStream
}
func (m mockPumpPullBinlogsClient) Recv() (*binlog.PullBinlogResp, error) {
return nil, nil
}
func (p *mockBinlogPump) PullBinlogs(ctx context.Context, in *binlog.PullBinlogReq, opts ...grpc.CallOption) (binlog.Pump_PullBinlogsClient, error) {
return mockPumpPullBinlogsClient{mocktikv.MockGRPCClientStream()}, nil
}
func (s *testSessionSuite) TestForCoverage(c *C) {
// Just for test coverage.
tk := testkit.NewTestKitWithInit(c, s.store)
tk.MustExec("drop table if exists t")
tk.MustExec("create table t (id int auto_increment, v int, index (id))")
tk.MustExec("insert t values ()")
tk.MustExec("insert t values ()")
tk.MustExec("insert t values ()")
// Normal request will not cover txn.Seek.
tk.MustExec("admin check table t")
// Cover dirty table operations in StateTxn.
tk.Se.GetSessionVars().BinlogClient = binloginfo.MockPumpsClient(&mockBinlogPump{})
tk.MustExec("begin")
tk.MustExec("truncate table t")
tk.MustExec("insert t values ()")
tk.MustExec("delete from t where id = 2")
tk.MustExec("update t set v = 5 where id = 2")
tk.MustExec("insert t values ()")
tk.MustExec("rollback")
c.Check(tk.Se.SetCollation(mysql.DefaultCollationID), IsNil)
tk.MustExec("show processlist")
_, err := tk.Se.FieldList("t")
c.Check(err, IsNil)
}
func (s *testSessionSuite2) TestErrorRollback(c *C) {
tk := testkit.NewTestKitWithInit(c, s.store)
tk.MustExec("drop table if exists t_rollback")
tk.MustExec("create table t_rollback (c1 int, c2 int, primary key(c1))")
tk.MustExec("insert into t_rollback values (0, 0)")
var wg sync.WaitGroup
cnt := 4
wg.Add(cnt)
num := 20
for i := 0; i < cnt; i++ {
go func() {
defer wg.Done()
localTk := testkit.NewTestKitWithInit(c, s.store)
localTk.MustExec("set @@session.tidb_retry_limit = 100")
for j := 0; j < num; j++ {
localTk.Exec("insert into t_rollback values (1, 1)")
localTk.MustExec("update t_rollback set c2 = c2 + 1 where c1 = 0")
}
}()
}
wg.Wait()
tk.MustQuery("select c2 from t_rollback where c1 = 0").Check(testkit.Rows(fmt.Sprint(cnt * num)))
}
func (s *testSessionSuite) TestQueryString(c *C) {
tk := testkit.NewTestKitWithInit(c, s.store)
tk.MustExec("create table mutil1 (a int);create table multi2 (a int)")
queryStr := tk.Se.Value(sessionctx.QueryString)
c.Assert(queryStr, Equals, "create table multi2 (a int)")
// Test execution of DDL through the "ExecutePreparedStmt" interface.
_, err := tk.Se.Execute(context.Background(), "use test;")
c.Assert(err, IsNil)
_, err = tk.Se.Execute(context.Background(), "CREATE TABLE t (id bigint PRIMARY KEY, age int)")
c.Assert(err, IsNil)
_, err = tk.Se.Execute(context.Background(), "show create table t")
c.Assert(err, IsNil)
id, _, _, err := tk.Se.PrepareStmt("CREATE TABLE t2(id bigint PRIMARY KEY, age int)")
c.Assert(err, IsNil)
params := []types.Datum{}
_, err = tk.Se.ExecutePreparedStmt(context.Background(), id, params)
c.Assert(err, IsNil)
qs := tk.Se.Value(sessionctx.QueryString)
c.Assert(qs.(string), Equals, "CREATE TABLE t2(id bigint PRIMARY KEY, age int)")
// Test execution of DDL through the "Execute" interface.
_, err = tk.Se.Execute(context.Background(), "use test;")
c.Assert(err, IsNil)
_, err = tk.Se.Execute(context.Background(), "drop table t2")
c.Assert(err, IsNil)
_, err = tk.Se.Execute(context.Background(), "prepare stmt from 'CREATE TABLE t2(id bigint PRIMARY KEY, age int)'")
c.Assert(err, IsNil)
_, err = tk.Se.Execute(context.Background(), "execute stmt")
c.Assert(err, IsNil)
qs = tk.Se.Value(sessionctx.QueryString)
c.Assert(qs.(string), Equals, "CREATE TABLE t2(id bigint PRIMARY KEY, age int)")
}
func (s *testSessionSuite) TestAffectedRows(c *C) {
tk := testkit.NewTestKitWithInit(c, s.store)
tk.MustExec("drop table if exists t")
tk.MustExec("create table t(id TEXT)")
tk.MustExec(`INSERT INTO t VALUES ("a");`)
c.Assert(int(tk.Se.AffectedRows()), Equals, 1)
tk.MustExec(`INSERT INTO t VALUES ("b");`)
c.Assert(int(tk.Se.AffectedRows()), Equals, 1)
tk.MustExec(`UPDATE t set id = 'c' where id = 'a';`)
c.Assert(int(tk.Se.AffectedRows()), Equals, 1)
tk.MustExec(`UPDATE t set id = 'a' where id = 'a';`)
c.Assert(int(tk.Se.AffectedRows()), Equals, 0)
tk.MustQuery(`SELECT * from t`).Check(testkit.Rows("c", "b"))
c.Assert(int(tk.Se.AffectedRows()), Equals, 0)
tk.MustExec("drop table if exists t")
tk.MustExec("create table t (id int, data int)")
tk.MustExec(`INSERT INTO t VALUES (1, 0), (0, 0), (1, 1);`)
tk.MustExec(`UPDATE t set id = 1 where data = 0;`)
c.Assert(int(tk.Se.AffectedRows()), Equals, 1)
tk.MustExec("drop table if exists t")
tk.MustExec("create table t (id int, c1 timestamp);")
tk.MustExec(`insert t values(1, 0);`)
tk.MustExec(`UPDATE t set id = 1 where id = 1;`)
c.Assert(int(tk.Se.AffectedRows()), Equals, 0)
// With ON DUPLICATE KEY UPDATE, the affected-rows value per row is 1 if the row is inserted as a new row,
// 2 if an existing row is updated, and 0 if an existing row is set to its current values.
tk.MustExec("drop table if exists t")
tk.MustExec("create table t (c1 int PRIMARY KEY, c2 int);")
tk.MustExec(`insert t values(1, 1);`)
tk.MustExec(`insert into t values (1, 1) on duplicate key update c2=2;`)
c.Assert(int(tk.Se.AffectedRows()), Equals, 2)
tk.MustExec(`insert into t values (1, 1) on duplicate key update c2=2;`)
c.Assert(int(tk.Se.AffectedRows()), Equals, 0)
tk.MustExec("drop table if exists test")
createSQL := `CREATE TABLE test (
id VARCHAR(36) PRIMARY KEY NOT NULL,
factor INTEGER NOT NULL DEFAULT 2);`
tk.MustExec(createSQL)
insertSQL := `INSERT INTO test(id) VALUES('id') ON DUPLICATE KEY UPDATE factor=factor+3;`
tk.MustExec(insertSQL)
c.Assert(int(tk.Se.AffectedRows()), Equals, 1)
tk.MustExec(insertSQL)
c.Assert(int(tk.Se.AffectedRows()), Equals, 2)
tk.MustExec(insertSQL)
c.Assert(int(tk.Se.AffectedRows()), Equals, 2)
tk.Se.SetClientCapability(mysql.ClientFoundRows)
tk.MustExec("drop table if exists t")
tk.MustExec("create table t (id int, data int)")
tk.MustExec(`INSERT INTO t VALUES (1, 0), (0, 0), (1, 1);`)
tk.MustExec(`UPDATE t set id = 1 where data = 0;`)
c.Assert(int(tk.Se.AffectedRows()), Equals, 2)
}
func (s *testSessionSuite3) TestLastMessage(c *C) {
tk := testkit.NewTestKitWithInit(c, s.store)
tk.MustExec("drop table if exists t")
tk.MustExec("create table t(id TEXT)")
// Insert
tk.MustExec(`INSERT INTO t VALUES ("a");`)
tk.CheckLastMessage("")
tk.MustExec(`INSERT INTO t VALUES ("b"), ("c");`)
tk.CheckLastMessage("Records: 2 Duplicates: 0 Warnings: 0")
// Update
tk.MustExec(`UPDATE t set id = 'c' where id = 'a';`)
c.Assert(int(tk.Se.AffectedRows()), Equals, 1)
tk.CheckLastMessage("Rows matched: 1 Changed: 1 Warnings: 0")
tk.MustExec(`UPDATE t set id = 'a' where id = 'a';`)
c.Assert(int(tk.Se.AffectedRows()), Equals, 0)
tk.CheckLastMessage("Rows matched: 0 Changed: 0 Warnings: 0")
// Replace
tk.MustExec(`drop table if exists t, t1;
create table t (c1 int PRIMARY KEY, c2 int);
create table t1 (a1 int, a2 int);`)
tk.MustExec(`INSERT INTO t VALUES (1,1)`)
tk.MustExec(`REPLACE INTO t VALUES (2,2)`)
tk.CheckLastMessage("")
tk.MustExec(`INSERT INTO t1 VALUES (1,10), (3,30);`)
tk.CheckLastMessage("Records: 2 Duplicates: 0 Warnings: 0")
tk.MustExec(`REPLACE INTO t SELECT * from t1`)
tk.CheckLastMessage("Records: 2 Duplicates: 1 Warnings: 0")
// Check insert with CLIENT_FOUND_ROWS is set
tk.Se.SetClientCapability(mysql.ClientFoundRows)
tk.MustExec(`drop table if exists t, t1;
create table t (c1 int PRIMARY KEY, c2 int);
create table t1 (a1 int, a2 int);`)
tk.MustExec(`INSERT INTO t1 VALUES (1, 10), (2, 2), (3, 30);`)
tk.MustExec(`INSERT INTO t1 VALUES (1, 10), (2, 20), (3, 30);`)
tk.MustExec(`INSERT INTO t SELECT * FROM t1 ON DUPLICATE KEY UPDATE c2=a2;`)
tk.CheckLastMessage("Records: 6 Duplicates: 3 Warnings: 0")
}
// TestRowLock . See http://dev.mysql.com/doc/refman/5.7/en/commit.html.
func (s *testSessionSuite) TestRowLock(c *C) {
tk := testkit.NewTestKitWithInit(c, s.store)
tk1 := testkit.NewTestKitWithInit(c, s.store)
tk2 := testkit.NewTestKitWithInit(c, s.store)
tk.MustExec("drop table if exists t")
txn, err := tk.Se.Txn(true)
c.Assert(kv.ErrInvalidTxn.Equal(err), IsTrue)
c.Assert(txn.Valid(), IsFalse)
tk.MustExec("create table t (c1 int, c2 int, c3 int)")
tk.MustExec("insert t values (11, 2, 3)")
tk.MustExec("insert t values (12, 2, 3)")
tk.MustExec("insert t values (13, 2, 3)")
tk1.MustExec("set @@tidb_disable_txn_auto_retry = 0")
tk1.MustExec("begin")
tk1.MustExec("update t set c2=21 where c1=11")
tk2.MustExec("begin")
tk2.MustExec("update t set c2=211 where c1=11")
tk2.MustExec("commit")
// tk1 will retry and the final value is 21
tk1.MustExec("commit")
// Check the result is correct
tk.MustQuery("select c2 from t where c1=11").Check(testkit.Rows("21"))
tk1.MustExec("begin")
tk1.MustExec("update t set c2=21 where c1=11")
tk2.MustExec("begin")
tk2.MustExec("update t set c2=22 where c1=12")
tk2.MustExec("commit")
tk1.MustExec("commit")
}
// TestAutocommit . See https://dev.mysql.com/doc/internals/en/status-flags.html
func (s *testSessionSuite) TestAutocommit(c *C) {
tk := testkit.NewTestKitWithInit(c, s.store)
tk.MustExec("drop table if exists t;")
c.Assert(int(tk.Se.Status()&mysql.ServerStatusAutocommit), Greater, 0)
tk.MustExec("create table t (id BIGINT PRIMARY KEY AUTO_INCREMENT NOT NULL)")
c.Assert(int(tk.Se.Status()&mysql.ServerStatusAutocommit), Greater, 0)
tk.MustExec("insert t values ()")
c.Assert(int(tk.Se.Status()&mysql.ServerStatusAutocommit), Greater, 0)
tk.MustExec("begin")
c.Assert(int(tk.Se.Status()&mysql.ServerStatusAutocommit), Greater, 0)
tk.MustExec("insert t values ()")
c.Assert(int(tk.Se.Status()&mysql.ServerStatusAutocommit), Greater, 0)
tk.MustExec("drop table if exists t")
c.Assert(int(tk.Se.Status()&mysql.ServerStatusAutocommit), Greater, 0)
tk.MustExec("create table t (id BIGINT PRIMARY KEY AUTO_INCREMENT NOT NULL)")
c.Assert(int(tk.Se.Status()&mysql.ServerStatusAutocommit), Greater, 0)
tk.MustExec("set autocommit=0")
c.Assert(int(tk.Se.Status()&mysql.ServerStatusAutocommit), Equals, 0)
tk.MustExec("insert t values ()")
c.Assert(int(tk.Se.Status()&mysql.ServerStatusAutocommit), Equals, 0)
tk.MustExec("commit")
c.Assert(int(tk.Se.Status()&mysql.ServerStatusAutocommit), Equals, 0)
tk.MustExec("drop table if exists t")
c.Assert(int(tk.Se.Status()&mysql.ServerStatusAutocommit), Equals, 0)
tk.MustExec("set autocommit='On'")
c.Assert(int(tk.Se.Status()&mysql.ServerStatusAutocommit), Greater, 0)
// When autocommit is 0, transaction start ts should be the first *valid*
// statement, rather than *any* statement.
tk.MustExec("create table t (id int)")
tk.MustExec("set @@autocommit = 0")
tk.MustExec("rollback")
tk.MustExec("set @@autocommit = 0")
tk1 := testkit.NewTestKitWithInit(c, s.store)
tk1.MustExec("insert into t select 1")
tk.MustQuery("select * from t").Check(testkit.Rows("1"))
// TODO: MySQL compatibility for setting global variable.
// tk.MustExec("begin")
// tk.MustExec("insert into t values (42)")
// tk.MustExec("set @@global.autocommit = 1")
// tk.MustExec("rollback")
// tk.MustQuery("select count(*) from t where id = 42").Check(testkit.Rows("0"))
// Even the transaction is rollbacked, the set statement succeed.
// tk.MustQuery("select @@global.autocommit").Rows("1")
}
// TestTxnLazyInitialize tests that when autocommit = 0, not all statement starts
// a new transaction.
func (s *testSessionSuite) TestTxnLazyInitialize(c *C) {
testTxnLazyInitialize(s, c, false)
testTxnLazyInitialize(s, c, true)
}
func testTxnLazyInitialize(s *testSessionSuite, c *C, isPessimistic bool) {
tk := testkit.NewTestKitWithInit(c, s.store)
tk.MustExec("drop table if exists t")
tk.MustExec("create table t (id int)")
if isPessimistic {
tk.MustExec("set tidb_txn_mode = 'pessimistic'")
}
tk.MustExec("set @@autocommit = 0")
_, err := tk.Se.Txn(true)
c.Assert(kv.ErrInvalidTxn.Equal(err), IsTrue)
txn, err := tk.Se.Txn(false)
c.Assert(err, IsNil)
c.Assert(txn.Valid(), IsFalse)
tk.MustQuery("select @@tidb_current_ts").Check(testkit.Rows("0"))
tk.MustQuery("select @@tidb_current_ts").Check(testkit.Rows("0"))
// Those statement should not start a new transaction automacally.
tk.MustQuery("select 1")
tk.MustQuery("select @@tidb_current_ts").Check(testkit.Rows("0"))
tk.MustExec("set @@tidb_general_log = 0")
tk.MustQuery("select @@tidb_current_ts").Check(testkit.Rows("0"))
tk.MustQuery("explain select * from t")
tk.MustQuery("select @@tidb_current_ts").Check(testkit.Rows("0"))
// Begin statement should start a new transaction.
tk.MustExec("begin")
txn, err = tk.Se.Txn(false)
c.Assert(err, IsNil)
c.Assert(txn.Valid(), IsTrue)
tk.MustExec("rollback")
tk.MustExec("select * from t")
txn, err = tk.Se.Txn(false)
c.Assert(err, IsNil)
c.Assert(txn.Valid(), IsTrue)
tk.MustExec("rollback")
tk.MustExec("insert into t values (1)")
txn, err = tk.Se.Txn(false)
c.Assert(err, IsNil)
c.Assert(txn.Valid(), IsTrue)
tk.MustExec("rollback")
}
func (s *testSessionSuite) TestGlobalVarAccessor(c *C) {
varName := "max_allowed_packet"
varValue := "67108864" // This is the default value for max_allowed_packet
varValue1 := "4194305"
varValue2 := "4194306"
tk := testkit.NewTestKitWithInit(c, s.store)
se := tk.Se.(variable.GlobalVarAccessor)
// Get globalSysVar twice and get the same value
v, err := se.GetGlobalSysVar(varName)
c.Assert(err, IsNil)
c.Assert(v, Equals, varValue)
v, err = se.GetGlobalSysVar(varName)
c.Assert(err, IsNil)
c.Assert(v, Equals, varValue)
// Set global var to another value
err = se.SetGlobalSysVar(varName, varValue1)
c.Assert(err, IsNil)
v, err = se.GetGlobalSysVar(varName)
c.Assert(err, IsNil)
c.Assert(v, Equals, varValue1)
c.Assert(tk.Se.CommitTxn(context.TODO()), IsNil)
tk1 := testkit.NewTestKitWithInit(c, s.store)
se1 := tk1.Se.(variable.GlobalVarAccessor)
v, err = se1.GetGlobalSysVar(varName)
c.Assert(err, IsNil)
c.Assert(v, Equals, varValue1)
err = se1.SetGlobalSysVar(varName, varValue2)
c.Assert(err, IsNil)
v, err = se1.GetGlobalSysVar(varName)
c.Assert(err, IsNil)
c.Assert(v, Equals, varValue2)
c.Assert(tk1.Se.CommitTxn(context.TODO()), IsNil)
// Make sure the change is visible to any client that accesses that global variable.
v, err = se.GetGlobalSysVar(varName)
c.Assert(err, IsNil)
c.Assert(v, Equals, varValue2)
// For issue 10955, make sure the new session load `max_execution_time` into sessionVars.
s.dom.GetGlobalVarsCache().Disable()
tk1.MustExec("set @@global.max_execution_time = 100")
tk2 := testkit.NewTestKitWithInit(c, s.store)
c.Assert(tk2.Se.GetSessionVars().MaxExecutionTime, Equals, uint64(100))
tk1.MustExec("set @@global.max_execution_time = 0")
result := tk.MustQuery("show global variables where variable_name='sql_select_limit';")
result.Check(testkit.Rows("sql_select_limit 18446744073709551615"))
result = tk.MustQuery("show session variables where variable_name='sql_select_limit';")
result.Check(testkit.Rows("sql_select_limit 18446744073709551615"))
tk.MustExec("set session sql_select_limit=100000000000;")
result = tk.MustQuery("show global variables where variable_name='sql_select_limit';")
result.Check(testkit.Rows("sql_select_limit 18446744073709551615"))
result = tk.MustQuery("show session variables where variable_name='sql_select_limit';")
result.Check(testkit.Rows("sql_select_limit 100000000000"))
tk.MustExec("set @@global.sql_select_limit = 1")
result = tk.MustQuery("show global variables where variable_name='sql_select_limit';")
result.Check(testkit.Rows("sql_select_limit 1"))
tk.MustExec("set @@global.sql_select_limit = default")
result = tk.MustQuery("show global variables where variable_name='sql_select_limit';")
result.Check(testkit.Rows("sql_select_limit 18446744073709551615"))
result = tk.MustQuery("select @@global.autocommit;")
result.Check(testkit.Rows("1"))
result = tk.MustQuery("select @@autocommit;")
result.Check(testkit.Rows("1"))
tk.MustExec("set @@global.autocommit = 0;")
result = tk.MustQuery("select @@global.autocommit;")
result.Check(testkit.Rows("0"))
result = tk.MustQuery("select @@autocommit;")
result.Check(testkit.Rows("1"))
tk.MustExec("set @@global.autocommit=1")
_, err = tk.Exec("set global time_zone = 'timezone'")
c.Assert(err, NotNil)
c.Assert(terror.ErrorEqual(err, variable.ErrUnknownTimeZone), IsTrue)
}
func (s *testSessionSuite) TestGetSysVariables(c *C) {
tk := testkit.NewTestKitWithInit(c, s.store)
// Test ScopeSession
tk.MustExec("select @@warning_count")
tk.MustExec("select @@session.warning_count")
tk.MustExec("select @@local.warning_count")
_, err := tk.Exec("select @@global.warning_count")
c.Assert(terror.ErrorEqual(err, variable.ErrIncorrectScope), IsTrue, Commentf("err %v", err))
// Test ScopeGlobal
tk.MustExec("select @@max_connections")
tk.MustExec("select @@global.max_connections")
_, err = tk.Exec("select @@session.max_connections")
c.Assert(terror.ErrorEqual(err, variable.ErrIncorrectScope), IsTrue, Commentf("err %v", err))
_, err = tk.Exec("select @@local.max_connections")
c.Assert(terror.ErrorEqual(err, variable.ErrIncorrectScope), IsTrue, Commentf("err %v", err))
// Test ScopeNone
tk.MustExec("select @@performance_schema_max_mutex_classes")
tk.MustExec("select @@global.performance_schema_max_mutex_classes")
// For issue 19524, test
tk.MustExec("select @@session.performance_schema_max_mutex_classes")
tk.MustExec("select @@local.performance_schema_max_mutex_classes")
}
func (s *testSessionSuite) TestRetryResetStmtCtx(c *C) {
tk := testkit.NewTestKitWithInit(c, s.store)
tk.MustExec("create table retrytxn (a int unique, b int)")
tk.MustExec("insert retrytxn values (1, 1)")
tk.MustExec("set @@tidb_disable_txn_auto_retry = 0")
tk.MustExec("begin")
tk.MustExec("update retrytxn set b = b + 1 where a = 1")
// Make retryable error.
tk1 := testkit.NewTestKitWithInit(c, s.store)
tk1.MustExec("update retrytxn set b = b + 1 where a = 1")
err := tk.Se.CommitTxn(context.TODO())
c.Assert(err, IsNil)
c.Assert(tk.Se.AffectedRows(), Equals, uint64(1))
}
func (s *testSessionSuite) TestRetryCleanTxn(c *C) {
tk := testkit.NewTestKitWithInit(c, s.store)
tk.MustExec("create table retrytxn (a int unique, b int)")
tk.MustExec("insert retrytxn values (1, 1)")
tk.MustExec("begin")
tk.MustExec("update retrytxn set b = b + 1 where a = 1")
// Make retryable error.
tk1 := testkit.NewTestKitWithInit(c, s.store)
tk1.MustExec("update retrytxn set b = b + 1 where a = 1")
// Hijack retry history, add a statement that returns error.
history := session.GetHistory(tk.Se)
stmtNode, err := parser.New().ParseOneStmt("insert retrytxn values (2, 'a')", "", "")
c.Assert(err, IsNil)
stmt, _ := session.Compile(context.TODO(), tk.Se, stmtNode)
executor.ResetContextOfStmt(tk.Se, stmtNode)
history.Add(stmt, tk.Se.GetSessionVars().StmtCtx)
_, err = tk.Exec("commit")
c.Assert(err, NotNil)
txn, err := tk.Se.Txn(false)
c.Assert(err, IsNil)
c.Assert(txn.Valid(), IsFalse)
c.Assert(tk.Se.GetSessionVars().InTxn(), IsFalse)
}
func (s *testSessionSuite) TestReadOnlyNotInHistory(c *C) {
tk := testkit.NewTestKitWithInit(c, s.store)
tk.MustExec("create table history (a int)")
tk.MustExec("insert history values (1), (2), (3)")
tk.MustExec("set @@autocommit = 0")
tk.MustExec("set tidb_disable_txn_auto_retry = 0")
tk.MustQuery("select * from history")
history := session.GetHistory(tk.Se)
c.Assert(history.Count(), Equals, 0)
tk.MustExec("insert history values (4)")
tk.MustExec("insert history values (5)")
c.Assert(history.Count(), Equals, 2)
tk.MustExec("commit")
tk.MustQuery("select * from history")
history = session.GetHistory(tk.Se)
c.Assert(history.Count(), Equals, 0)
}
func (s *testSessionSuite) TestRetryUnion(c *C) {
tk := testkit.NewTestKitWithInit(c, s.store)
tk.MustExec("create table history (a int)")
tk.MustExec("insert history values (1), (2), (3)")
tk.MustExec("set @@autocommit = 0")
tk.MustExec("set tidb_disable_txn_auto_retry = 0")
// UNION should't be in retry history.
tk.MustQuery("(select * from history) union (select * from history)")
history := session.GetHistory(tk.Se)
c.Assert(history.Count(), Equals, 0)
tk.MustQuery("(select * from history for update) union (select * from history)")
tk.MustExec("update history set a = a + 1")
history = session.GetHistory(tk.Se)
c.Assert(history.Count(), Equals, 2)
// Make retryable error.
tk1 := testkit.NewTestKitWithInit(c, s.store)
tk1.MustExec("update history set a = a + 1")
_, err := tk.Exec("commit")
c.Assert(err, ErrorMatches, ".*can not retry select for update statement")
}
func (s *testSessionSuite) TestRetryShow(c *C) {
tk := testkit.NewTestKitWithInit(c, s.store)
tk.MustExec("set @@autocommit = 0")
tk.MustExec("set tidb_disable_txn_auto_retry = 0")
// UNION should't be in retry history.
tk.MustQuery("show variables")
tk.MustQuery("show databases")
history := session.GetHistory(tk.Se)
c.Assert(history.Count(), Equals, 0)
}
func (s *testSessionSuite) TestNoRetryForCurrentTxn(c *C) {
tk := testkit.NewTestKitWithInit(c, s.store)
tk1 := testkit.NewTestKitWithInit(c, s.store)
tk.MustExec("create table history (a int)")
tk.MustExec("insert history values (1)")
// Firstly, disable retry.
tk.MustExec("set tidb_disable_txn_auto_retry = 1")
tk.MustExec("begin")
tk.MustExec("update history set a = 2")
// Enable retry now.
tk.MustExec("set tidb_disable_txn_auto_retry = 0")
tk1.MustExec("update history set a = 3")
c.Assert(tk.ExecToErr("commit"), NotNil)
}
func (s *testSessionSuite) TestRetryForCurrentTxn(c *C) {
tk := testkit.NewTestKitWithInit(c, s.store)
tk1 := testkit.NewTestKitWithInit(c, s.store)
tk.MustExec("create table history (a int)")
tk.MustExec("insert history values (1)")
// Firstly, enable retry.
tk.MustExec("set tidb_disable_txn_auto_retry = 0")
tk.MustExec("begin")
tk.MustExec("update history set a = 2")
// Disable retry now.
tk.MustExec("set tidb_disable_txn_auto_retry = 1")
tk1.MustExec("update history set a = 3")
tk.MustExec("commit")
tk.MustQuery("select * from history").Check(testkit.Rows("2"))
}
// TestTruncateAlloc tests that the auto_increment ID does not reuse the old table's allocator.
func (s *testSessionSuite) TestTruncateAlloc(c *C) {
tk := testkit.NewTestKitWithInit(c, s.store)
tk.MustExec("create table truncate_id (a int primary key auto_increment)")
tk.MustExec("insert truncate_id values (), (), (), (), (), (), (), (), (), ()")
tk.MustExec("truncate table truncate_id")
tk.MustExec("insert truncate_id values (), (), (), (), (), (), (), (), (), ()")
tk.MustQuery("select a from truncate_id where a > 11").Check(testkit.Rows())
}
func (s *testSessionSuite) TestString(c *C) {
tk := testkit.NewTestKitWithInit(c, s.store)
tk.MustExec("select 1")
// here to check the panic bug in String() when txn is nil after committed.
c.Log(tk.Se.String())
}
func (s *testSessionSuite) TestDatabase(c *C) {
tk := testkit.NewTestKitWithInit(c, s.store)
// Test database.
tk.MustExec("create database xxx")
tk.MustExec("drop database xxx")
tk.MustExec("drop database if exists xxx")
tk.MustExec("create database xxx")
tk.MustExec("create database if not exists xxx")
tk.MustExec("drop database if exists xxx")
// Test schema.
tk.MustExec("create schema xxx")
tk.MustExec("drop schema xxx")
tk.MustExec("drop schema if exists xxx")
tk.MustExec("create schema xxx")
tk.MustExec("create schema if not exists xxx")
tk.MustExec("drop schema if exists xxx")
}
func (s *testSessionSuite) TestExecRestrictedSQL(c *C) {
tk := testkit.NewTestKitWithInit(c, s.store)
r, _, err := tk.Se.(sqlexec.RestrictedSQLExecutor).ExecRestrictedSQL("select 1;")
c.Assert(err, IsNil)
c.Assert(len(r), Equals, 1)
}
// TestInTrans . See https://dev.mysql.com/doc/internals/en/status-flags.html
func (s *testSessionSuite) TestInTrans(c *C) {
tk := testkit.NewTestKitWithInit(c, s.store)
tk.MustExec("drop table if exists t;")
tk.MustExec("create table t (id BIGINT PRIMARY KEY AUTO_INCREMENT NOT NULL)")
tk.MustExec("insert t values ()")
tk.MustExec("begin")
txn, err := tk.Se.Txn(true)
c.Assert(err, IsNil)
c.Assert(txn.Valid(), IsTrue)
tk.MustExec("insert t values ()")
c.Assert(txn.Valid(), IsTrue)
tk.MustExec("drop table if exists t;")
c.Assert(txn.Valid(), IsFalse)
tk.MustExec("create table t (id BIGINT PRIMARY KEY AUTO_INCREMENT NOT NULL)")
c.Assert(txn.Valid(), IsFalse)
tk.MustExec("insert t values ()")
c.Assert(txn.Valid(), IsFalse)
tk.MustExec("commit")
tk.MustExec("insert t values ()")
tk.MustExec("set autocommit=0")
tk.MustExec("begin")
c.Assert(txn.Valid(), IsTrue)
tk.MustExec("insert t values ()")
c.Assert(txn.Valid(), IsTrue)
tk.MustExec("commit")
c.Assert(txn.Valid(), IsFalse)
tk.MustExec("insert t values ()")
c.Assert(txn.Valid(), IsTrue)
tk.MustExec("commit")
c.Assert(txn.Valid(), IsFalse)
tk.MustExec("set autocommit=1")
tk.MustExec("drop table if exists t")
tk.MustExec("create table t (id BIGINT PRIMARY KEY AUTO_INCREMENT NOT NULL)")
tk.MustExec("begin")
c.Assert(txn.Valid(), IsTrue)
tk.MustExec("insert t values ()")
c.Assert(txn.Valid(), IsTrue)
tk.MustExec("rollback")
c.Assert(txn.Valid(), IsFalse)
}
func (s *testSessionSuite) TestRetryPreparedStmt(c *C) {
tk := testkit.NewTestKitWithInit(c, s.store)
tk1 := testkit.NewTestKitWithInit(c, s.store)
tk2 := testkit.NewTestKitWithInit(c, s.store)
tk.MustExec("drop table if exists t")
txn, err := tk.Se.Txn(true)
c.Assert(kv.ErrInvalidTxn.Equal(err), IsTrue)
c.Assert(txn.Valid(), IsFalse)
tk.MustExec("create table t (c1 int, c2 int, c3 int)")
tk.MustExec("insert t values (11, 2, 3)")
tk1.MustExec("set @@tidb_disable_txn_auto_retry = 0")
tk1.MustExec("begin")
tk1.MustExec("update t set c2=? where c1=11;", 21)
tk2.MustExec("begin")
tk2.MustExec("update t set c2=? where c1=11", 22)
tk2.MustExec("commit")
tk1.MustExec("commit")
tk.MustQuery("select c2 from t where c1=11").Check(testkit.Rows("21"))
}
func (s *testSessionSuite) TestSession(c *C) {
tk := testkit.NewTestKitWithInit(c, s.store)
tk.MustExec("ROLLBACK;")
tk.Se.Close()
}
func (s *testSessionSuite) TestSessionAuth(c *C) {
tk := testkit.NewTestKitWithInit(c, s.store)
c.Assert(tk.Se.Auth(&auth.UserIdentity{Username: "Any not exist username with zero password!", Hostname: "anyhost"}, []byte(""), []byte("")), IsFalse)
}
func (s *testSessionSerialSuite) TestSkipWithGrant(c *C) {
tk := testkit.NewTestKitWithInit(c, s.store)
save2 := privileges.SkipWithGrant
privileges.SkipWithGrant = false
c.Assert(tk.Se.Auth(&auth.UserIdentity{Username: "user_not_exist"}, []byte("yyy"), []byte("zzz")), IsFalse)
privileges.SkipWithGrant = true
c.Assert(tk.Se.Auth(&auth.UserIdentity{Username: "xxx", Hostname: `%`}, []byte("yyy"), []byte("zzz")), IsTrue)
c.Assert(tk.Se.Auth(&auth.UserIdentity{Username: "root", Hostname: `%`}, []byte(""), []byte("")), IsTrue)
tk.MustExec("create table t (id int)")
tk.MustExec("create role r_1")
tk.MustExec("grant r_1 to root")
tk.MustExec("set role all")
tk.MustExec("show grants for root")
privileges.SkipWithGrant = save2
}
func (s *testSessionSuite) TestLastInsertID(c *C) {
tk := testkit.NewTestKitWithInit(c, s.store)
// insert
tk.MustExec("create table t (c1 int not null auto_increment, c2 int, PRIMARY KEY (c1))")
tk.MustExec("insert into t set c2 = 11")
tk.MustQuery("select last_insert_id()").Check(testkit.Rows("1"))
tk.MustExec("insert into t (c2) values (22), (33), (44)")
tk.MustQuery("select last_insert_id()").Check(testkit.Rows("2"))
tk.MustExec("insert into t (c1, c2) values (10, 55)")
tk.MustQuery("select last_insert_id()").Check(testkit.Rows("2"))
// replace
tk.MustExec("replace t (c2) values(66)")
tk.MustQuery("select * from t").Check(testkit.Rows("1 11", "2 22", "3 33", "4 44", "10 55", "11 66"))
tk.MustQuery("select last_insert_id()").Check(testkit.Rows("11"))
// update
tk.MustExec("update t set c1=last_insert_id(c1 + 100)")
tk.MustQuery("select * from t").Check(testkit.Rows("101 11", "102 22", "103 33", "104 44", "110 55", "111 66"))
tk.MustQuery("select last_insert_id()").Check(testkit.Rows("111"))
tk.MustExec("insert into t (c2) values (77)")
tk.MustQuery("select last_insert_id()").Check(testkit.Rows("112"))
// drop
tk.MustExec("drop table t")
tk.MustQuery("select last_insert_id()").Check(testkit.Rows("112"))
tk.MustExec("create table t (c2 int, c3 int, c1 int not null auto_increment, PRIMARY KEY (c1))")
tk.MustExec("insert into t set c2 = 30")
// insert values
lastInsertID := tk.Se.LastInsertID()
tk.MustExec("prepare stmt1 from 'insert into t (c2) values (?)'")
tk.MustExec("set @v1=10")