Module: StatementTimeout::QueryMethodsExtension

Defined in:
lib/statement_timeout.rb

Instance Method Summary collapse

Instance Method Details

#statement_timeout(timeout, mode: StatementTimeout.config.default_mode) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/statement_timeout.rb', line 42

def statement_timeout(timeout, mode: StatementTimeout.config.default_mode)
  timeout = if timeout in ActiveSupport::Duration
              timeout.in_milliseconds
            else
              timeout
            end

  connection_pool.with_connection do |connection|
    raise ActiveRecord::AdapterError, "statement_timeout is not supported for the #{connection.class.inspect} adapter" unless
      connection.supports_statement_timeout?

    case mode
    when :transaction
      connection.transaction do
        statement_timeout_was, connection.local_statement_timeout = connection.statement_timeout, timeout

        yield connection
      ensure
        connection.local_statement_timeout = statement_timeout_was
      end
    when :session
      begin
        statement_timeout_was, connection.statement_timeout = connection.statement_timeout, timeout

        yield connection
      ensure
        connection.statement_timeout = statement_timeout_was
      end
    else
      raise ArgumentError, "mode is not supported: #{mode.inspect}"
    end
  end
end