Skip to content

Instantly share code, notes, and snippets.

@lawrencepit
Forked from mauricioszabo/connection_fix.rb
Created January 15, 2012 22:42
Show Gist options
  • Save lawrencepit/1617803 to your computer and use it in GitHub Desktop.
Save lawrencepit/1617803 to your computer and use it in GitHub Desktop.
MySQL server has gone away fix
# If your workers are inactive for a long period of time, they'll lose
# their MySQL connection.
#
# This hack ensures we re-connect whenever a connection is
# lost. Because, really. why not?
#
# Stick this in RAILS_ROOT/config/initializers/connection_fix.rb (or somewhere similar)
#
# From:
# http://coderrr.wordpress.com/2009/01/08/activerecord-threading-issues-and-resolutions/
# https://gist.github.com/1276131/e2b02748173eb0fc5cfed80a9d9c01df6264f8db
unless $LOADED_FEATURES.include?(__FILE__)
$LOADED_FEATURES << __FILE__
if ActiveRecord::ConnectionAdapters.const_defined?(:MysqlAdapter)
module ActiveRecord::ConnectionAdapters
class MysqlAdapter
alias_method :execute_without_retry, :execute
def execute(*args)
execute_without_retry(*args)
rescue ActiveRecord::StatementInvalid, Mysql::Error => e
if e.message =~ /server has gone away/i
warn "Server timed out, retrying"
reconnect!
retry
else
raise e
end
end
end
end
elsif ActiveRecord::ConnectionAdapters.const_defined?(:Mysql2Adapter)
module ActiveRecord::ConnectionAdapters
class Mysql2Adapter
alias_method :execute_without_retry, :execute
def execute(*args)
execute_without_retry(*args)
rescue ActiveRecord::StatementInvalid, Mysql2::Error => e
if e.message =~ /server has gone away/i
warn "Server timed out, retrying"
reconnect!
retry
else
raise e
end
end
end
end
end
end
@lawrencepit
Copy link
Author

I was getting Mysql::Error instead of ActiveRecord::StatementInvalid since Rails 3. See also: brianmario/mysql2#213

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment