Skip to content

Instantly share code, notes, and snippets.

@aray12
Created April 5, 2016 22:22
Show Gist options
  • Save aray12/b3ab8eea86916f0b46fb9716579d104b to your computer and use it in GitHub Desktop.
Save aray12/b3ab8eea86916f0b46fb9716579d104b to your computer and use it in GitHub Desktop.
#!/usr/bin/env bash
# This kills all connections to a database a resets it based
# on a backup file. The first argument passed should be the
# name of the database. The second should be the complete
# filepath for the backup. The backup should have already been
# compressed using the gzip utility. If you are working on a
# remote database set the environment variables recognized by
# psql
#
# http://www.postgresql.org/docs/9.5/static/libpq-envars.html
#
# e.g.
# ./resetdb.sh test-db /home/backup.gz
read -d '' KILLQUERY << EOD
SELECT pg_terminate_backend(pg_stat_activity.pid)
FROM pg_stat_activity WHERE datname = current_database()
AND pid <> pg_backend_pid();
EOD
(psql $1 -c "$KILLQUERY" && dropdb $1) || :
createdb $1
gunzip -c $2 | psql $1
@aray12
Copy link
Author

aray12 commented Apr 5, 2016

I spent a lot of time trying to figure out the best way to reset my test database to a consistent state in between each test. I was eventually able to boil it down to these 10 lines of code.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment