Class: PGI::Connection

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

Defined Under Namespace

Classes: JSONDecoder

Instance Method Summary collapse

Constructor Details

#initialize(logger:, conn_uri: nil, conn: nil) ⇒ Connection

Create instance

Parameters:

  • pool (ConnectionPool)
  • logger (Logger)


15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/pgi/connection.rb', line 15

def initialize(logger:, conn_uri: nil, conn: nil)
  @logger = logger

  @conn = conn || PG::Connection.new(conn_uri).tap do |new_conn|
    regi = PG::BasicTypeRegistry.new.register_default_types

    regi.register_type 0, "uuid", PG::TextEncoder::String, PG::TextDecoder::String
    regi.register_type 0, "json", PG::TextEncoder::JSON, JSONDecoder
    regi.alias_type(0, "jsonb", "json")

    new_conn.type_map_for_results = PG::BasicTypeMapForResults.new(new_conn, registry: regi)
    new_conn.type_map_for_queries = PG::BasicTypeMapForQueries.new(new_conn, registry: regi)
  end || raise("no connection provided")
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name) ⇒ Object

Pass the remainder of methods on to a PG::Connection



61
62
63
# File 'lib/pgi/connection.rb', line 61

def method_missing(name, ...)
  @conn.__send__(name, ...)
end

Instance Method Details

#exec_stmt(stmt_name, sql, params = []) ⇒ Object

Execute a prepared statement. Statements are auto-created with fallback to exec_params

Examples:

.exec_stmt("users_by_name", "SELECT * FROM users WHERE name = $1", ["joe"])

Parameters:

  • stmt_name (String)

    name of statement, must be unique for the query

  • sql (String)

    SQL query

  • params (Array) (defaults to: [])

    list of params



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/pgi/connection.rb', line 38

def exec_stmt(stmt_name, sql, params = [])
  if [PG::PQTRANS_ACTIVE, PG::PQTRANS_INTRANS, PG::PQTRANS_INERROR].include?(@conn.transaction_status)
    @logger&.debug "Unable to use statements within a transaction - falling back to #exec_params"
    return @conn.exec_params(sql, params)
  end

  begin
    @conn.exec_prepared(stmt_name, params)
  rescue PG::InvalidSqlStatementName
    @logger&.debug "Creating missing prepared statement: \"#{stmt_name}\""
    @conn.prepare(stmt_name, sql)
    retry
  end
rescue PG::Error => e
  # Log at the source so failures are traceable regardless of how the
  # consumer handles the exception
  @logger&.error(e)
  raise
end

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

Returns:

  • (Boolean)


65
66
67
# File 'lib/pgi/connection.rb', line 65

def respond_to_missing?(name, include_private = false)
  @conn.respond_to?(name, include_private) || super
end