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 31 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
129 changes: 102 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,106 @@ 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
AilinKid marked this conversation as resolved.
Show resolved Hide resolved
var policyName model.CIStr
var placementPolicyRef *model.PolicyRefInfo
var directPlacementOpts *model.PlacementSettings
var isAlterCharsetAndCollate bool
var isAlterPlacement bool

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 +1897,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
106 changes: 104 additions & 2 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 @@ -732,14 +734,14 @@ func (s *testDBSuite6) TestCreateSchemaWithPlacement(c *C) {
}()

tk.MustExec(`CREATE SCHEMA SchemaDirectPlacementTest PRIMARY_REGION='nl' REGIONS = "se,nz" FOLLOWERS=3`)
tk.MustQuery("SHOW CREATE SCHEMA schemadirectplacementtest").Check(testkit.Rows("SchemaDirectPlacementTest CREATE DATABASE `SchemaDirectPlacementTest` /*!40100 DEFAULT CHARACTER SET utf8mb4 */ PRIMARY_REGION=\"nl\" 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=\"nl\" REGIONS=\"se,nz\" 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`)
tk.MustQuery("SHOW PLACEMENT like 'POLICY %PolicySchemaTest%'").Check(testkit.Rows("POLICY PolicySchemaTest LEADER_CONSTRAINTS=\"[+region=nl]\" FOLLOWERS=4 FOLLOWER_CONSTRAINTS=\"[+region=se]\" LEARNERS=4 LEARNER_CONSTRAINTS=\"[+region=be]\""))
tk.MustQuery("SHOW PLACEMENT like 'POLICY %PolicyTableTest%'").Check(testkit.Rows("POLICY PolicyTableTest LEADER_CONSTRAINTS=\"[+region=tl]\" FOLLOWERS=2 FOLLOWER_CONSTRAINTS=\"[+region=tf]\" LEARNERS=1 LEARNER_CONSTRAINTS=\"[+region=tle]\""))
tk.MustExec("CREATE SCHEMA SchemaPolicyPlacementTest PLACEMENT POLICY = `PolicySchemaTest`")
tk.MustQuery("SHOW CREATE SCHEMA SCHEMAPOLICYPLACEMENTTEST").Check(testkit.Rows("SchemaPolicyPlacementTest CREATE DATABASE `SchemaPolicyPlacementTest` /*!40100 DEFAULT CHARACTER SET utf8mb4 */ PLACEMENT POLICY = `PolicySchemaTest`"))
tk.MustQuery("SHOW CREATE SCHEMA SCHEMAPOLICYPLACEMENTTEST").Check(testkit.Rows("SchemaPolicyPlacementTest CREATE DATABASE `SchemaPolicyPlacementTest` /*!40100 DEFAULT CHARACTER SET utf8mb4 */ /*T![placement] PLACEMENT POLICY=`PolicySchemaTest` */"))

tk.MustExec(`CREATE TABLE SchemaDirectPlacementTest.UseSchemaDefault (a int unsigned primary key, b varchar(255))`)
tk.MustQuery(`SHOW CREATE TABLE SchemaDirectPlacementTest.UseSchemaDefault`).Check(testkit.Rows(
Expand Down Expand Up @@ -802,3 +804,103 @@ 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\";")
tk.MustExec("create placement policy y PRIMARY_REGION=\"cn-east-2\";")

// Policy Test
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;")
// 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\" 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\" 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\" 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\" 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;")
tk.MustQuery(`show create database TestAlterDB`).Check(testutil.RowsWithSep("|",
"TestAlterDB CREATE DATABASE `TestAlterDB` /*!40100 DEFAULT CHARACTER SET utf8mb4 */ "+
"/*T![placement] PRIMARY_REGION=\"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
33 changes: 33 additions & 0 deletions ddl/schema.go
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,39 @@ 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
AilinKid marked this conversation as resolved.
Show resolved Hide resolved
var 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)
}

// Notice: dbInfo.DirectPlacementOpts and dbInfo.PlacementPolicyRef can not be both not nil.
if (dbInfo.DirectPlacementOpts == directPlacementOpts) && (dbInfo.PlacementPolicyRef == placementPolicyRef) {
AilinKid marked this conversation as resolved.
Show resolved Hide resolved
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
10 changes: 5 additions & 5 deletions executor/show.go
Original file line number Diff line number Diff line change
Expand Up @@ -1071,7 +1071,7 @@ func ConstructResultOfShowCreateTable(ctx sessionctx.Context, tableInfo *model.T
}

if tableInfo.PlacementPolicyRef != nil {
fmt.Fprintf(buf, " /*T![placement] PLACEMENT POLICY=`%s` */", tableInfo.PlacementPolicyRef.Name.String())
fmt.Fprintf(buf, " /*T![placement] PLACEMENT POLICY=%s */", stringutil.Escape(tableInfo.PlacementPolicyRef.Name.String(), sqlMode))
}

// add direct placement info here
Expand Down Expand Up @@ -1331,12 +1331,12 @@ func ConstructResultOfShowCreateDatabase(ctx sessionctx.Context, dbInfo *model.D
}
// MySQL 5.7 always show the charset info but TiDB may ignore it, which makes a slight difference. We keep this
// behavior unchanged because it is trivial enough.
if dbInfo.DirectPlacementOpts != nil {
fmt.Fprintf(buf, " %s", dbInfo.DirectPlacementOpts)
}

if dbInfo.PlacementPolicyRef != nil {
fmt.Fprintf(buf, " PLACEMENT POLICY = %s", stringutil.Escape(dbInfo.PlacementPolicyRef.Name.O, sqlMode))
fmt.Fprintf(buf, " /*T![placement] PLACEMENT POLICY=%s */", stringutil.Escape(dbInfo.PlacementPolicyRef.Name.String(), sqlMode))
}
// add direct placement info here
appendDirectPlacementInfo(dbInfo.DirectPlacementOpts, buf)
return nil
}

Expand Down
Loading