-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathBackupDatabase-Recipe.rb
More file actions
48 lines (39 loc) · 1.62 KB
/
BackupDatabase-Recipe.rb
File metadata and controls
48 lines (39 loc) · 1.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
require 'mkmf'
_cset(:mysqldump_bin) { "/usr/bin/env mysqldump" }
_cset(:mysql_bin) { "/usr/bin/env mysql" }
_cset(:app_path) { "" }
# http://stackoverflow.com/questions/1661586/how-can-you-check-to-see-if-a-file-exists-on-the-remote-server-in-capistrano
def remote_file_exists?(full_path)
'true' == capture("if [ -e #{full_path} ]; then echo 'true'; fi").strip
end
namespace :database do
desc <<-DESC
Generate a backup for database project.
DESC
task :backup, :roles => :db, :only => { :primary => true } do
filename = "#{application}.dump.sql.gz"
file = "/tmp/#{filename}"
on_rollback { delete file }
unless exists?(:db_credentials)
raise("Cannot access database for #{application}")
end
logger.info("Dumping database")
run "#{mysqldump_bin} --add-drop-table --extended-insert --force -u #{db_credentials["username"]} --password='#{db_credentials["password"]}' #{db_credentials["dbname"]} -h #{db_credentials["host"]} | gzip > #{file}" do |ch, stream, data|
puts data
end
run "mv #{file} #{current_release}#{app_path}/#{filename}"
end
desc <<-DESC
Revert a database thanks to database backup
DESC
task :revert do
database_dump = "#{previous_release}#{app_path}/#{application}.dump.sql.gz"
unless remote_file_exists?(database_dump)
raise("No database backup found")
end
unless exists?(:db_credentials)
raise("Cannot access database for #{application}")
end
run "zcat #{database_dump} | #{mysql_bin} -u #{db_credentials["username"]} --password='#{db_credentials["password"]}' #{db_credentials["dbname"]} -h #{db_credentials["host"]}"
end
end