Jun 24 2011

Relying on migrations to setup your Rails database when you have multiple branches is pretty hard. And slow. And blows away your data.

Instead I decided to simply have one database for each branch, defaulting to master. So this is my new database.yml:

development:
  adapter: postgresql
  host: localhost
  database: <%= db_branch('myapp') %>

And the function referred above:

def db_branch(base)
  branch = \`git name-rev --name-only HEAD\`.strip
  [branch, "master"].uniq.each do |candidate|
    db_name = "#{base}_#{candidate}"
    return db_name if \`psql -c "SELECT 1 from pg_database WHERE datname='#{db_name}\'" -t`.include?('1')
  end
  base
end

So I have a database for each major branch of my app: myapp_master, myapp_newfeature, etc. If the branch doesn't have database migrations just don't create a database and it will keep using the one for master.

blog comments powered by Disqus