Skip to content

Instantly share code, notes, and snippets.

@scott-joe
Last active September 23, 2015 18:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scott-joe/3690b9e6d140ab882f71 to your computer and use it in GitHub Desktop.
Save scott-joe/3690b9e6d140ab882f71 to your computer and use it in GitHub Desktop.
Automatically create/update Heroku Postgres databases locally. Add to your custom.zsh file or .bashrc. Also, add `/dumps/*` to your .gitignore if you don't want all that in your repo
alias pgstart="pg_ctl -D /usr/local/var/postgres -l /usr/local/var/log/postgres/server.log start"
alias pgstop="pg_ctl -D /usr/local/var/postgres stop -m fast"
# find id of last backup
__getBackupId() {
echo $( heroku pg:backups | grep 'b\d\d\d' | head -1 | cut -b 1-6 | xargs )
}
# get the app's name from heroku info
__getAppName() {
echo $( heroku apps:info | grep '===' | sed -e 's/^=== s*//' )
}
alias getAppName=__getAppName
# prepare the fs for download and initiate population
__hpgbackup() {
DUMPDIR='./dumps'
if [ ! -d "$DUMPDIR" ]; then
mkdir "$DUMPDIR"
fi
BACKUPID=$( __getBackupId )
wait
DUMPFILE="$DUMPDIR/$BACKUPID.dump"
echo "Do you want to build a new remote backup? "
read response
if [[ $response =~ ^([yY][eE][sS]|[yY])$ ]]; then
heroku pg:backups capture
wait
fi
# if it already exists...don't bother
if [ ! -f "$DUMPFILE" ]; then
curl -o "$DUMPFILE" `heroku pg:backups -q public-url`
fi
__rebuilddb "$1"
}
# Populate the db
__rebuilddb() {
$( pg_restore --verbose --clean --no-acl --no-owner -h localhost -U $USER -d $1 $DUMPFILE )
}
# Create a the db based on the appname and proceed to populate it
__dbinit() {
$( createdb $1 )
__hpgbackup "$1"
}
# rebuilds the local db from the latest dump
__dbupdate() {
echo "Are you in a Heroku Postgres project's root? "
read response
if [[ $response =~ ^([yY][eE][sS]|[yY])$ ]]; then
# while we're waiting on the app name, might as well ensure the local server is running
pgstop
pgstart
APPNAME=$( __getAppName )
DBSTATUS=$( psql -l | grep '$APPNAME' );
if [[ $DBSTATUS != '' ]]; then
# create and populate the db
__dbinit $APPNAME
else
# populate the db
__hpgbackup $APPNAME
fi
else
echo "Move into a Heroku project with Postgres' root directory before executing."
fi
}
alias dbupdate=__dbupdate
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment