forked from pingcap/tidb
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathserial_test.go
1535 lines (1353 loc) · 67.5 KB
/
serial_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 2019 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 (
"context"
"fmt"
"math"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
. "github.com/pingcap/check"
"github.com/pingcap/errors"
"github.com/pingcap/failpoint"
"github.com/pingcap/parser/model"
"github.com/pingcap/parser/mysql"
"github.com/pingcap/tidb/config"
"github.com/pingcap/tidb/ddl"
ddlutil "github.com/pingcap/tidb/ddl/util"
"github.com/pingcap/tidb/domain"
"github.com/pingcap/tidb/errno"
"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/session"
"github.com/pingcap/tidb/sessionctx"
"github.com/pingcap/tidb/sessionctx/variable"
"github.com/pingcap/tidb/store/mockstore"
"github.com/pingcap/tidb/store/tikv/mockstore/cluster"
"github.com/pingcap/tidb/util/admin"
"github.com/pingcap/tidb/util/collate"
"github.com/pingcap/tidb/util/gcutil"
"github.com/pingcap/tidb/util/mock"
"github.com/pingcap/tidb/util/testkit"
. "github.com/pingcap/tidb/util/testutil"
)
// Make it serial because config is modified in test cases.
var _ = SerialSuites(&testSerialSuite{})
type testSerialSuite struct {
CommonHandleSuite
store kv.Storage
cluster cluster.Cluster
dom *domain.Domain
}
func (s *testSerialSuite) SetUpSuite(c *C) {
session.SetSchemaLease(200 * time.Millisecond)
session.DisableStats4Test()
config.UpdateGlobal(func(conf *config.Config) {
// Test for add/drop primary key.
conf.AlterPrimaryKey = false
})
ddl.SetWaitTimeWhenErrorOccurred(1 * time.Microsecond)
var err error
s.store, err = mockstore.NewMockStore(
mockstore.WithClusterInspector(func(c cluster.Cluster) {
mockstore.BootstrapWithSingleStore(c)
s.cluster = c
}),
)
c.Assert(err, IsNil)
s.dom, err = session.BootstrapSession(s.store)
c.Assert(err, IsNil)
}
func (s *testSerialSuite) TearDownSuite(c *C) {
if s.dom != nil {
s.dom.Close()
}
if s.store != nil {
s.store.Close()
}
}
func (s *testSerialSuite) TestChangeMaxIndexLength(c *C) {
tk := testkit.NewTestKitWithInit(c, s.store)
defer config.RestoreFunc()()
config.UpdateGlobal(func(conf *config.Config) {
conf.MaxIndexLength = config.DefMaxOfMaxIndexLength
})
tk.MustExec("drop table if exists t;")
tk.MustExec("drop table if exists t1;")
tk.MustExec("create table t (c1 varchar(3073), index(c1)) charset = ascii;")
tk.MustExec(fmt.Sprintf("create table t1 (c1 varchar(%d), index(c1)) charset = ascii;", config.DefMaxOfMaxIndexLength))
_, err := tk.Exec(fmt.Sprintf("create table t2 (c1 varchar(%d), index(c1)) charset = ascii;", config.DefMaxOfMaxIndexLength+1))
c.Assert(err.Error(), Equals, "[ddl:1071]Specified key was too long; max key length is 12288 bytes")
tk.MustExec("drop table t, t1")
}
func (s *testSerialSuite) TestPrimaryKey(c *C) {
tk := testkit.NewTestKit(c, s.store)
tk.MustExec("use test")
tk.Se.GetSessionVars().EnableClusteredIndex = false
tk.MustExec("create table primary_key_test (a int, b varchar(10))")
tk.MustExec("create table primary_key_test_1 (a int, b varchar(10), primary key(a))")
_, err := tk.Exec("alter table primary_key_test add primary key(a)")
c.Assert(ddl.ErrUnsupportedModifyPrimaryKey.Equal(err), IsTrue)
_, err = tk.Exec("alter table primary_key_test drop primary key")
c.Assert(err.Error(), Equals, "[ddl:8200]Unsupported drop primary key when alter-primary-key is false")
// for "drop index `primary` on ..." syntax
_, err = tk.Exec("drop index `primary` on primary_key_test")
c.Assert(err.Error(), Equals, "[ddl:8200]Unsupported drop primary key when alter-primary-key is false")
_, err = tk.Exec("drop index `primary` on primary_key_test_1")
c.Assert(err.Error(), Equals, "[ddl:8200]Unsupported drop primary key when alter-primary-key is false")
// Change the value of AlterPrimaryKey.
tk.MustExec("create table primary_key_test1 (a int, b varchar(10), primary key(a))")
tk.MustExec("create table primary_key_test2 (a int, b varchar(10), primary key(b))")
tk.MustExec("create table primary_key_test3 (a int, b varchar(10))")
defer config.RestoreFunc()()
config.UpdateGlobal(func(conf *config.Config) {
conf.AlterPrimaryKey = true
})
_, err = tk.Exec("alter table primary_key_test2 add primary key(a)")
c.Assert(infoschema.ErrMultiplePriKey.Equal(err), IsTrue)
// We can't add a primary key when the table's pk_is_handle is true.
_, err = tk.Exec("alter table primary_key_test1 add primary key(a)")
c.Assert(infoschema.ErrMultiplePriKey.Equal(err), IsTrue)
_, err = tk.Exec("alter table primary_key_test1 add primary key(b)")
c.Assert(infoschema.ErrMultiplePriKey.Equal(err), IsTrue)
_, err = tk.Exec("alter table primary_key_test1 drop primary key")
c.Assert(err.Error(), Equals, "[ddl:8200]Unsupported drop primary key when the table's pkIsHandle is true")
tk.MustExec("alter table primary_key_test2 drop primary key")
_, err = tk.Exec("alter table primary_key_test3 drop primary key")
c.Assert(err.Error(), Equals, "[ddl:1091]Can't DROP 'PRIMARY'; check that column/key exists")
// for "drop index `primary` on ..." syntax
tk.MustExec("create table primary_key_test4 (a int, b varchar(10), primary key(a))")
config.UpdateGlobal(func(conf *config.Config) {
conf.AlterPrimaryKey = false
})
_, err = tk.Exec("drop index `primary` on primary_key_test4")
c.Assert(err.Error(), Equals, "[ddl:8200]Unsupported drop primary key when alter-primary-key is false")
// for the index name is `primary`
tk.MustExec("create table tt(`primary` int);")
tk.MustExec("alter table tt add index (`primary`);")
_, err = tk.Exec("drop index `primary` on tt")
c.Assert(err.Error(), Equals, "[ddl:8200]Unsupported drop primary key when alter-primary-key is false")
// The primary key cannot be invisible, for the case pk_is_handle.
tk.MustExec("drop table if exists t1, t2;")
_, err = tk.Exec("create table t1(c1 int not null, primary key(c1) invisible);")
c.Assert(ddl.ErrPKIndexCantBeInvisible.Equal(err), IsTrue)
tk.MustExec("create table t2 (a int, b int not null, primary key(a), unique(b) invisible);")
// Test drop clustered primary key.
config.UpdateGlobal(func(conf *config.Config) {
conf.AlterPrimaryKey = false
})
tk.MustExec("drop table if exists t;")
tk.Se.GetSessionVars().EnableClusteredIndex = true
tk.MustExec("create table t(a int, b varchar(64), primary key(b));")
tk.MustExec("insert into t values(1,'a'), (2, 'b');")
config.UpdateGlobal(func(conf *config.Config) {
conf.AlterPrimaryKey = true
})
errMsg := "[ddl:8200]Unsupported drop primary key when the table is using clustered index"
tk.MustGetErrMsg("alter table t drop primary key;", errMsg)
}
func (s *testSerialSuite) TestDropAutoIncrementIndex(c *C) {
tk := testkit.NewTestKit(c, s.store)
tk.MustExec("use test")
tk.MustExec("drop table if exists t1")
tk.MustExec("create table t1 (a int(11) not null auto_increment key, b int(11), c bigint, unique key (a, b, c))")
tk.MustExec("alter table t1 drop index a")
}
func (s *testSerialSuite) TestMultiRegionGetTableEndHandle(c *C) {
tk := testkit.NewTestKit(c, s.store)
tk.MustExec("drop database if exists test_get_endhandle")
tk.MustExec("create database test_get_endhandle")
tk.MustExec("use test_get_endhandle")
tk.MustExec("create table t(a bigint PRIMARY KEY, b int)")
var builder strings.Builder
fmt.Fprintf(&builder, "insert into t values ")
for i := 0; i < 1000; i++ {
fmt.Fprintf(&builder, "(%v, %v),", i, i)
}
sql := builder.String()
tk.MustExec(sql[:len(sql)-1])
// Get table ID for split.
dom := domain.GetDomain(tk.Se)
is := dom.InfoSchema()
tbl, err := is.TableByName(model.NewCIStr("test_get_endhandle"), model.NewCIStr("t"))
c.Assert(err, IsNil)
tblID := tbl.Meta().ID
d := s.dom.DDL()
testCtx := newTestMaxTableRowIDContext(c, d, tbl)
// Split the table.
s.cluster.SplitTable(tblID, 100)
maxHandle, emptyTable := getMaxTableHandle(testCtx, s.store)
c.Assert(emptyTable, IsFalse)
c.Assert(maxHandle, Equals, kv.IntHandle(999))
tk.MustExec("insert into t values(10000, 1000)")
maxHandle, emptyTable = getMaxTableHandle(testCtx, s.store)
c.Assert(emptyTable, IsFalse)
c.Assert(maxHandle, Equals, kv.IntHandle(10000))
tk.MustExec("insert into t values(-1, 1000)")
maxHandle, emptyTable = getMaxTableHandle(testCtx, s.store)
c.Assert(emptyTable, IsFalse)
c.Assert(maxHandle, Equals, kv.IntHandle(10000))
}
func (s *testSerialSuite) TestGetTableEndHandle(c *C) {
// TestGetTableEndHandle test ddl.GetTableMaxHandle method, which will return the max row id of the table.
tk := testkit.NewTestKit(c, s.store)
tk.MustExec("drop database if exists test_get_endhandle")
tk.MustExec("create database test_get_endhandle")
tk.MustExec("use test_get_endhandle")
// Test PK is handle.
tk.MustExec("create table t(a bigint PRIMARY KEY, b int)")
is := s.dom.InfoSchema()
d := s.dom.DDL()
tbl, err := is.TableByName(model.NewCIStr("test_get_endhandle"), model.NewCIStr("t"))
c.Assert(err, IsNil)
testCtx := newTestMaxTableRowIDContext(c, d, tbl)
// test empty table
checkGetMaxTableRowID(testCtx, s.store, true, nil)
tk.MustExec("insert into t values(-1, 1)")
checkGetMaxTableRowID(testCtx, s.store, false, kv.IntHandle(-1))
tk.MustExec("insert into t values(9223372036854775806, 1)")
checkGetMaxTableRowID(testCtx, s.store, false, kv.IntHandle(9223372036854775806))
tk.MustExec("insert into t values(9223372036854775807, 1)")
checkGetMaxTableRowID(testCtx, s.store, false, kv.IntHandle(9223372036854775807))
tk.MustExec("insert into t values(10, 1)")
tk.MustExec("insert into t values(102149142, 1)")
checkGetMaxTableRowID(testCtx, s.store, false, kv.IntHandle(9223372036854775807))
tk.MustExec("create table t1(a bigint PRIMARY KEY, b int)")
var builder strings.Builder
fmt.Fprintf(&builder, "insert into t1 values ")
for i := 0; i < 1000; i++ {
fmt.Fprintf(&builder, "(%v, %v),", i, i)
}
sql := builder.String()
tk.MustExec(sql[:len(sql)-1])
is = s.dom.InfoSchema()
testCtx.tbl, err = is.TableByName(model.NewCIStr("test_get_endhandle"), model.NewCIStr("t1"))
c.Assert(err, IsNil)
checkGetMaxTableRowID(testCtx, s.store, false, kv.IntHandle(999))
// Test PK is not handle
tk.MustExec("create table t2(a varchar(255))")
is = s.dom.InfoSchema()
testCtx.tbl, err = is.TableByName(model.NewCIStr("test_get_endhandle"), model.NewCIStr("t2"))
c.Assert(err, IsNil)
checkGetMaxTableRowID(testCtx, s.store, true, nil)
builder.Reset()
fmt.Fprintf(&builder, "insert into t2 values ")
for i := 0; i < 1000; i++ {
fmt.Fprintf(&builder, "(%v),", i)
}
sql = builder.String()
tk.MustExec(sql[:len(sql)-1])
result := tk.MustQuery("select MAX(_tidb_rowid) from t2")
maxHandle, emptyTable := getMaxTableHandle(testCtx, s.store)
result.Check(testkit.Rows(fmt.Sprintf("%v", maxHandle.IntValue())))
c.Assert(emptyTable, IsFalse)
tk.MustExec("insert into t2 values(100000)")
result = tk.MustQuery("select MAX(_tidb_rowid) from t2")
maxHandle, emptyTable = getMaxTableHandle(testCtx, s.store)
result.Check(testkit.Rows(fmt.Sprintf("%v", maxHandle.IntValue())))
c.Assert(emptyTable, IsFalse)
tk.MustExec(fmt.Sprintf("insert into t2 values(%v)", math.MaxInt64-1))
result = tk.MustQuery("select MAX(_tidb_rowid) from t2")
maxHandle, emptyTable = getMaxTableHandle(testCtx, s.store)
result.Check(testkit.Rows(fmt.Sprintf("%v", maxHandle.IntValue())))
c.Assert(emptyTable, IsFalse)
tk.MustExec(fmt.Sprintf("insert into t2 values(%v)", math.MaxInt64))
result = tk.MustQuery("select MAX(_tidb_rowid) from t2")
maxHandle, emptyTable = getMaxTableHandle(testCtx, s.store)
result.Check(testkit.Rows(fmt.Sprintf("%v", maxHandle.IntValue())))
c.Assert(emptyTable, IsFalse)
tk.MustExec("insert into t2 values(100)")
result = tk.MustQuery("select MAX(_tidb_rowid) from t2")
maxHandle, emptyTable = getMaxTableHandle(testCtx, s.store)
result.Check(testkit.Rows(fmt.Sprintf("%v", maxHandle.IntValue())))
c.Assert(emptyTable, IsFalse)
}
func (s *testSerialSuite) TestMultiRegionGetTableEndCommonHandle(c *C) {
tk := testkit.NewTestKit(c, s.store)
tk.MustExec("drop database if exists test_get_endhandle")
tk.MustExec("create database test_get_endhandle")
tk.MustExec("use test_get_endhandle")
tk.Se.GetSessionVars().EnableClusteredIndex = true
tk.MustExec("create table t(a varchar(20), b int, c float, d bigint, primary key (a, b, c))")
var builder strings.Builder
fmt.Fprintf(&builder, "insert into t values ")
for i := 0; i < 1000; i++ {
fmt.Fprintf(&builder, "('%v', %v, %v, %v),", i, i, i, i)
}
sql := builder.String()
tk.MustExec(sql[:len(sql)-1])
// Get table ID for split.
dom := domain.GetDomain(tk.Se)
is := dom.InfoSchema()
tbl, err := is.TableByName(model.NewCIStr("test_get_endhandle"), model.NewCIStr("t"))
c.Assert(err, IsNil)
tblID := tbl.Meta().ID
d := s.dom.DDL()
testCtx := newTestMaxTableRowIDContext(c, d, tbl)
// Split the table.
s.cluster.SplitTable(tblID, 100)
maxHandle, emptyTable := getMaxTableHandle(testCtx, s.store)
c.Assert(emptyTable, IsFalse)
c.Assert(maxHandle, HandleEquals, MustNewCommonHandle(c, "999", 999, 999))
tk.MustExec("insert into t values('a', 1, 1, 1)")
maxHandle, emptyTable = getMaxTableHandle(testCtx, s.store)
c.Assert(emptyTable, IsFalse)
c.Assert(maxHandle, HandleEquals, MustNewCommonHandle(c, "a", 1, 1))
tk.MustExec("insert into t values('0000', 1, 1, 1)")
maxHandle, emptyTable = getMaxTableHandle(testCtx, s.store)
c.Assert(emptyTable, IsFalse)
c.Assert(maxHandle, HandleEquals, MustNewCommonHandle(c, "a", 1, 1))
}
func (s *testSerialSuite) TestGetTableEndCommonHandle(c *C) {
tk := testkit.NewTestKit(c, s.store)
tk.MustExec("drop database if exists test_get_endhandle")
tk.MustExec("create database test_get_endhandle")
tk.MustExec("use test_get_endhandle")
tk.Se.GetSessionVars().EnableClusteredIndex = true
tk.MustExec("create table t(a varchar(15), b bigint, c int, primary key (a, b))")
tk.MustExec("create table t1(a varchar(15), b bigint, c int, primary key (a(2), b))")
is := s.dom.InfoSchema()
d := s.dom.DDL()
tbl, err := is.TableByName(model.NewCIStr("test_get_endhandle"), model.NewCIStr("t"))
c.Assert(err, IsNil)
testCtx := newTestMaxTableRowIDContext(c, d, tbl)
// test empty table
checkGetMaxTableRowID(testCtx, s.store, true, nil)
tk.MustExec("insert into t values('abc', 1, 10)")
expectedHandle := MustNewCommonHandle(c, "abc", 1)
checkGetMaxTableRowID(testCtx, s.store, false, expectedHandle)
tk.MustExec("insert into t values('abchzzzzzzzz', 1, 10)")
expectedHandle = MustNewCommonHandle(c, "abchzzzzzzzz", 1)
checkGetMaxTableRowID(testCtx, s.store, false, expectedHandle)
tk.MustExec("insert into t values('a', 1, 10)")
tk.MustExec("insert into t values('ab', 1, 10)")
checkGetMaxTableRowID(testCtx, s.store, false, expectedHandle)
// Test MaxTableRowID with prefixed primary key.
tbl, err = is.TableByName(model.NewCIStr("test_get_endhandle"), model.NewCIStr("t1"))
c.Assert(err, IsNil)
is = s.dom.InfoSchema()
d = s.dom.DDL()
testCtx = newTestMaxTableRowIDContext(c, d, tbl)
checkGetMaxTableRowID(testCtx, s.store, true, nil)
tk.MustExec("insert into t1 values('abccccc', 1, 10)")
expectedHandle = MustNewCommonHandle(c, "ab", 1)
checkGetMaxTableRowID(testCtx, s.store, false, expectedHandle)
tk.MustExec("insert into t1 values('azzzz', 1, 10)")
expectedHandle = MustNewCommonHandle(c, "az", 1)
checkGetMaxTableRowID(testCtx, s.store, false, expectedHandle)
}
func (s *testSerialSuite) TestCreateTableWithLike(c *C) {
tk := testkit.NewTestKit(c, s.store)
// for the same database
tk.MustExec("create database ctwl_db")
tk.MustExec("use ctwl_db")
tk.MustExec("create table tt(id int primary key)")
tk.MustExec("create table t (c1 int not null auto_increment, c2 int, constraint cc foreign key (c2) references tt(id), primary key(c1)) auto_increment = 10")
tk.MustExec("insert into t set c2=1")
tk.MustExec("create table t1 like ctwl_db.t")
tk.MustExec("insert into t1 set c2=11")
tk.MustExec("create table t2 (like ctwl_db.t1)")
tk.MustExec("insert into t2 set c2=12")
tk.MustQuery("select * from t").Check(testkit.Rows("10 1"))
tk.MustQuery("select * from t1").Check(testkit.Rows("1 11"))
tk.MustQuery("select * from t2").Check(testkit.Rows("1 12"))
ctx := tk.Se.(sessionctx.Context)
is := domain.GetDomain(ctx).InfoSchema()
tbl1, err := is.TableByName(model.NewCIStr("ctwl_db"), model.NewCIStr("t1"))
c.Assert(err, IsNil)
tbl1Info := tbl1.Meta()
c.Assert(tbl1Info.ForeignKeys, IsNil)
c.Assert(tbl1Info.PKIsHandle, Equals, true)
col := tbl1Info.Columns[0]
hasNotNull := mysql.HasNotNullFlag(col.Flag)
c.Assert(hasNotNull, IsTrue)
tbl2, err := is.TableByName(model.NewCIStr("ctwl_db"), model.NewCIStr("t2"))
c.Assert(err, IsNil)
tbl2Info := tbl2.Meta()
c.Assert(tbl2Info.ForeignKeys, IsNil)
c.Assert(tbl2Info.PKIsHandle, Equals, true)
c.Assert(mysql.HasNotNullFlag(tbl2Info.Columns[0].Flag), IsTrue)
// for different databases
tk.MustExec("create database ctwl_db1")
tk.MustExec("use ctwl_db1")
tk.MustExec("create table t1 like ctwl_db.t")
tk.MustExec("insert into t1 set c2=11")
tk.MustQuery("select * from t1").Check(testkit.Rows("1 11"))
is = domain.GetDomain(ctx).InfoSchema()
tbl1, err = is.TableByName(model.NewCIStr("ctwl_db1"), model.NewCIStr("t1"))
c.Assert(err, IsNil)
c.Assert(tbl1.Meta().ForeignKeys, IsNil)
// for table partition
tk.MustExec("use ctwl_db")
tk.MustExec("create table pt1 (id int) partition by range columns (id) (partition p0 values less than (10))")
tk.MustExec("insert into pt1 values (1),(2),(3),(4);")
tk.MustExec("create table ctwl_db1.pt1 like ctwl_db.pt1;")
tk.MustQuery("select * from ctwl_db1.pt1").Check(testkit.Rows())
// Test create table like for partition table.
atomic.StoreUint32(&ddl.EnableSplitTableRegion, 1)
tk.MustExec("use test")
tk.MustExec("set @@global.tidb_scatter_region=1;")
tk.MustExec("drop table if exists partition_t;")
tk.MustExec("create table partition_t (a int, b int,index(a)) partition by hash (a) partitions 3")
tk.MustExec("drop table if exists t1;")
tk.MustExec("create table t1 like partition_t")
re := tk.MustQuery("show table t1 regions")
rows := re.Rows()
c.Assert(len(rows), Equals, 3)
tbl := testGetTableByName(c, tk.Se, "test", "t1")
partitionDef := tbl.Meta().GetPartitionInfo().Definitions
c.Assert(rows[0][1], Matches, fmt.Sprintf("t_%d_.*", partitionDef[0].ID))
c.Assert(rows[1][1], Matches, fmt.Sprintf("t_%d_.*", partitionDef[1].ID))
c.Assert(rows[2][1], Matches, fmt.Sprintf("t_%d_.*", partitionDef[2].ID))
// Test pre-split table region when create table like.
tk.MustExec("drop table if exists t_pre")
tk.MustExec("create table t_pre (a int, b int) shard_row_id_bits = 2 pre_split_regions=2;")
tk.MustExec("drop table if exists t2;")
tk.MustExec("create table t2 like t_pre")
re = tk.MustQuery("show table t2 regions")
rows = re.Rows()
// Table t2 which create like t_pre should have 4 regions now.
c.Assert(len(rows), Equals, 4)
tbl = testGetTableByName(c, tk.Se, "test", "t2")
c.Assert(rows[1][1], Equals, fmt.Sprintf("t_%d_r_2305843009213693952", tbl.Meta().ID))
c.Assert(rows[2][1], Equals, fmt.Sprintf("t_%d_r_4611686018427387904", tbl.Meta().ID))
c.Assert(rows[3][1], Equals, fmt.Sprintf("t_%d_r_6917529027641081856", tbl.Meta().ID))
// Test after truncate table the region is also splited.
tk.MustExec("truncate table t2")
re = tk.MustQuery("show table t2 regions")
rows = re.Rows()
c.Assert(len(rows), Equals, 4)
tbl = testGetTableByName(c, tk.Se, "test", "t2")
c.Assert(rows[1][1], Equals, fmt.Sprintf("t_%d_r_2305843009213693952", tbl.Meta().ID))
c.Assert(rows[2][1], Equals, fmt.Sprintf("t_%d_r_4611686018427387904", tbl.Meta().ID))
c.Assert(rows[3][1], Equals, fmt.Sprintf("t_%d_r_6917529027641081856", tbl.Meta().ID))
defer atomic.StoreUint32(&ddl.EnableSplitTableRegion, 0)
// for failure table cases
tk.MustExec("use ctwl_db")
failSQL := fmt.Sprintf("create table t1 like test_not_exist.t")
tk.MustGetErrCode(failSQL, mysql.ErrNoSuchTable)
failSQL = fmt.Sprintf("create table t1 like test.t_not_exist")
tk.MustGetErrCode(failSQL, mysql.ErrNoSuchTable)
failSQL = fmt.Sprintf("create table t1 (like test_not_exist.t)")
tk.MustGetErrCode(failSQL, mysql.ErrNoSuchTable)
failSQL = fmt.Sprintf("create table test_not_exis.t1 like ctwl_db.t")
tk.MustGetErrCode(failSQL, mysql.ErrBadDB)
failSQL = fmt.Sprintf("create table t1 like ctwl_db.t")
tk.MustGetErrCode(failSQL, mysql.ErrTableExists)
// test failure for wrong object cases
tk.MustExec("drop view if exists v")
tk.MustExec("create view v as select 1 from dual")
tk.MustGetErrCode("create table viewTable like v", mysql.ErrWrongObject)
tk.MustExec("drop sequence if exists seq")
tk.MustExec("create sequence seq")
tk.MustGetErrCode("create table sequenceTable like seq", mysql.ErrWrongObject)
tk.MustExec("drop database ctwl_db")
tk.MustExec("drop database ctwl_db1")
}
// TestCancelAddIndex1 tests canceling ddl job when the add index worker is not started.
func (s *testSerialSuite) TestCancelAddIndexPanic(c *C) {
c.Assert(failpoint.Enable("github.com/pingcap/tidb/ddl/errorMockPanic", `return(true)`), IsNil)
defer func() {
c.Assert(failpoint.Disable("github.com/pingcap/tidb/ddl/errorMockPanic"), IsNil)
}()
tk := testkit.NewTestKit(c, s.store)
tk.MustExec("use test")
tk.MustExec("drop table if exists t")
tk.MustExec("create table t(c1 int, c2 int)")
defer tk.MustExec("drop table t;")
for i := 0; i < 5; i++ {
tk.MustExec("insert into t values (?, ?)", i, i)
}
var checkErr error
oldReorgWaitTimeout := ddl.ReorgWaitTimeout
ddl.ReorgWaitTimeout = 50 * time.Millisecond
defer func() { ddl.ReorgWaitTimeout = oldReorgWaitTimeout }()
hook := &ddl.TestDDLCallback{}
hook.OnJobRunBeforeExported = func(job *model.Job) {
if job.Type == model.ActionAddIndex && job.State == model.JobStateRunning && job.SchemaState == model.StateWriteReorganization && job.SnapshotVer != 0 {
jobIDs := []int64{job.ID}
hookCtx := mock.NewContext()
hookCtx.Store = s.store
err := hookCtx.NewTxn(context.Background())
if err != nil {
checkErr = errors.Trace(err)
return
}
txn, err := hookCtx.Txn(true)
if err != nil {
checkErr = errors.Trace(err)
return
}
errs, err := admin.CancelJobs(txn, jobIDs)
if err != nil {
checkErr = errors.Trace(err)
return
}
if errs[0] != nil {
checkErr = errors.Trace(errs[0])
return
}
txn, err = hookCtx.Txn(true)
if err != nil {
checkErr = errors.Trace(err)
return
}
checkErr = txn.Commit(context.Background())
}
}
origHook := s.dom.DDL().GetHook()
defer s.dom.DDL().(ddl.DDLForTest).SetHook(origHook)
s.dom.DDL().(ddl.DDLForTest).SetHook(hook)
rs, err := tk.Exec("alter table t add index idx_c2(c2)")
if rs != nil {
rs.Close()
}
c.Assert(checkErr, IsNil)
c.Assert(err, NotNil)
errMsg := err.Error()
// Cancelling the job can either succeed or not, it depends on whether the cancelled job takes affect.
// For now, there's no way to guarantee that cancelling will always take effect.
// TODO: After issue #17904 is fixed, there is no need to tolerate it here.
c.Assert(strings.HasPrefix(errMsg, "[ddl:8214]Cancelled DDL job") || strings.HasPrefix(errMsg, "[ddl:8211]DDL job rollback"), IsTrue)
}
func (s *testSerialSuite) TestRecoverTableByJobID(c *C) {
tk := testkit.NewTestKit(c, s.store)
tk.MustExec("create database if not exists test_recover")
tk.MustExec("use test_recover")
tk.MustExec("drop table if exists t_recover")
tk.MustExec("create table t_recover (a int);")
defer func(originGC bool) {
if originGC {
ddl.EmulatorGCEnable()
} else {
ddl.EmulatorGCDisable()
}
}(ddl.IsEmulatorGCEnable())
// disable emulator GC.
// Otherwise emulator GC will delete table record as soon as possible after execute drop table ddl.
ddl.EmulatorGCDisable()
gcTimeFormat := "20060102-15:04:05 -0700 MST"
timeBeforeDrop := time.Now().Add(0 - 48*60*60*time.Second).Format(gcTimeFormat)
timeAfterDrop := time.Now().Add(48 * 60 * 60 * time.Second).Format(gcTimeFormat)
safePointSQL := `INSERT HIGH_PRIORITY INTO mysql.tidb VALUES ('tikv_gc_safe_point', '%[1]s', '')
ON DUPLICATE KEY
UPDATE variable_value = '%[1]s'`
// clear GC variables first.
tk.MustExec("delete from mysql.tidb where variable_name in ( 'tikv_gc_safe_point','tikv_gc_enable' )")
tk.MustExec("insert into t_recover values (1),(2),(3)")
tk.MustExec("drop table t_recover")
getDDLJobID := func(table, tp string) int64 {
rs, err := tk.Exec("admin show ddl jobs")
c.Assert(err, IsNil)
rows, err := session.GetRows4Test(context.Background(), tk.Se, rs)
c.Assert(err, IsNil)
for _, row := range rows {
if row.GetString(1) == table && row.GetString(3) == tp {
return row.GetInt64(0)
}
}
c.Errorf("can't find %s table of %s", tp, table)
return -1
}
jobID := getDDLJobID("test_recover", "drop table")
// if GC safe point is not exists in mysql.tidb
_, err := tk.Exec(fmt.Sprintf("recover table by job %d", jobID))
c.Assert(err, NotNil)
c.Assert(err.Error(), Equals, "can not get 'tikv_gc_safe_point'")
// set GC safe point
tk.MustExec(fmt.Sprintf(safePointSQL, timeBeforeDrop))
// if GC enable is not exists in mysql.tidb
tk.MustExec(fmt.Sprintf("recover table by job %d", jobID))
tk.MustExec("DROP TABLE t_recover")
err = gcutil.EnableGC(tk.Se)
c.Assert(err, IsNil)
// recover job is before GC safe point
tk.MustExec(fmt.Sprintf(safePointSQL, timeAfterDrop))
_, err = tk.Exec(fmt.Sprintf("recover table by job %d", jobID))
c.Assert(err, NotNil)
c.Assert(strings.Contains(err.Error(), "snapshot is older than GC safe point"), Equals, true)
// set GC safe point
tk.MustExec(fmt.Sprintf(safePointSQL, timeBeforeDrop))
// if there is a new table with the same name, should return failed.
tk.MustExec("create table t_recover (a int);")
_, err = tk.Exec(fmt.Sprintf("recover table by job %d", jobID))
c.Assert(err.Error(), Equals, infoschema.ErrTableExists.GenWithStackByArgs("t_recover").Error())
// drop the new table with the same name, then recover table.
tk.MustExec("drop table t_recover")
// do recover table.
tk.MustExec(fmt.Sprintf("recover table by job %d", jobID))
// check recover table meta and data record.
tk.MustQuery("select * from t_recover;").Check(testkit.Rows("1", "2", "3"))
// check recover table autoID.
tk.MustExec("insert into t_recover values (4),(5),(6)")
tk.MustQuery("select * from t_recover;").Check(testkit.Rows("1", "2", "3", "4", "5", "6"))
// recover table by none exits job.
_, err = tk.Exec(fmt.Sprintf("recover table by job %d", 10000000))
c.Assert(err, NotNil)
// Disable GC by manual first, then after recover table, the GC enable status should also be disabled.
err = gcutil.DisableGC(tk.Se)
c.Assert(err, IsNil)
tk.MustExec("delete from t_recover where a > 1")
tk.MustExec("drop table t_recover")
jobID = getDDLJobID("test_recover", "drop table")
tk.MustExec(fmt.Sprintf("recover table by job %d", jobID))
// check recover table meta and data record.
tk.MustQuery("select * from t_recover;").Check(testkit.Rows("1"))
// check recover table autoID.
tk.MustExec("insert into t_recover values (7),(8),(9)")
tk.MustQuery("select * from t_recover;").Check(testkit.Rows("1", "7", "8", "9"))
// Test for recover truncate table.
tk.MustExec("truncate table t_recover")
tk.MustExec("rename table t_recover to t_recover_new")
jobID = getDDLJobID("test_recover", "truncate table")
tk.MustExec(fmt.Sprintf("recover table by job %d", jobID))
tk.MustExec("insert into t_recover values (10)")
tk.MustQuery("select * from t_recover;").Check(testkit.Rows("1", "7", "8", "9", "10"))
gcEnable, err := gcutil.CheckGCEnable(tk.Se)
c.Assert(err, IsNil)
c.Assert(gcEnable, Equals, false)
}
func (s *testSerialSuite) TestRecoverTableByJobIDFail(c *C) {
tk := testkit.NewTestKit(c, s.store)
tk.MustExec("create database if not exists test_recover")
tk.MustExec("use test_recover")
tk.MustExec("drop table if exists t_recover")
tk.MustExec("create table t_recover (a int);")
defer func(originGC bool) {
if originGC {
ddl.EmulatorGCEnable()
} else {
ddl.EmulatorGCDisable()
}
}(ddl.IsEmulatorGCEnable())
// disable emulator GC.
// Otherwise emulator GC will delete table record as soon as possible after execute drop table ddl.
ddl.EmulatorGCDisable()
gcTimeFormat := "20060102-15:04:05 -0700 MST"
timeBeforeDrop := time.Now().Add(0 - 48*60*60*time.Second).Format(gcTimeFormat)
safePointSQL := `INSERT HIGH_PRIORITY INTO mysql.tidb VALUES ('tikv_gc_safe_point', '%[1]s', '')
ON DUPLICATE KEY
UPDATE variable_value = '%[1]s'`
tk.MustExec("insert into t_recover values (1),(2),(3)")
tk.MustExec("drop table t_recover")
rs, err := tk.Exec("admin show ddl jobs")
c.Assert(err, IsNil)
rows, err := session.GetRows4Test(context.Background(), tk.Se, rs)
c.Assert(err, IsNil)
row := rows[0]
c.Assert(row.GetString(1), Equals, "test_recover")
c.Assert(row.GetString(3), Equals, "drop table")
jobID := row.GetInt64(0)
// enableGC first
err = gcutil.EnableGC(tk.Se)
c.Assert(err, IsNil)
tk.MustExec(fmt.Sprintf(safePointSQL, timeBeforeDrop))
// set hook
hook := &ddl.TestDDLCallback{}
hook.OnJobRunBeforeExported = func(job *model.Job) {
if job.Type == model.ActionRecoverTable {
c.Assert(failpoint.Enable("github.com/pingcap/tidb/store/tikv/mockCommitError", `return(true)`), IsNil)
c.Assert(failpoint.Enable("github.com/pingcap/tidb/ddl/mockRecoverTableCommitErr", `return(true)`), IsNil)
}
}
origHook := s.dom.DDL().GetHook()
defer s.dom.DDL().(ddl.DDLForTest).SetHook(origHook)
s.dom.DDL().(ddl.DDLForTest).SetHook(hook)
// do recover table.
tk.MustExec(fmt.Sprintf("recover table by job %d", jobID))
c.Assert(failpoint.Disable("github.com/pingcap/tidb/store/tikv/mockCommitError"), IsNil)
c.Assert(failpoint.Disable("github.com/pingcap/tidb/ddl/mockRecoverTableCommitErr"), IsNil)
// make sure enable GC after recover table.
enable, err := gcutil.CheckGCEnable(tk.Se)
c.Assert(err, IsNil)
c.Assert(enable, Equals, true)
// check recover table meta and data record.
tk.MustQuery("select * from t_recover;").Check(testkit.Rows("1", "2", "3"))
// check recover table autoID.
tk.MustExec("insert into t_recover values (4),(5),(6)")
tk.MustQuery("select * from t_recover;").Check(testkit.Rows("1", "2", "3", "4", "5", "6"))
}
func (s *testSerialSuite) TestRecoverTableByTableNameFail(c *C) {
tk := testkit.NewTestKit(c, s.store)
tk.MustExec("create database if not exists test_recover")
tk.MustExec("use test_recover")
tk.MustExec("drop table if exists t_recover")
tk.MustExec("create table t_recover (a int);")
defer func(originGC bool) {
if originGC {
ddl.EmulatorGCEnable()
} else {
ddl.EmulatorGCDisable()
}
}(ddl.IsEmulatorGCEnable())
// disable emulator GC.
// Otherwise emulator GC will delete table record as soon as possible after execute drop table ddl.
ddl.EmulatorGCDisable()
gcTimeFormat := "20060102-15:04:05 -0700 MST"
timeBeforeDrop := time.Now().Add(0 - 48*60*60*time.Second).Format(gcTimeFormat)
safePointSQL := `INSERT HIGH_PRIORITY INTO mysql.tidb VALUES ('tikv_gc_safe_point', '%[1]s', '')
ON DUPLICATE KEY
UPDATE variable_value = '%[1]s'`
tk.MustExec("insert into t_recover values (1),(2),(3)")
tk.MustExec("drop table t_recover")
// enableGC first
err := gcutil.EnableGC(tk.Se)
c.Assert(err, IsNil)
tk.MustExec(fmt.Sprintf(safePointSQL, timeBeforeDrop))
// set hook
hook := &ddl.TestDDLCallback{}
hook.OnJobRunBeforeExported = func(job *model.Job) {
if job.Type == model.ActionRecoverTable {
c.Assert(failpoint.Enable("github.com/pingcap/tidb/store/tikv/mockCommitError", `return(true)`), IsNil)
c.Assert(failpoint.Enable("github.com/pingcap/tidb/ddl/mockRecoverTableCommitErr", `return(true)`), IsNil)
}
}
origHook := s.dom.DDL().GetHook()
defer s.dom.DDL().(ddl.DDLForTest).SetHook(origHook)
s.dom.DDL().(ddl.DDLForTest).SetHook(hook)
// do recover table.
tk.MustExec("recover table t_recover")
c.Assert(failpoint.Disable("github.com/pingcap/tidb/store/tikv/mockCommitError"), IsNil)
c.Assert(failpoint.Disable("github.com/pingcap/tidb/ddl/mockRecoverTableCommitErr"), IsNil)
// make sure enable GC after recover table.
enable, err := gcutil.CheckGCEnable(tk.Se)
c.Assert(err, IsNil)
c.Assert(enable, Equals, true)
// check recover table meta and data record.
tk.MustQuery("select * from t_recover;").Check(testkit.Rows("1", "2", "3"))
// check recover table autoID.
tk.MustExec("insert into t_recover values (4),(5),(6)")
tk.MustQuery("select * from t_recover;").Check(testkit.Rows("1", "2", "3", "4", "5", "6"))
}
func (s *testSerialSuite) TestCancelJobByErrorCountLimit(c *C) {
tk := testkit.NewTestKit(c, s.store)
c.Assert(failpoint.Enable("github.com/pingcap/tidb/ddl/mockExceedErrorLimit", `return(true)`), IsNil)
defer func() {
c.Assert(failpoint.Disable("github.com/pingcap/tidb/ddl/mockExceedErrorLimit"), IsNil)
}()
tk.MustExec("use test")
tk.MustExec("drop table if exists t")
limit := variable.GetDDLErrorCountLimit()
tk.MustExec("set @@global.tidb_ddl_error_count_limit = 16")
err := ddlutil.LoadDDLVars(tk.Se)
c.Assert(err, IsNil)
defer tk.MustExec(fmt.Sprintf("set @@global.tidb_ddl_error_count_limit = %d", limit))
_, err = tk.Exec("create table t (a int)")
c.Assert(err, NotNil)
c.Assert(err.Error(), Equals, "[ddl:-1]DDL job rollback, error msg: mock do job error")
}
func (s *testSerialSuite) TestTruncateTableUpdateSchemaVersionErr(c *C) {
tk := testkit.NewTestKit(c, s.store)
c.Assert(failpoint.Enable("github.com/pingcap/tidb/ddl/mockTruncateTableUpdateVersionError", `return(true)`), IsNil)
tk.MustExec("use test")
tk.MustExec("drop table if exists t")
limit := variable.GetDDLErrorCountLimit()
tk.MustExec("set @@global.tidb_ddl_error_count_limit = 5")
err := ddlutil.LoadDDLVars(tk.Se)
c.Assert(err, IsNil)
defer tk.MustExec(fmt.Sprintf("set @@global.tidb_ddl_error_count_limit = %d", limit))
tk.MustExec("create table t (a int)")
_, err = tk.Exec("truncate table t")
c.Assert(err, NotNil)
c.Assert(err.Error(), Equals, "[ddl:-1]DDL job rollback, error msg: mock update version error")
// Disable fail point.
c.Assert(failpoint.Disable("github.com/pingcap/tidb/ddl/mockTruncateTableUpdateVersionError"), IsNil)
tk.MustExec("truncate table t")
}
func (s *testSerialSuite) TestCanceledJobTakeTime(c *C) {
tk := testkit.NewTestKit(c, s.store)
tk.MustExec("use test")
tk.MustExec("create table t_cjtt(a int)")
hook := &ddl.TestDDLCallback{}
once := sync.Once{}
hook.OnJobUpdatedExported = func(job *model.Job) {
once.Do(func() {
err := kv.RunInNewTxn(context.Background(), s.store, false, func(ctx context.Context, txn kv.Transaction) error {
t := meta.NewMeta(txn)
return t.DropTableOrView(job.SchemaID, job.TableID, true)
})
c.Assert(err, IsNil)
})
}
origHook := s.dom.DDL().GetHook()
s.dom.DDL().(ddl.DDLForTest).SetHook(hook)
defer s.dom.DDL().(ddl.DDLForTest).SetHook(origHook)
originalWT := ddl.GetWaitTimeWhenErrorOccurred()
ddl.SetWaitTimeWhenErrorOccurred(1 * time.Second)
defer func() { ddl.SetWaitTimeWhenErrorOccurred(originalWT) }()
startTime := time.Now()
tk.MustGetErrCode("alter table t_cjtt add column b int", mysql.ErrNoSuchTable)
sub := time.Since(startTime)
c.Assert(sub, Less, ddl.GetWaitTimeWhenErrorOccurred())
}
func (s *testSerialSuite) TestTableLocksEnable(c *C) {
tk := testkit.NewTestKit(c, s.store)
tk.MustExec("use test")
tk.MustExec("drop table if exists t1")
defer tk.MustExec("drop table if exists t1")
tk.MustExec("create table t1 (a int)")
// Test for enable table lock config.
defer config.RestoreFunc()()
config.UpdateGlobal(func(conf *config.Config) {
conf.EnableTableLock = false
})
tk.MustExec("lock tables t1 write")
checkTableLock(c, tk.Se, "test", "t1", model.TableLockNone)
}
func (s *testSerialSuite) TestAutoRandom(c *C) {
tk := testkit.NewTestKit(c, s.store)
tk.MustExec("create database if not exists auto_random_db")
defer tk.MustExec("drop database if exists auto_random_db")
tk.MustExec("use auto_random_db")
databaseName, tableName := "auto_random_db", "t"
tk.MustExec("drop table if exists t")
tk.MustExec("set @@allow_auto_random_explicit_insert = true")
assertInvalidAutoRandomErr := func(sql string, errMsg string, args ...interface{}) {
_, err := tk.Exec(sql)
c.Assert(err, NotNil)
c.Assert(err.Error(), Equals, ddl.ErrInvalidAutoRandom.GenWithStackByArgs(fmt.Sprintf(errMsg, args...)).Error())
}
assertPKIsNotHandle := func(sql, errCol string) {
assertInvalidAutoRandomErr(sql, autoid.AutoRandomPKisNotHandleErrMsg, errCol)
}
assertAlterValue := func(sql string) {
assertInvalidAutoRandomErr(sql, autoid.AutoRandomAlterErrMsg)
}
assertDecreaseBitErr := func(sql string) {
assertInvalidAutoRandomErr(sql, autoid.AutoRandomDecreaseBitErrMsg)
}
assertWithAutoInc := func(sql string) {
assertInvalidAutoRandomErr(sql, autoid.AutoRandomIncompatibleWithAutoIncErrMsg)
}
assertOverflow := func(sql, colName string, maxAutoRandBits, actualAutoRandBits uint64) {
assertInvalidAutoRandomErr(sql, autoid.AutoRandomOverflowErrMsg, maxAutoRandBits, actualAutoRandBits, colName)
}
assertMaxOverflow := func(sql, colName string, autoRandBits uint64) {
assertInvalidAutoRandomErr(sql, autoid.AutoRandomOverflowErrMsg, autoid.MaxAutoRandomBits, autoRandBits, colName)
}
assertModifyColType := func(sql string) {
tk.MustGetErrCode(sql, errno.ErrUnsupportedDDLOperation)
}
assertDefault := func(sql string) {
assertInvalidAutoRandomErr(sql, autoid.AutoRandomIncompatibleWithDefaultValueErrMsg)
}
assertNonPositive := func(sql string) {
assertInvalidAutoRandomErr(sql, autoid.AutoRandomNonPositive)
}
assertBigIntOnly := func(sql, colType string) {
assertInvalidAutoRandomErr(sql, autoid.AutoRandomOnNonBigIntColumn, colType)
}
assertAddColumn := func(sql, colName string) {
{
assertInvalidAutoRandomErr(sql, autoid.AutoRandomAlterAddColumn, colName, databaseName, tableName)
}
}
mustExecAndDrop := func(sql string, fns ...func()) {
tk.MustExec(sql)
for _, f := range fns {
f()
}
tk.MustExec("drop table t")
}
ConfigTestUtils.SetupAutoRandomTestConfig()
defer ConfigTestUtils.RestoreAutoRandomTestConfig()
// Only bigint column can set auto_random
assertBigIntOnly("create table t (a char primary key auto_random(3), b int)", "char")
assertBigIntOnly("create table t (a varchar(255) primary key auto_random(3), b int)", "varchar")
assertBigIntOnly("create table t (a timestamp primary key auto_random(3), b int)", "timestamp")
// PKIsHandle, but auto_random is defined on non-primary key.
assertPKIsNotHandle("create table t (a bigint auto_random (3) primary key, b bigint auto_random (3))", "b")