Skip to content

Instantly share code, notes, and snippets.

@dnch
Created March 27, 2009 00:44
Show Gist options
  • Save dnch/86470 to your computer and use it in GitHub Desktop.
Save dnch/86470 to your computer and use it in GitHub Desktop.
namespace :db do
desc "Migrate database from MySQL to PostgreSQL"
task :translate => :environment do
# how many are we going to do at a time (ie, how many per file?)
BATCH_SIZE = 10_000
# what tables are we dumping?
$tables_to_ignore = ['schema_migrations', 'sessions']
$tables_to_dump = ActiveRecord::Base.connection.tables.sort - $tables_to_ignore
# mwuahahah.
module PostgresModels
$tables_to_dump.each do |table|
class_eval "class #{table.classify} < ActiveRecord::Base ; establish_connection({ :adapter => 'postgresql', :database => 'fullcircle_development', :username => 'rails', :password => 'rails', :host => 'localhost' }) ; end"
end
end
# right, let's go through them all...
$tables_to_dump.each do |table|
# set up our source class
klass = table.classify.constantize
postgres_klass = eval("PostgresModels::#{klass}")
# empty our target table
postgres_klass.connection.execute "TRUNCATE #{table}"
# start tracking (nice ui!)
batch_index = 1
count_for_klass = klass.count
estimated_batches_for_klass = (count_for_klass / BATCH_SIZE) + 1
klass.find_in_batches(:batch_size => BATCH_SIZE) do |batch|
puts "Writing #{table} batch #{batch_index} of #{estimated_batches_for_klass}"
# the magic!
batch.each do |r|
attrs = r.attributes_before_type_cast
n = postgres_klass.new(attrs)
n.id = r.id
n.save
end
batch_index = batch_index + 1
end
puts "Count for #{klass} (old -- new): #{klass.count} -- #{postgres_klass.count}"
puts "MaxId for #{klass} (old -- new): #{klass.last.id} -- #{postgres_klass.last.id}"
end
puts "All imported."
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment