Rails以外でもDBのスキーマ管理にMigrationが使えるStandaloneMigration

2012-02-08


RailsのMigrationの機能便利ですよね。 他の言語やレガシーコードなフレームワークを使っていると、このMigrationの機能だけでも使いたいと思うことがよくあります。

それを可能にしてくれるStandaloneMigrationというgemがあるようで試してみました。

Ruby1.9.2を使っています。

インストール手順

プロジェクトディレクトリ作成

mkdir hoge
cd hoge

Rakefileを作成し、以下を記述

begin
  require 'tasks/standalone_migrations'
rescue LoadError => e
  puts "gem install standalone_migrations to get db:migrate:* tasks! (Error: #{e})"
end

bundlerを使ってgemを管理するためbundlerをインストール

gem install bundler

Gemfileを作成し、以下を記述。

source 'http://rubygems.org'
#MySQLを使う場合
gem 'mysql2'

group :development, :test do
  gem 'standalone_migrations'
end
bundle install

db/config.ymlを作成

development:
   adapter: mysql2
   encoding: utf8
   reconnect: false
   database: hoge_development
   pool: 5
   username: hoge
   password: hogepass
   host: localhost

test:
   adapter: mysql2
   encoding: utf8
   reconnect: false
   database: hoge_test
   pool: 5
   username: hoge
   password: hogepass
   host: localhost

production:
   adapter: mysql2
   encoding: utf8
   reconnect: false
   database: hoge_production
   pool: 5
   username: hoge
   password: hogepass
   host: localhost

gem listするとGemfileに記述したgemがインストールされていることが確認できます。 また、rake -Tすると使用できるタスクの一覧が表示されます。

マイグレーションの作成

GithubのREADMEにはRailsのscaffoldのようなタスク rake db:generate model=”model_name” fields=”type:column_name0 type:column_name1 . があると書いてありますが、手元の環境では動作せず…

以下のコマンドでマイグレーションファイルの雛形を作ってやって自分で編集します。

rake db:new_migration name=CreatePerson

db/migrate/20120208022132_create_person.rbが作成されました。 中身はRails2でおなじみのマイグレーションファイルそのもの。

Rails3のようなchangeメソッド1つだけあるのではなくRails2ライクにself.upself.downの2つのメソッドが定義されている形であることに注意。 ロールバックできるようにself.downメソッド内も記述しておくのが吉。

class Createperson < ActiveRecord::Migration
  def self.up
    create_table :Person do |t|
      t.string :first_name
      t.string :last_name
      t.integer :age
      t.timestamps
    end
  end

  def self.down
    drop_table :Person
  end
end
rake db:migrate

最後に

rake -Tで表示されるように

rake db:create          # Create the database from config/database.yml for the current Rails.en...
rake db:drop            # Drops the database for the current Rails.env (use db:drop:all to drop...
rake db:fixtures:load   # Load fixtures into the current environment's database.
rake db:migrate         # Migrate the database (options: VERSION=x, VERBOSE=false).
rake db:migrate:status  # Display status of migrations
rake db:new_migration   # Create a new migration
rake db:rollback        # Rolls the schema back to the previous version (specify steps w/ STEP=n).
rake db:schema:dump     # Create a db/schema.rb file that can be portably used against any DB s...
rake db:schema:load     # Load a schema.rb file into the database
rake db:seed            # Load the seed data from db/seeds.rb
rake db:setup           # Create the database, load the schema, and initialize with the seed da...
rake db:structure:dump  # Dump the database structure to db/structure.sql. Specify another file...
rake db:version

などのタスクが用意されています。 rake db:rollbackでロールバックも可能です。

  • 他の環境へ変更を反映
  • 以前のバージョンへロールバック
  • 複数のデータベースへの対応が簡単(MySQL、PostgreSQL、Oracle、SQLite…)

などいろんなメリットがありそう。 絶賛開発途上ぽいのがアレなんですが…

おしまい。


Profile picture of sakama

Written by sakama Data engineer who lives and works in Tokyo for successful data analytics You can follow me on Twitter

© 2022, sakama.dev - Built with Gatsby

Author

Profile picture of sakama

Written by sakama Data engineer who lives and works in Tokyo for successful data analytics You can follow me on Twitter

Socials

github.com/sakama

Recent Posts

Categories

Tags