mysql で duplicate な error を防ぐために insert ignore はしないほうがいいのかなぁと思った
insert した際に unique key とか primary key で duplicate な場合に error が起きるのを防ぐために(無視して良いとうい仕様の場合に) insert ignore ...
すると良いみたいな記事があったりするけれども、実際どうなのかなぁと思って調べた。
If you use the IGNORE keyword, errors that occur while executing the INSERT statement are ignored. For example, without IGNORE, a row that duplicates an existing UNIQUE index or PRIMARY KEY value in the table causes a duplicate-key error and the statement is aborted. With IGNORE, the row still is not inserted, but no error occurs. Ignored errors may generate warnings instead, although duplicate-key errors do not.
https://dev.mysql.com/doc/refman/5.5/en/insert.html
これを読むと duplicate とか以外の error も ignore しちゃいそうな気がして、例えば set sql_mode='TRADITIONAL'
として int 型のものに "hoge" などを指定して insert
しようとすると
Incorrect integer value: 'hoge' for column 'foo' ...
のような error が起きるけど insert ignore
の場合は怒られない。show warnings
すると出てくる。つまり、duplicate だけ無視するつもりが、他のものまで無視してしまう可能性がありそう。
なので、duplicate を許可したい場合はこういう感じで
try { $dbh->do("insert ........"); } catch { die $_ unless duplicate error; };
みたいにちゃんとエラーの内容を見てあげるほうがいいのかなと思った。あと insert ignore した場合で duplicate な error の場合は show warnings にも出ない仕様となってるのだった。