diff --git a/mysql-test/r/alter_table.result b/mysql-test/r/alter_table.result index 5df0c2e3c96..e572fdb197c 100644 --- a/mysql-test/r/alter_table.result +++ b/mysql-test/r/alter_table.result @@ -2012,3 +2012,12 @@ t1 CREATE TABLE `t1` ( UNIQUE KEY `idx` (`i`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 DROP TABLE t1; +CREATE TABLE t1 ( +`event_id` bigint(20) unsigned NOT NULL DEFAULT '0', +`market_id` bigint(20) unsigned NOT NULL DEFAULT '0', +PRIMARY KEY (`event_id`,`market_id`) +); +ALTER TABLE t1 ADD PRIMARY KEY IF NOT EXISTS event_id (event_id,market_id); +Warnings: +Note 1061 Multiple primary key defined +DROP TABLE t1; diff --git a/mysql-test/t/alter_table.test b/mysql-test/t/alter_table.test index 4dde3ed6971..05d915ec478 100644 --- a/mysql-test/t/alter_table.test +++ b/mysql-test/t/alter_table.test @@ -1699,3 +1699,16 @@ alter table t1 add unique index if not exists idx(i); alter table t1 add unique index if not exists idx(i); show create table t1; DROP TABLE t1; + +# +# MDEV-8358 ADD PRIMARY KEY IF NOT EXISTS -> ERROR 1068 (42000): Multiple primary key +# + +CREATE TABLE t1 ( + `event_id` bigint(20) unsigned NOT NULL DEFAULT '0', + `market_id` bigint(20) unsigned NOT NULL DEFAULT '0', + PRIMARY KEY (`event_id`,`market_id`) + ); +ALTER TABLE t1 ADD PRIMARY KEY IF NOT EXISTS event_id (event_id,market_id); +DROP TABLE t1; + diff --git a/sql/sql_table.cc b/sql/sql_table.cc index 5ad4ceb9c35..e0f7184b0e8 100644 --- a/sql/sql_table.cc +++ b/sql/sql_table.cc @@ -5846,6 +5846,16 @@ drop_create_field: { if (!key->create_if_not_exists) continue; + + /* Check if the table already has a PRIMARY KEY */ + if (key->type == Key::PRIMARY && + table->s->primary_key != MAX_KEY) + { + push_warning_printf(thd, Sql_condition::WARN_LEVEL_NOTE, + ER_DUP_KEYNAME, ER(ER_MULTIPLE_PRI_KEY)); + goto remove_key_no_warn; + } + /* If the name of the key is not specified, */ /* let us check the name of the first key part. */ if ((keyname= key->name.str) == NULL) @@ -5912,6 +5922,7 @@ drop_create_field: remove_key: push_warning_printf(thd, Sql_condition::WARN_LEVEL_NOTE, ER_DUP_KEYNAME, ER(ER_DUP_KEYNAME), keyname); +remove_key_no_warn: key_it.remove(); if (key->type == Key::FOREIGN_KEY) {