Never been to DZone Snippets before?

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

Getting ActiveRecord to auto reconnect after lost connection (See related posts)

I puts this code in a file called active_record_hacks.rb in config/initializers but it could easily be a plugin.

   1  
   2  ActiveRecord::ConnectionAdapters::MysqlAdapter.module_eval do
   3    def execute_with_retry_once(sql, name = nil)
   4      retried = false
   5      begin
   6        execute_without_retry_once(sql, name)
   7      rescue ActiveRecord::StatementInvalid => exception
   8        ActiveRecord::Base.logger.info "#{exception}, retried? #{retried}"
   9  
  10        # Our database connection has gone away, reconnect and retry this method
  11        reconnect!
  12        unless retried
  13          retried = true
  14          retry
  15        end
  16      end
  17    end
  18  
  19    alias_method_chain :execute, :retry_once
  20  end

Comments on this post

selector37 posts on May 23, 2008 at 20:13
This isn't transaction safe. Consider the following:

   1  
   2  execute("START TRANSACTION")
   3  execute("UPDATE some_table SET do_not_delete = 1")
   4  execute("DELETE FROM some_table WHERE do_not_delete = 0")
   5  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.

You need to create an account or log in to post comments to this site.


Click here to browse all 5521 code snippets

Related Posts