Database Migrations

I’m working on a project where I needed to create and manage database tables. I find that the active_record migration system from Ruby on Rails to be the best system for creating, versioning database changes. The project itself is in Scala so I took a look at scala migrations and c5-db-migration but I found active_record migration to be better documented, supported and has a more concise syntax.

I recently created a template rails 3 project where I kept only the files necessary for generating migrations. Check it out at https://github.com/tc/database_migrations

To get started:
setup your database connection information in config/database.yml

Create a database:

rake db:create

Create a new migration:

rails g migration create_users

This will create a file in db/migrate.
Add columns:

class CreateUsers < ActiveRecord::Migration
def self.up
create_table :users do |t|
t.string :name
end
end

def self.down
drop_table :users
end
end

Perform the migration:

rake db:migrate

Now you have a working database which can be managed by this application.

You can rollback to a previous version:

rake db:migrate VERISON=XXXX

The versioning of the database is managed in the database’s schema_migrations table.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s