Skip to content

Instantly share code, notes, and snippets.

@niklas
Last active July 3, 2017 06:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save niklas/5585593 to your computer and use it in GitHub Desktop.
Save niklas/5585593 to your computer and use it in GitHub Desktop.
An own database for every branch - escape the migration hell
#!/bin/bash
# An own database for every branch
#
# 1) put this script somewhere, make it executable (chmod +x)
# 2) modify your database.yml:
# development:
# adapter: postgresql
# database: "<%= `path/to/stored_script development` %>"
# You can specify another environment as first arg.
# 3) If you want a separate db for your branch, follow the instructions on STDERR on environment startup
PREFIX=$(basename $(pwd))
echoerr() { echo "$@" 1>&2; }
BRANCH=$(git rev-parse --abbrev-ref HEAD)
ENV=${1:-development}
DATABASE="${PREFIX}~${BRANCH}~${ENV}"
DEFAULT_DATABASE="${PREFIX}_${ENV}"
if [ $(psql -l | grep "\b${DATABASE}\b" | wc -l) -eq 1 ]; then
echoerr "using branch specific database: ${DATABASE}"
else
echoerr "falling back to default database: ${DEFAULT_DATABASE}"
echoerr "run \`createdb ${DATABASE}\` for profit"
DATABASE="${DEFAULT_DATABASE}"
fi
echo -n $DATABASE
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment