Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- namespace :db do
- namespace :data do
- desc "Dump data into sql script file: filename=[target filename]"
- task :dump => 'environment' do
- environment = (ENV.include?("RAILS_ENV")) ? (ENV["RAILS_ENV"]) : 'development'
- ENV["RAILS_ENV"] = Rails.env = environment
- database = Rails.configuration.database_configuration[Rails.env]["database"]
- user = Rails.configuration.database_configuration[Rails.env]["username"]
- password = Rails.configuration.database_configuration[Rails.env]["password"]
- filename = (ENV.include?("FILENAME")) ? (ENV["FILENAME"]) : database
- timestamp = ENV['TIMESTAMP'] ? bool(ENV['TIMESTAMP']) : true
- file_suffix = DateTime.now.strftime('%Y%m%d_%H_%M_%S')
- full_filename = filename + (timestamp ? "_#{file_suffix}" : '') + '.sql'
- puts "Connecting to #{environment} environment..."
- sh "mysqldump -u#{user} -p#{password} #{database} --skip-triggers --compact " +
- "> #{Rails.root}/db/data/#{full_filename}"
- puts "Successfully created #{full_filename} from #{environment} environment."
- end
- desc "Load data from sql script file: filename=[data file]"
- task :load => 'environment' do
- environment = (ENV.include?("RAILS_ENV")) ? (ENV["RAILS_ENV"]) : 'development'
- ENV["RAILS_ENV"] = Rails.env = environment
- database = Rails.configuration.database_configuration[Rails.env]["database"]
- user = Rails.configuration.database_configuration[Rails.env]["username"]
- password = Rails.configuration.database_configuration[Rails.env]["password"]
- filename = ENV['FILENAME']
- raise "Please specify a source file (FILENAME=[source.sql])" if filename.blank?
- puts "Connecting to #{environment}..."
- ActiveRecord::Base.establish_connection(Rails.env.to_sym)
- puts "Dropping tables..."
- ActiveRecord::Base.connection.execute('show tables').each do |table|
- puts " Dropping #{table[0]}"
- ActiveRecord::Base.connection.execute("drop table #{table[0]}")
- end
- puts "Importing data from #{filename}..."
- sh "mysql -u#{user} -p#{password} #{database} < #{Rails.root}/db/data/#{filename}"
- puts "Completed loading #{filename} into #{environment} environment."
- end
- end
- end
- private
- def bool(s)
- s.match(/(true|t|yes|y|1)$/i) != nil
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement