🖥

#Rails + #MySQL で INSERT による transaction & Rollback を利用しての排他制御を試してみるが、

2019/12/26に公開

Console A

Start transaction
Insert to DB
Sleep some seconds

[6] pry(main)> SomeModel.transaction { SomeModel.create(unique_string: 'some unique key'); sleep 10 }
   (0.7ms)  BEGIN
  SomeModel Create (0.9ms)  INSERT INTO `stripe_webhook_succeeded_events` (`unique_string`, `created_at`) VALUES ('some unique key', '2019-12-25 01:43:00')

Console B

After INSERT in Console A
Run INSERT in Conssole B with same unique string
It will be blocked but Not raise error immediately

[3] pry(main)> SomeModel.transaction { SomeModel.create(unique_string: 'some unique key'); sleep 10 }
   (0.8ms)  BEGIN

Console A

After Sleep some seconds
committed After sleep

[6] pry(main)> SomeModel.transaction { SomeModel.create(unique_string: 'some unique key'); sleep 10 }
   (0.7ms)  BEGIN
  SomeModel Create (0.9ms)  INSERT INTO `stripe_webhook_succeeded_events` (`unique_string`, `created_at`) VALUES ('some unique key', '2019-12-25 01:43:00')
   (8.1ms)  COMMIT

Console B

After INSERT in Console A
INSERT Rollbacked

[3] pry(main)> SomeModel.transaction { SomeModel.create(unique_string: 'some unique key'); sleep 10 }
   (0.8ms)  BEGIN
  SomeModel Create (8756.6ms)  INSERT INTO `stripe_webhook_succeeded_events` (`unique_string`, `created_at`) VALUES ('some unique key', '2019-12-25 01:43:02')
   (7.7ms)  ROLLBACK
ActiveRecord::RecordNotUnique: Mysql2::Error: Duplicate entry 'some unique key' for key 'index_stripe_webhook_succeeded_events_on_unique_string': INSERT INTO `stripe_webhook_succeeded_events` (`unique_string`, `created_at`) VALUES ('some unique key', '2019-12-25 01:43:02')
from /usr/local/bundle/gems/mysql2-0.5.2/lib/mysql2/client.rb:131:in `_query'
Caused by Mysql2::Error: Duplicate entry 'some unique key' for key 'index_stripe_webhook_succeeded_events_on_unique_string'
from /usr/local/bundle/gems/mysql2-0.5.2/lib/mysql2/client.rb:131:in `_query'

Original by Github issue

https://github.com/YumaInaura/YumaInaura/issues/2869

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

https://line.me/ti/g2/eEPltQ6Tzh3pYAZV8JXKZqc7PJ6L0rpm573dcQ

Twitter

https://twitter.com/YumaInaura

公開日時

2019-12-26

Discussion