はじめに
RailsでのDBスキーマ管理としてRidgepoleを勧められたため、触ってみました。
↓こちらの方の記事を参考にさせていただきました。
さらば「rails migrate」、よろしく「ridgepole」
導入
Gemfileに追記します。
Gemfile
gem 'ridgepole'
$ bundle install
今回使用するテーブル
class CreateItems < ActiveRecord::Migration[5.0]
def change
create_table :items do |t|
t.string :name
t.integer :price
t.text :description
t.timestamps
end
end
end
Schemafileの作成
そして、下記のコマンドでテーブルを分割します。
--export
コマンドで対象ディレクトリにSchemafile
を出力します。
$ ./bin/bundle exec ridgepole -c config/database.yml -E development --export --split --output db/schemas/Schemafile
Export Schema
write `db/schemas/items.schema`
write `db/schemas/Schemafile`
これで、各テーブルのスキーマファイルと大元のSchemafile
が作成されます。
Schemafile
require 'items.schema'
items.schema
create_table "items", force: :cascade do |t|
t.string "name"
t.integer "price"
t.text "description"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
インデックスを追加してみる
items.schema
create_table "items", force: :cascade do |t|
t.string "name"
t.integer "price"
t.text "description"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
+ add_index :items, :price
実行するためには、以下のコマンドを叩きます。
$ ./bin/bundle exec ridgepole -c config/database.yml -E development --apply -f db/schemas/Schemafile
Apply `db/schemas/Schemafile`
-- add_index("items", ["price"], {})
-> 0.0113s
これだけで、index_items_on_price
というインデックスが作成されました。
カラムを追加してみる
items.schema
create_table "items", force: :cascade do |t|
t.string "name"
t.integer "price"
t.text "description"
+ t.integer "category", null: false, default: 0
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index :items, :price
わざわざマイグレーションを作成しなくてもカラムが追加できました。
$ ./bin/bundle exec ridgepole -c config/database.yml -E development --apply -f db/schemas/Schemafile
Apply `db/schemas/Schemafile`
-- add_column("items", "category", :integer, {:null=>false, :default=>0, :after=>"description"})
-> 0.0151s
おわりに
これだけ簡単にテーブル構造が変えられるのは非常に楽だと思います。
はじめは、テーブル構造の変遷を追いづらくなるのかな、と思いましたが、それはソース管理すれば良いだけの話なので、そこまで問題にはならないかと思います。
もう少し機能や使い方、運用ルールなどを考えていきます。
公式ドキュメント:https://github.com/winebarrel/ridgepole