LoginSignup
11
11

More than 5 years have passed since last update.

Railsでmysqlをdump、reset、restoreするRakeタスク

Last updated at Posted at 2018-06-11

やりたいこと

以下の処理を行うRakeコマンドを作る。
1. mysqlのデータをダンプする。
2. rails db:migrate:resetでスキーマを初期化する。
3. 1でダンプしたデータをリストアする。

ソースコード

lib/tasks/db.rake
namespace :db do
  desc 'Dump the database to tmp/dbname.dump'
  task dump: %i[environment load_config] do
    config = ActiveRecord::Base.configurations[Rails.env]
    ignore_table_option = %w[ar_internal_metadata schema_migrations].map { |table| "--ignore-table=#{config['database']}.#{table}" }.join(' ')
    sh "mysqldump -u #{config['username']} -p#{config['password']} #{config['database']} --no-create-info #{ignore_table_option} > tmp/#{config['database']}.dump"
  end

  desc 'Restore the database from tmp/dbname.dump'
  task restore: %i[environment load_config] do
    config = ActiveRecord::Base.configurations[Rails.env]
    sh "mysql -u #{config['username']} -p#{config['password']} #{config['database']} < tmp/#{config['database']}.dump"
  end

  desc 'Dump and reset and restore'
  task dump_reset_restore: %i[environment load_config] do
    Rake::Task['db:dump'].invoke
    Rake::Task['db:migrate:reset'].invoke
    Rake::Task['db:restore'].invoke
  end
end

使い方

rails db:dump_reset_restore

参考

11
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
11