Guest User

Untitled

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