-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpgconnect.bash
executable file
·61 lines (53 loc) · 1.61 KB
/
pgconnect.bash
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
#!/bin/bash
# function to imediately execute a query on connect
function watch_query() {
query=${1:-"show databases"}
DB_NAME_MAYBE=""
if [ -n "${DB_NAME}" ]; then
DB_NAME_MAYBE="-d ${DB_NAME}"
fi
PGPASSWORD="${DB_PASS}" watch -etn 1 "psql -h${DB_HOST} -p${DB_PORT} -U${DB_USER} ${DB_NAME_MAYBE} -c '${query}'"
clear
}
# Function to execute a query once
function execute_query_once() {
query=${1:-"show databases"}
DB_NAME_MAYBE=""
if [ -n "${DB_NAME}" ]; then
DB_NAME_MAYBE="-d ${DB_NAME}"
fi
PGPASSWORD="${DB_PASS}" psql -h"${DB_HOST}" -p${DB_PORT} -U"${DB_USER}" "${DB_NAME_MAYBE}" -c "${query}"
}
function execute_sql_script_file() {
script_file=${1}
if [ ! -f "${script_file}" ]; then
echo "File ${script_file} does not exist."
echo -e "Usage: $0 <db_index> --script <script_file>"
exit 1
fi
DB_NAME_MAYBE=""
if [ -n "${DB_NAME}" ]; then
DB_NAME_MAYBE="-d ${DB_NAME}"
fi
PGPASSWORD="${DB_PASS}" psql -h"${DB_HOST}" -U"${DB_USER}" "${DB_NAME_MAYBE}" -f "${script_file}"
}
# Load the environment variables
# shellcheck source=./.env
. ./api/.env
case "$1" in
"--watch" | "-w")
query=${2:-"show databases"}
watch_query "${query}"
;;
"--query" | "-q")
query=${2:-"show databases"}
execute_query_once "${query}"
;;
"--script" | "-s")
execute_sql_script_file "${2}"
;;
*)
# If no specific flag is provided, execute pgcli command
pgcli postgresql://"${DB_USER}":"${DB_PASS}"@"${DB_HOST}":"${DB_PORT}"/"${DB_NAME}"
;;
esac