module Sequel::ConnectionValidator

Attributes

connection_validation_timeout[RW]

The number of seconds that need to pass since connection checkin before attempting to validate the connection when checking it out from the pool. Defaults to 3600 seconds (1 hour).

Public Class Methods

extended(pool) click to toggle source

Initialize the data structures used by this extension.

# File lib/sequel/extensions/connection_validator.rb, line 58
def self.extended(pool)
  pool.instance_eval do
    @connection_timestamps ||= {}
    @connection_validation_timeout = 3600
  end

  # Make sure the valid connection SQL query is precached,
  # otherwise it's possible it will happen at runtime. While
  # it should work correctly at runtime, it's better to avoid
  # the possibility of failure altogether.
  pool.db.send(:valid_connection_sql)
end

Private Instance Methods

acquire(*a) click to toggle source

When acquiring a connection, if it has been idle for longer than the connection validation timeout, test the connection for validity. If it is not valid, disconnect the connection, and retry with a new connection.

Calls superclass method
# File lib/sequel/extensions/connection_validator.rb, line 84
def acquire(*a)
  begin
    if (conn = super) &&
       (t = sync{@connection_timestamps.delete(conn)}) &&
       Time.now - t > @connection_validation_timeout &&
       !db.valid_connection?(conn)

      if pool_type == :sharded_threaded
        sync{allocated(a.last).delete(Thread.current)}
      else
        sync{@allocated.delete(Thread.current)}
      end

      db.disconnect_connection(conn)
      raise Retry
    end
  rescue Retry
    retry
  end

  conn
end
checkin_connection(*) click to toggle source

Record the time the connection was checked back into the pool.

Calls superclass method
# File lib/sequel/extensions/connection_validator.rb, line 74
def checkin_connection(*)
  conn = super
  @connection_timestamps[conn] = Time.now
  conn
end