-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdump-cmd-restore
executable file
·53 lines (41 loc) · 1.11 KB
/
dump-cmd-restore
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#!/bin/bash
# Dump the database, run a given command, then restore from the original
# database dump.
usage() { echo "Usage: $0 [-x <command>] [-d <db_name>] [-u <db_username>]" 1>&2; exit 1; }
set -e
DIR=$(dirname "$0")/..
FILENAME="db$(date +'%Y%m%d_%H%M%S').dump"
while getopts ":x:d:u:" o; do
case "${o}" in
x)
COMMAND=${OPTARG}
;;
d)
DB_NAME=${OPTARG}
;;
u)
DB_USER=${OPTARG}
;;
*)
usage
;;
esac
done
shift $((OPTIND-1))
if [ -z "${COMMAND}" ] || [ -z "${DB_NAME}" ] || [ -z "${DB_USER}" ] ; then
usage
fi
command -v pm2 >/dev/null 2>&1 || { echo >&2 "Global pm2 install is required. Aborting."; exit 1; }
# Make backup of local db.
mkdir -p $DIR/dumps/local
pg_dump $DB_NAME > $DIR/dumps/local/$FILENAME
# Run user provided command.
eval $COMMAND
# Stop services.
pm2 stop all > /dev/null 2>&1
# Restore from the local dump.
dropdb $DB_NAME
createdb -O $DB_NAME $DB_USER
psql $DB_NAME < $DIR/dumps/local/$FILENAME > /dev/null 2>&1
# Restart services.
pm2 start all > /dev/null 2>&1