-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathpg.plugin.zsh
executable file
·112 lines (102 loc) · 2.12 KB
/
pg.plugin.zsh
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
#!/bin/sh
__pg_check() {
if [ "$#" != 2 ]; then
echo "Usage: pg $1 <db_name>"
return 1
fi
}
__pg_check2() {
if [ "$#" != 3 ]; then
echo "Usage: pg $1 <origin> <target>"
return 1
fi
}
_pg_ls() {
psql postgres -Atq -c "select d.datname from pg_catalog.pg_database d;"
}
_pg_kill_connections() {
if __pg_check "kill-connections" "$*"; then
psql postgres > /dev/null <<EOF
SELECT pg_terminate_backend(pid)
FROM pg_stat_activity
WHERE pid <> pg_backend_pid()
AND datname='$db_name';
EOF
fi
}
_pg_create() {
# shellcheck disable=SC2039
local db_name="$*"
__pg_check "create" "$db_name" && \
createdb "$db_name"
}
_pg_drop() {
# shellcheck disable=SC2039
local db_name="$*"
if __pg_check "drop" "$db_name"; then
_pg_kill_connections "$db_name"
dropdb --if-exists "$db_name"
fi
}
_pg_cp() {
# shellcheck disable=SC2039
local origin="$1" target="$2"
if __pg_check2 "cp" "$origin" "$target"; then
_pg_kill_connections "$origin"
psql postgres > /dev/null <<EOF
CREATE DATABASE "$target" WITH TEMPLATE "$origin";
EOF
fi
}
_pg_mv() {
# shellcheck disable=SC2039
local origin="$1" target="$2"
if __pg_check2 "mv" "$origin" "$target"; then
_pg_kill_connections "$origin"
psql postgres > /dev/null <<EOF
ALTER DATABASE "$origin" RENAME TO "$target";
EOF
fi
}
_pg_dump_table() {
# shellcheck disable=SC2039
local db_name="$1" table_name="$2"
if [ "$#" != 2 ]; then
echo "Usage: pg dump-table <db_name> <table_name>"
else
pg_dump --table="$table_name" --data-only --column-inserts "$db_name"
fi
}
pg() {
if [ "$#" != 0 ]; then
# shellcheck disable=SC2039
local command="$1"; shift
fi
case "$command" in
ls)
_pg_ls "$@"
;;
kill-connections)
_pg_kill_connections "$@"
;;
create)
_pg_create "$@"
;;
drop)
_pg_drop "$@"
;;
cp)
_pg_cp "$@"
;;
mv)
_pg_mv "$@"
;;
dump-table)
_pg_dump_table "$@"
;;
*)
echo "Usage: pg (ls|kill-connections|create|drop|cp|mv|dump-table) <args>"
return 0
;;
esac
}