Last active
December 18, 2015 04:49
-
-
Save basgys/5728380 to your computer and use it in GitHub Desktop.
Wrap mysql2 deadlocks in an ActiveRecord exception
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# This core extension aims to manage Deadlocks | |
# with a proper ActiveRecord exception. | |
# | |
# It only works for mysql2 | |
# | |
# Example: | |
# | |
# MyModel.transaction do | |
# begin | |
# record1 = MyModel.find(:id, lock: true) | |
# record2 = MyModel.find(:id2, lock: true) | |
# rescue ActiveRecord::Deadlock => e | |
# retry | |
# end | |
# end | |
# | |
# Author: Bastien Gysler <www.bastiengysler.com> | |
module ActiveRecord | |
class Deadlock < WrappedDatabaseException | |
end | |
module ConnectionAdapters | |
class Mysql2Adapter < AbstractMysqlAdapter | |
alias :core_translate_exception :translate_exception | |
def translate_exception(exception, message) | |
if (message =~ /Deadlock/) | |
Deadlock.new(message, exception) | |
else | |
core_translate_exception(exception, message) | |
end | |
end | |
end | |
end | |
end |
Yes I need to catch deadlocks. Do you want a test that cause a deadlock?
@basgys yea. If we introduce such an exception we should see if we can get it working with other db adapters.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What exactly was the usecase? You needed to catch a Deadlock in your application code? Can you write an executable test-case to reproduce the behavior: https://github.com/rails/rails/blob/master/guides/bug_report_templates/active_record_master.rb ?