Class: Leda::Stores::Postgresql

Inherits:
Object
  • Object
show all
Includes:
Leda::Store
Defined in:
lib/leda/stores/postgresql.rb

Overview

Store for PostgreSQL. Uses PG command line utilties to dump and restore.

Options:

  • ‘:tables`. An array of table names to dump/restore. The tables will be restored in the order given in the array.

Instance Attribute Summary collapse

Attributes included from Leda::Store

#options

Instance Method Summary collapse

Methods included from Leda::Store

default_name, find, included, #name, register_store, registered_stores

Constructor Details

#initialize(*args) ⇒ Postgresql

Returns a new instance of Postgresql.



20
21
22
23
24
25
# File 'lib/leda/stores/postgresql.rb', line 20

def initialize(*args)
  super

  @tables = options[:tables]
  @filter_executable = options[:filter]
end

Instance Attribute Details

#tablesObject (readonly)

Returns the value of attribute tables.



18
19
20
# File 'lib/leda/stores/postgresql.rb', line 18

def tables
  @tables
end

Instance Method Details

#dump(directory) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/leda/stores/postgresql.rb', line 31

def dump(directory)
  pgenv

  fn = filename(directory).to_s
  $stderr.puts "Exporting to #{fn} ..."
  dump_cmd = (['pg_dump', '-a', '-Fp', '-O', '-x'] + tables.flat_map { |t| ['-t', t] }).shelljoin

  # TODO:
  filter_cmd = nil
  if @filter_executable
    filter_cmd = "| #{@filter_executable}"
  end

  out_cmd = "> " + [fn].shelljoin
  if system([dump_cmd, filter_cmd, out_cmd].compact.join(' '))
    $stderr.puts "... export complete."
  else
    fail "Export failed."
  end
end

#filename(directory) ⇒ Object



27
28
29
# File 'lib/leda/stores/postgresql.rb', line 27

def filename(directory)
  directory.join('dump.psql')
end

#restore_from(directory) ⇒ Object



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/leda/stores/postgresql.rb', line 52

def restore_from(directory)
  pgenv

  source_file = filename(directory)

  unless source_file.exist?
    fail "Expected provider dump not found: #{source_file}"
  end

  begin
    $stderr.puts "Importing from #{source_file}"
    open('|psql -aq', 'w') do |psql|
      psql.puts '\set ON_ERROR_STOP'
      psql.puts "BEGIN;"
      psql.puts "TRUNCATE #{tables.join(', ')} CASCADE;"
      psql.puts source_file.read
      psql.puts "COMMIT;"
    end
  rescue Errno::EPIPE => e
    $stderr.puts "psql terminated early; check above for a reason"
  end
end