Every time I switch to a new branch in git, I ask the question, “Are my dev and test databases in a state that works with this branch?” Rarely being able to remember the answer, I go through the ritual of dropping the tables, migrating, loading fixtures, and prepping the test database. Annoying at best.
I hacked together a potential solution. This is intended for your dev and test databases only. This looks like an outstandingly stupid thing to do on your production server. Although, who deploys their database.yml file from git anyway?
For months, I’ve been using this great shell hack that puts your current branch in your command line. Thanks github.
jdl ~/hm(master) $ git co foo
Switched to branch "foo"
jdl ~/hm(foo) $
It finally dawned on me that my database.yml file could also use a similar treatment. Modifying the system call a bit, I ended up with this. Notice that I’m using an absolute path to git. That’s because the TextMate test runner wasn’t able to find git in whatever PATH it was picking up. If you’re just using rake or autotest, then you can simply specify ‘git’ there.
local_db: &local_db
adapter: mysql
username: root
password:
host: localhost
<% branch_name = `/usr/local/git/bin/git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/\1/'`.strip.gsub(/[* ]/, '') %>
development:
<<: *local_db
database: <%= "project_dev_#{branch_name} "%>
test:
<<: *local_db
database: <%= "project_test_#{branch_name} "%>
Creating a new branch takes a bit more effort, but switching is now faster.
jdl ~/hm(master) $ git co -b foo
Switched to a new branch "foo"
jdl ~/hm(foo) $ rake db:create:all; rake db:migrate; rake db:fixtures:load; rake db:test:prepare
The downside to this is that it’s overkill when creating a branch that has no migrations in it. I’m going to try it for a while and see how it goes.
Update: After a week of using this, I have to say that it’s neither terrible nor great. I still think that there is a good idea buried in there, but it needs to be integrated with the git branch hooks to ease the pain a bit. Specifically, I need to figure out the following.
- Deleting a branch should automatically clean up the databases that were created.
- It would be great to have this be optional when creating a new branch. If I could decide to just use my base dev db on a branch, or to create a whole new set of local db’s at the time of branch creation that would be the killer feature for this idea.
Not dead, but back to the drawing board.
