diff --git a/cmd/explaintest/r/clustered_index.result b/cmd/explaintest/r/clustered_index.result index 2dded83f272bd..5fc18247bdad4 100644 --- a/cmd/explaintest/r/clustered_index.result +++ b/cmd/explaintest/r/clustered_index.result @@ -3,24 +3,22 @@ create database with_cluster_index; drop database if exists wout_cluster_index; create database wout_cluster_index; use with_cluster_index; -set @@tidb_enable_clustered_index = 1; -create table tbl_0 ( col_0 decimal not null , col_1 blob(207) , col_2 text , col_3 datetime default '1986-07-01' , col_4 bigint unsigned default 1504335725690712365 , primary key idx_0 ( col_3,col_2(1),col_1(6) ) , key idx_1 ( col_3 ) , unique key idx_2 ( col_3 ) , unique key idx_3 ( col_0 ) , key idx_4 ( col_1(1),col_2(1) ) , key idx_5 ( col_2(1) ) ) ; -create table tbl_1 ( col_5 char(135) , col_6 bit(17) default 50609 not null , col_7 char(202) default 'IoQWYoGdbbgBDlxpDHQ' , col_8 char(213) , col_9 time not null , primary key idx_6 ( col_6 ) , unique key idx_7 ( col_5 ) ) ; -create table tbl_2 ( col_10 datetime default '1976-05-11' , col_11 datetime , col_12 float , col_13 double(56,29) default 18.0118 , col_14 char not null , primary key idx_8 ( col_14,col_13,col_10 ) , key idx_9 ( col_11 ) ) ; -create table tbl_3 ( col_15 tinyint default -91 not null , col_16 bit(61) default 990141831018971350 not null , col_17 double(244,22) default 3985 not null , col_18 binary(32) default 'kxMlWqvpxXNBlxoU' , col_19 text(401) , primary key idx_10 ( col_18,col_19(4) ) , key idx_11 ( col_17,col_18,col_19(2),col_15,col_16 ) , unique key idx_12 ( col_17 ) ) ; -create table tbl_4 ( col_20 double(230,16) default 8.49 not null , col_21 int unsigned not null , col_22 enum('Alice','Bob','Charlie','David') not null , col_23 float default 3066.13040283622 , col_24 datetime default '1980-10-27' not null , primary key idx_13 ( col_22,col_24 ) , key idx_14 ( col_23,col_20 ) , key idx_15 ( col_24 ) , key idx_16 ( col_20 ) , unique key idx_17 ( col_24 ) , key idx_18 ( col_21 ) ) ; +create table tbl_0 ( col_0 decimal not null , col_1 blob(207) , col_2 text , col_3 datetime default '1986-07-01' , col_4 bigint unsigned default 1504335725690712365 , primary key idx_0 ( col_3,col_2(1),col_1(6) ) clustered, key idx_1 ( col_3 ), unique key idx_2 ( col_3 ) , unique key idx_3 ( col_0 ) , key idx_4 ( col_1(1),col_2(1) ) , key idx_5 ( col_2(1) ) ) ; +create table tbl_1 ( col_5 char(135) , col_6 bit(17) default 50609 not null , col_7 char(202) default 'IoQWYoGdbbgBDlxpDHQ' , col_8 char(213) , col_9 time not null , primary key idx_6 ( col_6 ) clustered, unique key idx_7 ( col_5 ) ) ; +create table tbl_2 ( col_10 datetime default '1976-05-11' , col_11 datetime , col_12 float , col_13 double(56,29) default 18.0118 , col_14 char not null , primary key idx_8 ( col_14,col_13,col_10 ) clustered, key idx_9 ( col_11 ) ) ; +create table tbl_3 ( col_15 tinyint default -91 not null , col_16 bit(61) default 990141831018971350 not null , col_17 double(244,22) default 3985 not null , col_18 binary(32) default 'kxMlWqvpxXNBlxoU' , col_19 text(401) , primary key idx_10 ( col_18,col_19(4) ) clustered, key idx_11 ( col_17,col_18,col_19(2),col_15,col_16 ) , unique key idx_12 ( col_17 ) ) ; +create table tbl_4 ( col_20 double(230,16) default 8.49 not null , col_21 int unsigned not null , col_22 enum('Alice','Bob','Charlie','David') not null , col_23 float default 3066.13040283622 , col_24 datetime default '1980-10-27' not null , primary key idx_13 ( col_22,col_24 ) clustered, key idx_14 ( col_23,col_20 ) , key idx_15 ( col_24 ) , key idx_16 ( col_20 ) , unique key idx_17 ( col_24 ) , key idx_18 ( col_21 ) ) ; load stats 's/with_cluster_index_tbl_0.json'; load stats 's/with_cluster_index_tbl_1.json'; load stats 's/with_cluster_index_tbl_2.json'; load stats 's/with_cluster_index_tbl_3.json'; load stats 's/with_cluster_index_tbl_4.json'; use wout_cluster_index; -set @@tidb_enable_clustered_index = 0; -create table tbl_0 ( col_0 decimal not null , col_1 blob(207) , col_2 text , col_3 datetime default '1986-07-01' , col_4 bigint unsigned default 1504335725690712365 , primary key idx_0 ( col_3,col_2(1),col_1(6) ) , key idx_1 ( col_3 ) , unique key idx_2 ( col_3 ) , unique key idx_3 ( col_0 ) , key idx_4 ( col_1(1),col_2(1) ) , key idx_5 ( col_2(1) ) ) ; -create table tbl_1 ( col_5 char(135) , col_6 bit(17) default 50609 not null , col_7 char(202) default 'IoQWYoGdbbgBDlxpDHQ' , col_8 char(213) , col_9 time not null , primary key idx_6 ( col_6 ) , unique key idx_7 ( col_5 ) ) ; -create table tbl_2 ( col_10 datetime default '1976-05-11' , col_11 datetime , col_12 float , col_13 double(56,29) default 18.0118 , col_14 char not null , primary key idx_8 ( col_14,col_13,col_10 ) , key idx_9 ( col_11 ) ) ; -create table tbl_3 ( col_15 tinyint default -91 not null , col_16 bit(61) default 990141831018971350 not null , col_17 double(244,22) default 3985 not null , col_18 binary(32) default 'kxMlWqvpxXNBlxoU' , col_19 text(401) , primary key idx_10 ( col_18,col_19(4) ) , key idx_11 ( col_17,col_18,col_19(2),col_15,col_16 ) , unique key idx_12 ( col_17 ) ) ; -create table tbl_4 ( col_20 double(230,16) default 8.49 not null , col_21 int unsigned not null , col_22 enum('Alice','Bob','Charlie','David') not null , col_23 float default 3066.13040283622 , col_24 datetime default '1980-10-27' not null , primary key idx_13 ( col_22,col_24 ) , key idx_14 ( col_23,col_20 ) , key idx_15 ( col_24 ) , key idx_16 ( col_20 ) , unique key idx_17 ( col_24 ) , key idx_18 ( col_21 ) ) ; +create table tbl_0 ( col_0 decimal not null , col_1 blob(207) , col_2 text , col_3 datetime default '1986-07-01' , col_4 bigint unsigned default 1504335725690712365 , primary key idx_0 ( col_3,col_2(1),col_1(6) ) nonclustered, key idx_1 ( col_3 ) , unique key idx_2 ( col_3 ) , unique key idx_3 ( col_0 ) , key idx_4 ( col_1(1),col_2(1) ) , key idx_5 ( col_2(1) ) ) ; +create table tbl_1 ( col_5 char(135) , col_6 bit(17) default 50609 not null , col_7 char(202) default 'IoQWYoGdbbgBDlxpDHQ' , col_8 char(213) , col_9 time not null , primary key idx_6 ( col_6 ) nonclustered, unique key idx_7 ( col_5 ) ) ; +create table tbl_2 ( col_10 datetime default '1976-05-11' , col_11 datetime , col_12 float , col_13 double(56,29) default 18.0118 , col_14 char not null , primary key idx_8 ( col_14,col_13,col_10 ) nonclustered, key idx_9 ( col_11 ) ) ; +create table tbl_3 ( col_15 tinyint default -91 not null , col_16 bit(61) default 990141831018971350 not null , col_17 double(244,22) default 3985 not null , col_18 binary(32) default 'kxMlWqvpxXNBlxoU' , col_19 text(401) , primary key idx_10 ( col_18,col_19(4) ) nonclustered, key idx_11 ( col_17,col_18,col_19(2),col_15,col_16 ) , unique key idx_12 ( col_17 ) ) ; +create table tbl_4 ( col_20 double(230,16) default 8.49 not null , col_21 int unsigned not null , col_22 enum('Alice','Bob','Charlie','David') not null , col_23 float default 3066.13040283622 , col_24 datetime default '1980-10-27' not null , primary key idx_13 ( col_22,col_24 ) nonclustered, key idx_14 ( col_23,col_20 ) , key idx_15 ( col_24 ) , key idx_16 ( col_20 ) , unique key idx_17 ( col_24 ) , key idx_18 ( col_21 ) ) ; load stats 's/wout_cluster_index_tbl_0.json'; load stats 's/wout_cluster_index_tbl_1.json'; load stats 's/wout_cluster_index_tbl_2.json'; diff --git a/cmd/explaintest/t/clustered_index.test b/cmd/explaintest/t/clustered_index.test index 7c40b6ae6523d..9415781f7caf1 100644 --- a/cmd/explaintest/t/clustered_index.test +++ b/cmd/explaintest/t/clustered_index.test @@ -4,12 +4,11 @@ drop database if exists wout_cluster_index; create database wout_cluster_index; use with_cluster_index; -set @@tidb_enable_clustered_index = 1; -create table tbl_0 ( col_0 decimal not null , col_1 blob(207) , col_2 text , col_3 datetime default '1986-07-01' , col_4 bigint unsigned default 1504335725690712365 , primary key idx_0 ( col_3,col_2(1),col_1(6) ) , key idx_1 ( col_3 ) , unique key idx_2 ( col_3 ) , unique key idx_3 ( col_0 ) , key idx_4 ( col_1(1),col_2(1) ) , key idx_5 ( col_2(1) ) ) ; -create table tbl_1 ( col_5 char(135) , col_6 bit(17) default 50609 not null , col_7 char(202) default 'IoQWYoGdbbgBDlxpDHQ' , col_8 char(213) , col_9 time not null , primary key idx_6 ( col_6 ) , unique key idx_7 ( col_5 ) ) ; -create table tbl_2 ( col_10 datetime default '1976-05-11' , col_11 datetime , col_12 float , col_13 double(56,29) default 18.0118 , col_14 char not null , primary key idx_8 ( col_14,col_13,col_10 ) , key idx_9 ( col_11 ) ) ; -create table tbl_3 ( col_15 tinyint default -91 not null , col_16 bit(61) default 990141831018971350 not null , col_17 double(244,22) default 3985 not null , col_18 binary(32) default 'kxMlWqvpxXNBlxoU' , col_19 text(401) , primary key idx_10 ( col_18,col_19(4) ) , key idx_11 ( col_17,col_18,col_19(2),col_15,col_16 ) , unique key idx_12 ( col_17 ) ) ; -create table tbl_4 ( col_20 double(230,16) default 8.49 not null , col_21 int unsigned not null , col_22 enum('Alice','Bob','Charlie','David') not null , col_23 float default 3066.13040283622 , col_24 datetime default '1980-10-27' not null , primary key idx_13 ( col_22,col_24 ) , key idx_14 ( col_23,col_20 ) , key idx_15 ( col_24 ) , key idx_16 ( col_20 ) , unique key idx_17 ( col_24 ) , key idx_18 ( col_21 ) ) ; +create table tbl_0 ( col_0 decimal not null , col_1 blob(207) , col_2 text , col_3 datetime default '1986-07-01' , col_4 bigint unsigned default 1504335725690712365 , primary key idx_0 ( col_3,col_2(1),col_1(6) ) clustered, key idx_1 ( col_3 ), unique key idx_2 ( col_3 ) , unique key idx_3 ( col_0 ) , key idx_4 ( col_1(1),col_2(1) ) , key idx_5 ( col_2(1) ) ) ; +create table tbl_1 ( col_5 char(135) , col_6 bit(17) default 50609 not null , col_7 char(202) default 'IoQWYoGdbbgBDlxpDHQ' , col_8 char(213) , col_9 time not null , primary key idx_6 ( col_6 ) clustered, unique key idx_7 ( col_5 ) ) ; +create table tbl_2 ( col_10 datetime default '1976-05-11' , col_11 datetime , col_12 float , col_13 double(56,29) default 18.0118 , col_14 char not null , primary key idx_8 ( col_14,col_13,col_10 ) clustered, key idx_9 ( col_11 ) ) ; +create table tbl_3 ( col_15 tinyint default -91 not null , col_16 bit(61) default 990141831018971350 not null , col_17 double(244,22) default 3985 not null , col_18 binary(32) default 'kxMlWqvpxXNBlxoU' , col_19 text(401) , primary key idx_10 ( col_18,col_19(4) ) clustered, key idx_11 ( col_17,col_18,col_19(2),col_15,col_16 ) , unique key idx_12 ( col_17 ) ) ; +create table tbl_4 ( col_20 double(230,16) default 8.49 not null , col_21 int unsigned not null , col_22 enum('Alice','Bob','Charlie','David') not null , col_23 float default 3066.13040283622 , col_24 datetime default '1980-10-27' not null , primary key idx_13 ( col_22,col_24 ) clustered, key idx_14 ( col_23,col_20 ) , key idx_15 ( col_24 ) , key idx_16 ( col_20 ) , unique key idx_17 ( col_24 ) , key idx_18 ( col_21 ) ) ; load stats 's/with_cluster_index_tbl_0.json'; load stats 's/with_cluster_index_tbl_1.json'; load stats 's/with_cluster_index_tbl_2.json'; @@ -17,12 +16,11 @@ load stats 's/with_cluster_index_tbl_3.json'; load stats 's/with_cluster_index_tbl_4.json'; use wout_cluster_index; -set @@tidb_enable_clustered_index = 0; -create table tbl_0 ( col_0 decimal not null , col_1 blob(207) , col_2 text , col_3 datetime default '1986-07-01' , col_4 bigint unsigned default 1504335725690712365 , primary key idx_0 ( col_3,col_2(1),col_1(6) ) , key idx_1 ( col_3 ) , unique key idx_2 ( col_3 ) , unique key idx_3 ( col_0 ) , key idx_4 ( col_1(1),col_2(1) ) , key idx_5 ( col_2(1) ) ) ; -create table tbl_1 ( col_5 char(135) , col_6 bit(17) default 50609 not null , col_7 char(202) default 'IoQWYoGdbbgBDlxpDHQ' , col_8 char(213) , col_9 time not null , primary key idx_6 ( col_6 ) , unique key idx_7 ( col_5 ) ) ; -create table tbl_2 ( col_10 datetime default '1976-05-11' , col_11 datetime , col_12 float , col_13 double(56,29) default 18.0118 , col_14 char not null , primary key idx_8 ( col_14,col_13,col_10 ) , key idx_9 ( col_11 ) ) ; -create table tbl_3 ( col_15 tinyint default -91 not null , col_16 bit(61) default 990141831018971350 not null , col_17 double(244,22) default 3985 not null , col_18 binary(32) default 'kxMlWqvpxXNBlxoU' , col_19 text(401) , primary key idx_10 ( col_18,col_19(4) ) , key idx_11 ( col_17,col_18,col_19(2),col_15,col_16 ) , unique key idx_12 ( col_17 ) ) ; -create table tbl_4 ( col_20 double(230,16) default 8.49 not null , col_21 int unsigned not null , col_22 enum('Alice','Bob','Charlie','David') not null , col_23 float default 3066.13040283622 , col_24 datetime default '1980-10-27' not null , primary key idx_13 ( col_22,col_24 ) , key idx_14 ( col_23,col_20 ) , key idx_15 ( col_24 ) , key idx_16 ( col_20 ) , unique key idx_17 ( col_24 ) , key idx_18 ( col_21 ) ) ; +create table tbl_0 ( col_0 decimal not null , col_1 blob(207) , col_2 text , col_3 datetime default '1986-07-01' , col_4 bigint unsigned default 1504335725690712365 , primary key idx_0 ( col_3,col_2(1),col_1(6) ) nonclustered, key idx_1 ( col_3 ) , unique key idx_2 ( col_3 ) , unique key idx_3 ( col_0 ) , key idx_4 ( col_1(1),col_2(1) ) , key idx_5 ( col_2(1) ) ) ; +create table tbl_1 ( col_5 char(135) , col_6 bit(17) default 50609 not null , col_7 char(202) default 'IoQWYoGdbbgBDlxpDHQ' , col_8 char(213) , col_9 time not null , primary key idx_6 ( col_6 ) nonclustered, unique key idx_7 ( col_5 ) ) ; +create table tbl_2 ( col_10 datetime default '1976-05-11' , col_11 datetime , col_12 float , col_13 double(56,29) default 18.0118 , col_14 char not null , primary key idx_8 ( col_14,col_13,col_10 ) nonclustered, key idx_9 ( col_11 ) ) ; +create table tbl_3 ( col_15 tinyint default -91 not null , col_16 bit(61) default 990141831018971350 not null , col_17 double(244,22) default 3985 not null , col_18 binary(32) default 'kxMlWqvpxXNBlxoU' , col_19 text(401) , primary key idx_10 ( col_18,col_19(4) ) nonclustered, key idx_11 ( col_17,col_18,col_19(2),col_15,col_16 ) , unique key idx_12 ( col_17 ) ) ; +create table tbl_4 ( col_20 double(230,16) default 8.49 not null , col_21 int unsigned not null , col_22 enum('Alice','Bob','Charlie','David') not null , col_23 float default 3066.13040283622 , col_24 datetime default '1980-10-27' not null , primary key idx_13 ( col_22,col_24 ) nonclustered, key idx_14 ( col_23,col_20 ) , key idx_15 ( col_24 ) , key idx_16 ( col_20 ) , unique key idx_17 ( col_24 ) , key idx_18 ( col_21 ) ) ; load stats 's/wout_cluster_index_tbl_0.json'; load stats 's/wout_cluster_index_tbl_1.json'; load stats 's/wout_cluster_index_tbl_2.json'; diff --git a/config/config.go b/config/config.go index 8e1a4fe1d4214..123287b505dda 100644 --- a/config/config.go +++ b/config/config.go @@ -707,6 +707,7 @@ var deprecatedConfig = map[string]struct{}{ "experimental.allow-auto-random": {}, "enable-redact-log": {}, // use variable tidb_redact_log instead "tikv-client.copr-cache.enable": {}, + "alter-primary-key": {}, // use NONCLUSTERED keyword instead } func isAllDeprecatedConfigItems(items []string) bool { diff --git a/config/config.toml.example b/config/config.toml.example index 60e86c847f205..227836889f597 100644 --- a/config/config.toml.example +++ b/config/config.toml.example @@ -86,11 +86,6 @@ delay-clean-table-lock = 0 # Maximum number of the splitting region, which is used by the split region statement. split-region-max-num = 1000 -# alter-primary-key is used to control alter primary key feature. Default is false, indicate the alter primary key feature is disabled. -# If it is true, we can add the primary key by "alter table". However, if a table already exists before the switch is turned true and the data type of its primary key column is an integer, -# the primary key cannot be dropped. -alter-primary-key = false - # server-version is used to change the version string of TiDB in the following scenarios: # 1. the server version returned by builtin-function `VERSION()`. # 2. the server version filled in handshake packets of MySQL Connection Protocol, see https://dev.mysql.com/doc/internals/en/connection-phase-packets.html#packet-Protocol::Handshake for more details. diff --git a/config/config_test.go b/config/config_test.go index 39bc1448b61a5..1a4c7762597fc 100644 --- a/config/config_test.go +++ b/config/config_test.go @@ -184,7 +184,6 @@ unrecognized-option-test = true _, err = f.WriteString(` token-limit = 0 enable-table-lock = true -alter-primary-key = true delay-clean-table-lock = 5 split-region-max-num=10000 enable-batch-dml = true @@ -243,7 +242,6 @@ spilled-file-encryption-method = "plaintext" // Test that the value will be overwritten by the config file. c.Assert(conf.Performance.TxnTotalSizeLimit, Equals, uint64(2000)) - c.Assert(conf.AlterPrimaryKey, Equals, true) c.Assert(conf.TiKVClient.CommitTimeout, Equals, "41s") c.Assert(conf.TiKVClient.AsyncCommit.KeysLimit, Equals, uint(123)) diff --git a/ddl/db_change_test.go b/ddl/db_change_test.go index fe01b8bdf3f16..99a2de6ee3ef5 100644 --- a/ddl/db_change_test.go +++ b/ddl/db_change_test.go @@ -580,16 +580,11 @@ func (s *serialTestStateChangeSuite) TestWriteReorgForModifyColumnWithPKIsHandle s.se.GetSessionVars().EnableChangeColumnType = true defer func() { s.se.GetSessionVars().EnableChangeColumnType = enableChangeColumnType - config.RestoreFunc()() }() - config.UpdateGlobal(func(conf *config.Config) { - conf.AlterPrimaryKey = false - }) - _, err := s.se.Execute(context.Background(), "use test_db_state") c.Assert(err, IsNil) - _, err = s.se.Execute(context.Background(), `create table tt (a int not null, b int default 1, c int not null default 0, unique index idx(c), primary key idx1(a), index idx2(a, c))`) + _, err = s.se.Execute(context.Background(), `create table tt (a int not null, b int default 1, c int not null default 0, unique index idx(c), primary key idx1(a) clustered, index idx2(a, c))`) c.Assert(err, IsNil) _, err = s.se.Execute(context.Background(), "insert into tt (a, c) values(-1, -11)") c.Assert(err, IsNil) @@ -935,7 +930,7 @@ func (s *testStateChangeSuiteBase) CheckResult(tk *testkit.TestKit, sql string, } func (s *testStateChangeSuite) TestShowIndex(c *C) { - _, err := s.se.Execute(context.Background(), `create table t(c1 int primary key, c2 int)`) + _, err := s.se.Execute(context.Background(), `create table t(c1 int primary key nonclustered, c2 int)`) c.Assert(err, IsNil) defer func() { _, err := s.se.Execute(context.Background(), "drop table t") @@ -1062,12 +1057,7 @@ func (s *testStateChangeSuite) TestParallelAlterModifyColumn(c *C) { s.testControlParallelExecSQL(c, sql, sql, f) } -func (s *serialTestStateChangeSuite) TestParallelAlterModifyColumnAndAddPK(c *C) { - defer config.RestoreFunc()() - config.UpdateGlobal(func(conf *config.Config) { - conf.AlterPrimaryKey = true - }) - +func (s *testStateChangeSuite) TestParallelAlterModifyColumnAndAddPK(c *C) { _, err := s.se.Execute(context.Background(), "set global tidb_enable_change_column_type = 1") c.Assert(err, IsNil) defer func() { @@ -1076,7 +1066,7 @@ func (s *serialTestStateChangeSuite) TestParallelAlterModifyColumnAndAddPK(c *C) }() domain.GetDomain(s.se).GetGlobalVarsCache().Disable() - sql1 := "ALTER TABLE t ADD PRIMARY KEY (b);" + sql1 := "ALTER TABLE t ADD PRIMARY KEY (b) NONCLUSTERED;" sql2 := "ALTER TABLE t MODIFY COLUMN b tinyint;" f := func(c *C, err1, err2 error) { c.Assert(err1, IsNil) diff --git a/ddl/db_integration_test.go b/ddl/db_integration_test.go index 8aa31771e7f8f..7e27382395dd3 100644 --- a/ddl/db_integration_test.go +++ b/ddl/db_integration_test.go @@ -127,6 +127,7 @@ type testIntegrationSuite5 struct{ *testIntegrationSuite } type testIntegrationSuite6 struct{ *testIntegrationSuite } type testIntegrationSuite7 struct{ *testIntegrationSuite } type testIntegrationSuite8 struct{ *testIntegrationSuite } +type testIntegrationSuite9 struct{ *testIntegrationSuite } func (s *testIntegrationSuite5) TestNoZeroDateMode(c *C) { tk := testkit.NewTestKit(c, s.store) @@ -1262,7 +1263,7 @@ func (s *testIntegrationSuite3) TestMultiRegionGetTableEndHandle(c *C) { tk.MustExec("create database test_get_endhandle") tk.MustExec("use test_get_endhandle") - tk.MustExec("create table t(a bigint PRIMARY KEY, b int)") + tk.MustExec("create table t(a bigint PRIMARY KEY nonclustered, b int)") for i := 0; i < 1000; i++ { tk.MustExec(fmt.Sprintf("insert into t values(%v, %v)", i, i)) } @@ -1572,7 +1573,7 @@ func (s *testIntegrationSuite3) TestAlterColumn(c *C) { // The followings tests whether adding constraints via change / modify column // is forbidden as expected. tk.MustExec("drop table if exists mc") - tk.MustExec("create table mc(a int key, b int, c int)") + tk.MustExec("create table mc(a int key nonclustered, b int, c int)") _, err = tk.Exec("alter table mc modify column a int key") // Adds a new primary key c.Assert(err, NotNil) _, err = tk.Exec("alter table mc modify column c int unique") // Adds a new unique key @@ -1584,7 +1585,7 @@ func (s *testIntegrationSuite3) TestAlterColumn(c *C) { // Change / modify column should preserve index options. tk.MustExec("drop table if exists mc") - tk.MustExec("create table mc(a int key, b int, c int unique)") + tk.MustExec("create table mc(a int key nonclustered, b int, c int unique)") tk.MustExec("alter table mc modify column a bigint") // NOT NULL & PRIMARY KEY should be preserved tk.MustExec("alter table mc modify column b bigint") tk.MustExec("alter table mc modify column c bigint") // Unique should be preserved @@ -1595,7 +1596,7 @@ func (s *testIntegrationSuite3) TestAlterColumn(c *C) { // Dropping or keeping auto_increment is allowed, however adding is not allowed. tk.MustExec("drop table if exists mc") - tk.MustExec("create table mc(a int key auto_increment, b int)") + tk.MustExec("create table mc(a int key nonclustered auto_increment, b int)") tk.MustExec("alter table mc modify column a bigint auto_increment") // Keeps auto_increment result = tk.MustQuery("show create table mc") createSQL = result.Rows()[0][1] @@ -2228,19 +2229,18 @@ func (s *testIntegrationSuite7) TestCreateExpressionIndexError(c *C) { defer config.RestoreFunc()() config.UpdateGlobal(func(conf *config.Config) { conf.Experimental.AllowsExpressionIndex = true - conf.AlterPrimaryKey = true }) tk := testkit.NewTestKit(c, s.store) tk.MustExec("use test") tk.MustExec("drop table if exists t;") tk.MustExec("create table t (a int, b real);") - tk.MustGetErrCode("alter table t add primary key ((a+b));", errno.ErrFunctionalIndexPrimaryKey) + tk.MustGetErrCode("alter table t add primary key ((a+b)) nonclustered;", errno.ErrFunctionalIndexPrimaryKey) // Test for error tk.MustExec("drop table if exists t;") tk.MustExec("create table t (a int, b real);") - tk.MustGetErrCode("alter table t add primary key ((a+b));", errno.ErrFunctionalIndexPrimaryKey) + tk.MustGetErrCode("alter table t add primary key ((a+b)) nonclustered;", errno.ErrFunctionalIndexPrimaryKey) tk.MustGetErrCode("alter table t add index ((rand()));", errno.ErrFunctionalIndexFunctionIsNotAllowed) tk.MustGetErrCode("alter table t add index ((now()+1));", errno.ErrFunctionalIndexFunctionIsNotAllowed) @@ -2265,7 +2265,7 @@ func (s *testIntegrationSuite7) TestCreateExpressionIndexError(c *C) { tk.MustExec("create table t (j json, key k ((j+1),(j+1)))") tk.MustGetErrCode("create table t1 (col1 int, index ((concat(''))));", errno.ErrWrongKeyColumnFunctionalIndex) - tk.MustGetErrCode("CREATE TABLE t1 (col1 INT, PRIMARY KEY ((ABS(col1))));", errno.ErrFunctionalIndexPrimaryKey) + tk.MustGetErrCode("CREATE TABLE t1 (col1 INT, PRIMARY KEY ((ABS(col1))) NONCLUSTERED);", errno.ErrFunctionalIndexPrimaryKey) } func (s *testIntegrationSuite7) TestAddExpressionIndexOnPartition(c *C) { @@ -2307,7 +2307,7 @@ func (s *testIntegrationSuite3) TestCreateTableWithAutoIdCache(c *C) { tk.MustExec("drop table if exists t1;") // Test primary key is handle. - tk.MustExec("create table t(a int auto_increment key) auto_id_cache 100") + tk.MustExec("create table t(a int auto_increment key clustered) auto_id_cache 100") tblInfo, err := s.dom.InfoSchema().TableByName(model.NewCIStr("test"), model.NewCIStr("t")) c.Assert(err, IsNil) c.Assert(tblInfo.Meta().AutoIdCache, Equals, int64(100)) @@ -2371,13 +2371,15 @@ func (s *testIntegrationSuite3) TestCreateTableWithAutoIdCache(c *C) { tk.MustExec("drop table if exists t;") tk.MustExec("drop table if exists t1;") - tk.MustExec("create table t(a int auto_increment key) auto_id_cache 3") + tk.MustExec("create table t(a int auto_increment key clustered) auto_id_cache 3") tblInfo, err = s.dom.InfoSchema().TableByName(model.NewCIStr("test"), model.NewCIStr("t")) c.Assert(err, IsNil) c.Assert(tblInfo.Meta().AutoIdCache, Equals, int64(3)) // Test insert batch size(4 here) greater than the customized autoid step(3 here). - tk.MustExec("insert into t(a) values(NULL),(NULL),(NULL),(NULL)") + tk.MustExec("insert into t(a) values(NULL),(NULL),(NULL)") + // Cache 3 more values. We can't merge this two lines because the batch allocation overrides autoid step. + tk.MustExec("insert into t(a) values(NULL)") tk.MustQuery("select a from t").Check(testkit.Rows("1", "2", "3", "4")) tk.MustExec("delete from t") @@ -2522,17 +2524,12 @@ func (s *testIntegrationSuite5) TestDropLastVisibleColumns(c *C) { func (s *testIntegrationSuite7) TestAutoIncrementTableOption(c *C) { tk := testkit.NewTestKit(c, s.store) - defer config.RestoreFunc()() - config.UpdateGlobal(func(conf *config.Config) { - // Make sure the integer primary key is the handle(PkIsHandle). - conf.AlterPrimaryKey = false - }) tk.MustExec("drop database if exists test_auto_inc_table_opt;") tk.MustExec("create database test_auto_inc_table_opt;") tk.MustExec("use test_auto_inc_table_opt;") // Empty auto_inc allocator should not cause error. - tk.MustExec("create table t (a bigint primary key) auto_increment = 10;") + tk.MustExec("create table t (a bigint primary key clustered) auto_increment = 10;") tk.MustExec("alter table t auto_increment = 10;") tk.MustExec("alter table t auto_increment = 12345678901234567890;") @@ -2640,7 +2637,6 @@ func (s *testIntegrationSuite7) TestDuplicateErrorMessage(c *C) { restoreConfig := config.RestoreFunc() config.UpdateGlobal(func(conf *config.Config) { conf.EnableGlobalIndex = globalIndex - conf.AlterPrimaryKey = false }) for _, clusteredIndex := range []bool{false, true} { tk.Se.GetSessionVars().EnableClusteredIndex = clusteredIndex diff --git a/ddl/db_test.go b/ddl/db_test.go index 1f83765a48b47..bf9686e14423e 100644 --- a/ddl/db_test.go +++ b/ddl/db_test.go @@ -146,7 +146,7 @@ type testDBSuite6 struct{ *testDBSuite } type testDBSuite7 struct{ *testDBSuite } type testSerialDBSuite struct{ *testDBSuite } -func testAddIndexWithPK(tk *testkit.TestKit, s *testSerialDBSuite, c *C) { +func testAddIndexWithPK(tk *testkit.TestKit) { tk.MustExec("drop table if exists test_add_index_with_pk") tk.MustExec("create table test_add_index_with_pk(a int not null, b int not null default '0', primary key(a))") tk.MustExec("insert into test_add_index_with_pk values(1, 2)") @@ -173,17 +173,13 @@ func testAddIndexWithPK(tk *testkit.TestKit, s *testSerialDBSuite, c *C) { tk.MustExec("create index idx on t (a, b);") } -func (s *testSerialDBSuite) TestAddIndexWithPK(c *C) { +func (s *testDBSuite7) TestAddIndexWithPK(c *C) { tk := testkit.NewTestKit(c, s.store) tk.MustExec("use " + s.schemaName) - defer config.RestoreFunc()() - config.UpdateGlobal(func(conf *config.Config) { - conf.AlterPrimaryKey = false - }) - testAddIndexWithPK(tk, s, c) + testAddIndexWithPK(tk) tk.Se.GetSessionVars().EnableClusteredIndex = true - testAddIndexWithPK(tk, s, c) + testAddIndexWithPK(tk) } func (s *testDBSuite5) TestAddIndexWithDupIndex(c *C) { @@ -1140,11 +1136,7 @@ func (s *testDBSuite4) TestAddIndex4(c *C) { partition p4 values less than maxvalue)`, "") } -func (s *testSerialDBSuite) TestAddIndex5(c *C) { - defer config.RestoreFunc()() - config.UpdateGlobal(func(conf *config.Config) { - conf.AlterPrimaryKey = false - }) +func (s *testDBSuite5) TestAddIndex5(c *C) { testAddIndex(c, s.store, s.lease, testClusteredIndex, `create table test_add_index (c1 bigint, c2 bigint, c3 bigint, primary key(c2, c3))`, "") } @@ -1414,7 +1406,7 @@ func (s *testDBSuite1) TestCancelAddTableAndDropTablePartition(c *C) { func (s *testDBSuite1) TestDropPrimaryKey(c *C) { idxName := "primary" - createSQL := "create table test_drop_index (c1 int, c2 int, c3 int, unique key(c1), primary key(c3))" + createSQL := "create table test_drop_index (c1 int, c2 int, c3 int, unique key(c1), primary key(c3) nonclustered)" dropIdxSQL := "alter table test_drop_index drop primary key;" testDropIndex(c, s.store, s.lease, createSQL, dropIdxSQL, idxName) } @@ -1435,7 +1427,7 @@ func testDropIndex(c *C, store kv.Storage, lease time.Duration, createSQL, dropI tk.MustExec("delete from test_drop_index") num := 100 - // add some rows + // add some rows for i := 0; i < num; i++ { tk.MustExec("insert into test_drop_index values (?, ?, ?)", i, i, i) } @@ -1953,7 +1945,6 @@ func (s *testSerialDBSuite) TestAddGlobalIndex(c *C) { defer config.RestoreFunc()() config.UpdateGlobal(func(conf *config.Config) { conf.EnableGlobalIndex = true - conf.AlterPrimaryKey = true }) tk := testkit.NewTestKit(c, s.store) tk.MustExec("use test_db") @@ -1994,7 +1985,7 @@ func (s *testSerialDBSuite) TestAddGlobalIndex(c *C) { " (partition p0 values less than (10), " + " partition p1 values less than (maxvalue));") tk.MustExec("insert test_t2 values (1, 1)") - tk.MustExec("alter table test_t2 add primary key (a);") + tk.MustExec("alter table test_t2 add primary key (a) nonclustered;") tk.MustExec("insert test_t2 values (2, 11)") t = s.testGetTable(c, "test_t2") tblInfo = t.Meta() @@ -2432,6 +2423,7 @@ func (s *testDBSuite7) TestSelectInViewFromAnotherDB(c *C) { _, _ = s.s.Execute(context.Background(), "create database test_db2") tk := testkit.NewTestKit(c, s.store) tk.MustExec("use " + s.schemaName) + tk.MustExec("drop table if exists t;") tk.MustExec("create table t(a int)") tk.MustExec("use test_db2") tk.MustExec("create sql security invoker view v as select * from " + s.schemaName + ".t") @@ -2672,16 +2664,12 @@ func (s *testSerialDBSuite) TestRepairTable(c *C) { defer func() { c.Assert(failpoint.Disable("github.com/pingcap/tidb/infoschema/repairFetchCreateTable"), IsNil) }() - defer config.RestoreFunc()() - config.UpdateGlobal(func(conf *config.Config) { - conf.AlterPrimaryKey = true - }) tk := testkit.NewTestKit(c, s.store) tk.MustExec("use test") tk.MustExec("drop table if exists t, other_table, origin") // Test repair table when TiDB is not in repair mode. - tk.MustExec("CREATE TABLE t (a int primary key, b varchar(10));") + tk.MustExec("CREATE TABLE t (a int primary key nonclustered, b varchar(10));") _, err := tk.Exec("admin repair table t CREATE TABLE t (a float primary key, b varchar(5));") c.Assert(err, NotNil) c.Assert(err.Error(), Equals, "[ddl:8215]Failed to repair table: TiDB is not in REPAIR MODE") @@ -2757,7 +2745,7 @@ func (s *testSerialDBSuite) TestRepairTable(c *C) { turnRepairModeAndInit(true) defer turnRepairModeAndInit(false) // Domain reload the tableInfo and add it into repairInfo. - tk.MustExec("CREATE TABLE origin (a int primary key auto_increment, b varchar(10), c int);") + tk.MustExec("CREATE TABLE origin (a int primary key nonclustered auto_increment, b varchar(10), c int);") // Repaired tableInfo has been filtered by `domain.InfoSchema()`, so get it in repairInfo. originTableInfo, _ := domainutil.RepairInfo.GetRepairedTableInfoByTableName("test", "origin") @@ -2788,7 +2776,7 @@ func (s *testSerialDBSuite) TestRepairTable(c *C) { s.dom.DDL().(ddl.DDLForTest).SetHook(hook) // Exec the repair statement to override the tableInfo. - tk.MustExec("admin repair table origin CREATE TABLE origin (a int primary key auto_increment, b varchar(5), c int);") + tk.MustExec("admin repair table origin CREATE TABLE origin (a int primary key nonclustered auto_increment, b varchar(5), c int);") c.Assert(repairErr, IsNil) // Check the repaired tableInfo is exactly the same with old one in tableID, indexID, colID. @@ -4501,7 +4489,7 @@ func (s *testDBSuite4) TestIfExists(c *C) { tk.MustQuery("show warnings").Check(testutil.RowsWithSep("|", "Note|1507|Error in list of partitions to p1")) } -func testAddIndexForGeneratedColumn(tk *testkit.TestKit, s *testSerialDBSuite, c *C) { +func testAddIndexForGeneratedColumn(tk *testkit.TestKit, s *testDBSuite5, c *C) { tk.MustExec("use test_db") tk.MustExec("drop table if exists t") tk.MustExec("create table t(y year NOT NULL DEFAULT '2155')") @@ -4541,15 +4529,9 @@ func testAddIndexForGeneratedColumn(tk *testkit.TestKit, s *testSerialDBSuite, c tk.MustQuery("select id1 from gcai_table use index(idx1)").Check(testkit.Rows("6")) tk.MustExec("admin check table gcai_table") } -func (s *testSerialDBSuite) TestAddIndexForGeneratedColumn(c *C) { - tk := testkit.NewTestKit(c, s.store) - defer config.RestoreFunc()() - config.UpdateGlobal(func(conf *config.Config) { - conf.AlterPrimaryKey = false - }) - testAddIndexForGeneratedColumn(tk, s, c) - tk.Se.GetSessionVars().EnableClusteredIndex = true +func (s *testDBSuite5) TestAddIndexForGeneratedColumn(c *C) { + tk := testkit.NewTestKit(c, s.store) testAddIndexForGeneratedColumn(tk, s, c) } diff --git a/ddl/ddl_api.go b/ddl/ddl_api.go index 1bb5700dfdfe9..57a8f203b6575 100644 --- a/ddl/ddl_api.go +++ b/ddl/ddl_api.go @@ -39,6 +39,7 @@ import ( field_types "github.com/pingcap/parser/types" "github.com/pingcap/tidb/config" "github.com/pingcap/tidb/ddl/placement" + "github.com/pingcap/tidb/errno" "github.com/pingcap/tidb/expression" "github.com/pingcap/tidb/infoschema" "github.com/pingcap/tidb/kv" @@ -54,6 +55,7 @@ import ( "github.com/pingcap/tidb/util/chunk" "github.com/pingcap/tidb/util/codec" "github.com/pingcap/tidb/util/collate" + "github.com/pingcap/tidb/util/dbterror" "github.com/pingcap/tidb/util/domainutil" "github.com/pingcap/tidb/util/logutil" "github.com/pingcap/tidb/util/mock" @@ -1405,6 +1407,12 @@ func buildTableInfo( tbInfo.Columns = append(tbInfo.Columns, hiddenCol) tblColumns = append(tblColumns, table.ToColumn(hiddenCol)) } + // Check clustered on non-primary key. + if constr.Option != nil && constr.Option.PrimaryKeyTp != model.PrimaryKeyTypeDefault && + constr.Tp != ast.ConstraintPrimaryKey { + msg := mysql.Message("CLUSTERED/NONCLUSTERED keyword is only supported for primary key", nil) + return nil, dbterror.ClassDDL.NewStdErr(errno.ErrUnsupportedDDLOperation, msg) + } if constr.Tp == ast.ConstraintForeignKey { for _, fk := range tbInfo.ForeignKeys { if fk.Name.L == strings.ToLower(constr.Name) { @@ -1425,41 +1433,18 @@ func buildTableInfo( if err != nil { return nil, err } - pkTp := model.PrimaryKeyTypeDefault - if constr.Option != nil { - pkTp = constr.Option.PrimaryKeyTp - } - noBinlog := ctx.GetSessionVars().BinlogClient == nil - switch pkTp { - case model.PrimaryKeyTypeNonClustered: - break - case model.PrimaryKeyTypeClustered: - if isSingleIntPK(constr, lastCol) { + isSingleIntPK := isSingleIntPK(constr, lastCol) + if ShouldBuildClusteredIndex(ctx, constr.Option, isSingleIntPK) { + if isSingleIntPK { tbInfo.PKIsHandle = true } else { - tbInfo.IsCommonHandle = noBinlog - if tbInfo.IsCommonHandle { - tbInfo.CommonHandleVersion = 1 - } - if !noBinlog { - errMsg := "cannot build clustered index table because the binlog is ON" - ctx.GetSessionVars().StmtCtx.AppendWarning(errors.Errorf(errMsg)) - } - } - case model.PrimaryKeyTypeDefault: - // (AlterPrimaryKey = true) ----> all pk must be nonclustered - // (AlterPrimaryKey = false) + (EnableClusteredIndex = true) + noBinlog ---> all pk must be clustered - // (AlterPrimaryKey = false) + (EnableClusteredIndex = true) + HasBinlog ---> int pk must be clustered, other must be nonclustered - // (AlterPrimaryKey = false) + (EnableClusteredIndex = false) + (IntPrimaryKeyDefaultAsClustered = true) --> int pk must be clustered - // (AlterPrimaryKey = false) + (EnableClusteredIndex = false) + (IntPrimaryKeyDefaultAsClustered = false) --> all pk must be nonclustered [Default] - alterPKConf := config.GetGlobalConfig().AlterPrimaryKey - if isSingleIntPK(constr, lastCol) { - tbInfo.PKIsHandle = !alterPKConf && (ctx.GetSessionVars().EnableClusteredIndex || ctx.GetSessionVars().IntPrimaryKeyDefaultAsClustered) - } else { - tbInfo.IsCommonHandle = !alterPKConf && ctx.GetSessionVars().EnableClusteredIndex && noBinlog - if tbInfo.IsCommonHandle { - tbInfo.CommonHandleVersion = 1 + hasBinlog := ctx.GetSessionVars().BinlogClient != nil + if hasBinlog { + msg := mysql.Message("Cannot create clustered index table when the binlog is ON", nil) + return nil, dbterror.ClassDDL.NewStdErr(errno.ErrUnsupportedDDLOperation, msg) } + tbInfo.IsCommonHandle = true + tbInfo.CommonHandleVersion = 1 } } if tbInfo.PKIsHandle || tbInfo.IsCommonHandle { @@ -1535,6 +1520,15 @@ func isSingleIntPK(constr *ast.Constraint, lastCol *model.ColumnInfo) bool { return false } +// ShouldBuildClusteredIndex is used to determine whether the CREATE TABLE statement should build a clustered index table. +func ShouldBuildClusteredIndex(ctx sessionctx.Context, opt *ast.IndexOption, isSingleIntPK bool) bool { + if opt == nil || opt.PrimaryKeyTp == model.PrimaryKeyTypeDefault { + return ctx.GetSessionVars().EnableClusteredIndex || + (isSingleIntPK && ctx.GetSessionVars().IntPrimaryKeyDefaultAsClustered) + } + return opt.PrimaryKeyTp == model.PrimaryKeyTypeClustered +} + // checkTableInfoValidExtra is like checkTableInfoValid, but also assumes the // table info comes from untrusted source and performs further checks such as // name length and column count. @@ -2176,7 +2170,7 @@ func handleTableOptions(options []*ast.TableOption, tbInfo *model.TableInfo) err case ast.TableOptionCompression: tbInfo.Compression = op.StrValue case ast.TableOptionShardRowID: - if op.UintValue > 0 && tbInfo.PKIsHandle { + if op.UintValue > 0 && (tbInfo.PKIsHandle || tbInfo.IsCommonHandle) { return errUnsupportedShardRowIDBits } tbInfo.ShardRowIDBits = op.UintValue @@ -2604,7 +2598,7 @@ func (d *ddl) ShardRowID(ctx sessionctx.Context, tableIdent ast.Ident, uVal uint // Nothing need to do. return nil } - if uVal > 0 && t.Meta().PKIsHandle { + if uVal > 0 && (t.Meta().PKIsHandle || t.Meta().IsCommonHandle) { return errUnsupportedShardRowIDBits } err = verifyNoOverflowShardBits(d.sessPool, t, uVal) @@ -4759,11 +4753,10 @@ func getAnonymousIndex(t table.Table, colName model.CIStr, idxName model.CIStr) func (d *ddl) CreatePrimaryKey(ctx sessionctx.Context, ti ast.Ident, indexName model.CIStr, indexPartSpecifications []*ast.IndexPartSpecification, indexOption *ast.IndexOption) error { - if !config.GetGlobalConfig().AlterPrimaryKey { - return ErrUnsupportedModifyPrimaryKey.GenWithStack("Unsupported add primary key, alter-primary-key is false. " + - "Please check the documentation for the tidb-server configuration files") + if indexOption != nil && indexOption.PrimaryKeyTp == model.PrimaryKeyTypeClustered { + return ErrUnsupportedModifyPrimaryKey.GenWithStack("Adding clustered primary key is not supported. " + + "Please consider adding NONCLUSTERED primary key instead") } - schema, t, err := d.getSchemaAndTableByIdent(ctx, ti) if err != nil { return errors.Trace(err) @@ -5173,10 +5166,6 @@ func (d *ddl) DropIndex(ctx sessionctx.Context, ti ast.Ident, indexName model.CI isPK = true } if isPK { - if !config.GetGlobalConfig().AlterPrimaryKey { - return ErrUnsupportedModifyPrimaryKey.GenWithStack("Unsupported drop primary key when alter-primary-key is false") - - } // If the table's PKIsHandle is true, we can't find the index from the table. So we check the value of PKIsHandle. if indexInfo == nil && !t.Meta().PKIsHandle { return ErrCantDropFieldOrKey.GenWithStack("Can't DROP 'PRIMARY'; check that column/key exists") diff --git a/ddl/ddl_test.go b/ddl/ddl_test.go index a2bca47ee382e..90a8a091fe3c8 100644 --- a/ddl/ddl_test.go +++ b/ddl/ddl_test.go @@ -79,8 +79,6 @@ func TestT(t *testing.T) { // Test for table lock. conf.EnableTableLock = true conf.Log.SlowThreshold = 10000 - // Test for add/drop primary key. - conf.AlterPrimaryKey = true conf.TiKVClient.AsyncCommit.SafeWindow = 0 conf.TiKVClient.AsyncCommit.AllowedClockDrift = 0 }) diff --git a/ddl/serial_test.go b/ddl/serial_test.go index e5d84c90776a9..43b4773cadc85 100644 --- a/ddl/serial_test.go +++ b/ddl/serial_test.go @@ -53,6 +53,9 @@ import ( // Make it serial because config is modified in test cases. var _ = SerialSuites(&testSerialSuite{}) +// TODO(tangenta): Move all the parallel tests out of this file. +var _ = Suite(&testIntegrationSuite9{&testIntegrationSuite{}}) + type testSerialSuite struct { CommonHandleSuite store kv.Storage @@ -64,8 +67,7 @@ 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 + // Update config here. }) ddl.SetWaitTimeWhenErrorOccurred(1 * time.Microsecond) @@ -110,81 +112,72 @@ func (s *testSerialSuite) TestChangeMaxIndexLength(c *C) { tk.MustExec("drop table t, t1") } -func (s *testSerialSuite) TestPrimaryKey(c *C) { +func (s *testIntegrationSuite9) TestPrimaryKey(c *C) { tk := testkit.NewTestKit(c, s.store) - tk.MustExec("use test") + tk.MustExec("drop database if exists test_primary_key;") + tk.MustExec("create database test_primary_key;") + tk.MustExec("use test_primary_key;") 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") + // Test add/drop primary key on a plain table. + tk.MustExec("drop table if exists t;") + tk.MustExec("create table t (a int, b varchar(10));") + tk.MustGetErrCode("alter table t add primary key(a) clustered;", errno.ErrUnsupportedDDLOperation) + tk.MustExec("alter table t add primary key(a) nonclustered;") + tk.MustExec("alter table t drop primary key;") + tk.MustExec("alter table t add primary key(a) nonclustered;") + tk.MustExec("drop index `primary` on t;") + tk.MustExec("alter table t add primary key(a);") // implicit nonclustered + tk.MustExec("drop index `primary` on t;") + tk.MustGetErrCode("drop index `primary` on t;", errno.ErrCantDropFieldOrKey) + + // Test add/drop primary key on a PKIsHandle table. + tk.MustExec("drop table if exists t;") + tk.MustExec("create table t (a int, b varchar(10), primary key(a) clustered);") + tk.MustGetErrCode("alter table t drop primary key;", errno.ErrUnsupportedDDLOperation) + tk.MustGetErrCode("alter table t add primary key(a) clustered;", errno.ErrUnsupportedDDLOperation) + tk.MustGetErrCode("alter table t add primary key(a) nonclustered;", mysql.ErrMultiplePriKey) + tk.MustGetErrCode("alter table t add primary key(a);", errno.ErrMultiplePriKey) // implicit nonclustered + tk.MustGetErrCode("alter table t add primary key(b) clustered;", errno.ErrUnsupportedDDLOperation) + tk.MustGetErrCode("alter table t add primary key(b) nonclustered;", errno.ErrMultiplePriKey) + tk.MustGetErrCode("alter table t add primary key(b);", errno.ErrMultiplePriKey) // implicit nonclustered + + // Test add/drop primary key on a nonclustered primary key table. + tk.MustExec("drop table if exists t;") + tk.MustExec("create table t (a int, b varchar(10), primary key(a) nonclustered);") + tk.MustGetErrCode("alter table t add primary key(a) clustered;", errno.ErrUnsupportedDDLOperation) + tk.MustGetErrCode("alter table t add primary key(a) nonclustered;", errno.ErrMultiplePriKey) + tk.MustGetErrCode("alter table t add primary key(a);", errno.ErrMultiplePriKey) // implicit nonclustered + tk.MustGetErrCode("alter table t add primary key(b) clustered;", errno.ErrUnsupportedDDLOperation) + tk.MustGetErrCode("alter table t add primary key(b) nonclustered;", errno.ErrMultiplePriKey) + tk.MustGetErrCode("alter table t add primary key(b);", errno.ErrMultiplePriKey) // implicit nonclustered + tk.MustExec("alter table t drop primary key;") + + // Test add/drop primary key on a CommonHandle key table. + tk.MustExec("drop table if exists t;") + tk.MustExec("create table t (a int, b varchar(10), primary key(b) clustered);") + tk.MustGetErrCode("alter table t drop primary key;", errno.ErrUnsupportedDDLOperation) + tk.MustGetErrCode("alter table t add primary key(a) clustered;", errno.ErrUnsupportedDDLOperation) + tk.MustGetErrCode("alter table t add primary key(a) nonclustered;", errno.ErrMultiplePriKey) + tk.MustGetErrCode("alter table t add primary key(a);", errno.ErrMultiplePriKey) // implicit nonclustered + tk.MustGetErrCode("alter table t add primary key(b) clustered;", errno.ErrUnsupportedDDLOperation) + tk.MustGetErrCode("alter table t add primary key(b) nonclustered;", errno.ErrMultiplePriKey) + tk.MustGetErrCode("alter table t add primary key(b);", errno.ErrMultiplePriKey) // implicit nonclustered + + // Test add/drop primary key when the column&index name is `primary`. + tk.MustExec("drop table if exists t;") + tk.MustExec("create table t (`primary` int);") + tk.MustExec("alter table t add index (`primary`);") + tk.MustGetErrCode("drop index `primary` on t;", errno.ErrCantDropFieldOrKey) // 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) + tk.MustGetErrCode("create table t(c1 int not null, primary key(c1) invisible);", errno.ErrPKIndexCantBeInvisible) + tk.MustExec("create table t (a int, b int not null, primary key(a), unique(b) invisible);") + tk.MustExec("drop table t;") } -func (s *testSerialSuite) TestDropAutoIncrementIndex(c *C) { +func (s *testIntegrationSuite9) TestDropAutoIncrementIndex(c *C) { tk := testkit.NewTestKit(c, s.store) tk.MustExec("use test") tk.MustExec("drop table if exists t1") @@ -192,7 +185,7 @@ func (s *testSerialSuite) TestDropAutoIncrementIndex(c *C) { tk.MustExec("alter table t1 drop index a") } -func (s *testSerialSuite) TestMultiRegionGetTableEndHandle(c *C) { +func (s *testIntegrationSuite9) 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") @@ -235,7 +228,7 @@ func (s *testSerialSuite) TestMultiRegionGetTableEndHandle(c *C) { c.Assert(maxHandle, Equals, kv.IntHandle(10000)) } -func (s *testSerialSuite) TestGetTableEndHandle(c *C) { +func (s *testIntegrationSuite9) 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") @@ -327,7 +320,7 @@ func (s *testSerialSuite) TestGetTableEndHandle(c *C) { c.Assert(emptyTable, IsFalse) } -func (s *testSerialSuite) TestMultiRegionGetTableEndCommonHandle(c *C) { +func (s *testIntegrationSuite9) 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") @@ -371,7 +364,7 @@ func (s *testSerialSuite) TestMultiRegionGetTableEndCommonHandle(c *C) { c.Assert(maxHandle, HandleEquals, MustNewCommonHandle(c, "a", 1, 1)) } -func (s *testSerialSuite) TestGetTableEndCommonHandle(c *C) { +func (s *testIntegrationSuite9) 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") @@ -987,9 +980,6 @@ func (s *testSerialSuite) TestAutoRandom(c *C) { 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") @@ -1006,16 +996,10 @@ func (s *testSerialSuite) TestAutoRandom(c *C) { assertPKIsNotHandle("create table t (a bigint auto_random(3), b bigint, primary key (a, b))", "a") assertPKIsNotHandle("create table t (a bigint auto_random(3), b int, c char, primary key (a, c))", "a") - // PKIsNotHandle: table is created when alter-primary-key = true. - config.UpdateGlobal(func(conf *config.Config) { - conf.AlterPrimaryKey = true - }) - assertPKIsNotHandle("create table t (a bigint auto_random(3) primary key, b int)", "a") - assertPKIsNotHandle("create table t (a bigint auto_random(3) primary key, b int)", "a") - assertPKIsNotHandle("create table t (a int, b bigint auto_random(3) primary key)", "b") - config.UpdateGlobal(func(conf *config.Config) { - conf.AlterPrimaryKey = false - }) + // PKIsNotHandle: nonclustered integer primary key. + assertPKIsNotHandle("create table t (a bigint auto_random(3) primary key nonclustered, b int)", "a") + assertPKIsNotHandle("create table t (a bigint auto_random(3) primary key nonclustered, b int)", "a") + assertPKIsNotHandle("create table t (a int, b bigint auto_random(3) primary key nonclustered)", "b") // Can not set auto_random along with auto_increment. assertWithAutoInc("create table t (a bigint auto_random(3) primary key auto_increment)") @@ -1158,14 +1142,11 @@ func (s *testSerialSuite) TestAutoRandom(c *C) { }) } -func (s *testSerialSuite) TestAutoRandomExchangePartition(c *C) { +func (s *testIntegrationSuite9) TestAutoRandomExchangePartition(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") - ConfigTestUtils.SetupAutoRandomTestConfig() - defer ConfigTestUtils.RestoreAutoRandomTestConfig() - tk.MustExec("use auto_random_db") tk.MustExec("set @@tidb_enable_exchange_partition=1") @@ -1173,7 +1154,7 @@ func (s *testSerialSuite) TestAutoRandomExchangePartition(c *C) { tk.MustExec("drop table if exists e1, e2, e3, e4;") - tk.MustExec("create table e1 (a bigint primary key auto_random(3)) partition by hash(a) partitions 1;") + tk.MustExec("create table e1 (a bigint primary key clustered auto_random(3)) partition by hash(a) partitions 1;") tk.MustExec("create table e2 (a bigint primary key);") tk.MustGetErrCode("alter table e1 exchange partition p0 with table e2;", errno.ErrTablesDifferentMetadata) @@ -1195,19 +1176,16 @@ func (s *testSerialSuite) TestAutoRandomExchangePartition(c *C) { tk.MustQuery("select count(*) from e4").Check(testkit.Rows("4")) } -func (s *testSerialSuite) TestAutoRandomIncBitsIncrementAndOffset(c *C) { +func (s *testIntegrationSuite9) TestAutoRandomIncBitsIncrementAndOffset(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") tk.MustExec("drop table if exists t") - ConfigTestUtils.SetupAutoRandomTestConfig() - defer ConfigTestUtils.RestoreAutoRandomTestConfig() - recreateTable := func() { tk.MustExec("drop table if exists t") - tk.MustExec("create table t (a bigint auto_random(6) primary key)") + tk.MustExec("create table t (a bigint auto_random(6) primary key clustered)") } truncateTable := func() { _, _ = tk.Exec("delete from t") @@ -1262,15 +1240,13 @@ func (s *testSerialSuite) TestAutoRandomWithPreSplitRegion(c *C) { tk.MustExec("use auto_random_db;") tk.MustExec("drop table if exists t;") - ConfigTestUtils.SetupAutoRandomTestConfig() - defer ConfigTestUtils.RestoreAutoRandomTestConfig() origin := atomic.LoadUint32(&ddl.EnableSplitTableRegion) atomic.StoreUint32(&ddl.EnableSplitTableRegion, 1) defer atomic.StoreUint32(&ddl.EnableSplitTableRegion, origin) tk.MustExec("set @@global.tidb_scatter_region=1;") // Test pre-split table region for auto_random table. - tk.MustExec("create table t (a bigint auto_random(2) primary key, b int) pre_split_regions=2;") + tk.MustExec("create table t (a bigint auto_random(2) primary key clustered, b int) pre_split_regions=2;") re := tk.MustQuery("show table t regions;") rows := re.Rows() c.Assert(len(rows), Equals, 4) @@ -1352,7 +1328,7 @@ func (s *testSerialSuite) TestForbidUnsupportedCollations(c *C) { // mustGetUnsupportedCollation("alter table t convert to collate utf8mb4_unicode_ci", "utf8mb4_unicode_ci") } -func (s *testSerialSuite) TestInvisibleIndex(c *C) { +func (s *testIntegrationSuite9) TestInvisibleIndex(c *C) { tk := testkit.NewTestKit(c, s.store) tk.MustExec("use test") @@ -1391,17 +1367,12 @@ func (s *testSerialSuite) TestInvisibleIndex(c *C) { tk.MustExec("insert into t values (11, 12)") tk.MustQuery("select * from t").Check(testkit.Rows("1 2", "3 4", "5 6", "7 8", "9 10", "11 12")) - defer config.RestoreFunc()() - config.UpdateGlobal(func(conf *config.Config) { - conf.AlterPrimaryKey = true - }) - // Limitation: Primary key cannot be invisible index - tk.MustGetErrCode("create table t1 (a int, primary key (a) invisible)", errno.ErrPKIndexCantBeInvisible) - tk.MustGetErrCode("create table t1 (a int, b int, primary key (a, b) invisible)", errno.ErrPKIndexCantBeInvisible) + tk.MustGetErrCode("create table t1 (a int, primary key (a) nonclustered invisible)", errno.ErrPKIndexCantBeInvisible) + tk.MustGetErrCode("create table t1 (a int, b int, primary key (a, b) nonclustered invisible)", errno.ErrPKIndexCantBeInvisible) tk.MustExec("create table t1 (a int, b int)") - tk.MustGetErrCode("alter table t1 add primary key(a) invisible", errno.ErrPKIndexCantBeInvisible) - tk.MustGetErrCode("alter table t1 add primary key(a, b) invisible", errno.ErrPKIndexCantBeInvisible) + tk.MustGetErrCode("alter table t1 add primary key(a) nonclustered invisible", errno.ErrPKIndexCantBeInvisible) + tk.MustGetErrCode("alter table t1 add primary key(a, b) nonclustered invisible", errno.ErrPKIndexCantBeInvisible) // Implicit primary key cannot be invisible index // Create a implicit primary key @@ -1423,7 +1394,7 @@ func (s *testSerialSuite) TestInvisibleIndex(c *C) { tk.MustGetErrCode("alter table t5 drop index a", errno.ErrPKIndexCantBeInvisible) tk.MustGetErrCode("alter table t5 modify column a int null", errno.ErrPKIndexCantBeInvisible) // If these is a explicit primary key, no key will become implicit primary key - tk.MustExec("create table t6 (a int not null, b int, unique (a) invisible, primary key(b))") + tk.MustExec("create table t6 (a int not null, b int, unique (a) invisible, primary key(b) nonclustered)") showIndexes = "select index_name, is_visible from information_schema.statistics where table_schema = 'test' and table_name = 't6'" tk.MustQuery(showIndexes).Check(testkit.Rows("a NO", "PRIMARY YES")) tk.MustExec("insert into t6 values (1, 2)") @@ -1433,7 +1404,7 @@ func (s *testSerialSuite) TestInvisibleIndex(c *C) { c.Check(len(res.Rows()), Equals, 1) } -func (s *testSerialSuite) TestCreateClusteredIndex(c *C) { +func (s *testIntegrationSuite9) TestCreateClusteredIndex(c *C) { tk := testkit.NewTestKitWithInit(c, s.store) tk.Se.GetSessionVars().EnableClusteredIndex = true tk.MustExec("CREATE TABLE t1 (a int primary key, b int)") @@ -1456,11 +1427,8 @@ func (s *testSerialSuite) TestCreateClusteredIndex(c *C) { c.Assert(err, IsNil) c.Assert(tbl.Meta().IsCommonHandle, IsFalse) - config.UpdateGlobal(func(conf *config.Config) { - conf.AlterPrimaryKey = true - }) - tk.MustExec("CREATE TABLE t5 (a varchar(255) primary key, b int)") - tk.MustExec("CREATE TABLE t6 (a int, b int, c int, primary key (a, b))") + tk.MustExec("CREATE TABLE t5 (a varchar(255) primary key nonclustered, b int)") + tk.MustExec("CREATE TABLE t6 (a int, b int, c int, primary key (a, b) nonclustered)") is = domain.GetDomain(ctx).InfoSchema() tbl, err = is.TableByName(model.NewCIStr("test"), model.NewCIStr("t5")) c.Assert(err, IsNil) @@ -1468,9 +1436,6 @@ func (s *testSerialSuite) TestCreateClusteredIndex(c *C) { tbl, err = is.TableByName(model.NewCIStr("test"), model.NewCIStr("t6")) c.Assert(err, IsNil) c.Assert(tbl.Meta().IsCommonHandle, IsFalse) - config.UpdateGlobal(func(conf *config.Config) { - conf.AlterPrimaryKey = false - }) tk.MustExec("CREATE TABLE t21 like t2") tk.MustExec("CREATE TABLE t31 like t3") diff --git a/executor/analyze_test.go b/executor/analyze_test.go index d535707738173..66b7e03f52549 100644 --- a/executor/analyze_test.go +++ b/executor/analyze_test.go @@ -731,7 +731,7 @@ func (s *testFastAnalyze) TestFastAnalyzeRetryRowCount(c *C) { c.Assert(row[5], Equals, "30") } -func (s *testSuite9) TestFailedAnalyzeRequest(c *C) { +func (s *testSuite10) TestFailedAnalyzeRequest(c *C) { tk := testkit.NewTestKit(c, s.store) tk.MustExec("use test") tk.MustExec("drop table if exists t") diff --git a/executor/ddl_test.go b/executor/ddl_test.go index bc848091998a9..5ea9171649c71 100644 --- a/executor/ddl_test.go +++ b/executor/ddl_test.go @@ -790,12 +790,17 @@ func (s *testSuite8) TestShardRowIDBits(c *C) { tk.MustExec("alter table auto shard_row_id_bits = 0") tk.MustExec("drop table auto") + errMsg := "[ddl:8200]Unsupported shard_row_id_bits for table with primary key as row id" + tk.MustGetErrMsg("create table auto (id varchar(255) primary key clustered, b int) shard_row_id_bits = 4;", errMsg) + tk.MustExec("create table auto (id varchar(255) primary key clustered, b int) shard_row_id_bits = 0;") + tk.MustGetErrMsg("alter table auto shard_row_id_bits = 5;", errMsg) + tk.MustExec("alter table auto shard_row_id_bits = 0;") + tk.MustExec("drop table if exists auto;") + // After PR 10759, shard_row_id_bits is not supported with pk_is_handle tables. - err = tk.ExecToErr("create table auto (id int not null auto_increment primary key, b int) shard_row_id_bits = 4") - c.Assert(err.Error(), Equals, "[ddl:8200]Unsupported shard_row_id_bits for table with primary key as row id") + tk.MustGetErrMsg("create table auto (id int not null auto_increment primary key, b int) shard_row_id_bits = 4", errMsg) tk.MustExec("create table auto (id int not null auto_increment primary key, b int) shard_row_id_bits = 0") - err = tk.ExecToErr("alter table auto shard_row_id_bits = 5") - c.Assert(err.Error(), Equals, "[ddl:8200]Unsupported shard_row_id_bits for table with primary key as row id") + tk.MustGetErrMsg("alter table auto shard_row_id_bits = 5", errMsg) tk.MustExec("alter table auto shard_row_id_bits = 0") // Hack an existing table with shard_row_id_bits and primary key as handle @@ -862,14 +867,6 @@ type testAutoRandomSuite struct { *baseTestSuite } -func (s *testAutoRandomSuite) SetUpTest(c *C) { - testutil.ConfigTestUtils.SetupAutoRandomTestConfig() -} - -func (s *testAutoRandomSuite) TearDownTest(c *C) { - testutil.ConfigTestUtils.RestoreAutoRandomTestConfig() -} - func (s *testAutoRandomSuite) TestAutoRandomBitsData(c *C) { tk := testkit.NewTestKit(c, s.store) @@ -886,7 +883,7 @@ func (s *testAutoRandomSuite) TestAutoRandomBitsData(c *C) { tk.MustExec("set @@allow_auto_random_explicit_insert = true") - tk.MustExec("create table t (a bigint primary key auto_random(15), b int)") + tk.MustExec("create table t (a bigint primary key clustered auto_random(15), b int)") for i := 0; i < 100; i++ { tk.MustExec("insert into t(b) values (?)", i) } @@ -902,7 +899,7 @@ func (s *testAutoRandomSuite) TestAutoRandomBitsData(c *C) { } c.Assert(allZero, IsFalse) // Test non-shard-bits part of auto random id is monotonic increasing and continuous. - orderedHandles := testutil.ConfigTestUtils.MaskSortHandles(allHandles, 15, mysql.TypeLonglong) + orderedHandles := testutil.MaskSortHandles(allHandles, 15, mysql.TypeLonglong) size := int64(len(allHandles)) for i := int64(1); i <= size; i++ { c.Assert(i, Equals, orderedHandles[i-1]) @@ -910,7 +907,7 @@ func (s *testAutoRandomSuite) TestAutoRandomBitsData(c *C) { // Test explicit insert. autoRandBitsUpperBound := 2<<47 - 1 - tk.MustExec("create table t (a bigint primary key auto_random(15), b int)") + tk.MustExec("create table t (a bigint primary key clustered auto_random(15), b int)") for i := -10; i < 10; i++ { tk.MustExec(fmt.Sprintf("insert into t values(%d, %d)", i+autoRandBitsUpperBound, i)) } @@ -944,7 +941,7 @@ func (s *testAutoRandomSuite) TestAutoRandomBitsData(c *C) { tk.MustExec("insert into t(a, b) values (?, ?)", -i, i) } // orderedHandles should be [-100, -99, ..., -2, -1, 1, 2, ..., 99, 100] - orderedHandles = testutil.ConfigTestUtils.MaskSortHandles(extractAllHandles(), 15, mysql.TypeLonglong) + orderedHandles = testutil.MaskSortHandles(extractAllHandles(), 15, mysql.TypeLonglong) size = int64(len(allHandles)) for i := int64(0); i < 100; i++ { c.Assert(orderedHandles[i], Equals, i-100) @@ -1015,7 +1012,7 @@ func (s *testAutoRandomSuite) TestAutoRandomTableOption(c *C) { c.Assert(err, IsNil) c.Assert(len(allHandles), Equals, 5) // Test non-shard-bits part of auto random id is monotonic increasing and continuous. - orderedHandles := testutil.ConfigTestUtils.MaskSortHandles(allHandles, 5, mysql.TypeLonglong) + orderedHandles := testutil.MaskSortHandles(allHandles, 5, mysql.TypeLonglong) size := int64(len(allHandles)) for i := int64(0); i < size; i++ { c.Assert(i+1000, Equals, orderedHandles[i]) @@ -1029,7 +1026,7 @@ func (s *testAutoRandomSuite) TestAutoRandomTableOption(c *C) { tk.MustExec("insert into alter_table_auto_random_option values(),(),(),(),()") allHandles, err = ddltestutil.ExtractAllTableHandles(tk.Se, "test", "alter_table_auto_random_option") c.Assert(err, IsNil) - orderedHandles = testutil.ConfigTestUtils.MaskSortHandles(allHandles, 5, mysql.TypeLonglong) + orderedHandles = testutil.MaskSortHandles(allHandles, 5, mysql.TypeLonglong) size = int64(len(allHandles)) for i := int64(0); i < size; i++ { c.Assert(orderedHandles[i], Equals, i+1) @@ -1047,7 +1044,7 @@ func (s *testAutoRandomSuite) TestAutoRandomTableOption(c *C) { tk.MustExec("insert into alter_table_auto_random_option values(),(),(),(),()") allHandles, err = ddltestutil.ExtractAllTableHandles(tk.Se, "test", "alter_table_auto_random_option") c.Assert(err, IsNil) - orderedHandles = testutil.ConfigTestUtils.MaskSortHandles(allHandles, 5, mysql.TypeLonglong) + orderedHandles = testutil.MaskSortHandles(allHandles, 5, mysql.TypeLonglong) size = int64(len(allHandles)) for i := int64(0); i < size; i++ { c.Assert(orderedHandles[i], Equals, i+3000000) @@ -1079,7 +1076,7 @@ func (s *testAutoRandomSuite) TestFilterDifferentAllocators(c *C) { allHandles, err := ddltestutil.ExtractAllTableHandles(tk.Se, "test", "t") c.Assert(err, IsNil) c.Assert(len(allHandles), Equals, 1) - orderedHandles := testutil.ConfigTestUtils.MaskSortHandles(allHandles, 5, mysql.TypeLonglong) + orderedHandles := testutil.MaskSortHandles(allHandles, 5, mysql.TypeLonglong) c.Assert(orderedHandles[0], Equals, int64(1)) tk.MustExec("delete from t") @@ -1090,7 +1087,7 @@ func (s *testAutoRandomSuite) TestFilterDifferentAllocators(c *C) { allHandles, err = ddltestutil.ExtractAllTableHandles(tk.Se, "test", "t") c.Assert(err, IsNil) c.Assert(len(allHandles), Equals, 1) - orderedHandles = testutil.ConfigTestUtils.MaskSortHandles(allHandles, 5, mysql.TypeLonglong) + orderedHandles = testutil.MaskSortHandles(allHandles, 5, mysql.TypeLonglong) c.Assert(orderedHandles[0], Equals, int64(2)) tk.MustExec("delete from t") @@ -1101,7 +1098,7 @@ func (s *testAutoRandomSuite) TestFilterDifferentAllocators(c *C) { allHandles, err = ddltestutil.ExtractAllTableHandles(tk.Se, "test", "t") c.Assert(err, IsNil) c.Assert(len(allHandles), Equals, 1) - orderedHandles = testutil.ConfigTestUtils.MaskSortHandles(allHandles, 5, mysql.TypeLonglong) + orderedHandles = testutil.MaskSortHandles(allHandles, 5, mysql.TypeLonglong) c.Assert(orderedHandles[0], Equals, int64(3000000)) tk.MustExec("delete from t") @@ -1115,7 +1112,7 @@ func (s *testAutoRandomSuite) TestFilterDifferentAllocators(c *C) { allHandles, err = ddltestutil.ExtractAllTableHandles(tk.Se, "test", "t1") c.Assert(err, IsNil) c.Assert(len(allHandles), Equals, 1) - orderedHandles = testutil.ConfigTestUtils.MaskSortHandles(allHandles, 5, mysql.TypeLonglong) + orderedHandles = testutil.MaskSortHandles(allHandles, 5, mysql.TypeLonglong) c.Assert(orderedHandles[0], Greater, int64(3000001)) } diff --git a/executor/infoschema_reader.go b/executor/infoschema_reader.go index 8d5f44c785ba2..4d9a5b19ec1ad 100644 --- a/executor/infoschema_reader.go +++ b/executor/infoschema_reader.go @@ -458,7 +458,7 @@ func (e *memtableRetriever) setDataFromTables(ctx sessionctx.Context, schemas [] if checker != nil && !checker.RequestVerification(ctx.GetSessionVars().ActiveRoles, schema.Name.L, table.Name.L, "", mysql.AllPrivMask) { continue } - pkType := "NON-CLUSTERED" + pkType := "NONCLUSTERED" if !table.IsView() { if table.GetPartitionInfo() != nil { createOptions = "partitioned" diff --git a/executor/infoschema_reader_test.go b/executor/infoschema_reader_test.go index 903d42a02df29..bb3497ac564a8 100644 --- a/executor/infoschema_reader_test.go +++ b/executor/infoschema_reader_test.go @@ -875,9 +875,9 @@ func (s *testInfoschemaTableSuite) TestTablesPKType(c *C) { tk.MustQuery("SELECT TIDB_PK_TYPE FROM information_schema.tables where table_schema = 'test' and table_name = 't_int'").Check(testkit.Rows("CLUSTERED")) tk.Se.GetSessionVars().EnableClusteredIndex = false tk.MustExec("create table t_implicit (a varchar(64) primary key, b int)") - tk.MustQuery("SELECT TIDB_PK_TYPE FROM information_schema.tables where table_schema = 'test' and table_name = 't_implicit'").Check(testkit.Rows("NON-CLUSTERED")) + tk.MustQuery("SELECT TIDB_PK_TYPE FROM information_schema.tables where table_schema = 'test' and table_name = 't_implicit'").Check(testkit.Rows("NONCLUSTERED")) tk.Se.GetSessionVars().EnableClusteredIndex = true tk.MustExec("create table t_common (a varchar(64) primary key, b int)") tk.MustQuery("SELECT TIDB_PK_TYPE FROM information_schema.tables where table_schema = 'test' and table_name = 't_common'").Check(testkit.Rows("CLUSTERED")) - tk.MustQuery("SELECT TIDB_PK_TYPE FROM information_schema.tables where table_schema = 'INFORMATION_SCHEMA' and table_name = 'TABLES'").Check(testkit.Rows("NON-CLUSTERED")) + tk.MustQuery("SELECT TIDB_PK_TYPE FROM information_schema.tables where table_schema = 'INFORMATION_SCHEMA' and table_name = 'TABLES'").Check(testkit.Rows("NONCLUSTERED")) } diff --git a/executor/insert_test.go b/executor/insert_test.go index 467e9e022c77e..891a74f495660 100644 --- a/executor/insert_test.go +++ b/executor/insert_test.go @@ -1126,20 +1126,17 @@ func (s *testSuite3) TestAutoIDIncrementAndOffset(c *C) { c.Assert(err.Error(), Equals, "[autoid:8060]Invalid auto_increment settings: auto_increment_increment: 65536, auto_increment_offset: 65536, both of them must be in range [1..65535]") } -var _ = SerialSuites(&testSuite9{&baseTestSuite{}}) +var _ = Suite(&testSuite9{&baseTestSuite{}}) type testSuite9 struct { *baseTestSuite } func (s *testSuite9) TestAutoRandomID(c *C) { - testutil.ConfigTestUtils.SetupAutoRandomTestConfig() - defer testutil.ConfigTestUtils.RestoreAutoRandomTestConfig() - tk := testkit.NewTestKit(c, s.store) tk.MustExec(`use test`) tk.MustExec(`drop table if exists ar`) - tk.MustExec(`create table ar (id bigint key auto_random, name char(10))`) + tk.MustExec(`create table ar (id bigint key clustered auto_random, name char(10))`) tk.MustExec(`insert into ar(id) values (null)`) rs := tk.MustQuery(`select id from ar`) @@ -1168,7 +1165,7 @@ func (s *testSuite9) TestAutoRandomID(c *C) { tk.MustQuery(`select last_insert_id()`).Check(testkit.Rows(fmt.Sprintf("%d", firstValue))) tk.MustExec(`drop table ar`) - tk.MustExec(`create table ar (id bigint key auto_random(15), name char(10))`) + tk.MustExec(`create table ar (id bigint key clustered auto_random(15), name char(10))`) overflowVal := 1 << (64 - 5) errMsg := fmt.Sprintf(autoid.AutoRandomRebaseOverflow, overflowVal, 1<<(64-16)-1) _, err = tk.Exec(fmt.Sprintf("alter table ar auto_random_base = %d", overflowVal)) @@ -1177,13 +1174,10 @@ func (s *testSuite9) TestAutoRandomID(c *C) { } func (s *testSuite9) TestMultiAutoRandomID(c *C) { - testutil.ConfigTestUtils.SetupAutoRandomTestConfig() - defer testutil.ConfigTestUtils.RestoreAutoRandomTestConfig() - tk := testkit.NewTestKit(c, s.store) tk.MustExec(`use test`) tk.MustExec(`drop table if exists ar`) - tk.MustExec(`create table ar (id bigint key auto_random, name char(10))`) + tk.MustExec(`create table ar (id bigint key clustered auto_random, name char(10))`) tk.MustExec(`insert into ar(id) values (null),(null),(null)`) rs := tk.MustQuery(`select id from ar order by id`) @@ -1221,13 +1215,10 @@ func (s *testSuite9) TestMultiAutoRandomID(c *C) { } func (s *testSuite9) TestAutoRandomIDAllowZero(c *C) { - testutil.ConfigTestUtils.SetupAutoRandomTestConfig() - defer testutil.ConfigTestUtils.RestoreAutoRandomTestConfig() - tk := testkit.NewTestKit(c, s.store) tk.MustExec(`use test`) tk.MustExec(`drop table if exists ar`) - tk.MustExec(`create table ar (id bigint key auto_random, name char(10))`) + tk.MustExec(`create table ar (id bigint key clustered auto_random, name char(10))`) rs := tk.MustQuery(`select @@session.sql_mode`) sqlMode := rs.Rows()[0][0].(string) @@ -1254,15 +1245,12 @@ func (s *testSuite9) TestAutoRandomIDAllowZero(c *C) { } func (s *testSuite9) TestAutoRandomIDExplicit(c *C) { - testutil.ConfigTestUtils.SetupAutoRandomTestConfig() - defer testutil.ConfigTestUtils.RestoreAutoRandomTestConfig() - tk := testkit.NewTestKit(c, s.store) tk.MustExec("set @@allow_auto_random_explicit_insert = true") tk.MustExec(`use test`) tk.MustExec(`drop table if exists ar`) - tk.MustExec(`create table ar (id bigint key auto_random, name char(10))`) + tk.MustExec(`create table ar (id bigint key clustered auto_random, name char(10))`) tk.MustExec(`insert into ar(id) values (1)`) tk.MustQuery(`select id from ar`).Check(testkit.Rows("1")) diff --git a/executor/join_test.go b/executor/join_test.go index 1edac17004362..76afe571f3d41 100644 --- a/executor/join_test.go +++ b/executor/join_test.go @@ -2292,7 +2292,7 @@ func (s *testSuiteJoin1) TestInvalidEnumVal(c *C) { rows.Check(testkit.Rows("a a", " ", " ", " ", " ")) } -func (s *testSuite9) TestIssue18572_1(c *C) { +func (s *testSuiteJoinSerial) TestIssue18572_1(c *C) { tk := testkit.NewTestKitWithInit(c, s.store) tk.MustExec("drop table if exists t1") tk.MustExec("create table t1(a int, b int, index idx(b));") @@ -2311,7 +2311,7 @@ func (s *testSuite9) TestIssue18572_1(c *C) { c.Assert(rs.Close(), IsNil) } -func (s *testSuite9) TestIssue18572_2(c *C) { +func (s *testSuiteJoinSerial) TestIssue18572_2(c *C) { tk := testkit.NewTestKitWithInit(c, s.store) tk.MustExec("drop table if exists t1") tk.MustExec("create table t1(a int, b int, index idx(b));") @@ -2330,7 +2330,7 @@ func (s *testSuite9) TestIssue18572_2(c *C) { c.Assert(rs.Close(), IsNil) } -func (s *testSuite9) TestIssue18572_3(c *C) { +func (s *testSuiteJoinSerial) TestIssue18572_3(c *C) { tk := testkit.NewTestKitWithInit(c, s.store) tk.MustExec("drop table if exists t1") tk.MustExec("create table t1(a int, b int, index idx(b));") diff --git a/executor/seqtest/seq_executor_test.go b/executor/seqtest/seq_executor_test.go index fa85f36adba38..46b04af26d131 100644 --- a/executor/seqtest/seq_executor_test.go +++ b/executor/seqtest/seq_executor_test.go @@ -848,12 +848,10 @@ func HelperTestAdminShowNextID(c *C, s *seqTestSuite, str string) { r.Check(testkit.Rows("test1 tt id 41 AUTO_INCREMENT")) tk.MustExec("drop table tt") - testutil.ConfigTestUtils.SetupAutoRandomTestConfig() - defer testutil.ConfigTestUtils.RestoreAutoRandomTestConfig() tk.MustExec("set @@allow_auto_random_explicit_insert = true") // Test for a table with auto_random primary key. - tk.MustExec("create table t3(id bigint primary key auto_random(5), c int)") + tk.MustExec("create table t3(id bigint primary key clustered auto_random(5), c int)") // Start handle is 1. r = tk.MustQuery(str + " t3 next_row_id") r.Check(testkit.Rows("test1 t3 id 1 AUTO_RANDOM")) @@ -1381,17 +1379,15 @@ func (s *seqTestSuite) TestInsertFromSelectConflictRetryAutoID(c *C) { func (s *seqTestSuite) TestAutoRandIDRetry(c *C) { tk := testkit.NewTestKitWithInit(c, s.store) - testutil.ConfigTestUtils.SetupAutoRandomTestConfig() - defer testutil.ConfigTestUtils.RestoreAutoRandomTestConfig() tk.MustExec("create database if not exists auto_random_retry") tk.MustExec("use auto_random_retry") tk.MustExec("drop table if exists t") - tk.MustExec("create table t (id bigint auto_random(3) primary key)") + tk.MustExec("create table t (id bigint auto_random(3) primary key clustered)") extractMaskedOrderedHandles := func() []int64 { handles, err := ddltestutil.ExtractAllTableHandles(tk.Se, "auto_random_retry", "t") c.Assert(err, IsNil) - return testutil.ConfigTestUtils.MaskSortHandles(handles, 3, mysql.TypeLong) + return testutil.MaskSortHandles(handles, 3, mysql.TypeLong) } tk.MustExec("set @@tidb_disable_txn_auto_retry = 0") @@ -1425,8 +1421,6 @@ func (s *seqTestSuite) TestAutoRandIDRetry(c *C) { func (s *seqTestSuite) TestAutoRandRecoverTable(c *C) { tk := testkit.NewTestKit(c, s.store) - testutil.ConfigTestUtils.SetupAutoRandomTestConfig() - defer testutil.ConfigTestUtils.RestoreAutoRandomTestConfig() tk.MustExec("create database if not exists test_recover") tk.MustExec("use test_recover") tk.MustExec("drop table if exists t_recover_auto_rand") @@ -1462,14 +1456,14 @@ func (s *seqTestSuite) TestAutoRandRecoverTable(c *C) { defer autoid.SetStep(stp) // Check rebase auto_random id. - tk.MustExec("create table t_recover_auto_rand (a bigint auto_random(5) primary key);") + tk.MustExec("create table t_recover_auto_rand (a bigint auto_random(5) primary key clustered);") tk.MustExec("insert into t_recover_auto_rand values (),(),()") tk.MustExec("drop table t_recover_auto_rand") tk.MustExec("recover table t_recover_auto_rand") tk.MustExec("insert into t_recover_auto_rand values (),(),()") hs, err := ddltestutil.ExtractAllTableHandles(tk.Se, "test_recover", "t_recover_auto_rand") c.Assert(err, IsNil) - ordered := testutil.ConfigTestUtils.MaskSortHandles(hs, 5, mysql.TypeLong) + ordered := testutil.MaskSortHandles(hs, 5, mysql.TypeLong) c.Assert(ordered, DeepEquals, []int64{1, 2, 3, autoRandIDStep + 1, autoRandIDStep + 2, autoRandIDStep + 3}) } diff --git a/executor/show_test.go b/executor/show_test.go index 600c47c7c0586..61ec2e5bd1ec1 100644 --- a/executor/show_test.go +++ b/executor/show_test.go @@ -1025,16 +1025,14 @@ func (s *testAutoRandomSuite) TestAutoRandomBase(c *C) { )) } -func (s *testSerialSuite) TestAutoRandomWithLargeSignedShowTableRegions(c *C) { +func (s *testSuite5) TestAutoRandomWithLargeSignedShowTableRegions(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;") tk.MustExec("drop table if exists t;") - testutil.ConfigTestUtils.SetupAutoRandomTestConfig() - defer testutil.ConfigTestUtils.RestoreAutoRandomTestConfig() - tk.MustExec("create table t (a bigint unsigned auto_random primary key);") + tk.MustExec("create table t (a bigint unsigned auto_random primary key clustered);") tk.MustExec("set @@global.tidb_scatter_region=1;") // 18446744073709541615 is MaxUint64 - 10000. // 18446744073709551615 is the MaxUint64. diff --git a/expression/integration_test.go b/expression/integration_test.go index f16efa2c1095e..ad22742a891ad 100644 --- a/expression/integration_test.go +++ b/expression/integration_test.go @@ -7946,7 +7946,7 @@ func (s *testIntegrationSerialSuite) TestClusteredIndexAndNewCollationIndexEncod tk := testkit.NewTestKit(c, s.store) tk.MustExec("use test") tk.MustExec("drop table if exists t") - tk.MustExec("set @@tidb_enable_clustered_index=1;") + tk.Se.GetSessionVars().EnableClusteredIndex = true tk.MustExec("create table t(a int, b char(10) collate utf8mb4_bin, c char(10) collate utf8mb4_general_ci," + "d varchar(10) collate utf8mb4_bin, e varchar(10) collate utf8mb4_general_ci, f char(10) collate utf8mb4_unicode_ci, g varchar(10) collate utf8mb4_unicode_ci, " + "primary key(a, b, c, d, e, f, g), key a(a), unique key ua(a), key b(b), unique key ub(b), key c(c), unique key uc(c)," + @@ -8919,9 +8919,8 @@ func (s *testIntegrationSuite) TestClusteredIndexCorCol(c *C) { // For issue 23076 tk := testkit.NewTestKit(c, s.store) tk.MustExec("use test") - tk.MustExec("set @@tidb_enable_clustered_index=1;") tk.MustExec("drop table if exists t1, t2;") - tk.MustExec("create table t1 (c_int int, c_str varchar(40), primary key (c_int, c_str) , key(c_int) );") + tk.MustExec("create table t1 (c_int int, c_str varchar(40), primary key (c_int, c_str) clustered, key(c_int) );") tk.MustExec("create table t2 like t1 ;") tk.MustExec("insert into t1 values (1, 'crazy lumiere'), (10, 'goofy mestorf');") tk.MustExec("insert into t2 select * from t1 ;") diff --git a/infoschema/tables_test.go b/infoschema/tables_test.go index a952eff93db66..3858aece8d96b 100644 --- a/infoschema/tables_test.go +++ b/infoschema/tables_test.go @@ -641,13 +641,10 @@ func (s *testTableSuite) TestTableRowIDShardingInfo(c *C) { testFunc("performance_schema", nil) testFunc("uucc", "NOT_SHARDED") - testutil.ConfigTestUtils.SetupAutoRandomTestConfig() - defer testutil.ConfigTestUtils.RestoreAutoRandomTestConfig() - - tk.MustExec("CREATE TABLE `sharding_info_test_db`.`t4` (a bigint key auto_random)") + tk.MustExec("CREATE TABLE `sharding_info_test_db`.`t4` (a bigint key clustered auto_random)") assertShardingInfo("t4", "PK_AUTO_RANDOM_BITS=5") - tk.MustExec("CREATE TABLE `sharding_info_test_db`.`t5` (a bigint key auto_random(1))") + tk.MustExec("CREATE TABLE `sharding_info_test_db`.`t5` (a bigint key clustered auto_random(1))") assertShardingInfo("t5", "PK_AUTO_RANDOM_BITS=1") tk.MustExec("DROP DATABASE `sharding_info_test_db`") diff --git a/meta/autoid/errors.go b/meta/autoid/errors.go index ad0b1bcf5d12b..dbc279c0641a2 100644 --- a/meta/autoid/errors.go +++ b/meta/autoid/errors.go @@ -29,8 +29,8 @@ var ( ) const ( - // AutoRandomPKisNotHandleErrMsg indicates the auto_random column attribute is defined on a non-primary key column, or the table's primary key is not a single integer column. - AutoRandomPKisNotHandleErrMsg = "column %s is not the integer primary key, or table is created with alter-primary-key enabled" + // AutoRandomPKisNotHandleErrMsg indicates the auto_random column attribute is defined on a non-primary key column, or the primary key is nonclustered. + AutoRandomPKisNotHandleErrMsg = "column %s is not the integer primary key, or the primary key is nonclustered" // AutoRandomIncompatibleWithAutoIncErrMsg is reported when auto_random and auto_increment are specified on the same column. AutoRandomIncompatibleWithAutoIncErrMsg = "auto_random is incompatible with auto_increment" // AutoRandomIncompatibleWithDefaultValueErrMsg is reported when auto_random and default are specified on the same column. diff --git a/session/clustered_index_test.go b/session/clustered_index_test.go index 7e0479e22cce7..f9336b9f4991b 100644 --- a/session/clustered_index_test.go +++ b/session/clustered_index_test.go @@ -15,7 +15,6 @@ package session_test import ( . "github.com/pingcap/check" - "github.com/pingcap/tidb/config" "github.com/pingcap/tidb/errno" "github.com/pingcap/tidb/store/tikv" "github.com/pingcap/tidb/util/collate" @@ -417,44 +416,52 @@ func (s *testClusteredSuite) TestClusteredIndexSelectWhereInNull(c *C) { tk.MustQuery("select * from t where a in (null);").Check(testkit.Rows( /* empty result */ )) } -func (s *testClusteredSerialSuite) TestClusteredIndexSyntax(c *C) { +func (s *testClusteredSuite) TestClusteredIndexSyntax(c *C) { tk := testkit.NewTestKitWithInit(c, s.store) const showPKType = `select tidb_pk_type from information_schema.tables where table_schema = 'test' and table_name = 't';` - const nonClustered, clustered = `NON-CLUSTERED`, `CLUSTERED` + const nonClustered, clustered = `NONCLUSTERED`, `CLUSTERED` assertPkType := func(sql string, pkType string) { tk.MustExec("drop table if exists t;") tk.MustExec(sql) tk.MustQuery(showPKType).Check(testkit.Rows(pkType)) } - defer config.RestoreFunc()() - for _, allowAlterPK := range []bool{true, false} { - config.UpdateGlobal(func(conf *config.Config) { - conf.AlterPrimaryKey = allowAlterPK - }) - // Test single integer column as the primary key. - clusteredDefault := clustered - if allowAlterPK { - clusteredDefault = nonClustered - } - assertPkType("create table t (a int primary key, b int);", clusteredDefault) - assertPkType("create table t (a int, b int, primary key(a) clustered);", clustered) - assertPkType("create table t (a int, b int, primary key(a) /*T![clustered_index] clustered */);", clustered) - assertPkType("create table t (a int, b int, primary key(a) nonclustered);", nonClustered) - assertPkType("create table t (a int, b int, primary key(a) /*T![clustered_index] nonclustered */);", nonClustered) - - // Test for clustered index. - tk.Se.GetSessionVars().EnableClusteredIndex = false - assertPkType("create table t (a int, b varchar(255), primary key(b, a));", nonClustered) - assertPkType("create table t (a int, b varchar(255), primary key(b, a) nonclustered);", nonClustered) - assertPkType("create table t (a int, b varchar(255), primary key(b, a) clustered);", clustered) - tk.Se.GetSessionVars().EnableClusteredIndex = true - assertPkType("create table t (a int, b varchar(255), primary key(b, a));", clusteredDefault) - assertPkType("create table t (a int, b varchar(255), primary key(b, a) nonclustered);", nonClustered) - assertPkType("create table t (a int, b varchar(255), primary key(b, a) /*T![clustered_index] nonclustered */);", nonClustered) - assertPkType("create table t (a int, b varchar(255), primary key(b, a) clustered);", clustered) - assertPkType("create table t (a int, b varchar(255), primary key(b, a) /*T![clustered_index] clustered */);", clustered) - } + // Test single integer column as the primary key. + clusteredDefault := clustered + assertPkType("create table t (a int primary key, b int);", clusteredDefault) + assertPkType("create table t (a int, b int, primary key(a) clustered);", clustered) + assertPkType("create table t (a int, b int, primary key(a) /*T![clustered_index] clustered */);", clustered) + assertPkType("create table t (a int, b int, primary key(a) nonclustered);", nonClustered) + assertPkType("create table t (a int, b int, primary key(a) /*T![clustered_index] nonclustered */);", nonClustered) + + // Test for clustered index. + tk.Se.GetSessionVars().EnableClusteredIndex = false + assertPkType("create table t (a int, b varchar(255), primary key(b, a));", nonClustered) + assertPkType("create table t (a int, b varchar(255), primary key(b, a) nonclustered);", nonClustered) + assertPkType("create table t (a int, b varchar(255), primary key(b, a) clustered);", clustered) + tk.Se.GetSessionVars().EnableClusteredIndex = true + assertPkType("create table t (a int, b varchar(255), primary key(b, a));", clusteredDefault) + assertPkType("create table t (a int, b varchar(255), primary key(b, a) nonclustered);", nonClustered) + assertPkType("create table t (a int, b varchar(255), primary key(b, a) /*T![clustered_index] nonclustered */);", nonClustered) + assertPkType("create table t (a int, b varchar(255), primary key(b, a) clustered);", clustered) + assertPkType("create table t (a int, b varchar(255), primary key(b, a) /*T![clustered_index] clustered */);", clustered) + + tk.MustGetErrCode("create table t (a varchar(255) unique key clustered);", errno.ErrParse) + tk.MustGetErrCode("create table t (a varchar(255), foreign key (a) reference t1(a) clustered);", errno.ErrParse) + tk.MustGetErrCode("create table t (a varchar(255), foreign key (a) clustered reference t1(a));", errno.ErrParse) + tk.MustGetErrCode("create table t (a varchar(255) clustered);", errno.ErrParse) + + errMsg := "[ddl:8200]CLUSTERED/NONCLUSTERED keyword is only supported for primary key" + tk.MustGetErrMsg("create table t (a varchar(255), unique key(a) clustered);", errMsg) + tk.MustGetErrMsg("create table t (a varchar(255), unique key(a) nonclustered);", errMsg) + tk.MustGetErrMsg("create table t (a varchar(255), unique index(a) clustered);", errMsg) + tk.MustGetErrMsg("create table t (a varchar(255), unique index(a) nonclustered);", errMsg) + tk.MustGetErrMsg("create table t (a varchar(255), key(a) clustered);", errMsg) + tk.MustGetErrMsg("create table t (a varchar(255), key(a) nonclustered);", errMsg) + tk.MustGetErrMsg("create table t (a varchar(255), index(a) clustered);", errMsg) + tk.MustGetErrMsg("create table t (a varchar(255), index(a) nonclustered);", errMsg) + tk.MustGetErrMsg("create table t (a varchar(255), b decimal(5, 4), primary key (a, b) clustered, key (b) clustered)", errMsg) + tk.MustGetErrMsg("create table t (a varchar(255), b decimal(5, 4), primary key (a, b) clustered, key (b) nonclustered)", errMsg) } func (s *testClusteredSerialSuite) TestPrefixClusteredIndexAddIndexAndRecover(c *C) { @@ -478,10 +485,6 @@ func (s *testClusteredSerialSuite) TestPrefixClusteredIndexAddIndexAndRecover(c // https://github.com/pingcap/tidb/issues/23106 func (s *testClusteredSerialSuite) TestClusteredIndexDecodeRestoredDataV5(c *C) { tk := testkit.NewTestKitWithInit(c, s.store) - defer config.RestoreFunc()() - config.UpdateGlobal(func(conf *config.Config) { - conf.AlterPrimaryKey = false - }) defer collate.SetNewCollationEnabledForTest(false) collate.SetNewCollationEnabledForTest(true) tk.MustExec("use test") @@ -506,10 +509,6 @@ func (s *testClusteredSerialSuite) TestPrefixedClusteredIndexUniqueKeyWithNewCol defer collate.SetNewCollationEnabledForTest(false) collate.SetNewCollationEnabledForTest(true) tk := testkit.NewTestKitWithInit(c, s.store) - defer config.RestoreFunc()() - config.UpdateGlobal(func(conf *config.Config) { - conf.AlterPrimaryKey = false - }) tk.MustExec("use test;") tk.Se.GetSessionVars().EnableClusteredIndex = true tk.MustExec("create table t (a text collate utf8mb4_general_ci not null, b int(11) not null, " + diff --git a/sessionctx/binloginfo/binloginfo_test.go b/sessionctx/binloginfo/binloginfo_test.go index a6bb7a758a5e7..03a003543ada6 100644 --- a/sessionctx/binloginfo/binloginfo_test.go +++ b/sessionctx/binloginfo/binloginfo_test.go @@ -268,14 +268,15 @@ func (s *testBinlogSuite) TestBinlog(c *C) { binlog.MutationType_Insert, }) - // Test cannot build clustered index tables when binlog client exists. - tk.MustExec("create table local_clustered_index (c1 varchar(255) primary key clustered);") - warnMsg := "Warning 1105 cannot build clustered index table because the binlog is ON" - tk.MustQuery("show warnings;").Check(testkit.Rows(warnMsg)) + // Cannot create common clustered index table when binlog client exists. + errMsg := "[ddl:8200]Cannot create clustered index table when the binlog is ON" + tk.MustGetErrMsg("create table local_clustered_index (c1 varchar(255) primary key clustered);", errMsg) + // Create int clustered index table when binlog client exists. + tk.MustExec("create table local_clustered_index (c1 bigint primary key clustered);") tk.MustQuery("select tidb_pk_type from information_schema.tables where table_name = 'local_clustered_index' and table_schema = 'test';"). - Check(testkit.Rows("NON-CLUSTERED")) + Check(testkit.Rows("CLUSTERED")) tk.MustExec("drop table if exists local_clustered_index;") - // Test clustered index tables will not write binlog. + // Test common clustered index tables will not write binlog. tk.Se.GetSessionVars().BinlogClient = nil tk.MustExec("create table local_clustered_index (c1 varchar(255) primary key clustered);") tk.MustQuery("select tidb_pk_type from information_schema.tables where table_name = 'local_clustered_index' and table_schema = 'test';"). diff --git a/sessionctx/variable/sysvar.go b/sessionctx/variable/sysvar.go index 4c0957adb7558..0a7c4fbb02c79 100644 --- a/sessionctx/variable/sysvar.go +++ b/sessionctx/variable/sysvar.go @@ -768,7 +768,7 @@ var defaultSysVars = []*SysVar{ {Scope: ScopeSession, Name: TiDBFoundInBinding, Value: BoolToOnOff(DefTiDBFoundInBinding), Type: TypeBool, ReadOnly: true}, {Scope: ScopeSession, Name: TiDBEnableCollectExecutionInfo, Value: BoolToOnOff(DefTiDBEnableCollectExecutionInfo), Type: TypeBool}, {Scope: ScopeGlobal | ScopeSession, Name: TiDBAllowAutoRandExplicitInsert, Value: BoolToOnOff(DefTiDBAllowAutoRandExplicitInsert), Type: TypeBool}, - {Scope: ScopeGlobal | ScopeSession, Name: TiDBEnableClusteredIndex, Value: BoolToOnOff(DefTiDBEnableClusteredIndex), Type: TypeBool}, + {Scope: ScopeGlobal, Name: TiDBEnableClusteredIndex, Value: BoolToOnOff(DefTiDBEnableClusteredIndex), Type: TypeBool}, {Scope: ScopeGlobal | ScopeSession, Name: TiDBPartitionPruneMode, Value: string(Static), Type: TypeStr, Validation: func(vars *SessionVars, normalizedValue string, originalValue string, scope ScopeFlag) (string, error) { mode := PartitionPruneMode(normalizedValue).Update() if !mode.Valid() { diff --git a/statistics/selectivity_test.go b/statistics/selectivity_test.go index d5aca3cf8a6e0..f371d2189b0b7 100644 --- a/statistics/selectivity_test.go +++ b/statistics/selectivity_test.go @@ -607,14 +607,13 @@ func (s *testStatsSuite) TestStatsVer2(c *C) { testKit.MustExec("analyze table tprefix with 2 topn, 3 buckets") // test with clustered index - testKit.MustExec("set @@tidb_enable_clustered_index = 1") testKit.MustExec("drop table if exists ct1") - testKit.MustExec("create table ct1 (a int, pk varchar(10), primary key(pk))") + testKit.MustExec("create table ct1 (a int, pk varchar(10), primary key(pk) clustered)") testKit.MustExec("insert into ct1 values (1, '1'), (2, '2'), (3, '3'), (4, '4'), (5, '5'), (6, '6'), (7, '7'), (8, '8')") testKit.MustExec("analyze table ct1 with 2 topn, 3 buckets") testKit.MustExec("drop table if exists ct2") - testKit.MustExec("create table ct2 (a int, b int, c int, primary key(a, b))") + testKit.MustExec("create table ct2 (a int, b int, c int, primary key(a, b) clustered)") testKit.MustExec("insert into ct2 values (1, 1, 1), (2, 2, 2), (3, 3, 3), (4, 4, 4), (5, 5, 5), (6, 6, 6), (7, 7, 7), (8, 8, 8)") testKit.MustExec("analyze table ct2 with 2 topn, 3 buckets") diff --git a/util/testutil/testutil.go b/util/testutil/testutil.go index eb2c9ad565282..d1ecd061a5624 100644 --- a/util/testutil/testutil.go +++ b/util/testutil/testutil.go @@ -32,7 +32,6 @@ import ( "github.com/pingcap/check" "github.com/pingcap/errors" "github.com/pingcap/parser/mysql" - "github.com/pingcap/tidb/config" "github.com/pingcap/tidb/kv" "github.com/pingcap/tidb/sessionctx/stmtctx" "github.com/pingcap/tidb/types" @@ -409,34 +408,8 @@ func (t *TestData) GenerateOutputIfNeeded() error { return err } -// ConfigTestUtils contains a set of set-up/restore methods related to config used in tests. -var ConfigTestUtils configTestUtils - -type configTestUtils struct { - autoRandom -} - -type autoRandom struct { - originAlterPrimaryKey bool -} - -// SetupAutoRandomTestConfig set alter-primary-key to false and save its origin values. -// This method should only be used for the tests in SerialSuite. -func (a *autoRandom) SetupAutoRandomTestConfig() { - globalCfg := config.GetGlobalConfig() - a.originAlterPrimaryKey = globalCfg.AlterPrimaryKey - globalCfg.AlterPrimaryKey = false -} - -// RestoreAutoRandomTestConfig restore the values had been saved in SetupTestConfig. -// This method should only be used for the tests in SerialSuite. -func (a *autoRandom) RestoreAutoRandomTestConfig() { - globalCfg := config.GetGlobalConfig() - globalCfg.AlterPrimaryKey = a.originAlterPrimaryKey -} - // MaskSortHandles sorts the handles by lowest (fieldTypeBits - 1 - shardBitsCount) bits. -func (a *autoRandom) MaskSortHandles(handles []int64, shardBitsCount int, fieldType byte) []int64 { +func MaskSortHandles(handles []int64, shardBitsCount int, fieldType byte) []int64 { typeBitsLength := mysql.DefaultLengthOfMysqlTypes[fieldType] * 8 const signBitCount = 1 shiftBitsCount := 64 - typeBitsLength + shardBitsCount + signBitCount