Sequel Migrations on Heroku

2011-11-30 10:39:02 by jdixon

I find myself using Sequel in conjunction with Sinatra these days to write more of my web applications. Never having been a fan of ORMs in general, and mostly comfortable with the ickier bits of SQL wizardry, it took me a while to warm up to the idea of using one for database migrations. But I've seen the possibilities with stuff like ActiveRecord. Being able to migrate my schema into a versioned state is "dee-lish".

The following is an example for using migrations with Sequel in your Heroku-hosted app. Actually there's nothing here that's Heroku-specific; Heroku uses config vars in favor of configuration settings for values like your database path or third-party URLs. In this setup I'm using one of their free shared PostgreSQL databases with the DATABASE_URL config var populated by their addon service. You could just as easily set this environment variable within your local development shell (which is exactly what I do).

First we start with the Rakefile We define all of our target tasks (:reset, :to, :up, :down). The only one that might seem unusual is :to. By setting our VERSION config var, Sequel should migrate to that specific version. Admittedly, this style of migration pales to some of the nicer features found in ActiveRecord, like auto-migration and incremental migration "stepping". But for my purposes it works great.

The actual model migration files are found below. For now let's go ahead and run some of these and see how they behave. Note that this Heroku app is on their Cedar platform, which supports the heroku run action. If you're working on the older Aspen or Bamboo platforms you'll want to use heroku rake instead.

Well that was easy enough. Here is the base schema. Nothing to get excited over. Astute readers will notice that migration 002_AddForeignKeys only exists because the foreign key name doesn't match up with the target model (:owner_id, :users).

Lastly we need to insert some actual data. This is performed as a separate step because we need all the foreign keys defined first. I ran into some problems with the :down target for this particular migration. If anyone finds a way to get the down action working here please let me know in the comments.

In conclusion, I'd like to thank John E. Vincent for reviewing this post and asking me to write a conclusion. Mazel Tov!

Add a comment:




max length 4000 chars