2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

MySQLでDROP DATABASEしたらデッドロック

Posted at

スクリプトでデータベースを自動生成するシステムで、CREATE DATABASEはトランザクションが効かないクエリなので例外でrollbackする時自力でrollbackします。その時、防御的措置として、メインのテーブルにレコードが無いものだけを削除できるように以下のように実装しました。

public function dropDatabase()
{
  $db = $this->getConnection();
  $rec = $db->fetchOne('SELECT id FROM item LIMIT 1');
  if($rec)
  {
  	throw new Sdx_Exception("You can't drop database having any item record.");
  }
  
  $rootdb = Fc_Db::getRootConnection();
  $rootdb->query(sprintf('DROP DATABASE %s', $this->getDatabaseName()));
}

するとデッドロックが発生。SHOW PROCESSLISTで確認すると

Waiting for table metadata lock

とのこと。connectしたDBをそのままドロップすると発生するらしい。

  //接続を閉じないとデッドロック
  $db->closeConnection();
  
  $rootdb = Fc_Db::getRootConnection();
  $rootdb->query(sprintf('DROP DATABASE %s', $this->getDatabaseName()));
}

明示的にconnectを切れば発生しません。MySQL5.5/Autocomit OFFで試しました。

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?