Skip to content

Instantly share code, notes, and snippets.

@basgys
Last active December 18, 2015 04:49
Show Gist options
  • Save basgys/5728380 to your computer and use it in GitHub Desktop.
Save basgys/5728380 to your computer and use it in GitHub Desktop.
Wrap mysql2 deadlocks in an ActiveRecord exception
# 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
@senny
Copy link

senny commented Sep 5, 2013

@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