Module: Actn::DB::PG

Included in:
Actn::DB, Mod, Set
Defined in:
lib/actn/db/pg.rb

Defined Under Namespace

Classes: JsonSchemaError

Instance Method Summary collapse

Instance Method Details

#db_configObject

:singleton method parses database url



65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/actn/db/pg.rb', line 65

def db_config
  @@config ||= begin
    db = URI.parse(ENV['DATABASE_URL'] || 'postgres://localhost')
    config = {
      dbname: db.path[1..-1],
      host: db.host,
      port: db.port,
      size: ENV['DB_POOL_SIZE'] || 5,          
      async_autoreconnect: ENV['DB_ASYNC_AUTO_RECONNECT'] || true,
      connect_timeout: ENV['DB_CONN_TIMEOUT'] || 60,
      query_timeout: ENV['DB_QUERY_TIMEOUT'] || 30,
      on_autoreconnect: proc { |pg| pg.exec "SELECT plv8_startup();" rescue nil },
      on_connect: proc { |pg| pg.exec "SELECT plv8_startup();" rescue nil }
    }
    config[:user] = db.user if db.user
    config[:password] = db.password if db.password
    config
  end
end

#exec_func(func_name, *params) ⇒ Object



25
26
27
28
# File 'lib/actn/db/pg.rb', line 25

def exec_func func_name, *params
  sql = "SELECT __#{func_name}(#{ (params.length-1).times.inject("$1"){ |m,i| "#{m},$#{ i + 2 }"} })"
  exec_prepared sql.parameterize.underscore, sql, params
end

#exec_params(sql, params = []) ⇒ Object



45
46
47
48
49
50
# File 'lib/actn/db/pg.rb', line 45

def exec_params sql, params = []
  result = pg.exec_params(sql, params)
  json = result.values.flatten.first
  result.clear
  json
end

#exec_prepared(statement, sql, params = []) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/actn/db/pg.rb', line 30

def exec_prepared statement, sql, params = []
  
  pg.prepare statement, sql rescue ::PG::DuplicatePstatement
  
  begin          
    result = pg.exec_prepared(statement, params)
    json = result.values.flatten.first
    result.clear
    json
  rescue ::PG::InvalidSqlStatementName
    exec_params sql, params
  end
  
end

#pgObject

:singleton method holds db connection



56
57
58
# File 'lib/actn/db/pg.rb', line 56

def pg 
  @@connection_pool ||= ::PG::EM::ConnectionPool.new(db_config)
end