Class: Perpetuity::Postgres::Connection
- Inherits:
-
Object
- Object
- Perpetuity::Postgres::Connection
- Defined in:
- lib/perpetuity/postgres/connection.rb
Instance Attribute Summary collapse
-
#options ⇒ Object
readonly
Returns the value of attribute options.
Instance Method Summary collapse
- #active? ⇒ Boolean
- #connect ⇒ Object
- #db ⇒ Object
- #execute(sql) ⇒ Object
-
#initialize(options = {}) ⇒ Connection
constructor
A new instance of Connection.
- #pg_connection ⇒ Object
- #sanitize_options(options) ⇒ Object
- #tables ⇒ Object
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 = () end |
Instance Attribute Details
#options ⇒ Object (readonly)
Returns the value of attribute options.
6 7 8 |
# File 'lib/perpetuity/postgres/connection.rb', line 6 def @options end |
Instance Method Details
#active? ⇒ Boolean
40 41 42 |
# File 'lib/perpetuity/postgres/connection.rb', line 40 def active? !!@pg_connection end |
#connect ⇒ Object
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() @pg_connection.exec 'SET client_min_messages TO warning' @pg_connection rescue PG::ConnectionBad => e tries ||= 0 = .dup .delete :dbname conn = PG.connect conn.exec "CREATE DATABASE #{db}" conn.close if tries.zero? retry else raise e end end |
#db ⇒ Object
12 13 14 |
# File 'lib/perpetuity/postgres/connection.rb', line 12 def db [: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. =~ /uuid_generate/ use_uuid_extension retry else raise end end |
#pg_connection ⇒ Object
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 = .dup db = .delete(:db) username = .delete(:username) if db [:dbname] = db end if username [:user] = username end end |
#tables ⇒ Object
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 |