How to use Rake for backing up MySQL databases
Ruby posted 10 months ago by christian
This is a customized version of this script:
1 require 'find' 2 3 namespace :db do 4 5 desc "Backup the database to a file. Options: DIR=base_dir RAILS_ENV=production MAX=20" 6 7 task :backup => [:environment] do 8 datestamp = Time.now.strftime("%Y-%m-%d_%H-%M-%S") 9 base_path = ENV["DIR"] || "db" 10 backup_base = File.join(base_path, 'backup') 11 backup_folder = File.join(backup_base, datestamp) 12 backup_file = File.join(backup_folder, "#{RAILS_ENV}_dump.sql.gz") 13 FileUtils.mkdir_p(backup_folder) 14 db_config = ActiveRecord::Base.configurations[RAILS_ENV] 15 pass = '' 16 pass = '-p' + db_config['password'] if db_config['password'] 17 cmd = "mysqldump -P #{db_config['port']} -h #{db_config['host']} -u #{db_config['username']} #{pass} #{db_config['da 18 tabase']} -Q --add-drop-table -O add-locks=FALSE -O lock-tables=FALSE | gzip -c > #{backup_file}" 19 sh cmd 20 dir = Dir.new(backup_base) 21 all_backups = dir.entries[2..-1].sort.reverse 22 puts "Created backup: #{backup_file}" 23 max_backups = (ENV["MAX"] || 20).to_i 24 puts max_backups 25 unwanted_backups = all_backups[max_backups..-1] || [] 26 for unwanted_backup in unwanted_backups 27 FileUtils.rm_rf(File.join(backup_base, unwanted_backup)) 28 puts "deleted #{unwanted_backup}" 29 end 30 puts "Deleted #{unwanted_backups.length} backups, #{all_backups.length - unwanted_backups.length} backups available" 31 32 end 33 34 end
Bootstraping your database with rake
Ruby posted about 1 year ago by christian
In lib/tasks/app.rake:
1 namespace :db do 2 desc "Bootstraps the database" 3 task :bootstrap => ['db:schema:load'] do 4 5 { 'Ruby' => 'ruby', 6 'JavaScript' => 'javascript', 7 }.each do |name, short_name| 8 Category.create!(:name => name, :short_name => short_name) 9 end 10 11 end 12 end