Skip to content

Instantly share code, notes, and snippets.

@kenaniah
Created July 28, 2015 21:19
Show Gist options
  • Save kenaniah/72ee2c273909e75e62a4 to your computer and use it in GitHub Desktop.
Save kenaniah/72ee2c273909e75e62a4 to your computer and use it in GitHub Desktop.
#!/bin/bash
processors=$(cat /proc/cpuinfo | awk '/^processor/{print $3}' | wc -l)
# Usage information
if [ $# -ne 2 ]
then
echo "Usage: $0 <source_file> <dbname>"
echo
echo "This script will restore the requested database from the given source file."
exit 1
fi
# Ensure the source file is valid
if [ ! -f "$1" ]
then
echo "The source file $1 does not exist."
exit 2
fi
# Close all connections to the requested database
echo "Closing connections to database $2..."
psql -c "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname='$2'"
# Check if database exists
found=$(psql -Altc "SELECT datname FROM pg_database WHERE NOT datistemplate AND datallowconn AND datname != 'postgres' AND datname = '$2';")
# Drop the database if it exists
if [ "${found[0]}" = $2 ]
then
echo "Dropping database $2..."
dropdb "$2"
fi
# Create the database
echo "Creating database $2..."
createdb -T template0 "$2"
# Restore the contents of the database
echo "Restoring database $2..."
pg_restore -d "$2" -j $processors -v $1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment