Skip to content

Instantly share code, notes, and snippets.

@siong1987
Created July 29, 2012 08:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save siong1987/3196693 to your computer and use it in GitHub Desktop.
Save siong1987/3196693 to your computer and use it in GitHub Desktop.
copy db from mongo
namespace :db do
namespace :copy do
def get_mongohq_url(env)
"mongohq_url"
end
def parse_mongodb_url(url)
uri = URI.parse(url)
[ uri, uri.path.gsub("/", "") ]
end
namespace :production do
desc "Copy production data to local"
task :to_local => :environment do
Rake::Task["db:copy:copyDatabase"].execute({ from: get_mongohq_url(:production), to: "mongodb://localhost:27017/name_development" })
end
end
desc "MongoDB database to database copy"
task :copyDatabase, [:from, :to] => :environment do |t, args|
from, from_db_name = parse_mongodb_url(args[:from])
to, to_db_name = parse_mongodb_url(args[:to])
# mongodump
tmp_db_dir = File.join(Dir.tmpdir, 'db/' + from.host + "_" + from.port.to_s)
tmp_db_name_dir = File.join(tmp_db_dir, from_db_name)
FileUtils.rm_rf tmp_db_name_dir if File.directory? tmp_db_name_dir
system "mongodump -h %s:%s -d %s -u %s -p%s -o %s" % [ from.host, from.port, from_db_name, from.user, from.password, tmp_db_dir ]
puts "[#{Time.now}] connecting to #{to_db_name} on #{to.host}:#{to.port} as #{to.user}"
# clear target database
to_conn = Mongo::Connection.new(to.host, to.port)
puts "[#{Time.now}] opening #{to_db_name} on #{to.host}:#{to.port}"
puts "[#{Time.now}] dropping collections in #{to_db_name} on #{to.host}:#{to.port}"
to_db = to_conn.db(to_db_name)
to_db.authenticate(to.user, to.password) unless (to.user.nil? || to.user.blank?)
to_db.collections.select { |c| c.name !~ /system/ }.each do |c|
puts " [#{Time.now}] dropping #{c.name}"
c.drop
end
# mongorestore
if to.user.nil?
system "mongorestore -h %s:%s -d %s %s" % [ to.host, to.port, to_db_name, tmp_db_name_dir ]
else
system "mongorestore -h %s:%s -d %s -u %s -p%s %s" % [ to.host, to.port, to_db_name, to.user, to.password, tmp_db_name_dir ]
end
puts "[#{Time.now}] db:copy complete"
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment