02354a3cd3a39370e35c770432038052aa54bbe2 — Sean Lang 2 years ago 292f63f master
add scripts for getting and loading databases from heroku
2 files changed, 38 insertions(+), 0 deletions(-)

A script/get-heroku-dump
A script/sync-heroku-db
A script/get-heroku-dump => script/get-heroku-dump +14 -0
@@ 0,0 1,14 @@
mkdir -p /data/collection/heroku-db-backup/

# backup the database for each supplied arg
for application in "$@"
    mkdir -p /data/collection/heroku-db-backup/$application

    # the last part of this output file name must be sortable for
    # sync-heroku-db to find the latest backup
    output="/data/collection/heroku-db-backup/$application/$(date +%s).dump";
    heroku pg:backups:capture --app $application || exit 1
    heroku pg:backups:download --app $application --output $output || exit 1

A script/sync-heroku-db => script/sync-heroku-db +24 -0
@@ 0,0 1,24 @@

# get a fresh backup of the database
~/bin/get-heroku-dump $application || exit 1

# the directory that get-heroku-dump creates

# find the backup we just made. filename should be like 123456.dump, where the
# number is a UNIX timestamp
latest_backup=$(find "$backup_dir" -name "*.dump" -printf "%f\n" | sort -n --field-separator="." -k1 | tail -n 1)

# this script assumes that you want to restore to the default postgres
# instance, which should be running with no password. we also assume that you
# only have one database ending in "_dev" or "_development". this works well if you're running
# one postgres instance at a time with docker containers

# find the first database ending in "_dev" or "_development". also trim whitespace with xargs
db_name=$(psql -U postgres -h -c "SELECT datname FROM pg_database" | grep -m 1 -E "(_dev|_development)$" | xargs)

pg_restore --verbose --clean --no-acl --no-owner -h -U postgres -d $db_name "$backup_dir/$latest_backup"

echo "restored from $backup_dir/$latest_backup to $db_name"