Occasionally, as developers, we have to import staging or production databases and restore them to our local system in order to recreate bugs or maintain the most recent version, among other reasons.
Manual work takes a lot of time and can result in mistakes.
I propose creating a shell script that will do everything automatically, giving us more time to focus on our work.
Here's an example
File name can be import_remote_db.sh
for example
#!/bin/bash
# stop on first error
set -e
for ARGUMENT in "$@"
do
KEY=$(echo $ARGUMENT | cut -f1 -d=)
KEY_LENGTH=${#KEY}
VALUE="${ARGUMENT:$KEY_LENGTH+1}"
export "$KEY"="$VALUE"
done
command -v heroku >/dev/null 2>&1 || { echo >&2 "heroku command is required"; exit 1; }
command -v docker-compose >/dev/null 2>&1 || { echo >&2 "docker-compose command is required"; exit 1; }
DUMPFILE="tmp/db_dump.dump"
if [ -e $DUMPFILE ]
then
echo "backup db found trying to restore it"
else
echo "backup db not found downloading from heroku"
heroku pg:backups:download --output=$DUMPFILE --app=${app:-heroku-app-name}
fi
# This will usually generate some warnings, due to differences between your Heroku database
# and a local database, but they are generally safe to ignore.
docker-compose run db pg_restore --verbose --clean --no-acl --no-owner -h db -p 5433 -U u_name -d db_name $DUMPFILE
Here, it first verifies that the packages docker-compose
and heroku
are installed.
Next, it attempts to retrieve the database backup file; if this fails, it attempts to fetch data from heroku
. Keep in mind that we must first complete the heroku login
instruction.
Using the docker-compose
console, it adds to a local database after the backup is done. If you do not need to use docker images at all, you can simply replace this with your local PostgreSql
server.
To run the script use
sh import_remote_db.sh
You can also specify app name via
sh import_remote_db.sh app=heroku_app_name
Note: Make sure you backup your data before running the script if the Heroku app does not have automated daily or hourly backups. If not, you risk running out of backup data.
I saved a ton of time and effort during my work with this straightforward script.
Top comments (0)