Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save crofty/143129 to your computer and use it in GitHub Desktop.
Save crofty/143129 to your computer and use it in GitHub Desktop.
Capistrano task for mysql refresh
# Capistrano task for refreshing local db
require 'yaml'
desc "Copy the remote production database to the local development database"
task :backup, :roles => :db, :only => { :primary => true } do
filename = "#{application}.dump.#{Time.now.to_i}.sql.bz2"
file = "/tmp/#{filename}"
on_rollback { delete file }
get "#{current_path}/config/database.yml", "tmp/prod_database.yml"
db = YAML::load(ERB.new(IO.read('tmp/prod_database.yml')).result)['production']
run "mysqldump --add-drop-database -u #{db['username']} --password=#{db['password']} #{db['database']} | bzip2 -c > #{file}" do |ch, stream, out|
puts out
end
`mkdir -p #{File.dirname(__FILE__)}/../db/backups/`
get file, "db/backups/#{filename}"
run "rm #{file}"
File.delete('tmp/prod_database.yml')
end
desc "Copy the latest backup to the local development database"
task :import_backup do
filename = `ls -tr backups | tail -n 1`.chomp
if filename.empty?
logger.important "No backups found"
else
ddb = YAML::load(ERB.new(IO.read(File.join(File.dirname(__FILE__), 'database.yml'))).result)['development']
logger.debug "Loading backups/#{filename} into local development database"
`bzip2 -cd backups/#{filename} | mysql -u #{ddb['username']} --password=#{ddb['password']} #{ddb['database']}`
logger.debug "command finished"
end
end
desc "Backup the remote production database and import it to the local development database"
task :backup_and_import do
backup
import_backup
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment