Class: Psql

Inherits:
Object
  • Object
show all
Defined in:
lib/raka/lang/psql/impl.rb

Overview

postgresql protocol using psql, requires HOST, PORT, USER, DB

Instance Method Summary collapse

Constructor Details

#initialize(conn: nil, create: 'mview', schema: '', params: {}) ⇒ Psql

  1. do not add required argument here, so psql.config will work or we can only use psql(conn: xxx).config



27
28
29
30
31
32
# File 'lib/raka/lang/psql/impl.rb', line 27

def initialize(conn: nil, create: 'mview', schema: '', params: {})
  @create = create
  @params = params
  @schema = schema
  @conn = conn
end

Instance Method Details

#build(code, _) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/raka/lang/psql/impl.rb', line 34

def build(code, _)
  # 2. lazily check the argument only when used
  raise 'argument conn required' if @conn.nil?

  if @create.to_s == 'table'
    'DROP TABLE IF EXISTS :_schema_:_name_;' \
      'CREATE TABLE :schema:_name_ AS (' + code + ');'
  elsif @create.to_s == 'mview'
    'DROP MATERIALIZED VIEW IF EXISTS :_schema_:_name_;' \
      'CREATE MATERIALIZED VIEW :schema:_name_ AS (' + code + ');'
  else
    code
  end
end

#run_script(env, fname, task) ⇒ Object



49
50
51
52
53
54
55
56
57
58
# File 'lib/raka/lang/psql/impl.rb', line 49

def run_script(env, fname, task)
  param_str = (@params || {}).map { |k, v| "-v #{k}=\"#{v}\"" }.join(' ')
  schema = @schema.empty? ? task.rule_scopes.join('__') : @schema

  bash env, %(
  #{sh_cmd(schema)} #{param_str} -v _name_=#{task.output_stem} \
    -v _schema_=#{schema.empty? ? '' : schema + '.'} -f #{fname} | tee #{fname}.log
  mv #{fname}.log #{task.name}
  )
end

#sh_cmd(schema) ⇒ Object

Sometimes we want to use the psql command with bash directly



20
21
22
23
24
# File 'lib/raka/lang/psql/impl.rb', line 20

def sh_cmd(schema)
  c = @conn
  env_vars = "PGOPTIONS='-c search_path=#{schema.empty? ? '' : schema + ','}public' "
  "PGPASSWORD=#{c.password} #{env_vars} psql -h #{c.host} -p #{c.port} -U #{c.user} -d #{c.db} -v ON_ERROR_STOP=1"
end