Last active
September 23, 2015 18:55
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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