Module: Jrec::PG

Included in:
Jrec, Collection, Model
Defined in:
lib/jrec/pg.rb

Instance Method Summary collapse

Instance Method Details

#configObject

:singleton method parses database url



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/jrec/pg.rb', line 41

def config 
  @@config ||= begin
    
    if File.exists?(config_file)
      db = YAML.load(config_file)[env]
    elsif ENV['DATABASE_URL']
      db = URI.parse(ENV['DATABASE_URL'])
    else
      raise "Database configuration not found"  
    end
    
    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

#config_fileObject



69
70
71
# File 'lib/jrec/pg.rb', line 69

def config_file
  ENV['DATABASE_CONFIG_FILE'] || "#{Jrec.root}/config/database.yml"
end

#envObject



73
74
75
# File 'lib/jrec/pg.rb', line 73

def env
  ENV['RACK_ENV'] || "development"
end

#exec_func(func_name, *params) ⇒ Object



16
17
18
19
# File 'lib/jrec/pg.rb', line 16

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

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



21
22
23
24
25
26
# File 'lib/jrec/pg.rb', line 21

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

#pgObject

:singleton method holds db connection



32
33
34
# File 'lib/jrec/pg.rb', line 32

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