rake task
Ruby
code posted
created at 30 Mar 17:13
Edit
|
Back
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 |
#= encoding: utf-8 namespace :db do desc "Backup the database to a file. Options: DIR=base_dir RAILS_ENV=production MAX=20" task :backup => [:environment] do datestamp = Time.now.strftime("%Y-%m-%d_%H-%M-%S") base_path = ENV["DIR"] || "db" backup_base = File.join(base_path, 'backup') backup_folder = File.join(backup_base, datestamp) backup_file = File.join(backup_folder, "#{RAILS_ENV}_dump.sql.gz") FileUtils.mkdir_p(backup_folder) db_config = ActiveRecord::Base.configurations[RAILS_ENV] pass = '' pass = '-p' + db_config['password'] if db_config['password'] sh "mysqldump -u #{db_config['username']} #{pass} #{db_config['database']} -Q --add-drop-table=true --add-locks=FALSE --lock-tables=FALSE | gzip -c > #{backup_file}" dir = Dir.new(backup_base) all_backups = dir.entries[2..-1].sort.reverse puts "Created backup: #{backup_file}" max_backups = (ENV["MAX"] || 20).to_i unwanted_backups = all_backups[max_backups..-1] || [] for unwanted_backup in unwanted_backups FileUtils.rm_rf(File.join(backup_base, unwanted_backup)) puts "deleted #{unwanted_backup}" end puts "Deleted #{unwanted_backups.length} backups, #{all_backups.length - unwanted_backups.length} backups available" end task :restore => [:environment] do base_path = ENV["DIR"] || "db" backup_base = File.join(base_path, 'backup') dir = Dir.new(backup_base) all_backups = dir.entries[2..-1].sort.reverse last_backup_dir = File.join(backup_base,all_backups[0]) last_backup=Dir.new(last_backup_dir).entries[2..-1] backup= File.join(last_backup_dir,"#{RAILS_ENV}_dump.sql.gz") if File.exist?( backup) puts "Restore #{backup}" db_config = ActiveRecord::Base.configurations[RAILS_ENV] pass = '' pass = '-p' + db_config['password'] if db_config['password'] cmd_str="gunzip < #{backup} | mysql -u #{db_config['username']} #{pass} #{db_config['database']}" puts cmd_str else puts "Backup file <#{backup}> not found" end end end |
2.08 KB in 4 ms with coderay