forked from pingcap/tidb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb_test.go
3369 lines (3024 loc) · 122 KB
/
db_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 ddl_test
import (
"fmt"
"io"
"math"
"math/rand"
"strconv"
"strings"
"sync"
"time"
"github.com/juju/errors"
. "github.com/pingcap/check"
"github.com/pingcap/tidb/ast"
"github.com/pingcap/tidb/ddl"
"github.com/pingcap/tidb/domain"
"github.com/pingcap/tidb/infoschema"
"github.com/pingcap/tidb/kv"
"github.com/pingcap/tidb/meta"
"github.com/pingcap/tidb/meta/autoid"
"github.com/pingcap/tidb/model"
"github.com/pingcap/tidb/mysql"
tmysql "github.com/pingcap/tidb/mysql"
"github.com/pingcap/tidb/session"
"github.com/pingcap/tidb/sessionctx"
"github.com/pingcap/tidb/store/mockstore"
"github.com/pingcap/tidb/store/mockstore/mocktikv"
"github.com/pingcap/tidb/table"
"github.com/pingcap/tidb/table/tables"
"github.com/pingcap/tidb/tablecodec"
"github.com/pingcap/tidb/terror"
"github.com/pingcap/tidb/types"
"github.com/pingcap/tidb/util/admin"
"github.com/pingcap/tidb/util/mock"
"github.com/pingcap/tidb/util/testkit"
"github.com/pingcap/tidb/util/testleak"
"github.com/pingcap/tidb/util/testutil"
"golang.org/x/net/context"
)
const (
// waitForCleanDataRound indicates how many times should we check data is cleaned or not.
waitForCleanDataRound = 150
// waitForCleanDataInterval is a min duration between 2 check for data clean.
waitForCleanDataInterval = time.Millisecond * 100
)
var _ = Suite(&testDBSuite{})
const defaultBatchSize = 2048
type testDBSuite struct {
cluster *mocktikv.Cluster
mvccStore mocktikv.MVCCStore
store kv.Storage
dom *domain.Domain
schemaName string
tk *testkit.TestKit
s session.Session
lease time.Duration
autoIDStep int64
}
func (s *testDBSuite) SetUpSuite(c *C) {
var err error
testleak.BeforeTest()
s.lease = 200 * time.Millisecond
session.SetSchemaLease(s.lease)
session.SetStatsLease(0)
s.schemaName = "test_db"
s.autoIDStep = autoid.GetStep()
autoid.SetStep(5000)
ddl.WaitTimeWhenErrorOccured = 1 * time.Microsecond
s.cluster = mocktikv.NewCluster()
mocktikv.BootstrapWithSingleStore(s.cluster)
s.mvccStore = mocktikv.MustNewMVCCStore()
s.store, err = mockstore.NewMockTikvStore(
mockstore.WithCluster(s.cluster),
mockstore.WithMVCCStore(s.mvccStore),
)
c.Assert(err, IsNil)
s.dom, err = session.BootstrapSession(s.store)
c.Assert(err, IsNil)
s.s, err = session.CreateSession4Test(s.store)
c.Assert(err, IsNil)
_, err = s.s.Execute(context.Background(), "create database test_db")
c.Assert(err, IsNil)
s.tk = testkit.NewTestKit(c, s.store)
}
func (s *testDBSuite) TearDownSuite(c *C) {
s.s.Execute(context.Background(), "drop database if exists test_db")
s.s.Close()
s.dom.Close()
s.store.Close()
testleak.AfterTest(c)()
autoid.SetStep(s.autoIDStep)
}
func (s *testDBSuite) testErrorCode(c *C, sql string, errCode int) {
_, err := s.tk.Exec(sql)
c.Assert(err, NotNil)
originErr := errors.Cause(err)
tErr, ok := originErr.(*terror.Error)
c.Assert(ok, IsTrue, Commentf("err: %T", originErr))
c.Assert(tErr.ToSQLError().Code, DeepEquals, uint16(errCode), Commentf("MySQL code:%v", tErr.ToSQLError()))
}
func (s *testDBSuite) TestMySQLErrorCode(c *C) {
s.tk = testkit.NewTestKit(c, s.store)
s.tk.MustExec("use " + s.schemaName)
// create database
sql := "create database aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
s.testErrorCode(c, sql, tmysql.ErrTooLongIdent)
sql = "create database test"
s.testErrorCode(c, sql, tmysql.ErrDBCreateExists)
sql = "create database test1 character set uft8;"
s.testErrorCode(c, sql, tmysql.ErrUnknownCharacterSet)
sql = "create database test2 character set gkb;"
s.testErrorCode(c, sql, tmysql.ErrUnknownCharacterSet)
sql = "create database test3 character set laitn1;"
s.testErrorCode(c, sql, tmysql.ErrUnknownCharacterSet)
// drop database
sql = "drop database db_not_exist"
s.testErrorCode(c, sql, tmysql.ErrDBDropExists)
// create table
s.tk.MustExec("create table test_error_code_succ (c1 int, c2 int, c3 int, primary key(c3))")
sql = "create table test_error_code_succ (c1 int, c2 int, c3 int)"
s.testErrorCode(c, sql, tmysql.ErrTableExists)
sql = "create table test_error_code1 (c1 int, c2 int, c2 int)"
s.testErrorCode(c, sql, tmysql.ErrDupFieldName)
sql = "create table test_error_code1 (c1 int, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa int)"
s.testErrorCode(c, sql, tmysql.ErrTooLongIdent)
sql = "create table aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(a int)"
s.testErrorCode(c, sql, tmysql.ErrTooLongIdent)
sql = "create table test_error_code1 (c1 int, c2 int, key aa (c1, c2), key aa (c1))"
s.testErrorCode(c, sql, tmysql.ErrDupKeyName)
sql = "create table test_error_code1 (c1 int, c2 int, c3 int, key(c_not_exist))"
s.testErrorCode(c, sql, tmysql.ErrKeyColumnDoesNotExits)
sql = "create table test_error_code1 (c1 int, c2 int, c3 int, primary key(c_not_exist))"
s.testErrorCode(c, sql, tmysql.ErrKeyColumnDoesNotExits)
sql = "create table test_error_code1 (c1 int not null default '')"
s.testErrorCode(c, sql, tmysql.ErrInvalidDefault)
sql = "CREATE TABLE `t` (`a` double DEFAULT 1.0 DEFAULT 2.0 DEFAULT now());"
s.testErrorCode(c, sql, tmysql.ErrInvalidDefault)
sql = "CREATE TABLE `t` (`a` double DEFAULT now());"
s.testErrorCode(c, sql, tmysql.ErrInvalidDefault)
sql = "create table t1(a int) character set uft8;"
s.testErrorCode(c, sql, tmysql.ErrUnknownCharacterSet)
sql = "create table t1(a int) character set gkb;"
s.testErrorCode(c, sql, tmysql.ErrUnknownCharacterSet)
sql = "create table t1(a int) character set laitn1;"
s.testErrorCode(c, sql, tmysql.ErrUnknownCharacterSet)
sql = "create table test_error_code (a int not null ,b int not null,c int not null, d int not null, foreign key (b, c) references product(id));"
s.testErrorCode(c, sql, tmysql.ErrWrongFkDef)
sql = "create table test_error_code_2;"
s.testErrorCode(c, sql, tmysql.ErrTableMustHaveColumns)
sql = "create table test_error_code_2 (unique(c1));"
s.testErrorCode(c, sql, tmysql.ErrTableMustHaveColumns)
sql = "create table test_error_code_2(c1 int, c2 int, c3 int, primary key(c1), primary key(c2));"
s.testErrorCode(c, sql, tmysql.ErrMultiplePriKey)
sql = "create table test_error_code_3(pt blob ,primary key (pt));"
s.testErrorCode(c, sql, tmysql.ErrBlobKeyWithoutLength)
sql = "create table test_error_code_3(a text, unique (a(3073)));"
s.testErrorCode(c, sql, tmysql.ErrTooLongKey)
sql = "create table test_error_code_3(`id` int, key `primary`(`id`));"
s.testErrorCode(c, sql, tmysql.ErrWrongNameForIndex)
sql = "create table t2(c1.c2 blob default null);"
s.testErrorCode(c, sql, tmysql.ErrWrongTableName)
sql = "create table t2 (id int default null primary key , age int);"
s.testErrorCode(c, sql, tmysql.ErrInvalidDefault)
sql = "create table t2 (id int null primary key , age int);"
s.testErrorCode(c, sql, tmysql.ErrPrimaryCantHaveNull)
sql = "create table t2 (id int default null, age int, primary key(id));"
s.testErrorCode(c, sql, tmysql.ErrPrimaryCantHaveNull)
sql = "create table t2 (id int null, age int, primary key(id));"
s.testErrorCode(c, sql, tmysql.ErrPrimaryCantHaveNull)
sql = "create table t2 (id int primary key , age int);"
s.tk.MustExec(sql)
// add column
sql = "alter table test_error_code_succ add column c1 int"
s.testErrorCode(c, sql, tmysql.ErrDupFieldName)
sql = "alter table test_error_code_succ add column aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa int"
s.testErrorCode(c, sql, tmysql.ErrTooLongIdent)
sql = "alter table test_comment comment 'test comment'"
s.testErrorCode(c, sql, tmysql.ErrNoSuchTable)
sql = "alter table test_error_code_succ add column `a ` int ;"
s.testErrorCode(c, sql, tmysql.ErrWrongColumnName)
s.tk.MustExec("create table test_on_update (c1 int, c2 int);")
sql = "alter table test_on_update add column c3 int on update current_timestamp;"
s.testErrorCode(c, sql, tmysql.ErrInvalidOnUpdate)
sql = "create table test_on_update_2(c int on update current_timestamp);"
s.testErrorCode(c, sql, tmysql.ErrInvalidOnUpdate)
// drop column
sql = "alter table test_error_code_succ drop c_not_exist"
s.testErrorCode(c, sql, tmysql.ErrCantDropFieldOrKey)
s.tk.MustExec("create table test_drop_column (c1 int );")
sql = "alter table test_drop_column drop column c1;"
s.testErrorCode(c, sql, tmysql.ErrCantRemoveAllFields)
// add index
sql = "alter table test_error_code_succ add index idx (c_not_exist)"
s.testErrorCode(c, sql, tmysql.ErrKeyColumnDoesNotExits)
s.tk.Exec("alter table test_error_code_succ add index idx (c1)")
sql = "alter table test_error_code_succ add index idx (c1)"
s.testErrorCode(c, sql, tmysql.ErrDupKeyName)
// drop index
sql = "alter table test_error_code_succ drop index idx_not_exist"
s.testErrorCode(c, sql, tmysql.ErrCantDropFieldOrKey)
sql = "alter table test_error_code_succ drop column c3"
s.testErrorCode(c, sql, int(tmysql.ErrUnknown))
// modify column
sql = "alter table test_error_code_succ modify testx.test_error_code_succ.c1 bigint"
s.testErrorCode(c, sql, tmysql.ErrWrongDBName)
sql = "alter table test_error_code_succ modify t.c1 bigint"
s.testErrorCode(c, sql, tmysql.ErrWrongTableName)
// insert value
s.tk.MustExec("create table test_error_code_null(c1 char(100) not null);")
sql = "insert into test_error_code_null (c1) values(null);"
s.testErrorCode(c, sql, tmysql.ErrBadNull)
}
func (s *testDBSuite) TestAddIndexAfterAddColumn(c *C) {
s.tk = testkit.NewTestKit(c, s.store)
s.tk.MustExec("use " + s.schemaName)
s.tk.MustExec("create table test_add_index_after_add_col(a int, b int not null default '0')")
s.tk.MustExec("insert into test_add_index_after_add_col values(1, 2),(2,2)")
s.tk.MustExec("alter table test_add_index_after_add_col add column c int not null default '0'")
sql := "alter table test_add_index_after_add_col add unique index cc(c) "
s.testErrorCode(c, sql, tmysql.ErrDupEntry)
sql = "alter table test_add_index_after_add_col add index idx_test(f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f15,f16,f17);"
s.testErrorCode(c, sql, tmysql.ErrTooManyKeyParts)
}
func (s *testDBSuite) TestAddIndexWithPK(c *C) {
s.tk = testkit.NewTestKit(c, s.store)
s.tk.MustExec("use " + s.schemaName)
s.tk.MustExec("create table test_add_index_with_pk(a int not null, b int not null default '0', primary key(a))")
s.tk.MustExec("insert into test_add_index_with_pk values(1, 2)")
s.tk.MustExec("alter table test_add_index_with_pk add index idx (a)")
s.tk.MustQuery("select a from test_add_index_with_pk").Check(testkit.Rows("1"))
s.tk.MustExec("insert into test_add_index_with_pk values(2, 2)")
s.tk.MustExec("alter table test_add_index_with_pk add index idx1 (a, b)")
s.tk.MustQuery("select * from test_add_index_with_pk").Check(testkit.Rows("1 2", "2 2"))
s.tk.MustExec("create table test_add_index_with_pk1(a int not null, b int not null default '0', c int, d int, primary key(c))")
s.tk.MustExec("insert into test_add_index_with_pk1 values(1, 1, 1, 1)")
s.tk.MustExec("alter table test_add_index_with_pk1 add index idx (c)")
s.tk.MustExec("insert into test_add_index_with_pk1 values(2, 2, 2, 2)")
s.tk.MustQuery("select * from test_add_index_with_pk1").Check(testkit.Rows("1 1 1 1", "2 2 2 2"))
s.tk.MustExec("create table test_add_index_with_pk2(a int not null, b int not null default '0', c int unsigned, d int, primary key(c))")
s.tk.MustExec("insert into test_add_index_with_pk2 values(1, 1, 1, 1)")
s.tk.MustExec("alter table test_add_index_with_pk2 add index idx (c)")
s.tk.MustExec("insert into test_add_index_with_pk2 values(2, 2, 2, 2)")
s.tk.MustQuery("select * from test_add_index_with_pk2").Check(testkit.Rows("1 1 1 1", "2 2 2 2"))
}
func (s *testDBSuite) TestRenameIndex(c *C) {
s.tk = testkit.NewTestKit(c, s.store)
s.tk.MustExec("use " + s.schemaName)
s.tk.MustExec("create table t (pk int primary key, c int default 1, c1 int default 1, unique key k1(c), key k2(c1))")
// Test rename success
s.tk.MustExec("alter table t rename index k1 to k3")
s.tk.MustExec("admin check index t k3")
// Test rename to the same name
s.tk.MustExec("alter table t rename index k3 to k3")
s.tk.MustExec("admin check index t k3")
// Test rename on non-exists keys
s.testErrorCode(c, "alter table t rename index x to x", mysql.ErrKeyDoesNotExist)
// Test rename on already-exists keys
s.testErrorCode(c, "alter table t rename index k3 to k2", mysql.ErrDupKeyName)
s.tk.MustExec("alter table t rename index k2 to K2")
s.testErrorCode(c, "alter table t rename key k3 to K2", mysql.ErrDupKeyName)
}
func (s *testDBSuite) testGetTable(c *C, name string) table.Table {
ctx := s.s.(sessionctx.Context)
dom := domain.GetDomain(ctx)
// Make sure the table schema is the new schema.
err := dom.Reload()
c.Assert(err, IsNil)
tbl, err := dom.InfoSchema().TableByName(model.NewCIStr(s.schemaName), model.NewCIStr(name))
c.Assert(err, IsNil)
return tbl
}
func backgroundExec(s kv.Storage, sql string, done chan error) {
se, err := session.CreateSession4Test(s)
if err != nil {
done <- errors.Trace(err)
return
}
defer se.Close()
_, err = se.Execute(context.Background(), "use test_db")
if err != nil {
done <- errors.Trace(err)
return
}
_, err = se.Execute(context.Background(), sql)
done <- errors.Trace(err)
}
func (s *testDBSuite) TestAddUniqueIndexRollback(c *C) {
s.tk = testkit.NewTestKit(c, s.store)
s.mustExec(c, "use test_db")
s.mustExec(c, "drop table if exists t1")
s.mustExec(c, "create table t1 (c1 int, c2 int, c3 int, primary key(c1))")
// defaultBatchSize is equal to ddl.defaultBatchSize
base := defaultBatchSize * 2
count := base
// add some rows
for i := 0; i < count; i++ {
s.mustExec(c, "insert into t1 values (?, ?, ?)", i, i, i)
}
// add some duplicate rows
for i := count - 10; i < count; i++ {
s.mustExec(c, "insert into t1 values (?, ?, ?)", i+10, i, i)
}
done := make(chan error, 1)
go backgroundExec(s.store, "create unique index c3_index on t1 (c3)", done)
times := 0
ticker := time.NewTicker(s.lease / 2)
defer ticker.Stop()
LOOP:
for {
select {
case err := <-done:
c.Assert(err, NotNil)
c.Assert(err.Error(), Equals, "[kv:1062]Duplicate for key c3_index", Commentf("err:%v", err))
break LOOP
case <-ticker.C:
if times >= 10 {
break
}
step := 10
// delete some rows, and add some data
for i := count; i < count+step; i++ {
n := rand.Intn(count)
s.mustExec(c, "delete from t1 where c1 = ?", n)
s.mustExec(c, "insert into t1 values (?, ?, ?)", i+10, i, i)
}
count += step
times++
}
}
t := s.testGetTable(c, "t1")
for _, tidx := range t.Indices() {
c.Assert(strings.EqualFold(tidx.Meta().Name.L, "c3_index"), IsFalse)
}
// delete duplicate rows, then add index
for i := base - 10; i < base; i++ {
s.mustExec(c, "delete from t1 where c1 = ?", i+10)
}
sessionExec(c, s.store, "create index c3_index on t1 (c3)")
s.mustExec(c, "drop table t1")
}
func (s *testDBSuite) TestCancelAddIndex(c *C) {
s.tk = testkit.NewTestKit(c, s.store)
s.mustExec(c, "use test_db")
s.mustExec(c, "drop table if exists t1")
s.mustExec(c, "create table t1 (c1 int, c2 int, c3 int, primary key(c1))")
// defaultBatchSize is equal to ddl.defaultBatchSize
base := defaultBatchSize * 2
count := base
// add some rows
for i := 0; i < count; i++ {
s.mustExec(c, "insert into t1 values (?, ?, ?)", i, i, i)
}
var checkErr error
var c3IdxInfo *model.IndexInfo
hook := &ddl.TestDDLCallback{}
oldReorgWaitTimeout := ddl.ReorgWaitTimeout
// let hook.OnJobUpdatedExported has chance to cancel the job.
// the hook.OnJobUpdatedExported is called when the job is updated, runReorgJob will wait ddl.ReorgWaitTimeout, then return the ddl.runDDLJob.
// After that ddl call d.hook.OnJobUpdated(job), so that we can canceled the job in this test case.
ddl.ReorgWaitTimeout = 50 * time.Millisecond
hook.OnJobUpdatedExported, c3IdxInfo = backgroundExecOnJobUpdatedExported(c, s, hook, checkErr)
s.dom.DDL().(ddl.DDLForTest).SetHook(hook)
done := make(chan error, 1)
go backgroundExec(s.store, "create unique index c3_index on t1 (c3)", done)
times := 0
ticker := time.NewTicker(s.lease / 2)
defer ticker.Stop()
LOOP:
for {
select {
case err := <-done:
c.Assert(checkErr, IsNil)
c.Assert(err, NotNil)
c.Assert(err.Error(), Equals, "[ddl:12]cancelled DDL job")
break LOOP
case <-ticker.C:
if times >= 10 {
break
}
step := 10
// delete some rows, and add some data
for i := count; i < count+step; i++ {
n := rand.Intn(count)
s.mustExec(c, "delete from t1 where c1 = ?", n)
s.mustExec(c, "insert into t1 values (?, ?, ?)", i+10, i, i)
}
count += step
times++
}
}
t := s.testGetTable(c, "t1")
for _, tidx := range t.Indices() {
c.Assert(strings.EqualFold(tidx.Meta().Name.L, "c3_index"), IsFalse)
}
ctx := s.s.(sessionctx.Context)
idx := tables.NewIndex(t.Meta().ID, t.Meta(), c3IdxInfo)
checkDelRangeDone(c, ctx, idx)
s.mustExec(c, "drop table t1")
ddl.ReorgWaitTimeout = oldReorgWaitTimeout
callback := &ddl.TestDDLCallback{}
s.dom.DDL().(ddl.DDLForTest).SetHook(callback)
}
func (s *testDBSuite) TestAddAnonymousIndex(c *C) {
s.tk = testkit.NewTestKit(c, s.store)
s.tk.MustExec("use " + s.schemaName)
s.mustExec(c, "create table t_anonymous_index (c1 int, c2 int, C3 int)")
s.mustExec(c, "alter table t_anonymous_index add index (c1, c2)")
// for dropping empty index
_, err := s.tk.Exec("alter table t_anonymous_index drop index")
c.Assert(err, NotNil)
// The index name is c1 when adding index (c1, c2).
s.mustExec(c, "alter table t_anonymous_index drop index c1")
t := s.testGetTable(c, "t_anonymous_index")
c.Assert(t.Indices(), HasLen, 0)
// for adding some indices that the first column name is c1
s.mustExec(c, "alter table t_anonymous_index add index (c1)")
_, err = s.tk.Exec("alter table t_anonymous_index add index c1 (c2)")
c.Assert(err, NotNil)
t = s.testGetTable(c, "t_anonymous_index")
c.Assert(t.Indices(), HasLen, 1)
idx := t.Indices()[0].Meta().Name.L
c.Assert(idx, Equals, "c1")
// The MySQL will be a warning.
s.mustExec(c, "alter table t_anonymous_index add index c1_3 (c1)")
s.mustExec(c, "alter table t_anonymous_index add index (c1, c2, C3)")
// The MySQL will be a warning.
s.mustExec(c, "alter table t_anonymous_index add index (c1)")
t = s.testGetTable(c, "t_anonymous_index")
c.Assert(t.Indices(), HasLen, 4)
s.mustExec(c, "alter table t_anonymous_index drop index c1")
s.mustExec(c, "alter table t_anonymous_index drop index c1_2")
s.mustExec(c, "alter table t_anonymous_index drop index c1_3")
s.mustExec(c, "alter table t_anonymous_index drop index c1_4")
// for case insensitive
s.mustExec(c, "alter table t_anonymous_index add index (C3)")
s.mustExec(c, "alter table t_anonymous_index drop index c3")
s.mustExec(c, "alter table t_anonymous_index add index c3 (C3)")
s.mustExec(c, "alter table t_anonymous_index drop index C3")
// for anonymous index with column name `primary`
s.mustExec(c, "create table t_primary (`primary` int, key (`primary`))")
t = s.testGetTable(c, "t_primary")
c.Assert(t.Indices()[0].Meta().Name.String(), Equals, "primary_2")
s.mustExec(c, "create table t_primary_2 (`primary` int, key primary_2 (`primary`), key (`primary`))")
t = s.testGetTable(c, "t_primary_2")
c.Assert(t.Indices()[0].Meta().Name.String(), Equals, "primary_2")
c.Assert(t.Indices()[1].Meta().Name.String(), Equals, "primary_3")
s.mustExec(c, "create table t_primary_3 (`primary_2` int, key(`primary_2`), `primary` int, key(`primary`));")
t = s.testGetTable(c, "t_primary_3")
c.Assert(t.Indices()[0].Meta().Name.String(), Equals, "primary_2")
c.Assert(t.Indices()[1].Meta().Name.String(), Equals, "primary_3")
}
// TestModifyColumnAfterAddIndex Issue 5134
func (s *testDBSuite) TestModifyColumnAfterAddIndex(c *C) {
s.tk = testkit.NewTestKit(c, s.store)
s.tk.MustExec("use " + s.schemaName)
s.mustExec(c, "create table city (city VARCHAR(2) KEY);")
s.mustExec(c, "alter table city change column city city varchar(50);")
s.mustExec(c, `insert into city values ("abc"), ("abd");`)
}
func (s *testDBSuite) testAlterLock(c *C) {
s.tk = testkit.NewTestKit(c, s.store)
s.tk.MustExec("use " + s.schemaName)
s.mustExec(c, "create table t_index_lock (c1 int, c2 int, C3 int)")
s.mustExec(c, "alter table t_indx_lock add index (c1, c2), lock=none")
}
func (s *testDBSuite) TestAddMultiColumnsIndex(c *C) {
s.tk = testkit.NewTestKit(c, s.store)
s.tk.MustExec("use " + s.schemaName)
s.tk.MustExec("drop database if exists tidb;")
s.tk.MustExec("create database tidb;")
s.tk.MustExec("use tidb;")
s.tk.MustExec("create table tidb.test (a int auto_increment primary key, b int);")
s.tk.MustExec("insert tidb.test values (1, 1);")
s.tk.MustExec("update tidb.test set b = b + 1 where a = 1;")
s.tk.MustExec("insert into tidb.test values (2, 2);")
// Test that the b value is nil.
s.tk.MustExec("insert into tidb.test (a) values (3);")
s.tk.MustExec("insert into tidb.test values (4, 4);")
// Test that the b value is nil again.
s.tk.MustExec("insert into tidb.test (a) values (5);")
s.tk.MustExec("insert tidb.test values (6, 6);")
s.tk.MustExec("alter table tidb.test add index idx1 (a, b);")
s.tk.MustExec("admin check table test")
}
func (s *testDBSuite) TestAddIndex(c *C) {
s.testAddIndex(c, false, "create table test_add_index (c1 bigint, c2 bigint, c3 bigint, primary key(c1))")
s.testAddIndex(c, true, `create table test_add_index (c1 bigint, c2 bigint, c3 bigint, primary key(c1))
partition by range (c1) (
partition p0 values less than (3440),
partition p1 values less than (61440),
partition p2 values less than (122880),
partition p3 values less than (204800),
partition p4 values less than maxvalue)`)
}
func (s *testDBSuite) testAddIndex(c *C, testPartition bool, createTableSQL string) {
s.tk = testkit.NewTestKit(c, s.store)
s.tk.MustExec("use " + s.schemaName)
s.tk.MustExec("set @@tidb_enable_table_partition = 1")
s.tk.MustExec("drop table if exists test_add_index")
s.tk.MustExec(createTableSQL)
done := make(chan error, 1)
start := -10
num := defaultBatchSize
// first add some rows
for i := start; i < num; i++ {
sql := fmt.Sprintf("insert into test_add_index values (%d, %d, %d)", i, i, i)
s.mustExec(c, sql)
}
// Add some discrete rows.
maxBatch := 20
batchCnt := 100
otherKeys := make([]int, 0, batchCnt*maxBatch)
// Make sure there are no duplicate keys.
base := defaultBatchSize * 20
for i := 1; i < batchCnt; i++ {
n := base + i*defaultBatchSize + i
for j := 0; j < rand.Intn(maxBatch); j++ {
n += j
sql := fmt.Sprintf("insert into test_add_index values (%d, %d, %d)", n, n, n)
s.mustExec(c, sql)
otherKeys = append(otherKeys, n)
}
}
// Encounter the value of math.MaxInt64 in middle of
v := math.MaxInt64 - defaultBatchSize/2
sql := fmt.Sprintf("insert into test_add_index values (%d, %d, %d)", v, v, v)
s.mustExec(c, sql)
otherKeys = append(otherKeys, v)
sessionExecInGoroutine(c, s.store, "create index c3_index on test_add_index (c3)", done)
deletedKeys := make(map[int]struct{})
ticker := time.NewTicker(s.lease / 2)
defer ticker.Stop()
LOOP:
for {
select {
case err := <-done:
if err == nil {
break LOOP
}
c.Assert(err, IsNil, Commentf("err:%v", errors.ErrorStack(err)))
case <-ticker.C:
// When the server performance is particularly poor,
// the adding index operation can not be completed.
// So here is a limit to the number of rows inserted.
if num > defaultBatchSize*10 {
break
}
step := 10
// delete some rows, and add some data
for i := num; i < num+step; i++ {
n := rand.Intn(num)
deletedKeys[n] = struct{}{}
sql := fmt.Sprintf("delete from test_add_index where c1 = %d", n)
s.mustExec(c, sql)
sql = fmt.Sprintf("insert into test_add_index values (%d, %d, %d)", i, i, i)
s.mustExec(c, sql)
}
num += step
}
}
// get exists keys
keys := make([]int, 0, num)
for i := start; i < num; i++ {
if _, ok := deletedKeys[i]; ok {
continue
}
keys = append(keys, i)
}
keys = append(keys, otherKeys...)
// test index key
expectedRows := make([][]interface{}, 0, len(keys))
for _, key := range keys {
expectedRows = append(expectedRows, []interface{}{key})
}
rows := s.mustQuery(c, fmt.Sprintf("select c1 from test_add_index where c3 >= %d order by c1", start))
matchRows(c, rows, expectedRows)
if testPartition {
s.tk.MustExec("admin check table test_add_index")
return
}
// test index range
for i := 0; i < 100; i++ {
index := rand.Intn(len(keys) - 3)
rows := s.mustQuery(c, "select c1 from test_add_index where c3 >= ? limit 3", keys[index])
matchRows(c, rows, [][]interface{}{{keys[index]}, {keys[index+1]}, {keys[index+2]}})
}
// TODO: Support explain in future.
// rows := s.mustQuery(c, "explain select c1 from test_add_index where c3 >= 100")
// ay := dumpRows(c, rows)
// c.Assert(strings.Contains(fmt.Sprintf("%v", ay), "c3_index"), IsTrue)
// get all row handles
ctx := s.s.(sessionctx.Context)
c.Assert(ctx.NewTxn(), IsNil)
t := s.testGetTable(c, "test_add_index")
handles := make(map[int64]struct{})
startKey := t.RecordKey(math.MinInt64)
err := t.IterRecords(ctx, startKey, t.Cols(),
func(h int64, data []types.Datum, cols []*table.Column) (bool, error) {
handles[h] = struct{}{}
return true, nil
})
c.Assert(err, IsNil)
// check in index
var nidx table.Index
for _, tidx := range t.Indices() {
if tidx.Meta().Name.L == "c3_index" {
nidx = tidx
break
}
}
// Make sure there is index with name c3_index.
c.Assert(nidx, NotNil)
c.Assert(nidx.Meta().ID, Greater, int64(0))
ctx.Txn().Rollback()
c.Assert(ctx.NewTxn(), IsNil)
defer ctx.Txn().Rollback()
it, err := nidx.SeekFirst(ctx.Txn())
c.Assert(err, IsNil)
defer it.Close()
for {
_, h, err := it.Next()
if terror.ErrorEqual(err, io.EOF) {
break
}
c.Assert(err, IsNil)
_, ok := handles[h]
c.Assert(ok, IsTrue)
delete(handles, h)
}
c.Assert(handles, HasLen, 0)
s.tk.MustExec("drop table test_add_index")
}
func (s *testDBSuite) TestDropIndex(c *C) {
s.tk = testkit.NewTestKit(c, s.store)
s.tk.MustExec("use " + s.schemaName)
s.tk.MustExec("drop table if exists test_drop_index")
s.tk.MustExec("create table test_drop_index (c1 int, c2 int, c3 int, primary key(c1))")
s.tk.MustExec("create index c3_index on test_drop_index (c3)")
done := make(chan error, 1)
s.mustExec(c, "delete from test_drop_index")
num := 100
// add some rows
for i := 0; i < num; i++ {
s.mustExec(c, "insert into test_drop_index values (?, ?, ?)", i, i, i)
}
t := s.testGetTable(c, "test_drop_index")
var c3idx table.Index
for _, tidx := range t.Indices() {
if tidx.Meta().Name.L == "c3_index" {
c3idx = tidx
break
}
}
c.Assert(c3idx, NotNil)
sessionExecInGoroutine(c, s.store, "drop index c3_index on test_drop_index", done)
ticker := time.NewTicker(s.lease / 2)
defer ticker.Stop()
LOOP:
for {
select {
case err := <-done:
if err == nil {
break LOOP
}
c.Assert(err, IsNil, Commentf("err:%v", errors.ErrorStack(err)))
case <-ticker.C:
step := 10
// delete some rows, and add some data
for i := num; i < num+step; i++ {
n := rand.Intn(num)
s.mustExec(c, "update test_drop_index set c2 = 1 where c1 = ?", n)
s.mustExec(c, "insert into test_drop_index values (?, ?, ?)", i, i, i)
}
num += step
}
}
rows := s.mustQuery(c, "explain select c1 from test_drop_index where c3 >= 0")
c.Assert(strings.Contains(fmt.Sprintf("%v", rows), "c3_index"), IsFalse)
// check in index, must no index in kv
ctx := s.s.(sessionctx.Context)
// Make sure there is no index with name c3_index.
t = s.testGetTable(c, "test_drop_index")
var nidx table.Index
for _, tidx := range t.Indices() {
if tidx.Meta().Name.L == "c3_index" {
nidx = tidx
break
}
}
c.Assert(nidx, IsNil)
idx := tables.NewIndex(t.Meta().ID, t.Meta(), c3idx.Meta())
checkDelRangeDone(c, ctx, idx)
s.tk.MustExec("drop table test_drop_index")
}
func checkDelRangeDone(c *C, ctx sessionctx.Context, idx table.Index) {
startTime := time.Now()
f := func() map[int64]struct{} {
handles := make(map[int64]struct{})
c.Assert(ctx.NewTxn(), IsNil)
defer ctx.Txn().Rollback()
it, err := idx.SeekFirst(ctx.Txn())
c.Assert(err, IsNil)
defer it.Close()
for {
_, h, err := it.Next()
if terror.ErrorEqual(err, io.EOF) {
break
}
c.Assert(err, IsNil)
handles[h] = struct{}{}
}
return handles
}
var handles map[int64]struct{}
for i := 0; i < waitForCleanDataRound; i++ {
handles = f()
if len(handles) != 0 {
time.Sleep(waitForCleanDataInterval)
} else {
break
}
}
c.Assert(handles, HasLen, 0, Commentf("take time %v", time.Since(startTime)))
}
func (s *testDBSuite) TestAddIndexWithDupCols(c *C) {
s.tk = testkit.NewTestKit(c, s.store)
s.tk.MustExec("use " + s.schemaName)
err1 := infoschema.ErrColumnExists.GenByArgs("b")
err2 := infoschema.ErrColumnExists.GenByArgs("B")
s.tk.MustExec("create table test_add_index_with_dup (a int, b int)")
_, err := s.tk.Exec("create index c on test_add_index_with_dup(b, a, b)")
c.Check(err1.Equal(err), Equals, true)
_, err = s.tk.Exec("create index c on test_add_index_with_dup(b, a, B)")
c.Check(err2.Equal(err), Equals, true)
_, err = s.tk.Exec("alter table test_add_index_with_dup add index c (b, a, b)")
c.Check(err1.Equal(err), Equals, true)
_, err = s.tk.Exec("alter table test_add_index_with_dup add index c (b, a, B)")
c.Check(err2.Equal(err), Equals, true)
s.tk.MustExec("drop table test_add_index_with_dup")
}
func (s *testDBSuite) showColumns(c *C, tableName string) [][]interface{} {
return s.mustQuery(c, fmt.Sprintf("show columns from %s", tableName))
}
func (s *testDBSuite) TestIssue2293(c *C) {
s.tk = testkit.NewTestKit(c, s.store)
s.tk.MustExec("use " + s.schemaName)
s.tk.MustExec("create table t_issue_2293 (a int)")
sql := "alter table t_issue_2293 add b int not null default 'a'"
s.testErrorCode(c, sql, tmysql.ErrInvalidDefault)
s.tk.MustExec("insert into t_issue_2293 value(1)")
s.tk.MustQuery("select * from t_issue_2293").Check(testkit.Rows("1"))
}
func (s *testDBSuite) TestIssue6101(c *C) {
s.tk = testkit.NewTestKit(c, s.store)
s.tk.MustExec("use " + s.schemaName)
s.tk.MustExec("create table t1 (quantity decimal(2) unsigned);")
_, err := s.tk.Exec("insert into t1 values (500), (-500), (~0), (-1);")
terr := errors.Trace(err).(*errors.Err).Cause().(*terror.Error)
c.Assert(terr.Code(), Equals, terror.ErrCode(tmysql.ErrWarnDataOutOfRange))
s.tk.MustExec("drop table t1")
s.tk.MustExec("set sql_mode=''")
s.tk.MustExec("create table t1 (quantity decimal(2) unsigned);")
s.tk.MustExec("insert into t1 values (500), (-500), (~0), (-1);")
s.tk.MustQuery("select * from t1").Check(testkit.Rows("99", "0", "99", "0"))
s.tk.MustExec("drop table t1")
}
func (s *testDBSuite) TestCreateIndexType(c *C) {
s.tk = testkit.NewTestKit(c, s.store)
s.tk.MustExec("use " + s.schemaName)
sql := `CREATE TABLE test_index (
price int(5) DEFAULT '0' NOT NULL,
area varchar(40) DEFAULT '' NOT NULL,
type varchar(40) DEFAULT '' NOT NULL,
transityes set('a','b'),
shopsyes enum('Y','N') DEFAULT 'Y' NOT NULL,
schoolsyes enum('Y','N') DEFAULT 'Y' NOT NULL,
petsyes enum('Y','N') DEFAULT 'Y' NOT NULL,
KEY price (price,area,type,transityes,shopsyes,schoolsyes,petsyes));`
s.tk.MustExec(sql)
}
func (s *testDBSuite) TestIssue3833(c *C) {
s.tk = testkit.NewTestKit(c, s.store)
s.tk.MustExec("use " + s.schemaName)
s.tk.MustExec("create table issue3833 (b char(0))")
s.testErrorCode(c, "create index idx on issue3833 (b)", tmysql.ErrWrongKeyColumn)
s.testErrorCode(c, "alter table issue3833 add index idx (b)", tmysql.ErrWrongKeyColumn)
s.testErrorCode(c, "create table issue3833_2 (b char(0), index (b))", tmysql.ErrWrongKeyColumn)
}
func (s *testDBSuite) TestColumn(c *C) {
s.tk = testkit.NewTestKit(c, s.store)
s.tk.MustExec("use " + s.schemaName)
s.tk.MustExec("create table t2 (c1 int, c2 int, c3 int)")
s.testAddColumn(c)
s.testDropColumn(c)
s.tk.MustExec("drop table t2")
}
func (s *testDBSuite) TestAddColumnTooMany(c *C) {
s.tk = testkit.NewTestKit(c, s.store)
s.tk.MustExec("use test")
count := ddl.TableColumnCountLimit - 1
var cols []string
for i := 0; i < count; i++ {
cols = append(cols, fmt.Sprintf("a%d int", i))
}
createSQL := fmt.Sprintf("create table t_column_too_many (%s)", strings.Join(cols, ","))
s.tk.MustExec(createSQL)
s.tk.MustExec("alter table t_column_too_many add column a_512 int")
alterSQL := "alter table t_column_too_many add column a_513 int"
s.testErrorCode(c, alterSQL, tmysql.ErrTooManyFields)
}
func sessionExec(c *C, s kv.Storage, sql string) {
se, err := session.CreateSession4Test(s)
c.Assert(err, IsNil)
_, err = se.Execute(context.Background(), "use test_db")
c.Assert(err, IsNil)
rs, err := se.Execute(context.Background(), sql)
c.Assert(err, IsNil, Commentf("err:%v", errors.ErrorStack(err)))
c.Assert(rs, IsNil)
se.Close()
}
func sessionExecInGoroutine(c *C, s kv.Storage, sql string, done chan error) {
execMultiSQLInGoroutine(c, s, "test_db", []string{sql}, done)
}
func execMultiSQLInGoroutine(c *C, s kv.Storage, dbName string, multiSQL []string, done chan error) {
go func() {
se, err := session.CreateSession4Test(s)
if err != nil {
done <- errors.Trace(err)
return
}
defer se.Close()
_, err = se.Execute(context.Background(), "use "+dbName)
if err != nil {
done <- errors.Trace(err)
return
}
for _, sql := range multiSQL {
rs, err := se.Execute(context.Background(), sql)
if err != nil {
done <- errors.Trace(err)
return
}
if rs != nil {
done <- errors.Errorf("RecordSet should be empty.")
return
}
done <- nil
}
}()
}
func (s *testDBSuite) testAddColumn(c *C) {
done := make(chan error, 1)
num := defaultBatchSize + 10
// add some rows
for i := 0; i < num; i++ {
s.mustExec(c, "insert into t2 values (?, ?, ?)", i, i, i)
}
sessionExecInGoroutine(c, s.store, "alter table t2 add column c4 int default -1", done)
ticker := time.NewTicker(s.lease / 2)
defer ticker.Stop()
step := 10
LOOP:
for {
select {
case err := <-done:
if err == nil {
break LOOP
}
c.Assert(err, IsNil, Commentf("err:%v", errors.ErrorStack(err)))
case <-ticker.C:
// delete some rows, and add some data
for i := num; i < num+step; i++ {
n := rand.Intn(num)
s.tk.MustExec("begin")
s.tk.MustExec("delete from t2 where c1 = ?", n)
s.tk.MustExec("commit")
// Make sure that statement of insert and show use the same infoSchema.
s.tk.MustExec("begin")
_, err := s.tk.Exec("insert into t2 values (?, ?, ?)", i, i, i)
if err != nil {
// if err is failed, the column number must be 4 now.
values := s.showColumns(c, "t2")
c.Assert(values, HasLen, 4, Commentf("err:%v", errors.ErrorStack(err)))
}
s.tk.MustExec("commit")
}