LoginSignup
22
19

More than 5 years have passed since last update.

db:migrateの管理からridgepoleに移行する

Posted at

ridgepoleとは

winebarrel/ridgepole
DBスキーマを管理するgem。
これを使ってdb:migrateから卒業します!

導入手順

gemインストール

Gemfileに以下を追加して、bundle installします。

Gemfile
gem 'ridgepole'

現状のSchemaを吐き出す

今回は、すでにDBがあるので、現状のSchemaをファイルに吐き出します。
また、テーブルごとに別ファイルに切り出してほしかったので--splitオプションを指定しています。

$ bundle exec ridgepole -c config/database.yml -E development --split --export -o db/schemas/Schemafile
Export Schema
...

試しにさっき吐き出されたスキーマファイルでapplyしてみる。

$ bundle exec ridgepole -c config/database.yml -E development --apply -f db/schemas/Schemafile
Apply `db/schemas/Schemafile`
No change

No Change!まあ当たり前ですね。

あと、db/migrateにあるファイルは不要なので一括削除しておきます。

使い方などの詳細は以下をご覧ください :)
https://github.com/winebarrel/ridgepole#usage

capistranoでデプロイ時に実行する

gemインストール

執筆時点でver0.0.4ですが、自作するのも面倒なのでgemで対応します。(やってることはすごくシンプル)

Gemfile
gem 'capistrano3-ridgepole'

Capfileに記述

必要のないmigrationタスクもついでに削除しておきます。

Capfile
 require 'capistrano/bundler'
 require 'capistrano/rails/assets'
+require 'capistrano3/ridgepole'
-require 'capistrano/rails/migrations'
 require 'capistrano3/unicorn'

deployタスクを追加

capistrano3-ridgepole/lib/capistrano3/tasks/ridgepole.rake
...
  task :defaults do
    set :ridgepole_roles, -> { :db }
    set :ridgepole_schema_file, -> { File.join(current_path, "Schemafile") }
    set :ridgepole_config_file, -> { File.join(current_path, "config", "database.yml") }
    set :ridgepole_env, -> { fetch(:rails_env) || "development" }
    set :ridgepole_options, -> { "" }
    set :overwrite_migration_tasks, -> { false }
  end
...

初期値が上記のようになっているので、よしなに上書きしていきます。

config/deploy.rb
set :ridgepole_schema_file, File.join(current_path, 'db/schemas', 'Schemafile')
after 'deploy:publishing', 'ridgepole:apply'

タスクはwithin current_pathで実行されるので、applyのタイミングはcurrent_path上書き後のafter 'depoy:publishing'にします。

これで、capisrano deployしたときに一緒にapplyされます。

※ちなみにdb:migrateタスクはafter 'deploy:updated'のタイミングにwithin release_pathで実行されます。
参考:capistrano/tasks/migrations

導入後の流れ

  1. ローカルでdb/schemasにあるスキーマファイルを変更する
  2. ridgepole applyで変更内容をDBに適用する
  3. スキーマファイルをcommit, push, deployしてリモートに反映する

以上!

参考

22
19
2

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
22
19