Index "PRIMARY_KEY_B" belongs to a constraint
エラーの概要
H2で、あるテーブルのプライマリーキーを削除しようとした時に以下のようなエラーメッセージが発生("PRIMARY_KEY_A5"の部分はそのテーブルのプライマリーキーの名前で、通常は自動採番)。
Index "PRIMARY_KEY_A5" belongs to a constraint; SQL statement: alter table t2 drop primary key [90085-169] 90085/90085
削除しようとしているプライマリーキーの対象カラムが、別のテーブルの外部キーになっている場合に発生。
再現方法
create table t1 ( id integer, primary key (id) ); create table t2 ( id integer, primary key (id) ); create table t3 ( t1_id integer, t2_id integer, constraint t3_pkey primary key (t1_id, t2_id), constraint t3_t1_id_fkey foreign key (t1_id) references t1(id), constraint t3_t2_id_fkey foreign key (t2_id) references t2(id) );
この後、以下のSQLを発行するとエラー
alter table t3 drop primary key;
t3のプライマリーキーを削除しても、別に外部キーの整合性を壊すことにはならないから、エラーにしなくてもいい気がするけど。
解決方法
先に外部キーを削除してからプライマリーキーを削除。その後、外部キーは付け直し。
alter table t3 drop constraint t3_t1_id_fkey; alter table t3 drop constraint t3_t2_id_fkey; alter table t3 drop primary key; alter table t3 add constraint t3_t1_id_fkey foreign key (t1_id) references t1(id); alter table t3 add constraint t3_t2_id_fkey foreign key (t2_id) references t2(id);
参考URL