forked from pingcap/tidb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathddl_db_test.go
1511 lines (1350 loc) · 53.9 KB
/
ddl_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"
"time"
"github.com/juju/errors"
. "github.com/pingcap/check"
"github.com/pingcap/tidb"
"github.com/pingcap/tidb/context"
"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/model"
"github.com/pingcap/tidb/mysql"
tmysql "github.com/pingcap/tidb/mysql"
"github.com/pingcap/tidb/sessionctx"
"github.com/pingcap/tidb/store/localstore"
"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/util/testkit"
"github.com/pingcap/tidb/util/testleak"
"github.com/pingcap/tidb/util/types"
)
var _ = Suite(&testDBSuite{})
const defaultBatchSize = 4196
type testDBSuite struct {
store kv.Storage
dom *domain.Domain
schemaName string
tk *testkit.TestKit
s tidb.Session
lease time.Duration
}
func (s *testDBSuite) SetUpSuite(c *C) {
var err error
s.lease = 200 * time.Millisecond
tidb.SetSchemaLease(s.lease)
s.schemaName = "test_db"
s.store, err = tidb.NewStore(tidb.EngineGoLevelDBMemory)
c.Assert(err, IsNil)
localstore.MockRemoteStore = true
s.dom, err = tidb.BootstrapSession(s.store)
c.Assert(err, IsNil)
s.s, err = tidb.CreateSession(s.store)
c.Assert(err, IsNil)
_, err = s.s.Execute("create database test_db")
c.Assert(err, IsNil)
_, err = s.s.Execute("use " + s.schemaName)
c.Assert(err, IsNil)
_, err = s.s.Execute("create table t1 (c1 int, c2 int, c3 int, primary key(c1))")
c.Assert(err, IsNil)
_, err = s.s.Execute("create table t2 (c1 int, c2 int, c3 int)")
c.Assert(err, IsNil)
}
func (s *testDBSuite) TearDownSuite(c *C) {
localstore.MockRemoteStore = false
s.s.Execute("drop database if exists test_db")
s.s.Close()
s.dom.Close()
s.store.Close()
}
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)
// drop database
sql = "drop database db_not_exist"
s.testErrorCode(c, sql, tmysql.ErrDBDropExists)
// crate 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)
// 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)
// drop column
sql = "alter table test_error_code_succ drop c_not_exist"
s.testErrorCode(c, sql, tmysql.ErrCantDropFieldOrKey)
// 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)
}
func (s *testDBSuite) TestAddIndexAfterAddColumn(c *C) {
defer testleak.AfterTest(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)
}
func (s *testDBSuite) TestAddIndexWithPK(c *C) {
defer testleak.AfterTest(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) TestIndex(c *C) {
defer testleak.AfterTest(c)()
s.tk = testkit.NewTestKit(c, s.store)
s.tk.MustExec("use " + s.schemaName)
s.testAddIndex(c)
s.testAddAnonymousIndex(c)
s.testDropIndex(c)
s.testAddUniqueIndexRollback(c)
s.testAddIndexWithDupCols(c)
}
func (s *testDBSuite) testGetTable(c *C, name string) table.Table {
ctx := s.s.(context.Context)
domain := sessionctx.GetDomain(ctx)
// Make sure the table schema is the new schema.
err := domain.Reload()
c.Assert(err, IsNil)
tbl, err := domain.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 := tidb.CreateSession(s)
if err != nil {
done <- errors.Trace(err)
return
}
defer se.Close()
_, err = se.Execute("use test_db")
if err != nil {
done <- errors.Trace(err)
return
}
_, err = se.Execute(sql)
done <- errors.Trace(err)
}
func (s *testDBSuite) testAddUniqueIndexRollback(c *C) {
// t1 (c1 int, c2 int, c3 int, primary key(c1))
s.mustExec(c, "delete from t1")
// 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)")
}
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")
}
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) testAddIndex(c *C) {
done := make(chan error, 1)
start := -10
num := defaultBatchSize
// first add some rows
for i := start; i < num; i++ {
s.mustExec(c, "insert into t1 values (?, ?, ?)", i, i, i)
}
sessionExecInGoroutine(c, s.store, "create index c3_index on t1 (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 t1 where c1 = %d", n)
s.mustExec(c, sql)
sql = fmt.Sprintf("insert into t1 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)
}
// 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 t1 where c3 >= %d", start))
matchRows(c, rows, expectedRows)
// test index range
for i := 0; i < 100; i++ {
index := rand.Intn(len(keys) - 3)
rows := s.mustQuery(c, "select c1 from t1 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 t1 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.(context.Context)
c.Assert(ctx.NewTxn(), IsNil)
t := s.testGetTable(c, "t1")
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)
}
func (s *testDBSuite) testDropIndex(c *C) {
done := make(chan error, 1)
s.mustExec(c, "delete from t1")
num := 100
// add some rows
for i := 0; i < num; i++ {
s.mustExec(c, "insert into t1 values (?, ?, ?)", i, i, i)
}
t := s.testGetTable(c, "t1")
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 t1", 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 t1 set c2 = 1 where c1 = ?", n)
s.mustExec(c, "insert into t1 values (?, ?, ?)", i, i, i)
}
num += step
}
}
rows := s.mustQuery(c, "explain select c1 from t1 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.(context.Context)
// Make sure there is no index with name c3_index.
t = s.testGetTable(c, "t1")
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(), c3idx.Meta())
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 < 30; i++ {
handles = f()
if len(handles) != 0 {
time.Sleep(time.Millisecond * 100)
} else {
break
}
}
c.Assert(handles, HasLen, 0)
}
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 t (a int, b int)")
_, err := s.tk.Exec("create index c on t(b, a, b)")
c.Check(err1.Equal(err), Equals, true)
_, err = s.tk.Exec("create index c on t(b, a, B)")
c.Check(err2.Equal(err), Equals, true)
_, err = s.tk.Exec("alter table t add index c (b, a, b)")
c.Check(err1.Equal(err), Equals, true)
_, err = s.tk.Exec("alter table t add index c (b, a, B)")
c.Check(err2.Equal(err), Equals, true)
}
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) {
defer testleak.AfterTest(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) 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) {
defer testleak.AfterTest(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) {
defer testleak.AfterTest(c)()
s.tk = testkit.NewTestKit(c, s.store)
s.tk.MustExec("use " + s.schemaName)
s.testAddColumn(c)
s.testDropColumn(c)
}
func sessionExec(c *C, s kv.Storage, sql string) {
se, err := tidb.CreateSession(s)
c.Assert(err, IsNil)
_, err = se.Execute("use test_db")
c.Assert(err, IsNil)
rs, err := se.Execute(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) {
go func() {
se, err := tidb.CreateSession(s)
if err != nil {
done <- errors.Trace(err)
return
}
defer se.Close()
_, err = se.Execute("use test_db")
if err != nil {
done <- errors.Trace(err)
return
}
rs, err := se.Execute(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")
}
num += step
}
}
// add data, here c4 must exist
for i := num; i < num+step; i++ {
s.tk.MustExec("insert into t2 values (?, ?, ?, ?)", i, i, i, i)
}
rows := s.mustQuery(c, "select count(c4) from t2")
c.Assert(rows, HasLen, 1)
c.Assert(rows[0], HasLen, 1)
count, err := strconv.ParseInt(rows[0][0].(string), 10, 64)
c.Assert(err, IsNil)
c.Assert(count, Greater, int64(0))
rows = s.mustQuery(c, "select count(c4) from t2 where c4 = -1")
matchRows(c, rows, [][]interface{}{{count - int64(step)}})
for i := num; i < num+step; i++ {
rows = s.mustQuery(c, "select c4 from t2 where c4 = ?", i)
matchRows(c, rows, [][]interface{}{{i}})
}
ctx := s.s.(context.Context)
t := s.testGetTable(c, "t2")
i := 0
j := 0
ctx.NewTxn()
defer ctx.Txn().Rollback()
err = t.IterRecords(ctx, t.FirstKey(), t.Cols(),
func(h int64, data []types.Datum, cols []*table.Column) (bool, error) {
i++
// c4 must be -1 or > 0
v, err1 := data[3].ToInt64(ctx.GetSessionVars().StmtCtx)
c.Assert(err1, IsNil)
if v == -1 {
j++
} else {
c.Assert(v, Greater, int64(0))
}
return true, nil
})
c.Assert(err, IsNil)
c.Assert(i, Equals, int(count))
c.Assert(i, LessEqual, num+step)
c.Assert(j, Equals, int(count)-step)
// for modifying columns after adding columns
s.tk.MustExec("alter table t2 modify c4 int default 11")
for i := num + step; i < num+step+10; i++ {
s.mustExec(c, "insert into t2 values (?, ?, ?, ?)", i, i, i, i)
}
rows = s.mustQuery(c, "select count(c4) from t2 where c4 = -1")
matchRows(c, rows, [][]interface{}{{count - int64(step)}})
}
func (s *testDBSuite) testDropColumn(c *C) {
done := make(chan error, 1)
s.mustExec(c, "delete from t2")
num := 100
// add some rows
for i := 0; i < num; i++ {
s.mustExec(c, "insert into t2 values (?, ?, ?, ?)", i, i, i, i)
}
// get c4 column id
sessionExecInGoroutine(c, s.store, "alter table t2 drop column c4", 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++ {
// 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 executing 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")
}
num += step
}
}
// add data, here c4 must not exist
for i := num; i < num+step; i++ {
s.mustExec(c, "insert into t2 values (?, ?, ?)", i, i, i)
}
rows := s.mustQuery(c, "select count(*) from t2")
c.Assert(rows, HasLen, 1)
c.Assert(rows[0], HasLen, 1)
count, err := strconv.ParseInt(rows[0][0].(string), 10, 64)
c.Assert(err, IsNil)
c.Assert(count, Greater, int64(0))
}
func (s *testDBSuite) TestPrimaryKey(c *C) {
defer testleak.AfterTest(c)()
s.tk = testkit.NewTestKit(c, s.store)
s.tk.MustExec("use " + s.schemaName)
s.mustExec(c, "create table primary_key_test (a int, b varchar(10))")
_, err := s.tk.Exec("alter table primary_key_test add primary key(a)")
c.Assert(ddl.ErrUnsupportedModifyPrimaryKey.Equal(err), IsTrue)
_, err = s.tk.Exec("alter table primary_key_test drop primary key")
c.Assert(ddl.ErrUnsupportedModifyPrimaryKey.Equal(err), IsTrue)
}
func (s *testDBSuite) TestChangeColumn(c *C) {
defer testleak.AfterTest(c)()
s.tk = testkit.NewTestKit(c, s.store)
s.tk.MustExec("use " + s.schemaName)
s.mustExec(c, "create table t3 (a int default '0', b varchar(10), d int not null default '0')")
s.mustExec(c, "insert into t3 set b = 'a'")
s.tk.MustQuery("select a from t3").Check(testkit.Rows("0"))
s.mustExec(c, "alter table t3 change a aa bigint")
s.mustExec(c, "insert into t3 set b = 'b'")
s.tk.MustQuery("select aa from t3").Check(testkit.Rows("0", "<nil>"))
// for no default flag
s.mustExec(c, "alter table t3 change d dd bigint not null")
ctx := s.tk.Se.(context.Context)
is := sessionctx.GetDomain(ctx).InfoSchema()
tbl, err := is.TableByName(model.NewCIStr("test_db"), model.NewCIStr("t3"))
c.Assert(err, IsNil)
tblInfo := tbl.Meta()
colD := tblInfo.Columns[2]
hasNoDefault := tmysql.HasNoDefaultValueFlag(colD.Flag)
c.Assert(hasNoDefault, IsTrue)
// for the following definitions: 'not null', 'null', 'default value' and 'comment'
s.mustExec(c, "alter table t3 change b b varchar(20) null default 'c' comment 'my comment'")
is = sessionctx.GetDomain(ctx).InfoSchema()
tbl, err = is.TableByName(model.NewCIStr("test_db"), model.NewCIStr("t3"))
c.Assert(err, IsNil)
tblInfo = tbl.Meta()
colB := tblInfo.Columns[1]
c.Assert(colB.Comment, Equals, "my comment")
hasNotNull := tmysql.HasNotNullFlag(colB.Flag)
c.Assert(hasNotNull, IsFalse)
s.mustExec(c, "insert into t3 set aa = 3, dd = 5")
s.tk.MustQuery("select b from t3").Check(testkit.Rows("a", "b", "c"))
// for timestamp
s.mustExec(c, "alter table t3 add column c timestamp not null")
s.mustExec(c, "alter table t3 change c c timestamp null default '2017-02-11' comment 'col c comment' on update current_timestamp")
is = sessionctx.GetDomain(ctx).InfoSchema()
tbl, err = is.TableByName(model.NewCIStr("test_db"), model.NewCIStr("t3"))
c.Assert(err, IsNil)
tblInfo = tbl.Meta()
colC := tblInfo.Columns[3]
c.Assert(colC.Comment, Equals, "col c comment")
hasNotNull = tmysql.HasNotNullFlag(colC.Flag)
c.Assert(hasNotNull, IsFalse)
// for enum
s.mustExec(c, "alter table t3 add column en enum('a', 'b', 'c') not null default 'a'")
// for failing tests
sql := "alter table t3 change aa a bigint default ''"
s.testErrorCode(c, sql, tmysql.ErrInvalidDefault)
sql = "alter table t3 change a testx.t3.aa bigint"
s.testErrorCode(c, sql, tmysql.ErrWrongDBName)
sql = "alter table t3 change t.a aa bigint"
s.testErrorCode(c, sql, tmysql.ErrWrongTableName)
sql = "alter table t3 change aa a bigint not null"
s.testErrorCode(c, sql, tmysql.ErrUnknown)
sql = "alter table t3 modify en enum('a', 'z', 'b', 'c') not null default 'a'"
s.testErrorCode(c, sql, tmysql.ErrUnknown)
}
func (s *testDBSuite) TestAlterColumn(c *C) {
defer testleak.AfterTest(c)()
s.tk = testkit.NewTestKit(c, s.store)
s.tk.MustExec("use " + s.schemaName)
s.mustExec(c, "create table test_alter_column (a int default 111, b varchar(8), c varchar(8) not null, d timestamp on update current_timestamp)")
s.mustExec(c, "insert into test_alter_column set b = 'a', c = 'aa'")
s.tk.MustQuery("select a from test_alter_column").Check(testkit.Rows("111"))
ctx := s.tk.Se.(context.Context)
is := sessionctx.GetDomain(ctx).InfoSchema()
tbl, err := is.TableByName(model.NewCIStr("test_db"), model.NewCIStr("test_alter_column"))
c.Assert(err, IsNil)
tblInfo := tbl.Meta()
colA := tblInfo.Columns[0]
hasNoDefault := tmysql.HasNoDefaultValueFlag(colA.Flag)
c.Assert(hasNoDefault, IsFalse)
s.mustExec(c, "alter table test_alter_column alter column a set default 222")
s.mustExec(c, "insert into test_alter_column set b = 'b', c = 'bb'")
s.tk.MustQuery("select a from test_alter_column").Check(testkit.Rows("111", "222"))
is = sessionctx.GetDomain(ctx).InfoSchema()
tbl, err = is.TableByName(model.NewCIStr("test_db"), model.NewCIStr("test_alter_column"))
c.Assert(err, IsNil)
tblInfo = tbl.Meta()
colA = tblInfo.Columns[0]
hasNoDefault = tmysql.HasNoDefaultValueFlag(colA.Flag)
c.Assert(hasNoDefault, IsFalse)
s.mustExec(c, "alter table test_alter_column alter column b set default null")
s.mustExec(c, "insert into test_alter_column set c = 'cc'")
s.tk.MustQuery("select b from test_alter_column").Check(testkit.Rows("a", "b", "<nil>"))
is = sessionctx.GetDomain(ctx).InfoSchema()
tbl, err = is.TableByName(model.NewCIStr("test_db"), model.NewCIStr("test_alter_column"))
c.Assert(err, IsNil)
tblInfo = tbl.Meta()
colC := tblInfo.Columns[2]
hasNoDefault = tmysql.HasNoDefaultValueFlag(colC.Flag)
c.Assert(hasNoDefault, IsTrue)
s.mustExec(c, "alter table test_alter_column alter column c set default 'xx'")
s.mustExec(c, "insert into test_alter_column set a = 123")
s.tk.MustQuery("select c from test_alter_column").Check(testkit.Rows("aa", "bb", "cc", "xx"))
is = sessionctx.GetDomain(ctx).InfoSchema()
tbl, err = is.TableByName(model.NewCIStr("test_db"), model.NewCIStr("test_alter_column"))
c.Assert(err, IsNil)
tblInfo = tbl.Meta()
colC = tblInfo.Columns[2]
hasNoDefault = tmysql.HasNoDefaultValueFlag(colC.Flag)
c.Assert(hasNoDefault, IsFalse)
// TODO: After fix issue 2606.
// s.mustExec(c, "alter table test_alter_column alter column d set default null")
s.mustExec(c, "alter table test_alter_column alter column a drop default")
s.mustExec(c, "insert into test_alter_column set b = 'd', c = 'dd'")
s.tk.MustQuery("select a from test_alter_column").Check(testkit.Rows("111", "222", "222", "123", "<nil>"))
// for failing tests
sql := "alter table db_not_exist.test_alter_column alter column b set default 'c'"
s.testErrorCode(c, sql, tmysql.ErrNoSuchTable)
sql = "alter table test_not_exist alter column b set default 'c'"
s.testErrorCode(c, sql, tmysql.ErrNoSuchTable)
sql = "alter table test_alter_column alter column col_not_exist set default 'c'"
s.testErrorCode(c, sql, tmysql.ErrBadField)
sql = "alter table test_alter_column alter column c set default null"
s.testErrorCode(c, sql, tmysql.ErrInvalidDefault)
// The followings tests whether adding constraints via change / modify column
// is forbidden as expected.
s.mustExec(c, "drop table if exists mc")
s.mustExec(c, "create table mc(a int key, b int, c int)")
_, err = s.tk.Exec("alter table mc modify column a int key") // Adds a new primary key
c.Assert(err, NotNil)
_, err = s.tk.Exec("alter table mc modify column c int unique") // Adds a new unique key
c.Assert(err, NotNil)
result := s.tk.MustQuery("show create table mc")
createSQL := result.Rows()[0][1]
expected := "CREATE TABLE `mc` (\n `a` int(11) NOT NULL,\n `b` int(11) DEFAULT NULL,\n `c` int(11) DEFAULT NULL,\n PRIMARY KEY (`a`)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin"
c.Assert(createSQL, Equals, expected)
// Change / modify column should preserve index options.
s.mustExec(c, "drop table if exists mc")
s.mustExec(c, "create table mc(a int key, b int, c int unique)")
s.mustExec(c, "alter table mc modify column a bigint") // NOT NULL & PRIMARY KEY should be preserved
s.mustExec(c, "alter table mc modify column b bigint")
s.mustExec(c, "alter table mc modify column c bigint") // Unique should be preserved
result = s.tk.MustQuery("show create table mc")
createSQL = result.Rows()[0][1]
expected = "CREATE TABLE `mc` (\n `a` bigint(20) NOT NULL,\n `b` bigint(20) DEFAULT NULL,\n `c` bigint(20) DEFAULT NULL,\n PRIMARY KEY (`a`),\n UNIQUE KEY `c` (`c`)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin"
c.Assert(createSQL, Equals, expected)
// Dropping or keeping auto_increment is allowed, however adding is not allowed.
s.mustExec(c, "drop table if exists mc")
s.mustExec(c, "create table mc(a int key auto_increment, b int)")
s.mustExec(c, "alter table mc modify column a bigint auto_increment") // Keeps auto_increment
result = s.tk.MustQuery("show create table mc")
createSQL = result.Rows()[0][1]
expected = "CREATE TABLE `mc` (\n `a` bigint(20) NOT NULL AUTO_INCREMENT,\n `b` int(11) DEFAULT NULL,\n PRIMARY KEY (`a`)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin"
s.mustExec(c, "alter table mc modify column a bigint") // Drops auto_increment
result = s.tk.MustQuery("show create table mc")
createSQL = result.Rows()[0][1]
expected = "CREATE TABLE `mc` (\n `a` bigint(20) NOT NULL,\n `b` int(11) DEFAULT NULL,\n PRIMARY KEY (`a`)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin"
c.Assert(createSQL, Equals, expected)
_, err = s.tk.Exec("alter table mc modify column a bigint auto_increment") // Adds auto_increment should throw error
c.Assert(err, NotNil)
}
func (s *testDBSuite) mustExec(c *C, query string, args ...interface{}) {
s.tk.MustExec(query, args...)