-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpg_run_sql.sh
executable file
·83 lines (61 loc) · 1.38 KB
/
pg_run_sql.sh
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#!/usr/bin/bash
### VARIABLES
BASE=$( dirname "$0" )
HOST=''
CONF=''
FILES=()
PGHOST=''
PGUSER=''
PGPORT=''
PGDB=''
### FUNCTIONS
die() {
echo "ERROR: $*" 1>&2
kill 0
exit 99
}
get_host() {
HOST="$1"
[[ -z "$HOST" ]] && die 'Missing host'
}
get_files() {
local _fn
for _fn in "${@}"; do
[[ -f "${_fn}" ]] || die "File not found '${_fn}'"
FILES+=( "${_fn}" )
done
[[ ${#FILES[@]} -lt 1 ]] && die "Missing sql files for host: '$HOST'"
}
prep() {
CONF=~/.pgpass.cnf.${HOST}
[[ -f "${CONF}" ]] || die "config file not found '${CONF}'"
rsync "${CONF}" ${HOST}:.pgpass || die 'failed to rsync pgpass file'
ssh ${HOST} chmod 600 .pgpass || die 'failed to chmod remote pgpass file'
}
get_connection_parameters() {
PGHOST=$( head -1 "${CONF}" | cut -d: -f1 )
PGPORT=$( head -1 "${CONF}" | cut -d: -f2 )
PGDB=$( head -1 "${CONF}" | cut -d: -f3 )
PGUSER=$( head -1 "${CONF}" | cut -d: -f4 )
}
test_connection() {
ssh $HOST "pg_isready -q -h ${PGHOST} -p ${PGPORT} -d ${PGDB} -U ${PGUSER}"
}
run_sql() {
fn="$1"
# cat "$fn" | ssh $HOST 'psql -d jsmdb -h localhost -U jsmdb_user'
cat "$fn" | ssh $HOST "psql -h ${PGHOST} -p ${PGPORT} -d ${PGDB} -U ${PGUSER}"
}
### MAIN
get_host "$1"
shift
get_files "${@}"
prep
get_connection_parameters
test_connection || die "connection not ready"
for fn in "${FILES[@]}"; do
set -x
run_sql "$fn"
set +x
echo
done