Skip to content

Instantly share code, notes, and snippets.

@douglasjarquin
Created July 11, 2011 02:33
Show Gist options
  • Select an option

  • Save douglasjarquin/1075233 to your computer and use it in GitHub Desktop.

Select an option

Save douglasjarquin/1075233 to your computer and use it in GitHub Desktop.
Migrate a small database from one RDS instance to another
require 'fileutils'
start_time = Time.now
SOURCE_DATABASE = {
:name => '...',
:user => '...',
:password => '...',
:host => '...'
}
TARGET_DATABASE = {
:name => '...',
:user => '...',
:password => '...',
:host => '...'
}
DUMP_DIRECTORY = '/mnt/migrator'
def benchmark(label = nil)
puts label unless label.nil?
before = Time.now
yield
after = Time.now
puts "Took %.3fs" % (after - before)
end
def host_user_password(database)
"--host='#{database[:host]}' --user='#{database[:user]}' --password='#{database[:password]}'"
end
def dump_database_structure(database)
dump_file = "#{DUMP_DIRECTORY}/#{database[:name]}_structure.sql"
FileUtils.mkdir_p(DUMP_DIRECTORY, :mode => 0777)
benchmark("Dumping structure of #{database[:name]} to #{dump_file}") do
system "mysqldump --verbose --net_buffer_length=4096 --triggers --compress --no-data #{host_user_password(database)} #{database[:name]} > #{dump_file}"
end
end
def dump_database_data(database)
dump_file = "#{DUMP_DIRECTORY}/#{database[:name]}_data.sql"
benchmark("Dumping #{database[:name]} to #{dump_file}") do
system "mysqldump --verbose --net_buffer_length=4096 --order-by-primary --compress --single-transaction --no-create-info #{host_user_password(database)} #{database[:name]} > #{dump_file}"
end
end
def import_database_structure(source, target)
dump_file = "#{DUMP_DIRECTORY}/#{source[:name]}_structure.sql"
benchmark("Importing structure of #{source[:name]} from #{dump_file}") do
system "mysql #{host_user_password(target)} #{target[:name]} < #{dump_file}"
end
end
def import_database_data(source, target)
dump_file = "#{DUMP_DIRECTORY}/#{source[:name]}_data.sql"
benchmark("Importing tables from #{dump_file}") do
system "mysql #{host_user_password(target)} #{target[:name]} < #{dump_file}"
end
end
if ARGV.include?('--dump')
# Run the dumps
dump_database_structure(SOURCE_DATABASE)
dump_database_data(SOURCE_DATABASE)
elsif ARGV.include?('--import')
# Run the imports
import_database_structure(SOURCE_DATABASE, TARGET_DATABASE)
import_database_data(SOURCE_DATABASE, TARGET_DATABASE)
else
# Run it all
dump_database_structure(SOURCE_DATABASE)
dump_database_data(SOURCE_DATABASE)
import_database_structure(SOURCE_DATABASE, TARGET_DATABASE)
import_database_data(SOURCE_DATABASE, TARGET_DATABASE)
end
puts "Script ran for: %.3fs" % (Time.now - start_time)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment