Module: Pgbus::DedicatedConnection

Defined in:
lib/pgbus/dedicated_connection.rb

Overview

Single choke point for opening a DEDICATED PG connection outside the pgmq pools — the streamer's LISTEN connection and the worker NotifyListener. Every such path MUST route through here (enforced by spec/pgbus/pg_connect_guard_spec.rb): in :session GUC mode, Configuration#forward_connection_variables leaves the database.yml variables: hash on the connection options for the caller to apply post-connect, and :variables is not a libpq keyword — a raw PG.connect(**opts) fails with invalid connection option "variables" (issue #352). This mirrors Client#wrap_session_gucs, which does the same for pool connections: the GUCs are applied via post-connect SET because a transaction-mode pooler rejects the libpq options startup param (the reason :session mode exists).

Class Method Summary collapse

Class Method Details

.close_quietly(conn) ⇒ Object



47
48
49
50
51
# File 'lib/pgbus/dedicated_connection.rb', line 47

def close_quietly(conn)
  conn.close
rescue StandardError
  nil
end

.connect(opts) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
# File 'lib/pgbus/dedicated_connection.rb', line 19

def connect(opts)
  require "pg" unless defined?(::PG::Connection)
  case opts
  when String then ::PG.connect(opts)
  when Hash then connect_from_hash(opts)
  else
    raise Pgbus::ConfigurationError,
          "Cannot build a dedicated PG connection from #{opts.class}. " \
          "Set database_url or connection_params so pgbus can open its own connection."
  end
end

.connect_from_hash(opts) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/pgbus/dedicated_connection.rb', line 31

def connect_from_hash(opts)
  variables = opts[:variables]
  conn = ::PG.connect(**opts.except(:variables))
  begin
    variables&.each { |name, value| conn.exec("SET #{name} = '#{value}'") }
  rescue StandardError
    # A failing SET (e.g. a bogus GUC name in database.yml variables:)
    # must not orphan the freshly opened socket — the reconnect loops
    # retry on a tight backoff and would leak one server connection per
    # attempt until PostgreSQL exhausts max_connections.
    close_quietly(conn)
    raise
  end
  conn
end