LoginSignup
7
9

More than 5 years have passed since last update.

MySQLのトランザクションでハマったんだが

Last updated at Posted at 2014-09-11

MySQLのトランザクションについて、購入処理の調査をしていてハマったので記録。

トランザクション絡みでこんなコードがありました。

start_transaction

  insert_into_member #1

  start_transaction
    insert_into_coupon #2
  commit

  insert_into_order #3

if error?
  rollback
else
  commit
end

いざ、エラーを起こしてrollbackの検証をしたところ。
#2だけコミットされて、他はrollbackされることを期待したんですが、

全部commitされてる…。

なんでやー、と思って調べていったところ。
start transactionすると、自動的にコミットされるんですね。下記参照。

▼ 暗黙的なコミットを引き起こすステートメント
http://dev.mysql.com/doc/refman/4.1/ja/implicit-commit.html

最初の start transaction は、2回目のstart transaction 実行時にコミットされ、以後は普通にクエリを流してるのと変わらなくなっていました。

トランザクションの中にトランザクションは入れないように、と肝に銘じた一件です。

おそらく、最初に作ったときは問題なかったんでしょうが、
後から別メソッドを組み込んだところ、そちらの内側でトランザクションを利用していた、というトラップ。
勉強になりました。

7
9
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
7
9