forked from pingcap/tidb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplacement_policy_test.go
2043 lines (1747 loc) · 82.2 KB
/
placement_policy_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 2021 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package ddl_test
import (
"context"
"encoding/json"
"fmt"
"math"
"strconv"
. "github.com/pingcap/check"
"github.com/pingcap/failpoint"
"github.com/pingcap/tidb/ddl"
"github.com/pingcap/tidb/ddl/placement"
"github.com/pingcap/tidb/domain"
"github.com/pingcap/tidb/domain/infosync"
mysql "github.com/pingcap/tidb/errno"
"github.com/pingcap/tidb/infoschema"
"github.com/pingcap/tidb/kv"
"github.com/pingcap/tidb/meta"
"github.com/pingcap/tidb/parser/model"
"github.com/pingcap/tidb/sessionctx"
"github.com/pingcap/tidb/store/gcworker"
"github.com/pingcap/tidb/util/testkit"
"github.com/pingcap/tidb/util/testutil"
)
func clearAllBundles(c *C) {
bundles, err := infosync.GetAllRuleBundles(context.TODO())
c.Assert(err, IsNil)
clearBundles := make([]*placement.Bundle, 0, len(bundles))
for _, bundle := range bundles {
clearBundles = append(clearBundles, &placement.Bundle{ID: bundle.ID})
}
err = infosync.PutRuleBundles(context.TODO(), clearBundles)
c.Assert(err, IsNil)
}
func checkExistTableBundlesInPD(c *C, do *domain.Domain, dbName string, tbName string) {
tblInfo, err := do.InfoSchema().TableByName(model.NewCIStr(dbName), model.NewCIStr(tbName))
c.Assert(err, IsNil)
c.Assert(kv.RunInNewTxn(context.TODO(), do.Store(), false, func(ctx context.Context, txn kv.Transaction) error {
t := meta.NewMeta(txn)
checkTableBundlesInPD(c, t, tblInfo.Meta())
return nil
}), IsNil)
}
func checkAllBundlesNotChange(c *C, bundles []*placement.Bundle) {
currentBundles, err := infosync.GetAllRuleBundles(context.TODO())
c.Assert(err, IsNil)
bundlesMap := make(map[string]*placement.Bundle)
for _, bundle := range currentBundles {
bundlesMap[bundle.ID] = bundle
}
c.Assert(len(bundlesMap), Equals, len(currentBundles))
c.Assert(len(currentBundles), Equals, len(bundles))
for _, bundle := range bundles {
got, ok := bundlesMap[bundle.ID]
c.Assert(ok, IsTrue)
expectedJSON, err := json.Marshal(bundle)
c.Assert(err, IsNil)
gotJSON, err := json.Marshal(got)
c.Assert(err, IsNil)
c.Assert(string(gotJSON), Equals, string(expectedJSON))
}
}
func checkTableBundlesInPD(c *C, t *meta.Meta, tblInfo *model.TableInfo) {
checks := make([]*struct {
ID string
bundle *placement.Bundle
}, 0)
bundle, err := placement.NewTableBundle(t, tblInfo)
c.Assert(err, IsNil)
checks = append(checks, &struct {
ID string
bundle *placement.Bundle
}{ID: placement.GroupID(tblInfo.ID), bundle: bundle})
if tblInfo.Partition != nil {
for _, def := range tblInfo.Partition.Definitions {
bundle, err := placement.NewPartitionBundle(t, def)
c.Assert(err, IsNil)
checks = append(checks, &struct {
ID string
bundle *placement.Bundle
}{ID: placement.GroupID(def.ID), bundle: bundle})
}
}
for _, check := range checks {
got, err := infosync.GetRuleBundle(context.TODO(), check.ID)
c.Assert(err, IsNil)
if check.bundle == nil {
c.Assert(got.IsEmpty(), IsTrue)
} else {
expectedJSON, err := json.Marshal(check.bundle)
c.Assert(err, IsNil)
gotJSON, err := json.Marshal(got)
c.Assert(err, IsNil)
c.Assert(string(gotJSON), Equals, string(expectedJSON))
}
}
}
func (s *testDBSuite6) TestPlacementPolicy(c *C) {
clearAllBundles(c)
tk := testkit.NewTestKit(c, s.store)
tk.MustExec("use test")
tk.MustExec("drop placement policy if exists x")
originalHook := s.dom.DDL().GetHook()
defer s.dom.DDL().(ddl.DDLForTest).SetHook(originalHook)
hook := &ddl.TestDDLCallback{}
var policyID int64
hook.OnJobUpdatedExported = func(job *model.Job) {
if policyID != 0 {
return
}
// job.SchemaID will be assigned when the policy is created.
if job.SchemaName == "x" && job.Type == model.ActionCreatePlacementPolicy && job.SchemaID != 0 {
policyID = job.SchemaID
return
}
}
s.dom.DDL().(ddl.DDLForTest).SetHook(hook)
tk.MustExec("create placement policy x " +
"LEARNERS=1 " +
"LEARNER_CONSTRAINTS=\"[+region=cn-west-1]\" " +
"FOLLOWERS=3 " +
"FOLLOWER_CONSTRAINTS=\"[+disk=ssd]\"")
checkFunc := func(policyInfo *model.PolicyInfo) {
c.Assert(policyInfo.ID != 0, Equals, true)
c.Assert(policyInfo.Name.L, Equals, "x")
c.Assert(policyInfo.Followers, Equals, uint64(3))
c.Assert(policyInfo.FollowerConstraints, Equals, "[+disk=ssd]")
c.Assert(policyInfo.Voters, Equals, uint64(0))
c.Assert(policyInfo.VoterConstraints, Equals, "")
c.Assert(policyInfo.Learners, Equals, uint64(1))
c.Assert(policyInfo.LearnerConstraints, Equals, "[+region=cn-west-1]")
c.Assert(policyInfo.State, Equals, model.StatePublic)
c.Assert(policyInfo.Schedule, Equals, "")
}
// Check the policy is correctly reloaded in the information schema.
po := testGetPolicyByNameFromIS(c, tk.Se, "x")
checkFunc(po)
// Check the policy is correctly written in the kv meta.
po = testGetPolicyByIDFromMeta(c, s.store, policyID)
checkFunc(po)
tk.MustGetErrCode("create placement policy x "+
"PRIMARY_REGION=\"cn-east-1\" "+
"REGIONS=\"cn-east-1,cn-east-2\" ", mysql.ErrPlacementPolicyExists)
tk.MustGetErrCode("create placement policy X "+
"PRIMARY_REGION=\"cn-east-1\" "+
"REGIONS=\"cn-east-1,cn-east-2\" ", mysql.ErrPlacementPolicyExists)
tk.MustGetErrCode("create placement policy `X` "+
"PRIMARY_REGION=\"cn-east-1\" "+
"REGIONS=\"cn-east-1,cn-east-2\" ", mysql.ErrPlacementPolicyExists)
tk.MustExec("create placement policy if not exists X " +
"PRIMARY_REGION=\"cn-east-1\" " +
"REGIONS=\"cn-east-1,cn-east-2\" ")
tk.MustQuery("show warnings").Check(testkit.Rows("Note 8238 Placement policy 'X' already exists"))
bundles, err := infosync.GetAllRuleBundles(context.TODO())
c.Assert(err, IsNil)
c.Assert(0, Equals, len(bundles))
tk.MustExec("drop placement policy x")
tk.MustGetErrCode("drop placement policy x", mysql.ErrPlacementPolicyNotExists)
tk.MustExec("drop placement policy if exists x")
tk.MustQuery("show warnings").Check(testkit.Rows("Note 8239 Unknown placement policy 'x'"))
// TODO: privilege check & constraint syntax check.
}
func (s *testDBSuite6) TestPlacementFollowers(c *C) {
tk := testkit.NewTestKit(c, s.store)
tk.MustExec("use test")
defer tk.MustExec("drop placement policy if exists x")
tk.MustExec("drop placement policy if exists x")
tk.MustGetErrMsg("create placement policy x FOLLOWERS=99", "invalid placement option: followers should be less than or equal to 8: 99")
tk.MustExec("drop placement policy if exists x")
tk.MustExec("create placement policy x FOLLOWERS=4")
tk.MustGetErrMsg("alter placement policy x FOLLOWERS=99", "invalid placement option: followers should be less than or equal to 8: 99")
}
func testGetPolicyByIDFromMeta(c *C, store kv.Storage, policyID int64) *model.PolicyInfo {
var (
policyInfo *model.PolicyInfo
err error
)
err1 := kv.RunInNewTxn(context.Background(), store, false, func(ctx context.Context, txn kv.Transaction) error {
t := meta.NewMeta(txn)
policyInfo, err = t.GetPolicy(policyID)
if err != nil {
return err
}
return nil
})
c.Assert(err1, IsNil)
c.Assert(policyInfo, NotNil)
return policyInfo
}
func testGetPolicyByNameFromIS(c *C, ctx sessionctx.Context, policy string) *model.PolicyInfo {
dom := domain.GetDomain(ctx)
// Make sure the table schema is the new schema.
err := dom.Reload()
c.Assert(err, IsNil)
po, ok := dom.InfoSchema().PolicyByName(model.NewCIStr(policy))
c.Assert(ok, Equals, true)
return po
}
func (s *testDBSuite6) TestPlacementValidation(c *C) {
tk := testkit.NewTestKit(c, s.store)
tk.MustExec("use test")
tk.MustExec("drop placement policy if exists x")
cases := []struct {
name string
settings string
success bool
errmsg string
}{
{
name: "Dict is not allowed for common constraint",
settings: "LEARNERS=1 " +
"LEARNER_CONSTRAINTS=\"[+zone=cn-west-1]\" " +
"CONSTRAINTS=\"{'+disk=ssd':2}\"",
errmsg: "invalid label constraints format: 'Constraints' should be [constraint1, ...] or any yaml compatible array representation",
},
{
name: "constraints may be incompatible with itself",
settings: "FOLLOWERS=3 LEARNERS=1 " +
"LEARNER_CONSTRAINTS=\"[+zone=cn-west-1, +zone=cn-west-2]\"",
errmsg: "invalid label constraints format: should be [constraint1, ...] (error conflicting label constraints: '+zone=cn-west-2' and '+zone=cn-west-1'), {constraint1: cnt1, ...} (error yaml: unmarshal errors:\n" +
" line 1: cannot unmarshal !!seq into map[string]int), or any yaml compatible representation: invalid LearnerConstraints",
},
{
settings: "PRIMARY_REGION=\"cn-east-1\" " +
"REGIONS=\"cn-east-1,cn-east-2\" ",
success: true,
},
}
// test for create
for _, ca := range cases {
sql := fmt.Sprintf("%s %s", "create placement policy x", ca.settings)
if ca.success {
tk.MustExec(sql)
tk.MustExec("drop placement policy if exists x")
} else {
err := tk.ExecToErr(sql)
c.Assert(err, NotNil, Commentf(ca.name))
c.Assert(err.Error(), Equals, ca.errmsg, Commentf(ca.name))
}
}
// test for alter
tk.MustExec("create placement policy x primary_region=\"cn-east-1\" regions=\"cn-east-1,cn-east\"")
for _, ca := range cases {
sql := fmt.Sprintf("%s %s", "alter placement policy x", ca.settings)
if ca.success {
tk.MustExec(sql)
tk.MustExec("alter placement policy x primary_region=\"cn-east-1\" regions=\"cn-east-1,cn-east\"")
} else {
err := tk.ExecToErr(sql)
c.Assert(err, NotNil)
c.Assert(err.Error(), Equals, ca.errmsg)
tk.MustQuery("show placement where target='POLICY x'").Check(testkit.Rows("POLICY x PRIMARY_REGION=\"cn-east-1\" REGIONS=\"cn-east-1,cn-east\" NULL"))
}
}
tk.MustExec("drop placement policy x")
}
func (s *testDBSuite6) TestResetSchemaPlacement(c *C) {
tk := testkit.NewTestKit(c, s.store)
tk.MustExec("drop database if exists TestResetPlacementDB;")
tk.MustExec("create placement policy `TestReset` followers=4;")
tk.MustGetErrCode("create placement policy `default` followers=4;", mysql.ErrReservedSyntax)
tk.MustGetErrCode("create placement policy default followers=4;", mysql.ErrParse)
tk.MustExec("create database TestResetPlacementDB placement policy `TestReset`;")
tk.MustExec("use TestResetPlacementDB")
// Test for `=default`
tk.MustQuery(`show create database TestResetPlacementDB`).Check(testutil.RowsWithSep("|",
"TestResetPlacementDB CREATE DATABASE `TestResetPlacementDB` /*!40100 DEFAULT CHARACTER SET utf8mb4 */ "+
"/*T![placement] PLACEMENT POLICY=`TestReset` */",
))
tk.MustExec("ALTER DATABASE TestResetPlacementDB PLACEMENT POLICY=default;")
tk.MustQuery(`show create database TestResetPlacementDB`).Check(testutil.RowsWithSep("|",
"TestResetPlacementDB CREATE DATABASE `TestResetPlacementDB` /*!40100 DEFAULT CHARACTER SET utf8mb4 */",
))
// Test for `SET DEFAULT`
tk.MustExec("ALTER DATABASE TestResetPlacementDB PLACEMENT POLICY=`TestReset`;")
tk.MustQuery(`show create database TestResetPlacementDB`).Check(testutil.RowsWithSep("|",
"TestResetPlacementDB CREATE DATABASE `TestResetPlacementDB` /*!40100 DEFAULT CHARACTER SET utf8mb4 */ "+
"/*T![placement] PLACEMENT POLICY=`TestReset` */",
))
tk.MustExec("ALTER DATABASE TestResetPlacementDB PLACEMENT POLICY SET DEFAULT")
tk.MustQuery(`show create database TestResetPlacementDB`).Check(testutil.RowsWithSep("|",
"TestResetPlacementDB CREATE DATABASE `TestResetPlacementDB` /*!40100 DEFAULT CHARACTER SET utf8mb4 */",
))
// Test for `= 'DEFAULT'`
tk.MustExec("ALTER DATABASE TestResetPlacementDB PLACEMENT POLICY=`TestReset`;")
tk.MustQuery(`show create database TestResetPlacementDB`).Check(testutil.RowsWithSep("|",
"TestResetPlacementDB CREATE DATABASE `TestResetPlacementDB` /*!40100 DEFAULT CHARACTER SET utf8mb4 */ "+
"/*T![placement] PLACEMENT POLICY=`TestReset` */",
))
tk.MustExec("ALTER DATABASE TestResetPlacementDB PLACEMENT POLICY = 'DEFAULT'")
tk.MustQuery(`show create database TestResetPlacementDB`).Check(testutil.RowsWithSep("|",
"TestResetPlacementDB CREATE DATABASE `TestResetPlacementDB` /*!40100 DEFAULT CHARACTER SET utf8mb4 */",
))
// Test for "= `DEFAULT`"
tk.MustExec("ALTER DATABASE TestResetPlacementDB PLACEMENT POLICY=`TestReset`;")
tk.MustQuery(`show create database TestResetPlacementDB`).Check(testutil.RowsWithSep("|",
"TestResetPlacementDB CREATE DATABASE `TestResetPlacementDB` /*!40100 DEFAULT CHARACTER SET utf8mb4 */ "+
"/*T![placement] PLACEMENT POLICY=`TestReset` */",
))
tk.MustExec("ALTER DATABASE TestResetPlacementDB PLACEMENT POLICY = `DEFAULT`")
tk.MustQuery(`show create database TestResetPlacementDB`).Check(testutil.RowsWithSep("|",
"TestResetPlacementDB CREATE DATABASE `TestResetPlacementDB` /*!40100 DEFAULT CHARACTER SET utf8mb4 */",
))
tk.MustExec("drop placement policy `TestReset`;")
tk.MustExec("drop database TestResetPlacementDB;")
}
func (s *testDBSuite6) TestCreateOrReplacePlacementPolicy(c *C) {
tk := testkit.NewTestKit(c, s.store)
tk.MustExec("use test")
tk.MustExec("drop placement policy if exists x")
// If the policy does not exist, CREATE OR REPLACE PLACEMENT POLICY is the same as CREATE PLACEMENT POLICY
tk.MustExec("create or replace placement policy x primary_region=\"cn-east-1\" regions=\"cn-east-1,cn-east\"")
defer tk.MustExec("drop placement policy if exists x")
tk.MustQuery("show create placement policy x").Check(testkit.Rows("x CREATE PLACEMENT POLICY `x` PRIMARY_REGION=\"cn-east-1\" REGIONS=\"cn-east-1,cn-east\""))
// If the policy does exist, CREATE OR REPLACE PLACEMENT_POLICY is the same as ALTER PLACEMENT POLICY.
tk.MustExec("create or replace placement policy x primary_region=\"cn-east-1\" regions=\"cn-east-1\"")
tk.MustQuery("show create placement policy x").Check(testkit.Rows("x CREATE PLACEMENT POLICY `x` PRIMARY_REGION=\"cn-east-1\" REGIONS=\"cn-east-1\""))
// Cannot be used together with the if not exists clause. Ref: https://mariadb.com/kb/en/create-view
tk.MustGetErrMsg("create or replace placement policy if not exists x primary_region=\"cn-east-1\" regions=\"cn-east-1\"", "[ddl:1221]Incorrect usage of OR REPLACE and IF NOT EXISTS")
}
func (s *testDBSuite6) TestAlterPlacementPolicy(c *C) {
clearAllBundles(c)
tk := testkit.NewTestKit(c, s.store)
tk.MustExec("use test")
tk.MustExec("drop placement policy if exists x")
tk.MustExec("drop table if exists tp")
tk.MustExec("create placement policy x primary_region=\"cn-east-1\" regions=\"cn-east-1,cn-east\"")
defer tk.MustExec("drop placement policy if exists x")
// create a table ref to policy x, testing for alter policy will update PD bundles
tk.MustExec(`CREATE TABLE tp (id INT) placement policy x PARTITION BY RANGE (id) (
PARTITION p0 VALUES LESS THAN (100),
PARTITION p1 VALUES LESS THAN (1000) placement policy x
);`)
defer tk.MustExec("drop table if exists tp")
policy, ok := s.dom.InfoSchema().PolicyByName(model.NewCIStr("x"))
c.Assert(ok, IsTrue)
// test for normal cases
tk.MustExec("alter placement policy x PRIMARY_REGION=\"bj\" REGIONS=\"bj,sh\"")
tk.MustQuery("show placement where target='POLICY x'").Check(testkit.Rows("POLICY x PRIMARY_REGION=\"bj\" REGIONS=\"bj,sh\" NULL"))
tk.MustQuery("select * from information_schema.placement_policies where policy_name = 'x'").Check(testkit.Rows(strconv.FormatInt(policy.ID, 10) + " def x bj bj,sh 2 0"))
checkExistTableBundlesInPD(c, s.dom, "test", "tp")
tk.MustExec("alter placement policy x " +
"PRIMARY_REGION=\"bj\" " +
"REGIONS=\"bj\" " +
"SCHEDULE=\"EVEN\"")
tk.MustQuery("show placement where target='POLICY x'").Check(testkit.Rows("POLICY x PRIMARY_REGION=\"bj\" REGIONS=\"bj\" SCHEDULE=\"EVEN\" NULL"))
tk.MustQuery("select * from INFORMATION_SCHEMA.PLACEMENT_POLICIES WHERE POLICY_NAME='x'").Check(testkit.Rows(strconv.FormatInt(policy.ID, 10) + " def x bj bj EVEN 2 0"))
checkExistTableBundlesInPD(c, s.dom, "test", "tp")
tk.MustExec("alter placement policy x " +
"LEADER_CONSTRAINTS=\"[+region=us-east-1]\" " +
"FOLLOWER_CONSTRAINTS=\"[+region=us-east-2]\" " +
"FOLLOWERS=3")
tk.MustQuery("show placement where target='POLICY x'").Check(
testkit.Rows("POLICY x LEADER_CONSTRAINTS=\"[+region=us-east-1]\" FOLLOWERS=3 FOLLOWER_CONSTRAINTS=\"[+region=us-east-2]\" NULL"),
)
tk.MustQuery("SELECT POLICY_NAME,LEADER_CONSTRAINTS,FOLLOWER_CONSTRAINTS,FOLLOWERS FROM information_schema.PLACEMENT_POLICIES WHERE POLICY_NAME = 'x'").Check(
testkit.Rows("x [+region=us-east-1] [+region=us-east-2] 3"),
)
checkExistTableBundlesInPD(c, s.dom, "test", "tp")
tk.MustExec("alter placement policy x " +
"VOTER_CONSTRAINTS=\"[+region=bj]\" " +
"LEARNER_CONSTRAINTS=\"[+region=sh]\" " +
"CONSTRAINTS=\"[+disk=ssd]\"" +
"VOTERS=5 " +
"LEARNERS=3")
tk.MustQuery("show placement where target='POLICY x'").Check(
testkit.Rows("POLICY x CONSTRAINTS=\"[+disk=ssd]\" VOTERS=5 VOTER_CONSTRAINTS=\"[+region=bj]\" LEARNERS=3 LEARNER_CONSTRAINTS=\"[+region=sh]\" NULL"),
)
tk.MustQuery("SELECT " +
"CATALOG_NAME,POLICY_NAME," +
"PRIMARY_REGION,REGIONS,CONSTRAINTS,LEADER_CONSTRAINTS,FOLLOWER_CONSTRAINTS,LEARNER_CONSTRAINTS," +
"SCHEDULE,FOLLOWERS,LEARNERS FROM INFORMATION_SCHEMA.placement_policies WHERE POLICY_NAME='x'").Check(
testkit.Rows("def x [+disk=ssd] [+region=sh] 2 3"),
)
checkExistTableBundlesInPD(c, s.dom, "test", "tp")
// test alter not exist policies
tk.MustExec("drop table tp")
tk.MustExec("drop placement policy x")
tk.MustGetErrCode("alter placement policy x REGIONS=\"bj,sh\"", mysql.ErrPlacementPolicyNotExists)
tk.MustGetErrCode("alter placement policy x2 REGIONS=\"bj,sh\"", mysql.ErrPlacementPolicyNotExists)
tk.MustQuery("select * from INFORMATION_SCHEMA.PLACEMENT_POLICIES WHERE POLICY_NAME='x'").Check(testkit.Rows())
}
func (s *testDBSuite6) TestCreateTableWithPlacementPolicy(c *C) {
clearAllBundles(c)
tk := testkit.NewTestKit(c, s.store)
tk.MustExec("use test")
tk.MustExec("drop table if exists t,t_range_p,t_hash_p,t_list_p")
tk.MustExec("drop placement policy if exists x")
tk.MustExec("drop placement policy if exists y")
defer func() {
tk.MustExec("drop table if exists t,t_range_p,t_hash_p,t_list_p")
tk.MustExec("drop placement policy if exists x")
tk.MustExec("drop placement policy if exists y")
}()
// special constraints may be incompatible with common constraint.
_, err := tk.Exec("create placement policy pn " +
"FOLLOWERS=2 " +
"FOLLOWER_CONSTRAINTS=\"[+zone=cn-east-1]\" " +
"CONSTRAINTS=\"[+disk=ssd,-zone=cn-east-1]\"")
c.Assert(err, NotNil)
c.Assert(err, ErrorMatches, ".*conflicting label constraints.*")
// Only placement policy should check the policy existence.
tk.MustGetErrCode("create table t(a int)"+
"PLACEMENT POLICY=\"x\"", mysql.ErrPlacementPolicyNotExists)
tk.MustExec("create placement policy x " +
"FOLLOWERS=2 " +
"CONSTRAINTS=\"[+disk=ssd]\" ")
tk.MustExec("create placement policy y " +
"FOLLOWERS=3 " +
"CONSTRAINTS=\"[+region=bj]\" ")
tk.MustExec("create table t(a int)" +
"PLACEMENT POLICY=\"x\"")
tk.MustQuery("SELECT TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME, TIDB_PLACEMENT_POLICY_NAME FROM information_schema.Tables WHERE TABLE_SCHEMA='test' AND TABLE_NAME = 't'").Check(testkit.Rows(`def test t x`))
tk.MustExec("create table t_range_p(id int) placement policy x partition by range(id) (" +
"PARTITION p0 VALUES LESS THAN (100)," +
"PARTITION p1 VALUES LESS THAN (1000) placement policy y," +
"PARTITION p2 VALUES LESS THAN (10000))",
)
tk.MustExec("set tidb_enable_list_partition=1")
tk.MustExec("create table t_list_p(name varchar(10)) placement policy x partition by list columns(name) (" +
"PARTITION p0 VALUES IN ('a', 'b')," +
"PARTITION p1 VALUES IN ('c', 'd') placement policy y," +
"PARTITION p2 VALUES IN ('e', 'f'))",
)
tk.MustExec("create table t_hash_p(id int) placement policy x partition by HASH(id) PARTITIONS 4")
policyX := testGetPolicyByName(c, tk.Se, "x", true)
c.Assert(policyX.Name.L, Equals, "x")
c.Assert(policyX.ID != 0, Equals, true)
policyY := testGetPolicyByName(c, tk.Se, "y", true)
c.Assert(policyY.Name.L, Equals, "y")
c.Assert(policyY.ID != 0, Equals, true)
tbl := testGetTableByName(c, tk.Se, "test", "t")
c.Assert(tbl, NotNil)
c.Assert(tbl.Meta().PlacementPolicyRef, NotNil)
c.Assert(tbl.Meta().PlacementPolicyRef.Name.L, Equals, "x")
c.Assert(tbl.Meta().PlacementPolicyRef.ID, Equals, policyX.ID)
tk.MustExec("drop table if exists t")
checkPartitionTableFunc := func(tblName string) {
tbl = testGetTableByName(c, tk.Se, "test", tblName)
c.Assert(tbl, NotNil)
c.Assert(tbl.Meta().PlacementPolicyRef, NotNil)
c.Assert(tbl.Meta().PlacementPolicyRef.Name.L, Equals, "x")
c.Assert(tbl.Meta().PlacementPolicyRef.ID, Equals, policyX.ID)
c.Assert(tbl.Meta().Partition, NotNil)
c.Assert(len(tbl.Meta().Partition.Definitions), Equals, 3)
p0 := tbl.Meta().Partition.Definitions[0]
c.Assert(p0.PlacementPolicyRef, IsNil)
p1 := tbl.Meta().Partition.Definitions[1]
c.Assert(p1.PlacementPolicyRef, NotNil)
c.Assert(p1.PlacementPolicyRef.Name.L, Equals, "y")
c.Assert(p1.PlacementPolicyRef.ID, Equals, policyY.ID)
p2 := tbl.Meta().Partition.Definitions[2]
c.Assert(p2.PlacementPolicyRef, IsNil)
}
checkPartitionTableFunc("t_range_p")
tk.MustExec("drop table if exists t_range_p")
checkPartitionTableFunc("t_list_p")
tk.MustExec("drop table if exists t_list_p")
tbl = testGetTableByName(c, tk.Se, "test", "t_hash_p")
c.Assert(tbl, NotNil)
c.Assert(tbl.Meta().PlacementPolicyRef, NotNil)
c.Assert(tbl.Meta().PlacementPolicyRef.Name.L, Equals, "x")
c.Assert(tbl.Meta().PlacementPolicyRef.ID, Equals, policyX.ID)
for _, p := range tbl.Meta().Partition.Definitions {
c.Assert(p.PlacementPolicyRef, IsNil)
}
}
func (s *testDBSuite6) getClonedTable(dbName string, tableName string) (*model.TableInfo, error) {
tbl, err := s.dom.InfoSchema().TableByName(model.NewCIStr(dbName), model.NewCIStr(tableName))
if err != nil {
return nil, err
}
tblMeta := tbl.Meta()
tblMeta = tblMeta.Clone()
policyRef := *tblMeta.PlacementPolicyRef
tblMeta.PlacementPolicyRef = &policyRef
return tblMeta, nil
}
func (s *testDBSuite6) getClonedDatabase(dbName string) (*model.DBInfo, bool) {
db, ok := s.dom.InfoSchema().SchemaByName(model.NewCIStr(dbName))
if !ok {
return nil, ok
}
db = db.Clone()
policyRef := *db.PlacementPolicyRef
db.PlacementPolicyRef = &policyRef
return db, true
}
func (s *testDBSuite6) TestCreateTableWithInfoPlacement(c *C) {
clearAllBundles(c)
tk := testkit.NewTestKit(c, s.store)
tk.MustExec("use test")
tk.MustExec("drop table if exists t1")
tk.MustExec("drop database if exists test2")
tk.MustExec("drop placement policy if exists p1")
tk.MustExec("create placement policy p1 followers=1")
defer tk.MustExec("drop placement policy if exists p1")
tk.MustExec("create table t1(a int) placement policy p1")
defer tk.MustExec("drop table if exists t1")
tk.MustExec("create database test2")
defer tk.MustExec("drop database if exists test2")
tbl, err := s.getClonedTable("test", "t1")
c.Assert(err, IsNil)
policy, ok := s.dom.InfoSchema().PolicyByName(model.NewCIStr("p1"))
c.Assert(ok, IsTrue)
c.Assert(tbl.PlacementPolicyRef.ID, Equals, policy.ID)
tk.MustExec("alter table t1 placement policy='default'")
tk.MustExec("drop placement policy p1")
tk.MustExec("create placement policy p1 followers=2")
c.Assert(s.dom.DDL().CreateTableWithInfo(tk.Se, model.NewCIStr("test2"), tbl, ddl.OnExistError), IsNil)
tk.MustQuery("show create table t1").Check(testkit.Rows("t1 CREATE TABLE `t1` (\n" +
" `a` int(11) DEFAULT NULL\n" +
") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin"))
tk.MustQuery("show create table test2.t1").Check(testkit.Rows("t1 CREATE TABLE `t1` (\n" +
" `a` int(11) DEFAULT NULL\n" +
") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin /*T![placement] PLACEMENT POLICY=`p1` */"))
tk.MustQuery("show placement where target='TABLE test2.t1'").Check(testkit.Rows("TABLE test2.t1 FOLLOWERS=2 PENDING"))
// The ref id for new table should be the new policy id
tbl2, err := s.getClonedTable("test2", "t1")
c.Assert(err, IsNil)
policy2, ok := s.dom.InfoSchema().PolicyByName(model.NewCIStr("p1"))
c.Assert(ok, IsTrue)
c.Assert(tbl2.PlacementPolicyRef.ID, Equals, policy2.ID)
c.Assert(policy2.ID != policy.ID, IsTrue)
// Test policy not exists
tbl2.Name = model.NewCIStr("t3")
tbl2.PlacementPolicyRef.Name = model.NewCIStr("pxx")
err = s.dom.DDL().CreateTableWithInfo(tk.Se, model.NewCIStr("test2"), tbl2, ddl.OnExistError)
c.Assert(err.Error(), Equals, "[schema:8239]Unknown placement policy 'pxx'")
}
func (s *testDBSuite6) TestCreateSchemaWithInfoPlacement(c *C) {
clearAllBundles(c)
tk := testkit.NewTestKit(c, s.store)
tk.MustExec("use test")
tk.MustExec("drop database if exists test2")
tk.MustExec("drop database if exists test3")
tk.MustExec("drop placement policy if exists p1")
tk.MustExec("create placement policy p1 followers=1")
defer tk.MustExec("drop placement policy if exists p1")
tk.MustExec("create database test2 placement policy p1")
defer tk.MustExec("drop database if exists test2")
defer tk.MustExec("drop database if exists test3")
db, ok := s.getClonedDatabase("test2")
c.Assert(ok, IsTrue)
policy, ok := s.dom.InfoSchema().PolicyByName(model.NewCIStr("p1"))
c.Assert(ok, IsTrue)
c.Assert(db.PlacementPolicyRef.ID, Equals, policy.ID)
db2 := db.Clone()
db2.Name = model.NewCIStr("test3")
tk.MustExec("alter database test2 placement policy='default'")
tk.MustExec("drop placement policy p1")
tk.MustExec("create placement policy p1 followers=2")
c.Assert(s.dom.DDL().CreateSchemaWithInfo(tk.Se, db2, ddl.OnExistError), IsNil)
tk.MustQuery("show create database test2").Check(testkit.Rows("test2 CREATE DATABASE `test2` /*!40100 DEFAULT CHARACTER SET utf8mb4 */"))
tk.MustQuery("show create database test3").Check(testkit.Rows("test3 CREATE DATABASE `test3` /*!40100 DEFAULT CHARACTER SET utf8mb4 */ /*T![placement] PLACEMENT POLICY=`p1` */"))
tk.MustQuery("show placement where target='DATABASE test3'").Check(testkit.Rows("DATABASE test3 FOLLOWERS=2 SCHEDULED"))
// The ref id for new table should be the new policy id
db2, ok = s.getClonedDatabase("test3")
c.Assert(ok, IsTrue)
policy2, ok := s.dom.InfoSchema().PolicyByName(model.NewCIStr("p1"))
c.Assert(ok, IsTrue)
c.Assert(db2.PlacementPolicyRef.ID, Equals, policy2.ID)
c.Assert(policy2.ID != policy.ID, IsTrue)
// Test policy not exists
db2.Name = model.NewCIStr("test4")
db2.PlacementPolicyRef.Name = model.NewCIStr("p2")
err := s.dom.DDL().CreateSchemaWithInfo(tk.Se, db2, ddl.OnExistError)
c.Assert(err.Error(), Equals, "[schema:8239]Unknown placement policy 'p2'")
}
func (s *testDBSuite6) TestDropPlacementPolicyInUse(c *C) {
tk := testkit.NewTestKit(c, s.store)
tk.MustExec("use test")
tk.MustExec("create database if not exists test2")
tk.MustExec("drop table if exists test.t11, test.t12, test2.t21, test2.t21, test2.t22")
tk.MustExec("drop placement policy if exists p1")
tk.MustExec("drop placement policy if exists p2")
tk.MustExec("drop placement policy if exists p3")
tk.MustExec("drop placement policy if exists p4")
// p1 is used by test.t11 and test2.t21
tk.MustExec("create placement policy p1 " +
"PRIMARY_REGION=\"cn-east-1\" " +
"REGIONS=\"cn-east-1, cn-east-2\" " +
"SCHEDULE=\"EVEN\"")
defer tk.MustExec("drop placement policy if exists p1")
tk.MustExec("create table test.t11 (id int) placement policy 'p1'")
defer tk.MustExec("drop table if exists test.t11")
tk.MustExec("create table test2.t21 (id int) placement policy 'p1'")
defer tk.MustExec("drop table if exists test2.t21")
// p1 is used by test.t12
tk.MustExec("create placement policy p2 " +
"PRIMARY_REGION=\"cn-east-1\" " +
"REGIONS=\"cn-east-1, cn-east-2\" " +
"SCHEDULE=\"EVEN\"")
defer tk.MustExec("drop placement policy if exists p2")
tk.MustExec("create table test.t12 (id int) placement policy 'p2'")
defer tk.MustExec("drop table if exists test.t12")
tk.MustQuery("SELECT TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME, TIDB_PLACEMENT_POLICY_NAME FROM information_schema.Tables WHERE TABLE_SCHEMA='test' AND TABLE_NAME = 't12'").Check(testkit.Rows(`def test t12 p2`))
// p3 is used by test2.t22
tk.MustExec("create placement policy p3 " +
"PRIMARY_REGION=\"cn-east-1\" " +
"REGIONS=\"cn-east-1, cn-east-2\" " +
"SCHEDULE=\"EVEN\"")
defer tk.MustExec("drop placement policy if exists p3")
tk.MustExec("create table test.t21 (id int) placement policy 'p3'")
defer tk.MustExec("drop table if exists test.t21")
// p4 is used by test_p
tk.MustExec("create placement policy p4 " +
"PRIMARY_REGION=\"cn-east-1\" " +
"REGIONS=\"cn-east-1, cn-east-2\" " +
"SCHEDULE=\"EVEN\"")
defer tk.MustExec("drop placement policy if exists p4")
tk.MustExec("create database test_p placement policy 'p4'")
defer tk.MustExec("drop database if exists test_p")
txn, err := s.store.Begin()
c.Assert(err, IsNil)
defer func() {
c.Assert(txn.Rollback(), IsNil)
}()
for _, policyName := range []string{"p1", "p2", "p3", "p4"} {
err := tk.ExecToErr(fmt.Sprintf("drop placement policy %s", policyName))
c.Assert(err.Error(), Equals, fmt.Sprintf("[ddl:8241]Placement policy '%s' is still in use", policyName))
err = tk.ExecToErr(fmt.Sprintf("drop placement policy if exists %s", policyName))
c.Assert(err.Error(), Equals, fmt.Sprintf("[ddl:8241]Placement policy '%s' is still in use", policyName))
}
}
func testGetPolicyByName(c *C, ctx sessionctx.Context, name string, mustExist bool) *model.PolicyInfo {
dom := domain.GetDomain(ctx)
// Make sure the table schema is the new schema.
err := dom.Reload()
c.Assert(err, IsNil)
po, ok := dom.InfoSchema().PolicyByName(model.NewCIStr(name))
if mustExist {
c.Assert(ok, Equals, true)
}
return po
}
func testGetPolicyDependency(storage kv.Storage, name string) []int64 {
ids := make([]int64, 0, 32)
err1 := kv.RunInNewTxn(context.Background(), storage, false, func(ctx context.Context, txn kv.Transaction) error {
t := meta.NewMeta(txn)
dbs, err := t.ListDatabases()
if err != nil {
return err
}
for _, db := range dbs {
tbls, err := t.ListTables(db.ID)
if err != nil {
return err
}
for _, tbl := range tbls {
if tbl.PlacementPolicyRef != nil && tbl.PlacementPolicyRef.Name.L == name {
ids = append(ids, tbl.ID)
}
}
}
return nil
})
if err1 != nil {
return []int64{}
}
return ids
}
func (s *testDBSuite6) TestPolicyCacheAndPolicyDependency(c *C) {
tk := testkit.NewTestKit(c, s.store)
tk.MustExec("use test")
tk.MustExec("drop placement policy if exists x")
// Test policy cache.
tk.MustExec("create placement policy x primary_region=\"r1\" regions=\"r1,r2\" schedule=\"EVEN\";")
po := testGetPolicyByName(c, tk.Se, "x", true)
c.Assert(po, NotNil)
tk.MustQuery("show placement where target='POLICY x'").Check(testkit.Rows("POLICY x PRIMARY_REGION=\"r1\" REGIONS=\"r1,r2\" SCHEDULE=\"EVEN\" NULL"))
tk.MustExec("drop table if exists t")
tk.MustExec("create table t (a int) placement policy \"x\"")
defer tk.MustExec("drop table if exists t")
tk.MustQuery("SELECT TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME, TABLE_TYPE, TIDB_PLACEMENT_POLICY_NAME FROM information_schema.Tables WHERE TABLE_SCHEMA='test' AND TABLE_NAME = 't'").Check(testkit.Rows(`def test t BASE TABLE x`))
tbl := testGetTableByName(c, tk.Se, "test", "t")
// Test policy dependency cache.
dependencies := testGetPolicyDependency(s.store, "x")
c.Assert(dependencies, NotNil)
c.Assert(len(dependencies), Equals, 1)
c.Assert(dependencies[0], Equals, tbl.Meta().ID)
tk.MustExec("drop table if exists t2")
tk.MustExec("create table t2 (a int) placement policy \"x\"")
defer tk.MustExec("drop table if exists t2")
tk.MustQuery("SELECT TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME, TABLE_TYPE, TIDB_PLACEMENT_POLICY_NAME FROM information_schema.Tables WHERE TABLE_SCHEMA='test' AND TABLE_NAME = 't'").Check(testkit.Rows(`def test t BASE TABLE x`))
tbl2 := testGetTableByName(c, tk.Se, "test", "t2")
dependencies = testGetPolicyDependency(s.store, "x")
c.Assert(dependencies, NotNil)
c.Assert(len(dependencies), Equals, 2)
in := func() bool {
for _, one := range dependencies {
if one == tbl2.Meta().ID {
return true
}
}
return false
}
c.Assert(in(), Equals, true)
// Test drop policy can't succeed cause there are still some table depend on them.
_, err := tk.Exec("drop placement policy x")
c.Assert(err, NotNil)
c.Assert(err.Error(), Equals, "[ddl:8241]Placement policy 'x' is still in use")
// Drop depended table t firstly.
tk.MustExec("drop table if exists t")
dependencies = testGetPolicyDependency(s.store, "x")
c.Assert(dependencies, NotNil)
c.Assert(len(dependencies), Equals, 1)
c.Assert(dependencies[0], Equals, tbl2.Meta().ID)
_, err = tk.Exec("drop placement policy x")
c.Assert(err, NotNil)
c.Assert(err.Error(), Equals, "[ddl:8241]Placement policy 'x' is still in use")
// Drop depended table t2 secondly.
tk.MustExec("drop table if exists t2")
dependencies = testGetPolicyDependency(s.store, "x")
c.Assert(dependencies, NotNil)
c.Assert(len(dependencies), Equals, 0)
po = testGetPolicyByName(c, tk.Se, "x", true)
c.Assert(po, NotNil)
tk.MustExec("drop placement policy x")
po = testGetPolicyByName(c, tk.Se, "x", false)
c.Assert(po, IsNil)
dependencies = testGetPolicyDependency(s.store, "x")
c.Assert(dependencies, NotNil)
c.Assert(len(dependencies), Equals, 0)
}
func (s *testDBSuite6) TestAlterTablePartitionWithPlacementPolicy(c *C) {
clearAllBundles(c)
tk := testkit.NewTestKit(c, s.store)
defer func() {
tk.MustExec("drop table if exists t1")
tk.MustExec("drop placement policy if exists x")
}()
tk.MustExec("use test")
tk.MustExec("drop table if exists t1")
tk.MustExec("drop placement policy if exists x")
// Direct placement option: special constraints may be incompatible with common constraint.
tk.MustExec("create table t1 (c int) PARTITION BY RANGE (c) " +
"(PARTITION p0 VALUES LESS THAN (6)," +
"PARTITION p1 VALUES LESS THAN (11)," +
"PARTITION p2 VALUES LESS THAN (16)," +
"PARTITION p3 VALUES LESS THAN (21));")
defer tk.MustExec("drop table if exists t1")
checkExistTableBundlesInPD(c, s.dom, "test", "t1")
// Only placement policy should check the policy existence.
tk.MustGetErrCode("alter table t1 partition p0 "+
"PLACEMENT POLICY=\"x\"", mysql.ErrPlacementPolicyNotExists)
tk.MustExec("create placement policy x " +
"FOLLOWERS=2 ")
tk.MustExec("alter table t1 partition p0 " +
"PLACEMENT POLICY=\"x\"")
tk.MustQuery("SELECT TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME, PARTITION_NAME, TIDB_PLACEMENT_POLICY_NAME FROM information_schema.Partitions WHERE TABLE_SCHEMA='test' AND TABLE_NAME = 't1' AND PARTITION_NAME = 'p0'").Check(testkit.Rows(`def test t1 p0 x`))
checkExistTableBundlesInPD(c, s.dom, "test", "t1")
policyX, ok := s.dom.InfoSchema().PolicyByName(model.NewCIStr("x"))
c.Assert(ok, IsTrue)
ptDef := testGetPartitionDefinitionsByName(c, tk.Se, "test", "t1", "p0")
c.Assert(ptDef, NotNil)
c.Assert(ptDef.PlacementPolicyRef, NotNil)
c.Assert(ptDef.PlacementPolicyRef.Name.L, Equals, "x")
c.Assert(ptDef.PlacementPolicyRef.ID, Equals, policyX.ID)
}
func testGetPartitionDefinitionsByName(c *C, ctx sessionctx.Context, db string, table string, ptName string) model.PartitionDefinition {
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(db), model.NewCIStr(table))
c.Assert(err, IsNil)
c.Assert(tbl, NotNil)
var ptDef model.PartitionDefinition
for _, def := range tbl.Meta().Partition.Definitions {
if ptName == def.Name.L {
ptDef = def
break
}
}
return ptDef
}
func (s *testDBSuite6) TestPolicyInheritance(c *C) {
clearAllBundles(c)
tk := testkit.NewTestKit(c, s.store)
tk.MustExec("use test")
tk.MustExec("drop database if exists mydb")
tk.MustExec("drop placement policy if exists p1")
tk.MustExec("drop placement policy if exists p2")
defer func() {
tk.MustExec("drop database if exists mydb")
tk.MustExec("drop placement policy if exists p1")
tk.MustExec("drop placement policy if exists p2")
}()
// test table inherit database's placement rules.
tk.MustExec("create placement policy p1 constraints=\"[+zone=hangzhou]\"")
tk.MustExec("create database mydb placement policy p1")
tk.MustQuery("show create database mydb").Check(testkit.Rows("mydb CREATE DATABASE `mydb` /*!40100 DEFAULT CHARACTER SET utf8mb4 */ /*T![placement] PLACEMENT POLICY=`p1` */"))
tk.MustExec("use mydb")
tk.MustExec("create table t(a int)")
tk.MustQuery("show create table t").Check(testkit.Rows("t CREATE TABLE `t` (\n" +
" `a` int(11) DEFAULT NULL\n" +
") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin /*T![placement] PLACEMENT POLICY=`p1` */"))
checkExistTableBundlesInPD(c, s.dom, "mydb", "t")
tk.MustExec("drop table if exists t")
tk.MustExec("create placement policy p2 constraints=\"[+zone=suzhou]\"")
tk.MustExec("create table t(a int) placement policy p2")
tk.MustQuery("show create table t").Check(testkit.Rows("t CREATE TABLE `t` (\n" +
" `a` int(11) DEFAULT NULL\n" +
") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin /*T![placement] PLACEMENT POLICY=`p2` */"))
checkExistTableBundlesInPD(c, s.dom, "mydb", "t")
tk.MustExec("drop table if exists t")
// test create table like should not inherit database's placement rules.
tk.MustExec("create table t0 (a int) placement policy 'default'")
tk.MustQuery("show create table t0").Check(testkit.Rows("t0 CREATE TABLE `t0` (\n" +
" `a` int(11) DEFAULT NULL\n" +
") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin"))
checkExistTableBundlesInPD(c, s.dom, "mydb", "t0")
tk.MustExec("create table t1 like t0")
tk.MustQuery("show create table t1").Check(testkit.Rows("t1 CREATE TABLE `t1` (\n" +
" `a` int(11) DEFAULT NULL\n" +
") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin"))
checkExistTableBundlesInPD(c, s.dom, "mydb", "t1")
tk.MustExec("drop table if exists t0, t")
// table will inherit db's placement rules, which is shared by all partition as default one.
tk.MustExec("create table t(a int) partition by range(a) (partition p0 values less than (100), partition p1 values less than (200))")
tk.MustQuery("show create table t").Check(testkit.Rows("t CREATE TABLE `t` (\n" +
" `a` int(11) DEFAULT NULL\n" +
") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin /*T![placement] PLACEMENT POLICY=`p1` */\n" +
"PARTITION BY RANGE (`a`)\n" +
"(PARTITION `p0` VALUES LESS THAN (100),\n" +
" PARTITION `p1` VALUES LESS THAN (200))"))
checkExistTableBundlesInPD(c, s.dom, "mydb", "t")
tk.MustExec("drop table if exists t")
// partition's specified placement rules will override the default one.
tk.MustExec("create table t(a int) partition by range(a) (partition p0 values less than (100) placement policy p2, partition p1 values less than (200))")
tk.MustQuery("show create table t").Check(testkit.Rows("t CREATE TABLE `t` (\n" +
" `a` int(11) DEFAULT NULL\n" +
") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin /*T![placement] PLACEMENT POLICY=`p1` */\n" +
"PARTITION BY RANGE (`a`)\n" +
"(PARTITION `p0` VALUES LESS THAN (100) /*T![placement] PLACEMENT POLICY=`p2` */,\n" +
" PARTITION `p1` VALUES LESS THAN (200))"))
checkExistTableBundlesInPD(c, s.dom, "mydb", "t")
tk.MustExec("drop table if exists t")
// test partition override table's placement rules.
tk.MustExec("drop table if exists t")
tk.MustExec("create table t(a int) placement policy p2 partition by range(a) (partition p0 values less than (100) placement policy p1, partition p1 values less than (200))")
tk.MustQuery("show create table t").Check(testkit.Rows("t CREATE TABLE `t` (\n" +
" `a` int(11) DEFAULT NULL\n" +
") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin /*T![placement] PLACEMENT POLICY=`p2` */\n" +
"PARTITION BY RANGE (`a`)\n" +
"(PARTITION `p0` VALUES LESS THAN (100) /*T![placement] PLACEMENT POLICY=`p1` */,\n" +
" PARTITION `p1` VALUES LESS THAN (200))"))
checkExistTableBundlesInPD(c, s.dom, "mydb", "t")
}
func (s *testDBSuite6) TestDatabasePlacement(c *C) {
tk := testkit.NewTestKit(c, s.store)
tk.MustExec("drop database if exists db2")
tk.MustExec("drop placement policy if exists p1")
tk.MustExec("drop placement policy if exists p2")
tk.MustExec("create placement policy p1 primary_region='r1' regions='r1'")
defer tk.MustExec("drop placement policy p1")
tk.MustExec("create placement policy p2 primary_region='r2' regions='r1,r2'")
defer tk.MustExec("drop placement policy p2")
policy1, ok := s.dom.InfoSchema().PolicyByName(model.NewCIStr("p1"))
c.Assert(ok, IsTrue)
tk.MustExec(`create database db2`)
defer tk.MustExec("drop database db2")