Advertisement
Guest User

Untitled

a guest
Feb 14th, 2017
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.38 KB | None | 0 0
  1. namespace :db do
  2. namespace :data do
  3. desc "Dump data into sql script file: filename=[target filename]"
  4. task :dump => 'environment' do
  5. environment = (ENV.include?("RAILS_ENV")) ? (ENV["RAILS_ENV"]) : 'development'
  6. ENV["RAILS_ENV"] = RAILS_ENV = environment
  7.  
  8. database = get_database(environment)
  9. user = database
  10. password = ENV['PASSWORD']
  11. filename = ENV['FILENAME'] || environment
  12. timestamp = ENV['TIMESTAMP'] ? bool(ENV['TIMESTAMP']) : true
  13. file_suffix = DateTime.now.strftime('%Y-%m-%d-%H-%M-%S')
  14.  
  15. full_filename = filename + (timestamp ? "_#{file_suffix}" : '') + '.sql'
  16.  
  17. puts "Connecting to #{environment} environment..."
  18. sh "mysqldump -u#{user} -p#{password} #{database} --skip-triggers --compact " +
  19. "--ignore-table=#{database}.schema_migrations " +
  20. "--no-create-info > #{RAILS_ROOT}/db/data/#{full_filename}"
  21.  
  22. puts "Successfully created #{full_filename} from #{environment} environment."
  23. end
  24.  
  25. desc "Load data from sql script file: filename=[data file]"
  26. task :load => 'environment' do
  27. environment = (ENV.include?("RAILS_ENV")) ? (ENV["RAILS_ENV"]) : 'development'
  28. ENV["RAILS_ENV"] = RAILS_ENV = environment
  29.  
  30. database = get_database(environment)
  31. user = database
  32. password = ENV['PASSWORD']
  33. filename = ENV['FILENAME']
  34. raise "Please specify a source file (FILENAME=[source.sql])" if filename.blank?
  35.  
  36. puts "Connecting to #{environment}..."
  37. ActiveRecord::Base.establish_connection(RAILS_ENV.to_sym)
  38.  
  39. puts "Truncating tables..."
  40. ActiveRecord::Base.connection.execute('show tables').each do |table|
  41. unless table.to_s == 'schema_migrations'
  42. puts " Truncating #{table}"
  43. ActiveRecord::Base.connection.execute("truncate table #{table.to_s}")
  44. end
  45. end
  46.  
  47. puts "Importing data from #{filename}..."
  48. sh "mysql -u#{user} -p#{password} #{database} < #{RAILS_ROOT}/#{filename}"
  49. puts "Completed loading #{filename} into #{environment} environment."
  50. end
  51. end
  52. end
  53.  
  54. private
  55. def get_database(environment)
  56. case environment
  57. when 'test'
  58. raise 'add your TEST db name'
  59. when 'staging'
  60. raise 'add your STAGING db name'
  61. when 'production'
  62. raise 'add your PRODUCTION db name'
  63. else
  64. raise 'add your DEVELOPMENT db name'
  65. end
  66. end
  67.  
  68. def bool(s)
  69. s.match(/(true|t|yes|y|1)$/i) != nil
  70. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement