-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdbquery.sh
More file actions
executable file
·51 lines (46 loc) · 1.41 KB
/
Copy pathdbquery.sh
File metadata and controls
executable file
·51 lines (46 loc) · 1.41 KB
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
#!/bin/bash
# Run an ad-hoc SQL query against the configured database.
#
# ./dbquery.sh "select * from users" # inline query
# ./dbquery.sh -f query.sql # query from a file
# cat query.sql | ./dbquery.sh # query from stdin
# echo "select 1" | ./dbquery.sh # query from stdin
#
# Works across all backends (local client, docker, docker compose). Output is
# a pretty table on a terminal and tab-separated when piped.
set -euo pipefail
DIR="$( cd -P "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
. "$DIR/_init.sh"
usage() {
cat >&2 <<'EOF'
Usage:
dbquery.sh "SELECT * FROM users" run an inline query
dbquery.sh -f query.sql run a query from a file
cat query.sql | dbquery.sh run a query from stdin
EOF
exit 2
}
sql=""
case "${1:-}" in
-h|--help)
usage
;;
-f|--file)
file="${2:-}"
[ -n "$file" ] || { echo "missing file after $1" >&2; exit 2; }
[ -f "$file" ] || { echo "$file doesn't exist" >&2; exit 3; }
sql="$(cat "$file")"
;;
"")
# No args: read SQL from stdin (must be piped, not an interactive TTY).
[ -t 0 ] && usage
sql="$(cat)"
;;
*)
sql="$*"
;;
esac
# Pretty box table on a terminal, machine-friendly TSV when redirected/piped.
fmt=""
[ -t 1 ] && fmt=" --table"
printf '%s\n' "$sql" | db_exec notty "${MYSQL_CMD}${fmt} ${DBNAME}"