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



30
31
32
33
34
35
36
37
38
39
40
# File 'lib/database_operations.rb', line 30

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;"
    f.write pg(cfg, %{pg_dump -s})
    f.write pg(cfg, %{pg_dump -a -t schema_migrations})
    f.puts "commit;"
  }
end

.load_database_schema!(cfg, file) ⇒ Object



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

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



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

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) ⇒ Object



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

def self.pg(cfg, cmd)
  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}

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