Skip to content

Instantly share code, notes, and snippets.

@jambonrose
Created July 5, 2017 14:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jambonrose/935f766121ddb7897a5cb1e4f2025a14 to your computer and use it in GitHub Desktop.
Save jambonrose/935f766121ddb7897a5cb1e4f2025a14 to your computer and use it in GitHub Desktop.
Script to (re-)build a local development PostgreSQL database with optional GIS extension for Django projects
#!/usr/bin/env bash
# © 2017 Andrew Pinkham
# This code is licensed under the Simplified BSD License.
# https://opensource.org/licenses/BSD-2-Clause
#
# Script to (re-)build a local development PostgreSQL database
# Assumes a Django project; will migrate the database
# Used/Tested on Mac OS 10.10 & 10.11
#
# Built with help from:
# http://petereisentraut.blogspot.com/2010/03/running-sql-scripts-with-psql.html
# http://www.postgresql.org/docs/9.4/static/app-psql.html
# https://stackoverflow.com/questions/8546759/how-to-check-if-a-postgres-user-exists
# https://stackoverflow.com/questions/14549270/check-if-database-exists-in-postgresql-using-shell
DATABASE='REPLACE'
USER=$DATABASE
INSTALL_GIS=1 # 1 is true, 0 is false
# make sure PostgreSQL is running
psql --list &> /dev/null
if [[ $? != 0 ]]
then
echo 'PostgreSQL not found; please run DB.'
exit 1
fi
# create user if user does not exist
psql --dbname=postgres --no-align --tuples-only \
--command="SELECT 1 FROM pg_roles WHERE rolname='$USER'" \
| grep -q 1 \
|| createuser --pwprompt --createdb --encrypted --no-superuser "$USER"
# dump data and drop database if database exists
time=`date '+%Y'-'%m'-'%d'-'%H%M%S'`
# dump data if the database exists
psql --list --quiet --tuples-only \
| cut -d\| -f 1 \
| grep --quiet --word-regexp "$DATABASE" \
&& pg_dump --dbname="$DATABASE" --format=custom --file="pg-dump-$time.sqlc"
# drop db if database exists
psql --list --quiet --tuples-only \
| cut -d\| -f 1 \
| grep --quiet --word-regexp "$DATABASE" \
&& dropdb "$DATABASE"
createdb "$DATABASE"
psql --echo-hidden --dbname="$DATABASE" <<END 1>/dev/null
GRANT ALL PRIVILEGES ON DATABASE "$DATABASE" TO "$USER";
REVOKE ALL ON DATABASE "$DATABASE" FROM PUBLIC;
END
if [ "$INSTALL_GIS" = 1 ];
then
psql --echo-hidden --dbname="$DATABASE" <<END 1>/dev/null
CREATE EXTENSION postgis;
END
fi
cd src
./manage.py migrate -v 0
if [ -d fixtures ] # if a fixtures directory exists
then
find fixtures -name "*json" -o -name "*yaml" -o -name "*xml" | xargs ./manage.py loaddata -v 0
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment