Class: PgBouncerHero::Connection

Inherits:
Object
  • Object
show all
Defined in:
lib/pgbouncerhero/connection.rb

Instance Method Summary collapse

Constructor Details

#initialize(host, port, user, password, dbname) ⇒ Connection

Returns a new instance of Connection.



3
4
5
6
7
8
9
10
# File 'lib/pgbouncerhero/connection.rb', line 3

def initialize(host, port, user, password, dbname)
  @host = host
  @port = port
  @user = user
  @password = password
  @dbname = dbname
  @timeout = ENV["PGBOUNCERHERO_TIMEOUT"] || 5
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method_name) ⇒ Object



42
43
44
# File 'lib/pgbouncerhero/connection.rb', line 42

def method_missing(method_name, *, **, &)
  with_connection { |raw_connection| raw_connection.public_send(method_name, *, **, &) }
end

Instance Method Details

#connected?Boolean

Returns:

  • (Boolean)


20
21
22
# File 'lib/pgbouncerhero/connection.rb', line 20

def connected?
  !connection.nil?
end

#connectionObject



12
13
14
15
16
17
18
# File 'lib/pgbouncerhero/connection.rb', line 12

def connection
  disconnect! if @connection && connection_invalid?(@connection)
  @connection ||= connect
rescue StandardError => e
  Rails.logger.error("[PGBouncerHero] Host:#{@host} | Database Name:#{@dbname} | Timeout: #{@timeout}s => #{e}")
  nil
end

#disconnect!Object



34
35
36
37
38
39
40
# File 'lib/pgbouncerhero/connection.rb', line 34

def disconnect!
  @connection&.finish unless @connection&.finished?
rescue PG::Error
  nil
ensure
  @connection = nil
end

#respond_to_missing?(method_name, include_private = false) ⇒ Boolean

Returns:

  • (Boolean)


46
47
48
# File 'lib/pgbouncerhero/connection.rb', line 46

def respond_to_missing?(method_name, include_private = false)
  PG::Connection.public_instance_methods(include_private).include?(method_name) || super
end

#with_connectionObject



24
25
26
27
28
29
30
31
32
# File 'lib/pgbouncerhero/connection.rb', line 24

def with_connection
  raw_connection = connection
  return unless raw_connection

  yield raw_connection
rescue PG::Error
  disconnect!
  raise
end