Sha256: b1fc27cb8392455d5a8e82534e53cb5c93a19256fc5453f20417627c713284d9

Contents?: true

Size: 1.16 KB

Versions: 2

Compression:

Stored size: 1.16 KB

Contents

# frozen_string_literal: true

module ActiveRecordDataLoader
  class ConnectionHandler
    def initialize(connection_factory:, statement_timeout:)
      @connection_factory = connection_factory
      @statement_timeout = statement_timeout
      cache_facts
    end

    def with_connection
      connection = connection_factory.call
      if supports_timeout?
        connection.execute(timeout_set_command)
        yield connection
        connection.execute(reset_timeout_command)
      else
        yield connection
      end
    ensure
      connection&.close
    end

    def supports_timeout?
      @supports_timeout
    end

    def supports_copy?
      @supports_copy
    end

    def timeout_set_command
      "SET statement_timeout = \"#{statement_timeout}\""
    end

    def reset_timeout_command
      "RESET statement_timeout"
    end

    private

    attr_reader :connection_factory, :statement_timeout

    def cache_facts
      connection = connection_factory.call
      @supports_timeout = connection.adapter_name.downcase.to_sym == :postgresql
      @supports_copy = connection.raw_connection.respond_to?(:copy_data)
    ensure
      connection&.close
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
active_record_data_loader-1.3.1 lib/active_record_data_loader/connection_handler.rb
active_record_data_loader-1.3.0 lib/active_record_data_loader/connection_handler.rb