Great Sunday. I just finished backing up data of two of my sites. This blog site of mine is using Sinatra DSL which is an alternative to Ruby on Rails framework. Another site of mine runs in Drupal 6. I was able to successfully local production database for both without using PHPMYADMIN. It's all done via command line. For me, it was a time-saver.

I just want to share a few more Capistrano tips for non-Rails developers. Capistrano is a powerful tool especially for those Unix-savvy people. But for alpha geeks like me, I am comfortable just knowing how to do basic administration tasks.

Please find time to read this post if you are new to Capistrano and you are a PHP developer.

On my Drupal site, this is how the Capfile looks like:

desc "Load production data into development database"
task :importdb do

  filename = "dump.#{ '%Y-%m-%d_%H:%M:%S'}.sql"
  dbuser = "yourusername"
  dbhost = "yourhostname"
  dbpassword = "yourpassword"
  application_db = "yourdatabasename"
  local_db_host = "localhost"
  local_db_user = "local_user_name"
  local_db_password = "local_password"
  local_db = "localdatabasename"

  on_rollback do
    delete "/tmp/#{filename}"
    delete "/tmp/#{filename}.gz"

  cmd = "mysqldump --opt --compress -u #{dbuser} --password=#{dbpassword} 
   --host=#{dbhost} #{application_db} > /tmp/#{filename}"
  puts "Dumping remote database"
  run(cmd) do |channel, stream, data|
    puts data

  # compress the file on the server
  puts "Compressing remote data"
  run "gzip -9 /tmp/#{filename}"
  puts "Fetching remote data"
  get "/tmp/#{filename}.gz", "dump.sql.gz"

  # build the import command
  # no --password= needed if password is nil.
  if local_db_password.nil?
    cmd = "mysql -u #{local_db_user} #{local_db} < dump.sql"
    cmd = "mysql -u #{local_db_user} --password=#{local_db_password} 
    #{local_db} < dump.sql"

  # unzip the file. Can't use exec() for some reason so backticks will do
  puts "Uncompressing dump"
  `gzip -d dump.sql.gz`
  puts "Executing : #{cmd}"
  puts "Cleaning up"
  `rm -f dump.sql`


Running "cap importdb" will load the database from production server onto your development database. These would all work smoothly if you're running on a Unix OS like Mac OS or Ubuntu Linux.

Download the gist.

comments powered byDisqus

Hello! I am Kat. I've been a developer for several years. When I'm not sitting down, reading and working for long hours, I am traveling to some place of interest.
If you want to reach out, you can send me an email or add me up on Google Plus.