Sha256: 483384cdea2fcc47574f4059d4229f2374afd9c05cfe300a08a69fb14b08998a

Contents?: true

Size: 1.04 KB

Versions: 1

Compression:

Stored size: 1.04 KB

Contents

require 'active_record'
require 'active_record/connection_adapters/abstract_mysql_adapter'
require 'active_support'
require 'retryable'

class ActiveRecord::Base
  class_attribute :execution_tries
  class_attribute :execution_retry_wait
end

class ActiveRecord::ConnectionAdapters::AbstractMysqlAdapter
  MYSQL_SERVER_HAS_GONE_AWAY = 'MySQL server has gone away'
  DEFAULT_EXECUTION_TRIES = 1
  DEFAULT_EXECUTION_RETRY_WAIT = 0.5

  def execute_with_reconnect(sql, name = nil)
    retryable_options = {
      :tries    => (ActiveRecord::Base.execution_tries || DEFAULT_EXECUTION_TRIES),
      :matching => /#{MYSQL_SERVER_HAS_GONE_AWAY}/,
      :sleep    => proc {|n|
        wait = (ActiveRecord::Base.execution_retry_wait || DEFAULT_EXECUTION_RETRY_WAIT) * (n + 1)
        logger.warn("#{MYSQL_SERVER_HAS_GONE_AWAY}. Trying to reconnect in #{wait} seconds.")
        sleep(wait)
        reconnect!
        0
      }
    }
 
    retryable(retryable_options) do
      execute_without_reconnect(sql, name)
    end
  end
 
  alias_method_chain :execute, :reconnect
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
activerecord-mysql-reconnect-0.0.1 lib/activerecord/mysql/reconnect/abstract_mysql_adapter.rb