Class: Capistrano::DBSync::Postgres::CLI

Inherits:
Object
  • Object
show all
Defined in:
lib/capistrano/db_sync/postgres/cli.rb

Instance Method Summary collapse

Constructor Details

#initialize(config) ⇒ CLI

Returns a new instance of CLI.



2
3
4
# File 'lib/capistrano/db_sync/postgres/cli.rb', line 2

def initialize(config)
  @config = config
end

Instance Method Details

#copy_and_compress_to_file(to_compressed_file, db, query) ⇒ Object



42
43
44
# File 'lib/capistrano/db_sync/postgres/cli.rb', line 42

def copy_and_compress_to_file(to_compressed_file, db, query)
  psql "\\copy (#{query}) TO PROGRAM 'gzip > #{to_compressed_file}' WITH CSV", db
end

#copy_from_compressed_file(from_compressed_file, db, table) ⇒ Object



46
47
48
# File 'lib/capistrano/db_sync/postgres/cli.rb', line 46

def copy_from_compressed_file(from_compressed_file, db, table)
  psql "\\copy #{table} FROM PROGRAM 'gunzip --to-stdout #{from_compressed_file}' WITH CSV", db
end

#create_db(db) ⇒ Object



20
21
22
# File 'lib/capistrano/db_sync/postgres/cli.rb', line 20

def create_db(db)
  psql %Q|CREATE DATABASE "#{db}";|
end

#drop_db(db) ⇒ Object



16
17
18
# File 'lib/capistrano/db_sync/postgres/cli.rb', line 16

def drop_db(db)
  psql %Q|DROP DATABASE IF EXISTS "#{db}";|
end

#dump(to_file, db, options = []) ⇒ Object



6
7
8
9
# File 'lib/capistrano/db_sync/postgres/cli.rb', line 6

def dump(to_file, db, options = [])
  args = to_string_args(options)
  "#{with_pw} pg_dump #{credentials} #{format_args} -f #{to_file} #{args} #{db}".strip
end

#kill_processes_for_db(db) ⇒ Object



33
34
35
36
37
38
39
40
# File 'lib/capistrano/db_sync/postgres/cli.rb', line 33

def kill_processes_for_db(db)
  psql "    SELECT pg_terminate_backend(pg_stat_activity.pid)\n      FROM pg_stat_activity\n     WHERE pg_stat_activity.datname = $$\#{db}$$\n       AND pid <> pg_backend_pid();\n  SQL\nend\n".gsub("$", "\\$")

#psql(command, db = "postgres") ⇒ Object



28
29
30
31
# File 'lib/capistrano/db_sync/postgres/cli.rb', line 28

def psql(command, db = "postgres")
  normalized_command = command.gsub('"', '\"').gsub(/\s\s+|\n/, " ")
  %Q|#{with_pw} psql #{credentials} -d #{db} -c "#{normalized_command}"|.strip
end

#rename_db(old_db, new_db) ⇒ Object



24
25
26
# File 'lib/capistrano/db_sync/postgres/cli.rb', line 24

def rename_db(old_db, new_db)
  psql %Q|ALTER DATABASE "#{old_db}" RENAME TO "#{new_db}";|
end

#restore(from_file, db, options = []) ⇒ Object



11
12
13
14
# File 'lib/capistrano/db_sync/postgres/cli.rb', line 11

def restore(from_file, db, options = [])
  args = to_string_args(options)
  "#{with_pw} pg_restore #{credentials} #{format_args} -d #{db} #{args} #{from_file}".strip
end