Skip Links

Blog

Posts tagged with "migrations".

Generating SQL for rails migrations

Mark

Mark

07 Jun 2011 10:45

We have been migrating a lot of our apps onto JRuby with a goal of running them on Tomcat on AWS.

One of difficulties in doing that is that we can’t run migrations but need to migrate our database in just the same way you would for a standard rails app.

I searched around assuming there must be a solution and found Jay Fields article Rails Generate SQL from Migrations and also a hint at a tool active_record_io_mode which I could no longer access the source code for.

I had problems making Jay’s code run for certain migrations and not being as smart as him couldn’t fix them so I created a more basic version which is a combination of Jay’s and Mark/Zach’s approach.

I have patched Active Record to do a few things:

  • Patch ActiveRecord::Base to store an object which any sql that’s run gets written to
  • Patch the AbstractAdapter log_info method to check for that object and write any sql to it (with appropriate separators)
  • Patch the Migrator migrate method to create an up or down file for a migration and set that in the object (step 1).

This file just needs placing in lib at the start of your project and then require it in your environment.rb. I’m sure there is a cleaner way to do this.

There are a few limitations of the approach:

  • you have to run a migration to get the sql (which really means a migrate/rollback/migrate)
  • it’s not been tested far and wide, only on 2.3.5 and using jruby

Still, it helps us and I’m sure we can finess it as we move forward.

Tagged in: aws, rails, migrations, sql