Guest User

Untitled

a guest
Jun 29th, 2018
164
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.55 KB | None | 0 0
  1. def copy_template_database
  2. template_name = "customerdb1" # Database to copy from
  3. new_name = "temp" #database to create & copy to
  4.  
  5. #connect to template database to copy. Note that this will override any previous
  6. #connections for all Models that inherit from ActiveRecord::Base
  7. ActiveRecord::Base.establish_connection({:adapter => "mysql", :database => template_name, :host => "olddev",
  8. :username => "root", :password => "password" })
  9.  
  10. sql_connection = ActiveRecord::Base.connection
  11. sql_connection.execute("CREATE DATABASE #{new_name} CHARACTER SET latin1 COLLATE latin1_general_ci")
  12. tables = sql_connection.select_all("Show Tables")
  13. #the results are an array of hashes, ie:
  14. # [{"table_from_customerdb1" => "customers"},{"table_from_customerdb1" => "employees},...]
  15. table_names = Array.new
  16. tables.each { |hash| hash.each_value { |name| table_names << name }}
  17.  
  18. table_names.each { |name|
  19. sql_connection.execute("CREATE TABLE #{new_name}.#{name} LIKE #{template_name}.#{name}")
  20. sql_connection.execute("INSERT INTO #{new_name}.#{name} SELECT * FROM #{template_name}.#{name}")
  21. }
  22. #This statement is optional. It connects ActiveRecord to the new database
  23. ActiveRecord::Base.establish_connection({:adapter => "mysql", :database => new_name, :host => "olddev",
  24. :username => "root", :password => "password" })
  25. end
  26.  
  27. > mysqldump -uroot -proot templateDB > dump.sql
  28. > mysql -uroot -proot --execute="CREATE DATABASE newDB"
  29. > mysql -uroot -proot newDB < dump.sql
Add Comment
Please, Sign In to add comment