Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Directly copied from eycap-0.5.2 (thanks!)
- #
- # With these tasks you can:
- # - dump your production database and save it in shared_path/db_backups
- # - dump your production into your local database (clone_to_local)
- #
- # Tested and fixed by fjguzman
- # migrated to capistrano 3 by bjelline
- namespace :db do
- task :backup_name do
- on roles(:db), primary: true do
- execute "mkdir -p #{shared_path}/db_backups"
- backup_time = Time.now.strftime('%Y-%m-%d--%H-%M-%S')
- set :backup_file, "#{shared_path}/db_backups/#{backup_time}-dump.sql"
- end
- end
- desc 'Backup your MySQL or PostgreSQL database to shared_path+/db_backups'
- task :dump do
- on roles(:db), primary: true do
- invoke 'db:backup_name'
- rails_env = fetch(:stage).to_s
- data = capture("cat #{shared_path}/config/database.yml")
- environment_info = YAML.safe_load(data)[rails_env]
- dbuser = environment_info['username']
- dbpass = environment_info['password']
- environment_database = environment_info['database']
- adapter = environment_info['adapter']
- dbhost = environment_info['host']
- pipe = "| bzip2 -c > #{fetch(:backup_file)}.bz2"
- if adapter == 'mysql2'
- cmd = "mysqldump --add-drop-table -u #{dbuser} -h #{dbhost} -p #{environment_database} #{pipe}"
- execute(cmd, interaction_handler: { /Enter password/ => "#{dbpass}\n" })
- elsif adapter == 'pg'
- cmd = "pg_dump -W -c -U #{dbuser} -h #{dbhost} #{environment_database} #{pipe}"
- execute(cmd, interaction_handler: { /Password/ => "#{dbpass}\n" })
- else
- execute "echo \"I don't know how to dump your database adapter=#{adapter}\""
- end
- end
- end
- desc 'Sync your production database to your local workstation'
- task :clone_to_local do
- on roles(:db), primary: true do
- invoke 'db:dump'
- remote_file = fetch(:backup_file)
- filename = Pathname.new(remote_file).basename
- execute "echo \"Will download #{remote_file}.bz2 to #{filename}.bz2\""
- download! "#{remote_file}.bz2", "/tmp/#{filename}.bz2"
- info = YAML.load_file('config/database.yml')['development']
- pipe = "bzcat /tmp/#{filename}.bz2 | "
- if info['adapter'] == 'mysql2'
- cmd = "#{pipe} mysql -u #{info['username']} -h #{info['host']} #{info['database']}"
- run_locally do
- execute(cmd, interaction_handler: { /Enter password/ => "#{info['password']}\n" })
- end
- elsif adapter == 'pg'
- cmd = "#{pipe} psql -U #{info['username']} -h #{info['host']} #{info['database']}"
- run_locally do
- execute(cmd, interaction_handler: { /Password/ => "#{info['password']}\n" })
- end
- else
- execute "echo \"I don't know how to load dump for database adapter=#{adapter}\""
- end
- end
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement