Last active
July 5, 2023 14:15
-
-
Save iberianpig/856ab2cf2ee05f1ea564 to your computer and use it in GitHub Desktop.
lib/tasks/db.rake (mysql_dump/mysql_restore/dump_seed_fu) using ActiveRecord configuration
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # ./lib/tasks/db.rake | |
| require 'active_record' | |
| @logger = Logger.new(STDOUT) | |
| namespace :db do | |
| desc "Dumps the database to tmp/dbname.dump" | |
| task mysql_dump: [:environment, :load_config] do | |
| environment = Rails.env | |
| configuration = ActiveRecord::Base.configurations[environment] | |
| cmd = <<~COMMAND | |
| mysqldump \ | |
| -u#{configuration[:username]} \ | |
| -h#{configuration[:host]} \ | |
| -p#{configuration[:password]} \ | |
| #{configuration[:database]} \ | |
| > tmp/#{configuration[:database]}_#{DateTime.current.to_datetime.to_s.gsub(/\:|\+|-| /, '')}.sql | |
| COMMAND | |
| @logger.info cmd | |
| exec cmd | |
| end | |
| desc "restore the database from tmp/dbname.dump" | |
| task :mysql_restore, [:filepath] => [:environment, :load_config] do |_t, args| | |
| environment = Rails.env | |
| configuration = ActiveRecord::Base.configurations[environment] | |
| filepath = args.filepath | |
| cmd = <<~COMMAND | |
| mysql \ | |
| -u#{configuration[:username]} \ | |
| -h#{configuration[:host]} \ | |
| -p#{configuration[:password]} \ | |
| #{configuration[:database]} \ | |
| < #{filepath}" | |
| COMMAND | |
| @logger.info cmd | |
| exec cmd | |
| end | |
| desc "Make seed data importable with seed_fu" | |
| task :dump_seed_fu, [:model] => :environment do |_t, args| | |
| model_name = args.model.underscore | |
| class_name = args.model.camelize | |
| SeedFu::Writer.write("db/fixtures/#{model_name.pluralize}.rb", class_name: class_name.to_s) do |writer| | |
| Object.const_get(class_name.to_s).order(:id).find_each do |m| | |
| attributes = m.attributes | |
| attributes.each do |k, v| | |
| # NOTE: avoid import error with default TimeWithZone format | |
| next unless v.class == ActiveSupport::TimeWithZone | |
| attributes[k] = v.to_s | |
| end | |
| @logger.info attributes | |
| writer << attributes | |
| end | |
| end | |
| @logger.info "create db/fixtures/#{model_name.pluralize}.rb" | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment