Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ddl: Support ALTER DATABASE Placement Policy/ DirectOptions #27894

Merged
merged 50 commits into from
Oct 9, 2021
Merged
Show file tree
Hide file tree
Changes from 45 commits
Commits
Show all changes
50 commits
Select commit Hold shift + click to select a range
512cd43
init
sylzd Sep 8, 2021
e77119c
rebase
sylzd Sep 24, 2021
67ee34b
Merge branch 'master' of https://github.com/pingcap/tidb into placeme…
sylzd Sep 26, 2021
cad76e8
init complete
sylzd Sep 27, 2021
147cf14
complete policy& fix show database
sylzd Sep 28, 2021
232d992
complete alter db direct placement options
sylzd Sep 28, 2021
5698132
fix lint
sylzd Sep 28, 2021
2af1ad4
fix conflict test case
sylzd Sep 28, 2021
3da4985
Merge branch 'master' of https://github.com/pingcap/tidb into placeme…
sylzd Sep 28, 2021
a30b7de
fix go.sum
sylzd Sep 28, 2021
f057d05
fix go.sum
sylzd Sep 28, 2021
9160642
fix hybrid logic
sylzd Sep 28, 2021
1e4b8e8
support set default, bu can split with policy named
sylzd Sep 28, 2021
37cf608
fix
sylzd Sep 28, 2021
7e79db9
temp pass CI
sylzd Sep 28, 2021
c67e503
temp pass CI
sylzd Sep 28, 2021
22a0e4b
Merge branch 'master' into placement_db_ddl
sylzd Sep 28, 2021
339ec36
Merge branch 'master' of https://github.com/pingcap/tidb into placeme…
sylzd Sep 28, 2021
0f300c3
fix go.sum
sylzd Sep 28, 2021
fac6255
Merge branch 'placement_db_ddl' of github.com:sylzd/tidb into placeme…
sylzd Sep 28, 2021
03462d2
fix
sylzd Sep 28, 2021
3bc1744
make lint happy
sylzd Sep 28, 2021
92f3cdd
fix old test
sylzd Sep 29, 2021
ccb0046
fix unstable test
sylzd Sep 29, 2021
6a858f7
fix
sylzd Sep 30, 2021
3871a6d
fix
sylzd Sep 30, 2021
dbdd4c5
good lint
sylzd Sep 30, 2021
e003117
Merge branch 'master' of https://github.com/pingcap/tidb into placeme…
sylzd Sep 30, 2021
9bf4db7
happy lint again
sylzd Sep 30, 2021
8287740
god lint
sylzd Sep 30, 2021
ed87872
legendary lint
sylzd Sep 30, 2021
7ae23b4
Merge branch 'master' into placement_db_ddl
sylzd Oct 8, 2021
1322128
Merge branch 'master' into placement_db_ddl
sylzd Oct 8, 2021
733f75c
fix test case
sylzd Oct 8, 2021
0ed27ff
merge
sylzd Oct 8, 2021
77c9371
fix test case
sylzd Oct 8, 2021
f72686c
make vars more clear
sylzd Oct 8, 2021
639aa3f
ditto
sylzd Oct 8, 2021
f0010ee
fix wrong equal
sylzd Oct 8, 2021
72ac488
add test case
sylzd Oct 8, 2021
af93350
fix conflicts
sylzd Oct 8, 2021
37cfcb5
lint
sylzd Oct 8, 2021
3dc19b2
fix conflicts
sylzd Oct 8, 2021
bdf86be
double check policy exits
sylzd Oct 8, 2021
37d68f4
Merge branch 'master' into placement_db_ddl
AilinKid Oct 8, 2021
1755a7c
Merge branch 'master' into placement_db_ddl
ti-chi-bot Oct 9, 2021
d881b72
fix
sylzd Oct 9, 2021
87a35cf
Merge branch 'placement_db_ddl' of github.com:sylzd/tidb into placeme…
sylzd Oct 9, 2021
3118810
Merge branch 'master' into placement_db_ddl
AilinKid Oct 9, 2021
e2c5f5e
Merge branch 'master' into placement_db_ddl
ti-chi-bot Oct 9, 2021
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion br/pkg/restore/log_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -229,7 +229,7 @@ func (l *LogClient) collectDDLFiles(ctx context.Context) ([]string, error) {

func (l *LogClient) isDBRelatedDDL(ddl *cdclog.MessageDDL) bool {
switch ddl.Type {
case model.ActionDropSchema, model.ActionCreateSchema, model.ActionModifySchemaCharsetAndCollate:
case model.ActionDropSchema, model.ActionCreateSchema, model.ActionModifySchemaCharsetAndCollate, model.ActionModifySchemaDefaultPlacement:
return true
}
return false
Expand Down
130 changes: 103 additions & 27 deletions ddl/ddl_api.go
Original file line number Diff line number Diff line change
Expand Up @@ -153,31 +153,7 @@ func (d *ddl) CreateSchemaWithInfo(
return errors.Trace(err)
}

func (d *ddl) AlterSchema(ctx sessionctx.Context, stmt *ast.AlterDatabaseStmt) (err error) {
// Resolve target charset and collation from options.
var toCharset, toCollate string
for _, val := range stmt.Options {
switch val.Tp {
case ast.DatabaseOptionCharset:
if toCharset == "" {
toCharset = val.Value
} else if toCharset != val.Value {
return ErrConflictingDeclarations.GenWithStackByArgs(toCharset, val.Value)
}
case ast.DatabaseOptionCollate:
info, err := collate.GetCollationByName(val.Value)
if err != nil {
return errors.Trace(err)
}
if toCharset == "" {
toCharset = info.CharsetName
} else if toCharset != info.CharsetName {
return ErrConflictingDeclarations.GenWithStackByArgs(toCharset, info.CharsetName)
}
toCollate = info.Name

}
}
func (d *ddl) ModifySchemaCharsetAndCollate(ctx sessionctx.Context, stmt *ast.AlterDatabaseStmt, toCharset, toCollate string) (err error) {
if toCollate == "" {
if toCollate, err = charset.GetDefaultCollation(toCharset); err != nil {
return errors.Trace(err)
Expand All @@ -194,7 +170,6 @@ func (d *ddl) AlterSchema(ctx sessionctx.Context, stmt *ast.AlterDatabaseStmt) (
if dbInfo.Charset == toCharset && dbInfo.Collate == toCollate {
return nil
}

// Do the DDL job.
job := &model.Job{
SchemaID: dbInfo.ID,
Expand All @@ -208,6 +183,107 @@ func (d *ddl) AlterSchema(ctx sessionctx.Context, stmt *ast.AlterDatabaseStmt) (
return errors.Trace(err)
}

func (d *ddl) ModifySchemaDefaultPlacement(ctx sessionctx.Context, stmt *ast.AlterDatabaseStmt, placementPolicyRef *model.PolicyRefInfo, directPlacementOpts *model.PlacementSettings) (err error) {
dbName := model.NewCIStr(stmt.Name)
is := d.GetInfoSchemaWithInterceptor(ctx)
dbInfo, ok := is.SchemaByName(dbName)
if !ok {
return infoschema.ErrDatabaseNotExists.GenWithStackByArgs(dbName.O)
}

if directPlacementOpts != nil && placementPolicyRef != nil {
return errors.Trace(ErrPlacementPolicyWithDirectOption.GenWithStackByArgs(placementPolicyRef.Name))
}

if directPlacementOpts != nil {
// check the direct placement option compatibility.
if err := checkPolicyValidation(directPlacementOpts); err != nil {
return errors.Trace(err)
}
}

// Do the DDL job.
job := &model.Job{
SchemaID: dbInfo.ID,
SchemaName: dbInfo.Name.L,
Type: model.ActionModifySchemaDefaultPlacement,
BinlogInfo: &model.HistoryInfo{},
Args: []interface{}{placementPolicyRef, directPlacementOpts},
}
err = d.doDDLJob(ctx, job)
err = d.callHookOnChanged(err)
return errors.Trace(err)
}

func (d *ddl) AlterSchema(ctx sessionctx.Context, stmt *ast.AlterDatabaseStmt) (err error) {
// Resolve target charset and collation from options.
var (
toCharset, toCollate string
isAlterCharsetAndCollate, isAlterPlacement bool
policyName model.CIStr
placementPolicyRef *model.PolicyRefInfo
directPlacementOpts *model.PlacementSettings
)

for _, val := range stmt.Options {
switch val.Tp {
case ast.DatabaseOptionCharset:
if toCharset == "" {
toCharset = val.Value
} else if toCharset != val.Value {
return ErrConflictingDeclarations.GenWithStackByArgs(toCharset, val.Value)
}
isAlterCharsetAndCollate = true
case ast.DatabaseOptionCollate:
info, errGetCollate := collate.GetCollationByName(val.Value)
if errGetCollate != nil {
return errors.Trace(errGetCollate)
}
if toCharset == "" {
toCharset = info.CharsetName
} else if toCharset != info.CharsetName {
return ErrConflictingDeclarations.GenWithStackByArgs(toCharset, info.CharsetName)
}
toCollate = info.Name
isAlterCharsetAndCollate = true
case ast.DatabaseOptionPlacementPrimaryRegion, ast.DatabaseOptionPlacementRegions, ast.DatabaseOptionPlacementFollowerCount, ast.DatabaseOptionPlacementVoterCount, ast.DatabaseOptionPlacementLearnerCount, ast.DatabaseOptionPlacementSchedule, ast.DatabaseOptionPlacementConstraints, ast.DatabaseOptionPlacementLeaderConstraints, ast.DatabaseOptionPlacementLearnerConstraints, ast.DatabaseOptionPlacementFollowerConstraints, ast.DatabaseOptionPlacementVoterConstraints:
if directPlacementOpts == nil {
directPlacementOpts = &model.PlacementSettings{}
}
err = SetDirectPlacementOpt(directPlacementOpts, ast.PlacementOptionType(val.Tp), val.Value, val.UintValue)
if err != nil {
return err
}
isAlterPlacement = true
case ast.DatabaseOptionPlacementPolicy:
policyName = model.NewCIStr(val.Value)
if policyName.L == "default" {
placementPolicyRef = nil
} else {
policy, ok := ctx.GetInfoSchema().(infoschema.InfoSchema).PolicyByName(policyName)
if !ok {
return errors.Trace(infoschema.ErrPlacementPolicyNotExists.GenWithStackByArgs(policyName))
}
placementPolicyRef = &model.PolicyRefInfo{ID: policy.ID, Name: policyName}
}
isAlterPlacement = true
}
}

if isAlterCharsetAndCollate {
if err = d.ModifySchemaCharsetAndCollate(ctx, stmt, toCharset, toCollate); err != nil {
return err
}
}
if isAlterPlacement {
if err = d.ModifySchemaDefaultPlacement(ctx, stmt, placementPolicyRef, directPlacementOpts); err != nil {
return err
}
}

return nil
}

func (d *ddl) DropSchema(ctx sessionctx.Context, schema model.CIStr) (err error) {
is := d.GetInfoSchemaWithInterceptor(ctx)
old, ok := is.SchemaByName(schema)
Expand Down Expand Up @@ -1822,7 +1898,7 @@ func buildTableInfoWithStmt(ctx sessionctx.Context, s *ast.CreateTableStmt, dbCh
}

if tbInfo.PlacementPolicyRef == nil && tbInfo.DirectPlacementOpts == nil {
// Set the defaults from Schema. Note: they are mutual exlusive!
// Set the defaults from Schema. Note: they are mutual exclusive!
if placementPolicyRef != nil {
tbInfo.PlacementPolicyRef = placementPolicyRef
} else if directPlacementOpts != nil {
Expand Down
2 changes: 2 additions & 0 deletions ddl/ddl_worker.go
Original file line number Diff line number Diff line change
Expand Up @@ -744,6 +744,8 @@ func (w *worker) runDDLJob(d *ddlCtx, t *meta.Meta, job *model.Job) (ver int64,
ver, err = onModifySchemaCharsetAndCollate(t, job)
case model.ActionDropSchema:
ver, err = onDropSchema(d, t, job)
case model.ActionModifySchemaDefaultPlacement:
ver, err = onModifySchemaDefaultPlacement(t, job)
case model.ActionCreateTable:
ver, err = onCreateTable(d, t, job)
case model.ActionRepairTable:
Expand Down
4 changes: 4 additions & 0 deletions ddl/ddl_worker_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -661,6 +661,10 @@ func buildCancelJobTests(firstID int64) []testCancelJob {
{act: model.ActionDropIndexes, jobIDs: []int64{firstID + 72}, cancelRetErrs: []error{admin.ErrCannotCancelDDLJob.GenWithStackByArgs(firstID + 72)}, cancelState: model.StateWriteOnly},
{act: model.ActionDropIndexes, jobIDs: []int64{firstID + 73}, cancelRetErrs: []error{admin.ErrCannotCancelDDLJob.GenWithStackByArgs(firstID + 73)}, cancelState: model.StateDeleteOnly},
{act: model.ActionDropIndexes, jobIDs: []int64{firstID + 74}, cancelRetErrs: []error{admin.ErrCannotCancelDDLJob.GenWithStackByArgs(firstID + 74)}, cancelState: model.StateWriteReorganization},

// for alter db placement
{act: model.ActionModifySchemaDefaultPlacement, jobIDs: []int64{firstID + 75}, cancelRetErrs: noErrs, cancelState: model.StateNone},
{act: model.ActionModifySchemaDefaultPlacement, jobIDs: []int64{firstID + 76}, cancelRetErrs: []error{admin.ErrCancelFinishedDDLJob.GenWithStackByArgs(firstID + 76)}, cancelState: model.StatePublic},
}

return tests
Expand Down
116 changes: 111 additions & 5 deletions ddl/placement_sql_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,11 @@ import (
"github.com/pingcap/parser/model"
"github.com/pingcap/tidb/ddl"
"github.com/pingcap/tidb/ddl/placement"
mysql "github.com/pingcap/tidb/errno"
"github.com/pingcap/tidb/session"
"github.com/pingcap/tidb/table/tables"
"github.com/pingcap/tidb/util/testkit"
"github.com/pingcap/tidb/util/testutil"
)

func (s *testDBSuite6) TestAlterTableAlterPartition(c *C) {
Expand Down Expand Up @@ -731,8 +733,8 @@ func (s *testDBSuite6) TestCreateSchemaWithPlacement(c *C) {
tk.Se.GetSessionVars().EnableAlterPlacement = false
}()

tk.MustExec(`CREATE SCHEMA SchemaDirectPlacementTest PRIMARY_REGION='se' REGIONS = "se,nz" FOLLOWERS=3`)
tk.MustQuery("SHOW CREATE SCHEMA schemadirectplacementtest").Check(testkit.Rows("SchemaDirectPlacementTest CREATE DATABASE `SchemaDirectPlacementTest` /*!40100 DEFAULT CHARACTER SET utf8mb4 */ /*T![placement] PRIMARY_REGION=\"se\" REGIONS=\"se,nz\" FOLLOWERS=3 */"))
tk.MustExec(`CREATE SCHEMA SchemaDirectPlacementTest PRIMARY_REGION='nl' REGIONS = "se,nz,nl" FOLLOWERS=3`)
tk.MustQuery("SHOW CREATE SCHEMA schemadirectplacementtest").Check(testkit.Rows("SchemaDirectPlacementTest CREATE DATABASE `SchemaDirectPlacementTest` /*!40100 DEFAULT CHARACTER SET utf8mb4 */ /*T![placement] PRIMARY_REGION=\"nl\" REGIONS=\"se,nz,nl\" FOLLOWERS=3 */"))

tk.MustExec(`CREATE PLACEMENT POLICY PolicySchemaTest LEADER_CONSTRAINTS = "[+region=nl]" FOLLOWER_CONSTRAINTS="[+region=se]" FOLLOWERS=4 LEARNER_CONSTRAINTS="[+region=be]" LEARNERS=4`)
tk.MustExec(`CREATE PLACEMENT POLICY PolicyTableTest LEADER_CONSTRAINTS = "[+region=tl]" FOLLOWER_CONSTRAINTS="[+region=tf]" FOLLOWERS=2 LEARNER_CONSTRAINTS="[+region=tle]" LEARNERS=1`)
Expand All @@ -747,8 +749,9 @@ func (s *testDBSuite6) TestCreateSchemaWithPlacement(c *C) {
" `a` int(10) unsigned NOT NULL,\n" +
" `b` varchar(255) DEFAULT NULL,\n" +
" PRIMARY KEY (`a`) /*T![clustered_index] CLUSTERED */\n" +
") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin /*T![placement] PRIMARY_REGION=\"se\" REGIONS=\"se,nz\" FOLLOWERS=3 */"))
") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin /*T![placement] PRIMARY_REGION=\"nl\" REGIONS=\"se,nz,nl\" FOLLOWERS=3 */"))
tk.MustExec(`CREATE TABLE SchemaDirectPlacementTest.UseDirectPlacement (a int unsigned primary key, b varchar(255)) PRIMARY_REGION="se" REGIONS="se"`)

tk.MustQuery(`SHOW CREATE TABLE SchemaDirectPlacementTest.UseDirectPlacement`).Check(testkit.Rows(
"UseDirectPlacement CREATE TABLE `UseDirectPlacement` (\n" +
" `a` int(10) unsigned NOT NULL,\n" +
Expand Down Expand Up @@ -778,8 +781,8 @@ func (s *testDBSuite6) TestCreateSchemaWithPlacement(c *C) {
c.Assert(ok, IsTrue)
c.Assert(db.PlacementPolicyRef, IsNil)
c.Assert(db.DirectPlacementOpts, NotNil)
c.Assert(db.DirectPlacementOpts.PrimaryRegion, Matches, "se")
c.Assert(db.DirectPlacementOpts.Regions, Matches, "se,nz")
c.Assert(db.DirectPlacementOpts.PrimaryRegion, Matches, "nl")
c.Assert(db.DirectPlacementOpts.Regions, Matches, "se,nz,nl")
c.Assert(db.DirectPlacementOpts.Followers, Equals, uint64(3))
c.Assert(db.DirectPlacementOpts.Learners, Equals, uint64(0))

Expand All @@ -789,3 +792,106 @@ func (s *testDBSuite6) TestCreateSchemaWithPlacement(c *C) {
c.Assert(db.DirectPlacementOpts, IsNil)
c.Assert(db.PlacementPolicyRef.Name.O, Equals, "PolicySchemaTest")
}

func (s *testDBSuite6) TestAlterDBPlacement(c *C) {
tk := testkit.NewTestKit(c, s.store)
tk.MustExec("drop database if exists TestAlterDB;")
tk.MustExec("create database TestAlterDB;")
tk.MustExec("use TestAlterDB")
tk.MustExec("drop placement policy if exists x")
tk.MustExec("drop placement policy if exists y")
tk.MustExec("create placement policy x PRIMARY_REGION=\"cn-east-1\", REGIONS=\"cn-east-1\";")
tk.MustExec("create placement policy y PRIMARY_REGION=\"cn-east-2\", REGIONS=\"cn-east-2\";")

// Policy Test
// Test for Non-Exist policy
tk.MustGetErrCode("ALTER DATABASE TestAlterDB PLACEMENT POLICY=`z`;", mysql.ErrPlacementPolicyNotExists)

tk.MustExec("ALTER DATABASE TestAlterDB PLACEMENT POLICY=`x`;")
// Test for Show Create Database
tk.MustQuery(`show create database TestAlterDB`).Check(testutil.RowsWithSep("|",
"TestAlterDB CREATE DATABASE `TestAlterDB` /*!40100 DEFAULT CHARACTER SET utf8mb4 */ "+
"/*T![placement] PLACEMENT POLICY=`x` */",
))
// Test for Alter Placement Policy affect table created.
tk.MustExec("create table t(a int);")
tk.MustQuery(`show create table t`).Check(testutil.RowsWithSep("|",
"t CREATE TABLE `t` (\n"+
" `a` int(11) DEFAULT NULL\n"+
") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin "+
"/*T![placement] PLACEMENT POLICY=`x` */",
))
// Test for Alter Default Placement Policy, And will not update the old table options.
tk.MustExec("ALTER DATABASE TestAlterDB DEFAULT PLACEMENT POLICY=`y`;")
tk.MustExec("create table t2(a int);")
tk.MustQuery(`show create table t`).Check(testutil.RowsWithSep("|",
"t CREATE TABLE `t` (\n"+
" `a` int(11) DEFAULT NULL\n"+
") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin "+
"/*T![placement] PLACEMENT POLICY=`x` */",
))
tk.MustQuery(`show create table t2`).Check(testutil.RowsWithSep("|",
"t2 CREATE TABLE `t2` (\n"+
" `a` int(11) DEFAULT NULL\n"+
") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin "+
"/*T![placement] PLACEMENT POLICY=`y` */",
))

// Reset Test
tk.MustExec("drop database if exists TestAlterDB;")
tk.MustExec("create database TestAlterDB;")
tk.MustExec("use TestAlterDB")

// DirectOption Test
tk.MustExec("ALTER DATABASE TestAlterDB PRIMARY_REGION=\"se\" FOLLOWERS=2 REGIONS=\"se\";")
// Test for Show Create Database
tk.MustQuery(`show create database TestAlterDB`).Check(testutil.RowsWithSep("|",
"TestAlterDB CREATE DATABASE `TestAlterDB` /*!40100 DEFAULT CHARACTER SET utf8mb4 */ "+
"/*T![placement] PRIMARY_REGION=\"se\" REGIONS=\"se\" FOLLOWERS=2 */",
))
// Test for Alter Placement Rule affect table created.
tk.MustExec("create table t3(a int);")
tk.MustQuery(`show create table t3`).Check(testutil.RowsWithSep("|",
"t3 CREATE TABLE `t3` (\n"+
" `a` int(11) DEFAULT NULL\n"+
") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin "+
"/*T![placement] PRIMARY_REGION=\"se\" REGIONS=\"se\" FOLLOWERS=2 */",
))
// Test for override default option
tk.MustExec("create table t4(a int) PLACEMENT POLICY=\"x\";")
tk.MustQuery(`show create table t4`).Check(testutil.RowsWithSep("|",
"t4 CREATE TABLE `t4` (\n"+
" `a` int(11) DEFAULT NULL\n"+
") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin "+
"/*T![placement] PLACEMENT POLICY=`x` */",
))

// Hybrid Test
// Test for alter both policy and direct options.
tk.MustQuery(`show create database TestAlterDB`).Check(testutil.RowsWithSep("|",
"TestAlterDB CREATE DATABASE `TestAlterDB` /*!40100 DEFAULT CHARACTER SET utf8mb4 */ "+
"/*T![placement] PRIMARY_REGION=\"se\" REGIONS=\"se\" FOLLOWERS=2 */",
))
tk.MustGetErrCode("ALTER DATABASE TestAlterDB PLACEMENT POLICY=`x` FOLLOWERS=2;", mysql.ErrPlacementPolicyWithDirectOption)
tk.MustGetErrCode("ALTER DATABASE TestAlterDB DEFAULT PLACEMENT POLICY=`y` PRIMARY_REGION=\"se\" FOLLOWERS=2;", mysql.ErrPlacementPolicyWithDirectOption)
tk.MustQuery(`show create database TestAlterDB`).Check(testutil.RowsWithSep("|",
"TestAlterDB CREATE DATABASE `TestAlterDB` /*!40100 DEFAULT CHARACTER SET utf8mb4 */ "+
"/*T![placement] PRIMARY_REGION=\"se\" REGIONS=\"se\" FOLLOWERS=2 */",
))
// Test for change direct options to policy.
tk.MustExec("ALTER DATABASE TestAlterDB PLACEMENT POLICY=`x`;")
tk.MustQuery(`show create database TestAlterDB`).Check(testutil.RowsWithSep("|",
"TestAlterDB CREATE DATABASE `TestAlterDB` /*!40100 DEFAULT CHARACTER SET utf8mb4 */ "+
"/*T![placement] PLACEMENT POLICY=`x` */",
))
// Test for change policy to direct options.
tk.MustExec("ALTER DATABASE TestAlterDB PRIMARY_REGION=\"se\" FOLLOWERS=2 REGIONS=\"se\" ;")
tk.MustQuery(`show create database TestAlterDB`).Check(testutil.RowsWithSep("|",
"TestAlterDB CREATE DATABASE `TestAlterDB` /*!40100 DEFAULT CHARACTER SET utf8mb4 */ "+
"/*T![placement] PRIMARY_REGION=\"se\" REGIONS=\"se\" FOLLOWERS=2 */",
))

tk.MustExec(`DROP DATABASE IF EXISTS TestAlterDB;`)
tk.MustExec("drop placement policy if exists x")
tk.MustExec("drop placement policy if exists y")
}
2 changes: 1 addition & 1 deletion ddl/rollingback.go
Original file line number Diff line number Diff line change
Expand Up @@ -476,7 +476,7 @@ func convertJob2RollbackJob(w *worker, d *ddlCtx, t *meta.Meta, job *model.Job)
model.ActionModifyTableCharsetAndCollate, model.ActionTruncateTablePartition,
model.ActionModifySchemaCharsetAndCollate, model.ActionRepairTable,
model.ActionModifyTableAutoIdCache, model.ActionAlterIndexVisibility,
model.ActionExchangeTablePartition:
model.ActionExchangeTablePartition, model.ActionModifySchemaDefaultPlacement:
ver, err = cancelOnlyNotHandledJob(job)
default:
job.State = model.JobStateCancelled
Expand Down
41 changes: 41 additions & 0 deletions ddl/schema.go
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,47 @@ func onModifySchemaCharsetAndCollate(t *meta.Meta, job *model.Job) (ver int64, _
return ver, nil
}

func onModifySchemaDefaultPlacement(t *meta.Meta, job *model.Job) (ver int64, _ error) {
var (
placementPolicyRef *model.PolicyRefInfo
directPlacementOpts *model.PlacementSettings
)
if err := job.DecodeArgs(&placementPolicyRef, &directPlacementOpts); err != nil {
job.State = model.JobStateCancelled
return ver, errors.Trace(err)
}

dbInfo, err := checkSchemaExistAndCancelNotExistJob(t, job)
if err != nil {
return ver, errors.Trace(err)
}
//Double Check if policy exits while ddl executing
_, err = checkPlacementPolicyExistAndCancelNonExistJob(t, job, placementPolicyRef.ID)
if err != nil {
return ver, errors.Trace(err)
}

// Notice: dbInfo.DirectPlacementOpts and dbInfo.PlacementPolicyRef can not be both not nil, which checked before constructing ddl job.
// So that we can just check the two situation that do not need ddl: 1. DB.DP == DDL.DP && nil == nil 2. nil == nil && DB.PP == DDL.PP
if (*dbInfo.DirectPlacementOpts == *directPlacementOpts) && (*dbInfo.PlacementPolicyRef == *placementPolicyRef) {
job.FinishDBJob(model.JobStateDone, model.StatePublic, ver, dbInfo)
return ver, nil
}

// If placementPolicyRef and directPlacementOpts are both nil, And placement of dbInfo is not nil, it will remove all placement options.
dbInfo.PlacementPolicyRef = placementPolicyRef
sylzd marked this conversation as resolved.
Show resolved Hide resolved
dbInfo.DirectPlacementOpts = directPlacementOpts

if err = t.UpdateDatabase(dbInfo); err != nil {
return ver, errors.Trace(err)
}
if ver, err = updateSchemaVersion(t, job); err != nil {
return ver, errors.Trace(err)
}
job.FinishDBJob(model.JobStateDone, model.StatePublic, ver, dbInfo)
return ver, nil
}

func onDropSchema(d *ddlCtx, t *meta.Meta, job *model.Job) (ver int64, _ error) {
dbInfo, err := checkSchemaExistAndCancelNotExistJob(t, job)
if err != nil {
Expand Down
Loading