]> git.evergreen-ils.org Git - working/Evergreen.git/blob - build/tools/update_db.sh
d0c1f37441bbd71b00e5e76f91ab8a9dc8c17755
[working/Evergreen.git] / build / tools / update_db.sh
1 #!/bin/bash
2 #
3 # Based on a script by Bill Erickson.
4 #
5 # TODO:
6 #   ADD OPTIONS:
7 #     ~ single-step mode that calls psql -f once per file
8 #          (but also prompts for password once per file).
9 #     ~ help/usage option
10
11 DB_HOST=$1
12 DB_USER=$2
13 DB_NAME=$3
14
15 function usage() {
16     cat <<END_OF_USAGE
17 usage: $0  db_host  db_user  db_name
18
19 Automtically update the DB with all numbered updates beyond the last installed one.
20
21 ALL parameters are required to access the postgres database.
22
23 PARAMETERS:
24   db_host - database host system (e.g. "localhost" or "10.121.99.6")
25   db_user - database username
26   db_name - database name
27     
28 Run from your source repository Open-ILS/src/sql/Pg directory.
29
30 You will be prompted for the postgres password if necessary.
31
32 END_OF_USAGE
33 }
34
35 function die() {
36     echo "ERROR: $1" >&2;
37     exit 1;
38 }
39
40 function usage_die() {
41     exec >&2;
42     echo;
43     echo "ERROR: $1";
44     echo;
45     usage;
46     exit 1;
47 }
48
49 function feedback() {
50     #TODO: add a test and verbose mode that use this.
51     echo "Updating database $DB_NAME on $DB_HOST as user $DB_USER";
52 }
53
54 [ -z "$DB_HOST" -o -z "$DB_USER" -o -z "$DB_NAME" ] && usage_die "Need all DB parameters";
55
56 PSQL_ACCESS="-h $DB_HOST -U $DB_USER $DB_NAME";
57
58 VERSION=$(psql -c "select max(version) from config.upgrade_log" -t $PSQL_ACCESS);
59 [  $? -gt 0  ] && die "Database access failed.";
60 # [ $VERBOSE ] && echo RAW VERSION: $VERSION     # TODO: for verbose mode
61 VERSION=$(echo $VERSION | sed -e 's/^ *0*//');    # This is a separate step so we can check $? above.
62 [ -z "$VERSION" ] && usage_die "config.upgrade_log missing ANY installed version data!";
63 echo "* Last installed version -> $VERSION";
64
65 [ -d ./upgrade ] || usage_die "No ./upgrade directory found.  Please run from Open-ILS/src/sql/Pg";
66
67 declare -a FILES;
68 while true; do
69     VERSION=$(($VERSION + 1));
70     PREFIX=$(printf "%0.4d" $VERSION);
71     FILE=$(ls upgrade/$PREFIX* 2>/dev/null);
72     [ ! -f "$FILE" ] && break;
73     FILES[${#FILES[@]}]=$FILE;      # "push" onto FILES array
74     echo "* Pending $FILE";
75 done;
76
77 COUNT=${#FILES[@]};
78
79 if [ $COUNT -gt 0 ] ; then
80     echo "* $COUNT update scripts to apply."
81     exec 3>&1;  # our copy of STDOUT
82     for (( i=0; i<$COUNT; i++ )) ; do
83         echo "* Applying ${FILES[$i]}" >&3;   # to the main script STDOUT
84         cat ${FILES[$i]};                     # to the psql pipe
85     done | psql $PSQL_ACCESS ;
86 else
87     echo "* Nothing to update";
88 fi