DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Getting ActiveRecord To Auto Reconnect After Lost Connection

05.19.2008
| 8428 views |
  • submit to reddit
        I puts this code in a file called active_record_hacks.rb in config/initializers but it could easily be a plugin.

ActiveRecord::ConnectionAdapters::MysqlAdapter.module_eval do
  def execute_with_retry_once(sql, name = nil)
    retried = false
    begin
      execute_without_retry_once(sql, name)
    rescue ActiveRecord::StatementInvalid => exception
      ActiveRecord::Base.logger.info "#{exception}, retried? #{retried}"

      # Our database connection has gone away, reconnect and retry this method
      reconnect!
      unless retried
        retried = true
        retry
      end
    end
  end

  alias_method_chain :execute, :retry_once
end
    

Comments

Snippets Manager replied on Fri, 2008/05/23 - 8:02pm

This isn't transaction safe. Consider the following: execute("START TRANSACTION") execute("UPDATE some_table SET do_not_delete = 1") execute("DELETE FROM some_table WHERE do_not_delete = 0") execute("COMMIT") If you were to lose connection after the update, your marking of the records would be rolled back. Executing the delete would re-establish the connect and then run the delete outside of any transaction.