Tuesday, May 28, 2013

Fixing a database problem on a Heroku app

Recently, I was working on an upgrade to a Heroku app and found to my surprise that my schema_migrations table was wrong in production (horror, actually... I hate this kind of problem because of the possibility of data corruption). The database tables were correct, but the schema was behind by 11 migrations. Suffice it to say I have no idea how that happened, but it must have occurred when I was upgrading from a staging instance to production earlier this month [Note to self: figure out a reliable methodology for doing this].

There are a number of posts that recommend directly updating the Heroku database; this one, for example. I started to take this approach and then realized that there was a safer way to make this change. Heroku has a set of database commands that allow you to copy your production database down to your location machine or copy it back to production. This is better, IMO, than mucking with production data live... even with a backup. Working on your local machine, you can run your tests and generally use all available tools to make sure the modifications work before you upload it back to production.

The steps are dead simple:
  1. Find the id of your production database:
    heroku config --app [name]
    the id you want is usually something like "HEROKU_POSTGRESQL_PINK_URL"where "PINK" will probably be some other color.
  2. Make a backup of your production database using the database id:
    heroku pgbackups:capture --app [name] [database id]
  3. "Pull" the production database down to your local machine (Heroku drops it into your development database):
    heroku db:pull --app [name]
  4. Make your changes
  5. Run your tests
  6. "Push" the modified data back to production:
    heroku db:push --app [name]
  7. Open your browser and run a smoke test on your updated database.
Mission accomplished.

No comments:

Post a Comment