Separate databases for each git branch in a Rails project

January 29, 2013 by alex

Git makes it easy to branch your code. I love this. But when a branch needs migrations, switching back to master can be difficult. Just checking out the master codebase isn’t enough - you need to also spin up a database with the schema expected by master.

If you have no data worth keeping, simply running rake db:schema:load after checking out a different branch is fine. If that doesn’t work for you, read on.

Here’s the solution I’ve been trying out and which seems to be working quite well.

# config/database.yml
development:
  adapter: mysql2
  encoding: utf8
  reconnect: false
  database: project_development_<%= Git.open('.').current_branch %>
  pool: 5
  username: username
  password: userpassword
  host: 127.0.0.1

database.yml is automatically parsed for ERB snippets, so this just works without any extra setup. I’m using the git gem to figure out what branch I’m currently in, and select the right database accordingly.

You can see the databases I’ve set up to follow this convention in mysql.

mysql> show databases;
+-----------------------------------+
| Database                          |
+-----------------------------------+
| information_schema                |
| project_development_master        |
| project_development_experiment    |
| project_development_bugfix        |
+-----------------------------------+
4 rows in set (0.00 sec)

I think I want to add a feature/convention to allow me to keep using the master db on certain branches. (This will save setup time for branches which I know aren’t going to have any migrations.) Otherwise, that’s about it.

☙ ☙ ☙