-
Notifications
You must be signed in to change notification settings - Fork 0
/
steampipe-psql
executable file
·81 lines (67 loc) · 2.22 KB
/
steampipe-psql
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
#!/bin/bash
# usage: steampipe-psql [psql-options]
# steampipe-psql --help
#
# Run psql with provided arguments against a local Steampipe Postgres service.
#
# If the local Steampipe Postgres service isn't already running, it's
# automatically started before running psql and automatically stopped
# afterwards.
#
# All non-psql output is carefully sent to stderr so you may use stdout for
# results from psql.
#
set -euo pipefail
export PGHOST="${PGHOST:-localhost}"
export PGPORT="${PGPORT:-9193}"
export PGUSER="${PGUSER:-steampipe}"
export PGDATABASE="${PGDATABASE:-steampipe}"
main() {
print-help-if-requested "$@"
echo "Using PGHOST=$PGHOST PGPORT=$PGPORT PGUSER=$PGUSER PGDATABASE=$PGDATABASE" >&2
if ! steampipe-service-available; then
echo "Steampipe Postgres service not available; starting it…" >&2
if [[ "$PGHOST" != localhost ]]; then
echo "Cannot automatically start Steampipe Postgres service for host $PGHOST" >&2
exit 1
fi
steampipe service start \
--database-listen local \
--database-port "$PGPORT" \
>&2
# Stop the service when we exit, i.e. leave it in the same state as
# when we started.
trap '
echo "Stopping Steampipe Postgres service…" >&2
steampipe service stop >&2
' EXIT
fi
# Steampipe is sometimes slow about registering schemas for plugins and if
# we try to run a query before they exist it'll fail.
while ! steampipe-plugins-ready; do
echo "Waiting for Steampipe plugin schemas to be ready…" >&2
sleep 1
done
echo "Running psql" >&2
# No exec because of our trap above
psql "$@"
}
print-help-if-requested() {
if [[ "${1:-}" == --help ]]; then
sed -nE '/^#/!q; s/^#( |$)//p;' "$0"
exit
fi
}
steampipe-service-available() {
nc -zw3 "$PGHOST" "$PGPORT" &>/dev/null
}
steampipe-plugins-ready() {
local -a psql=(psql --quiet --no-psqlrc --no-align --tuples-only)
local query="
select count(*)
from steampipe_internal.steampipe_connection
where type = 'plugin' and state != 'ready'
"
[[ "$("${psql[@]}" <<<"$query")" -eq 0 ]]
}
main "$@"