Created
March 28, 2012 05:30
-
-
Save towski/2223905 to your computer and use it in GitHub Desktop.
sql timeout
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# ActiveRecord::Base.connection.timeout(20, []) do |connection| | |
# worrisome sql | |
# end | |
module ActiveRecord | |
class TimeoutError < ActiveRecordError | |
def initialize(message = nil) | |
super(message) | |
end | |
end | |
class ConnectionAdapters::MysqlAdapter | |
# the on_fail parameter gets returned if the sql times out | |
def timeout(time, on_fail = nil, &block) | |
old_timeout = @config[:read_timeout] | |
@config[:read_timeout] = (time / 3.0).ceil # read_timeout setting seems to be multiples of 3 | |
reconnect! | |
connection_id = execute("select connection_id()").fetch_row.first | |
begin | |
yield self | |
rescue ActiveRecord::StatementInvalid | |
if old_timeout | |
@config[:read_timeout] = old_timeout | |
else | |
@config.delete(:read_timeout) | |
end | |
reconnect! | |
execute("kill #{connection_id}") | |
if on_fail | |
return on_fail | |
else | |
raise TimeoutError | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment