Guest User

Untitled

a guest
Mar 4th, 2018
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.81 KB | None | 0 0
  1. namespace :db do
  2. desc "Migrate database from MySQL to PostgreSQL"
  3. task :translate => :environment do
  4.  
  5. # how many are we going to do at a time (ie, how many per file?)
  6. BATCH_SIZE = 10_000
  7.  
  8. # what tables are we dumping?
  9. $tables_to_ignore = ['schema_migrations', 'sessions']
  10. $tables_to_dump = ActiveRecord::Base.connection.tables.sort - $tables_to_ignore
  11.  
  12. # mwuahahah.
  13. module PostgresModels
  14. $tables_to_dump.each do |table|
  15. class_eval "class #{table.classify} < ActiveRecord::Base ; establish_connection({ :adapter => 'postgresql', :database => 'fullcircle_development', :username => 'rails', :password => 'rails', :host => 'localhost' }) ; end"
  16. end
  17. end
  18.  
  19. # right, let's go through them all...
  20. $tables_to_dump.each do |table|
  21.  
  22. # set up our source class
  23. klass = table.classify.constantize
  24. postgres_klass = eval("PostgresModels::#{klass}")
  25.  
  26. # empty our target table
  27. postgres_klass.connection.execute "TRUNCATE #{table}"
  28.  
  29. # start tracking (nice ui!)
  30. batch_index = 1
  31. count_for_klass = klass.count
  32. estimated_batches_for_klass = (count_for_klass / BATCH_SIZE) + 1
  33.  
  34. klass.find_in_batches(:batch_size => BATCH_SIZE) do |batch|
  35. puts "Writing #{table} batch #{batch_index} of #{estimated_batches_for_klass}"
  36.  
  37. # the magic!
  38. batch.each do |r|
  39. attrs = r.attributes_before_type_cast
  40.  
  41. n = postgres_klass.new(attrs)
  42. n.id = r.id
  43. n.save
  44. end
  45.  
  46. batch_index = batch_index + 1
  47. end
  48.  
  49. puts "Count for #{klass} (old -- new): #{klass.count} -- #{postgres_klass.count}"
  50. puts "MaxId for #{klass} (old -- new): #{klass.last.id} -- #{postgres_klass.last.id}"
  51. end
  52.  
  53. puts "All imported."
  54. end
  55. end
Add Comment
Please, Sign In to add comment