Class: DatabaseOperations

Inherits:
Object
  • Object
show all
Defined in:
lib/database_operations.rb

Class Method Summary collapse

Class Method Details

.dump_database_schema!(cfg, file) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/database_operations.rb', line 32

def self.dump_database_schema!(cfg, file)
  search_path = cfg["schema_search_path"]
  search_path = search_path.split(',').map{|x| "--schema=#{x}"}.join(' ') if search_path

  File.open(Rails.root.join(file), "w") { |f|
    f.puts "begin;"
    # Dump database but exclude PostGIS artifacts which are created with CREATE EXTENSION:
    f.write pg(cfg, %{pg_dump -s -T geometry_columns}, :pipe => %{perl -ne 'print unless /COPY.*spatial_ref_sys/ .. /\\x5c\\x2e/'})
    f.write pg(cfg, %{pg_dump -a -t schema_migrations})
    f.puts "commit;"
  }
end

.load_database_schema!(cfg, file) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
# File 'lib/database_operations.rb', line 20

def self.load_database_schema!(cfg, file)
  pg(cfg, 'createdb') unless pg(cfg, "psql -l") =~ /^ #{cfg['database']}\s*\|/m

  Tempfile.open('initdb') do |f|
    f.puts "set client_min_messages=error;"
    f.flush
    pg(cfg, "psql -f #{f.path}")
  end

  pg cfg, %{psql -f "#{file}"}
end

.load_views_and_triggers!(env = Rails.env) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/database_operations.rb', line 45

def self.load_views_and_triggers!(env=Rails.env)
  cfg = ActiveRecord::Base.configurations[env]
  unless pg(cfg, "createlang -l") =~ /plpgsql/
    pg(cfg, "createlang plpgsql")
  end

  output = nil 

  Tempfile.open('load_views') do |temp|

    Dir.glob(Rails.root.join('lib', 'sql_erb', '[0-9]*.sql.erb')).sort_by { |f| ('0.%s' % File.split(f).last.gsub(/\D.*/,'')).to_f }.each do |fpath|
      temp.puts File.open(fpath){|io| ERB.new(io.read).result }
    end 
    temp.flush
    output = pg cfg, %{psql --single-transaction -f #{temp.path} }
  end 
  output
end

.pg(cfg, cmd, opts = {}) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# File 'lib/database_operations.rb', line 4

def self.pg(cfg, cmd, opts = {})
  ENV['PGPASSWORD'] = cfg["password"]

  args = []
  args << %{-h "#{cfg["host"]}"}     if cfg["host"]
  args << %{-U "#{cfg["username"]}"} if cfg["username"]
  args << %{-p "#{cfg["port"]}"}     if cfg["port"]
  args << %{-w}

  pipe = opts[:pipe] ? " | #{opts[:pipe]}" : ""

  %x{#{cmd} #{args.join(' ')} "#{cfg['database']}"#{pipe}}
ensure
  ENV.delete('PGPASSWORD')
end