Standalone Migrations: Using Rails migrations in non Rails projects

Update 7/8/2009: With the latest batch of user submitted patches standalone migrations now works just like Rails migrations
Update 12/26/2008: I switched standalone migrations to use a Rakefile instead of a Ruby script.

Standalone MigrationsIn my work managing websites I end up working in Ruby, Java, and PHP. In everything but Rails managing the schema requires rolling your own solution. As a result I’ve started using Rails migrations in non-Rails projects to manage the schema. It’s not much code but I figured others might benefit from it so I created a little Github project called standalone migrations.

It’s based on Lincoln Stoll’s blog post titled Stand-alone ActiveRecord migrations and David Welton’s blog post titled Using Migrations Outside of Rails.

Assuming you have Ruby and Gem installed on your machine, here’s how to use it:

gem install -y activerecord rake mysql
wget http://github.com/thuss/standalone-migrations/zipball/master (or fetch it using git)
unzip it, and mv to something like my_non_rails_project/db
cd my_non_rails_project/db/ (or wherever you put it)
cp config/database_sample.yml config/database.yml
vi config/database.yml
./new_migration some_user_story
vi migrations/*_some_user_story.rb
rake db:migrate (this applies your newly created migration)

3 Responses to “Standalone Migrations: Using Rails migrations in non Rails projects”

  1. BryonB says:

    Todd, there doesn’t seem to be any config/database_sample.yml file in the GitHub project when I download it. Are there any differences between the database.yml file here and one in a standard rails project? Can you still define different environments (development, production, etc.)? If so, where do you define them?

  2. BryonB says:

    I wanted to be able to specify different environments in the database.yml file like I can in Rails, so I modifed the :ar_init task in the Rakefile as follows:

    task :ar_init do
    require ‘active_record’
    require ‘yaml’
    ENV['RAILS_ENV'] ||= ‘development’
    config = YAML.load_file(APP_BASE + “/config/database.yml”)[ENV['RAILS_ENV']]
    ActiveRecord::Base.establish_connection(config)
    logger = Logger.new $stderr
    logger.level = Logger::INFO
    ActiveRecord::Base.logger = logger
    end

    Now, I can pass RAILS_ENV as a parameter to db:migrate, like I can with Rails migrations, and it will use the ‘development’ environment by default.

    Also, adding the following line at the end of the migrate task, to invoke the db:schema:dump task causes a schema.rb file to be dumped at the end of each migration, like it does in Rails. This is handy if you want to be able to use db:schema:load to set up a new environment from the schema.rb file.

    Rake::Task[ "db:schema:dump" ].execute

    Cheers!

  3. Todd Huss says:

    Great suggestions Bryon, I’ve implemented all of your changes (and re-added the database_sample.yml file).

Leave a Reply