Class: Perpetuity::Postgres::Connection

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Connection

Returns a new instance of Connection.



8
9
10
# File 'lib/perpetuity/postgres/connection.rb', line 8

def initialize options={}
  @options = sanitize_options(options)
end

Instance Attribute Details

#optionsObject (readonly)

Returns the value of attribute options.



6
7
8
# File 'lib/perpetuity/postgres/connection.rb', line 6

def options
  @options
end

Instance Method Details

#active?Boolean

Returns:

  • (Boolean)


40
41
42
# File 'lib/perpetuity/postgres/connection.rb', line 40

def active?
  !!@pg_connection
end

#connectObject



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/perpetuity/postgres/connection.rb', line 20

def connect
  @pg_connection = PG.connect(options)
  @pg_connection.exec 'SET client_min_messages TO warning'
  @pg_connection
rescue PG::ConnectionBad => e
  tries ||= 0
  connect_options = options.dup
  connect_options.delete :dbname

  conn = PG.connect connect_options
  conn.exec "CREATE DATABASE #{db}"
  conn.close

  if tries.zero?
    retry
  else
    raise e
  end
end

#dbObject



12
13
14
# File 'lib/perpetuity/postgres/connection.rb', line 12

def db
  options[:dbname]
end

#execute(sql) ⇒ Object



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/perpetuity/postgres/connection.rb', line 44

def execute sql
  pg_connection.exec sql
rescue PG::AdminShutdown, PG::UnableToSend => e
  # server closed the connection unexpectedly
  # Try to reconnect 3 times in case it's just a server restart.
  unable_to_send_retries ||= 0
  if unable_to_send_retries < 3
    connect
    unable_to_send_retries += 1
    sleep 1
    retry
  else
    raise
  end
rescue PG::UndefinedFunction => e
  if e.message =~ /uuid_generate/
    use_uuid_extension
    retry
  else
    raise
  end
end

#pg_connectionObject



16
17
18
# File 'lib/perpetuity/postgres/connection.rb', line 16

def pg_connection
  @pg_connection ||= connect
end

#sanitize_options(options) ⇒ Object



75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# File 'lib/perpetuity/postgres/connection.rb', line 75

def sanitize_options options
  options = options.dup
  db = options.delete(:db)
  username = options.delete(:username)

  if db
    options[:dbname] = db
  end

  if username
    options[:user] = username
  end

  options
end

#tablesObject



67
68
69
70
71
72
73
# File 'lib/perpetuity/postgres/connection.rb', line 67

def tables
  sql = "SELECT table_name FROM information_schema.tables "
  sql << "WHERE table_schema = 'public'"

  result = execute(sql)
  result.to_a.map { |r| r['table_name'] }
end