Automating Database Migrations

Many app frameworks provide libraries for managing database migrations between different revisions of an app.

For example, Rails’ ActiveRecord library allows users to define migration files and then run bundle exec rake db:migrate to execute them.

To automatically run migrations on each deploy to Enclave, you can use a before_release command.

To do so, add the following to your .aptible.yml file (adjust the command as needed depending on your framework):

before_release:
  - bundle exec rake db:migrate

Warning

Don’t break your app when running database migrations! It’s easy to forget that your app will be running when automated database migrations execute, but it’s important not to.

For example, if your migration locks a table for 10 minutes (e.g. to create a new index synchronously), then that table is going to read-only for 10 minutes. If your app needs to write to this table to function, it will be down.

Also, if your app is a web app, review the docs over here: Concurrent Releases.

Migration Scripts

If you need to run more complex migration scripts (e.g. with if branches, etc.), we recommend encapsulating this logic in a separate script:

#!/bin/sh
# This file lives at script/before_release.sh

if [ "$RAILS_ENV" == "staging" ]; then
  bundle exec rake db:[TASK]
else
  bundle exec rake db:[OTHER_TASK]
fi

Warning

The script needs to be made executable. To do so, run chmod script/before_release.sh.

Your new .aptible.yml would read:

before_release:
  - script/before_release.sh