Project

General

Profile

1 9014 aaronmk
#!/bin/bash -e
2
. "$(dirname "${BASH_SOURCE[0]}")"/util.sh
3
4
if self_not_included; then
5
6
# using prefixed connection vars
7 9641 aaronmk
alias ssh2local='declare prefix=ssh_; import_vars; unset prefix
8
declare $(prefix=ssh_ get_prefix_vars); unset $(prefix=ssh_ get_prefix_vars)'
9 9464 aaronmk
alias use_local='declare prefix=local_; import_vars; unset prefix'
10
alias use_remote='declare prefix=remote_; import_vars; unset prefix'
11 11784 aaronmk
alias use_local_remote='{ use_remote; use_local; }'
12 9167 aaronmk
	# *must* be run inside a function
13 9574 aaronmk
alias use_root='declare prefix=root_; import_vars; unset prefix'
14 9014 aaronmk
15
quote='"'
16
17 9074 aaronmk
esc_name() { echo "$quote${1//$quote/$quote$quote}$quote"; }
18 9014 aaronmk
19 9423 aaronmk
mk_esc_name_alias() # usage: mk_esc_name_alias schema_esc
20 9426 aaronmk
{ alias mk_"$1"='declare '"$1"'="${'"$1"':-$(esc_name "$'"${1%_esc}"'")}"; '\
21
'echo_vars '"$1"; }
22 9014 aaronmk
23 9423 aaronmk
mk_esc_name_alias schema_esc
24
mk_esc_name_alias table_esc
25
26 9470 aaronmk
fi # load new aliases
27
if self_being_included; then
28
29 9623 aaronmk
skip_table() # usage: create_table || table=... skip_table || return 0
30
{ what="table $table" already_exists_msg; }
31
32 9817 aaronmk
: "${test=$(isset limit; exit2bool)}" # test mode when using limited # rows
33
34 9698 aaronmk
# usage: (set_large_table; to_file db_cmd...) || return
35
alias set_large_table='declare del="${del-$(test "$limit"; exit2bool)}"
36
echo_vars del'
37
38 11578 aaronmk
limit() # usage: "query... $([prefix=$'| |\n'] [limit|n=#] limit)"
39 9467 aaronmk
{
40
	echo_func; kw_params prefix; local prefix="${prefix-
41
}"
42 11578 aaronmk
	if isset n; then local limit="${limit-$n}"; fi
43 9467 aaronmk
	echo -n "${limit:+${prefix}LIMIT $limit}"
44
}
45
46 10401 aaronmk
cols2list() # usage: cols2list col...
47
{ echo_func; cmd=esc_name foreach_arg; delim=', ' join "$@"; }
48
49 10827 aaronmk
mk_select() # usage: {query=... | table=... [cols=...] [filter=...] \
50 11579 aaronmk
# [order_by=...]} [limit|n=#] mk_select
51 9468 aaronmk
{
52
	echo_func; kw_params query table cols filter; mk_table_esc
53 10827 aaronmk
	if is_array cols    ; then cols="$(    cols2list "${cols[@]}"    )"; fi
54
	if is_array order_by; then order_by="$(cols2list "${order_by[@]}")"; fi
55 9468 aaronmk
	echo "$(rtrim "${query:-SELECT ${cols:-*} ${cols:+
56 9335 aaronmk
}FROM $table_esc
57
${filter:+WHERE $filter
58 10827 aaronmk
}${order_by:+ORDER BY $order_by
59 9467 aaronmk
}}")\
60
$(limit)"
61 9468 aaronmk
}
62 9088 aaronmk
63 9468 aaronmk
# export func usage: export_func() { ...; mk_select_var; ... }
64
# caller usage: {query=... | table=... [cols=...] [filter=...]} export_func
65
# cmd line usage: [limit=...] caller
66
alias mk_select_var='declare query="$(mk_select)"'
67
68 9014 aaronmk
fi # load new aliases
69
if self_being_included; then
70
71 9482 aaronmk
mk_drop() # usage: table=... mk_drop|*sql_ANSI
72
{
73 12828 aaronmk
	log_local; log++; echo_func; kw_params table; : "${table?}"; mk_table_esc
74 9482 aaronmk
	echo "DROP TABLE IF EXISTS $table_esc"
75
}
76
77 9465 aaronmk
mk_truncate() # usage: table=... mk_truncate|*sql_ANSI
78 9432 aaronmk
{
79 12828 aaronmk
	log_local; log++; echo_func; kw_params table; : "${table?}"; mk_table_esc
80 9432 aaronmk
	echo "TRUNCATE $table_esc"
81
}
82 9014 aaronmk
83 9432 aaronmk
84 9014 aaronmk
### MySQL
85
86 9094 aaronmk
alias set_database=\
87
'if test "$schema"; then declare database="${database-$schema}"; fi'
88
89
fi # load new aliases
90
if self_being_included; then
91
92 9099 aaronmk
# usage: mysql*() { ...; mysql_cmd "$@"; } (with alias)
93 10888 aaronmk
# caller usage: [ssh_server=...] [server=...] [user=...] [password=...] mysql*()
94 9099 aaronmk
function mysql_cmd() # usage: mysql*() { ...; mysql_cmd cmd "$@"; }
95 9271 aaronmk
# auto-adds connection/login opts when specified
96 9014 aaronmk
{
97
	echo_func
98 9099 aaronmk
	local cmd="$1"; shift
99 9014 aaronmk
	local ssh_server="$(localize_url "$ssh_server")"
100
	local server="$(localize_url "$server")"
101 9050 aaronmk
	if test "$ssh_server"; then
102 9014 aaronmk
		local ssh_dest="${ssh_dest-${ssh_user:+$ssh_user@}$ssh_server}"
103
	fi
104
105
	local var=ssh_dest; local_inv
106 9701 aaronmk
	command "time" ${ssh_dest:+ssh "$ssh_dest" }"$cmd" \
107 9014 aaronmk
${server:+ --host="$server" }${user:+--user="$user" } --password\
108 9694 aaronmk
${password+="$password"} --quick "$@" # --quick: don't buffer entire result
109 9014 aaronmk
}
110 9099 aaronmk
alias mysql_cmd='mysql_cmd "$FUNCNAME"'
111 9014 aaronmk
112 9099 aaronmk
fi # load new aliases
113
if self_being_included; then
114
115 10887 aaronmk
function mysql() # usage: [database=...] [data_only=1] [log_queries=] mysql ...
116 9095 aaronmk
{
117 9578 aaronmk
	echo_func; kw_params output_data data_only query_verbosity
118 9557 aaronmk
	if test "$data_only"; then local output_data="${output_data-1}"; fi
119 9578 aaronmk
	local log_queries="${log_queries-1}"
120 9095 aaronmk
	set_database
121 9101 aaronmk
122 9557 aaronmk
	set -- ${database:+--database="$database" }--local-infile=1 \
123
--${data_only:+skip-}column-names "$@"
124 9150 aaronmk
	if test "$output_data"; then echo_stdin|mysql_cmd --batch "$@"
125 9591 aaronmk
	else cmd_log_fd=1 mysql_cmd ${log_queries:+--verbose --verbose --verbose }\
126
"$@" # --verbose*3: echo runtimes
127 9101 aaronmk
	fi
128 9095 aaronmk
}
129 9014 aaronmk
130 9074 aaronmk
mysql_ANSI()
131 9014 aaronmk
{
132
	echo_func
133
	(echo "SET sql_mode = 'ANSI';"; cat)|mysql "$@"
134
}
135
136 13168 aaronmk
# always use ANSI mode, to support "" identifiers. `` *are* still supported in
137 9706 aaronmk
# this mode, so it also works with SHOW CREATE TABLE output and dumpfiles.
138
alias mysql='mysql_ANSI'
139
140 9707 aaronmk
fi # load new aliases
141
if self_being_included; then
142
143
mysql_root() { echo_func; use_root; mysql "$@"; }
144
145 9777 aaronmk
mysql_truncate() { echo_func; mk_truncate|mysql; }
146 9466 aaronmk
147 9456 aaronmk
mysql_import() # usage: table=... [cols=...] [append=1] mysql_import <file
148
# without append=1, first ensures the table is empty
149 9430 aaronmk
{
150
	echo_func
151
	mk_table_esc
152
	local mysql_load_data_format="${mysql_load_data_format-\
153
FIELDS TERMINATED BY ','
154
OPTIONALLY ENCLOSED BY '\"'
155
}"
156
157 9466 aaronmk
	if test ! "$append"; then mysql_truncate; fi
158 9430 aaronmk
	mysql_load_data_format="${mysql_load_data_format%
159
}"
160 9642 aaronmk
	ssh2local # ssh does not tunnel nonstandard fds
161 9777 aaronmk
	mysql "$@" 40<&0 <<EOF
162 9651 aaronmk
LOAD DATA LOCAL INFILE '/dev/fd/40'
163 9660 aaronmk
${append:+IGNORE }INTO TABLE $table_esc
164 9430 aaronmk
$mysql_load_data_format
165
IGNORE 1 LINES
166
EOF
167
}
168
169 9152 aaronmk
mysql_export() # does not support CSV
170 10887 aaronmk
# caller usage: [database=...] {query=... | table=... [cols=...] [filter=...]} \
171
# mysql_export
172 9348 aaronmk
# cmd line usage: [limit=...] caller
173 9102 aaronmk
{
174
	echo_func
175 9463 aaronmk
	mk_select_var
176 9152 aaronmk
177 9777 aaronmk
	output_data=1 mysql "$@" <<<"$query"
178 9152 aaronmk
}
179
180
mysql_export_outfile() # supports CSV, but requires the FILE privilege
181
{
182
	echo_func
183 9102 aaronmk
	: "${file:?}"
184 9463 aaronmk
	mk_select_var
185 9102 aaronmk
	local mysql_load_data_format="${mysql_load_data_format-\
186
FIELDS TERMINATED BY ','
187
OPTIONALLY ENCLOSED BY '\"'
188
}"
189
190
	local head="${query%%FROM*}" # includes trailing newline
191 9105 aaronmk
	head="${head%
192
}"
193 9102 aaronmk
	local tail="${query#$head}"
194 9106 aaronmk
	mysql_load_data_format="${mysql_load_data_format%
195
}"
196 9777 aaronmk
	mysql "$@" <<EOF
197 9105 aaronmk
$head
198
INTO OUTFILE '$file'
199 9106 aaronmk
$mysql_load_data_format
200
$tail
201 9102 aaronmk
EOF
202
}
203
204 10649 aaronmk
mysqldump() # usage: [schema=1 | data=1] [create_db=1] mysqldump db [table...]
205 9014 aaronmk
{
206 10649 aaronmk
	echo_func
207
	echo_vars schema data create_db
208 9231 aaronmk
209 10649 aaronmk
	local var=create_db; local_inv
210
	mysql_cmd ${database:+--databases "$database" ${no_create_db:+--tables }} \
211 9694 aaronmk
--lock-tables=false --set-charset \
212 10446 aaronmk
${postgres_compat:+${data:+--compatible=postgresql }--add-locks=false }\
213 9014 aaronmk
${schema:+--no-data }${data:+--no-create-info }"$@"
214
}
215
216 9074 aaronmk
mysqldump_diffable()
217 9014 aaronmk
{
218
	echo_func
219 9550 aaronmk
	mysqldump "$@"|{ pipe_delay; echo_run sed 's/^(-- Dump completed).*$/\1/'; }
220 9014 aaronmk
}
221
222 9588 aaronmk
mysql_rm_privileged_statements()
223
{
224
	echo_func
225
	grep -vE -e '^/\*!40000 ALTER TABLE `.*` (DIS|EN)ABLE KEYS \*/;$' \
226
-e '^(UN)?LOCK TABLES( `.*` WRITE)?;$'
227
}
228 9017 aaronmk
229 9632 aaronmk
## permissions
230 9588 aaronmk
231 9632 aaronmk
mysql_seal_table() # usage: table=... user=... mysql_seal_table
232
# prevents further modifications to a table by a user
233
{
234 9634 aaronmk
	echo_func; kw_params table user; : "${table:?}" "${user:?}"; mk_table_esc
235 9632 aaronmk
236 9635 aaronmk
	benign_error=1 mysql_root <<<"REVOKE ALL PRIVILEGES ON $table FROM '$user'@'%'" || true
237 9636 aaronmk
	benign_error=1 mysql_root <<<"REVOKE GRANT OPTION   ON $table FROM '$user'@'%'" || true
238 9632 aaronmk
}
239
240
241 9014 aaronmk
### PostgreSQL
242
243 9648 aaronmk
alias use_pg='declare prefix=pg_; import_vars; unset prefix'
244
245 9649 aaronmk
fi # load new aliases
246
if self_being_included; then
247
248 10763 aaronmk
# usage: pg_*() { ...; pg_cmd "$@"; } (uses alias)
249
function pg_cmd() # usage for fn: pg_*() { ...; pg_cmd cmd "$@"; }
250
# auto-adds connection/login opts when specified
251 9646 aaronmk
{
252 13165 aaronmk
	echo_func; kw_params as_root
253 9646 aaronmk
254 9649 aaronmk
	use_pg
255 12828 aaronmk
	log_local
256 10154 aaronmk
	log- 2
257 11356 aaronmk
	if test "$server";   then local PGHOST="$server";       export PGHOST; fi
258
	if test "$user";     then local PGUSER="$user";         export PGUSER; fi
259 12846 aaronmk
	if test "$password"; then local PGPASSWORD="$password"; log++ export PGPASSWORD;fi
260 11356 aaronmk
	if test "$database"; then local PGDATABASE="$database"; export PGDATABASE;fi
261 9649 aaronmk
	log+ 2
262
263 13183 aaronmk
	time if test "$as_root"; then sudo -u postgres "$@"; else command "$@"; fi
264 10763 aaronmk
}
265
alias pg_cmd='"pg_cmd" "${FUNCNAME%%__*}"'
266
267
fi # load new aliases
268
if self_being_included; then
269
270 12739 aaronmk
psql() # usage: [stdin=copy_pstdin_file] [output_data=1] psql \
271
# <<<"cmds (eg. \copy from pstdin)"
272 11360 aaronmk
# SUDO_USER: when set, avoids outputting to /dev/fd/#, because this causes a
273
# "Permission denied" error when running as sudo on Linux
274 10763 aaronmk
{
275 12739 aaronmk
	echo_func; kw_params stdin output_data
276 12740 aaronmk
	local bypass_ok="$(! isset SUDO_USER; exit2bool)"; echo_vars bypass_ok
277
	local verbose_="$(test "$bypass_ok" && can_log; exit2bool)"
278 12737 aaronmk
		echo_vars verbose_
279 12740 aaronmk
	local data_bypasses_filter="$(test "$output_data" -a "$bypass_ok";
280 12739 aaronmk
		exit2bool)"; echo_vars data_bypasses_filter
281 10763 aaronmk
282 12737 aaronmk
	if test "$verbose_"; then set -- --echo-all --echo-hidden "$@"; fi
283 9651 aaronmk
	local redirs=("${redirs[@]}" '40<&0' "0<${stdin:-&20}" '41>&1')
284 9646 aaronmk
	(
285 10295 aaronmk
		# hide stack traces/DETAIL sections of error messages at verbosity <2
286 12829 aaronmk
		if ! log++ can_log; then echo '\set VERBOSITY terse'; fi
287 12738 aaronmk
		if test "$verbose_"; then echo '\timing on'; fi
288
		echo "SET client_min_messages = \
289
$(if test "$verbose_"; then echo NOTICE; else echo WARNING; fi);"
290 9646 aaronmk
		cat
291 12740 aaronmk
	)|cmd_log_fd=${bypass_ok:+1} pg_cmd --file /dev/fd/40 \
292 12739 aaronmk
${data_bypasses_filter:+--output /dev/fd/41 }--set ON_ERROR_STOP=1 --quiet "$@"\
293 12731 aaronmk
|| verbosity_min=2 die_error_hidden
294 9646 aaronmk
		# --output is for query *results*, not echoed statements
295
}
296
297 10755 aaronmk
pg_export() # usage: mk_select_opts... [pg_copy_format=CSV...] pg_export >out
298 9014 aaronmk
{
299
	echo_func
300 9463 aaronmk
	mk_select_var
301 9014 aaronmk
	local pg_copy_format="${pg_copy_format-CSV HEADER}"
302
303 12739 aaronmk
	output_data=1 psql "$@" <<<"COPY ($query) TO STDOUT $pg_copy_format;"
304 9014 aaronmk
}
305
306 9074 aaronmk
pg_header()
307 9014 aaronmk
{
308
	echo_func
309
	local pg_copy_format="CSV HEADER" limit=0
310 9083 aaronmk
	pg_export "$@"|echo_stdout
311 9014 aaronmk
}
312
313 9074 aaronmk
pg_export_table_no_header()
314 9014 aaronmk
{
315
	echo_func
316
	local pg_copy_format="CSV"
317 9083 aaronmk
	pg_export "$@"
318 9014 aaronmk
}
319
320 10825 aaronmk
pg_export_table_to_dir()
321
{
322
	echo_func
323
	local table="$1"; shift; mk_table_esc
324
	stdout="$exports_dir/$table.csv" to_file pg_export "$@"
325
}
326
327 9074 aaronmk
pg_export_table_to_dir_no_header()
328 9014 aaronmk
{
329
	echo_func
330
	local table="$1"; shift; mk_table_esc
331 9476 aaronmk
	stdout="$exports_dir/$table.no_header.cols=$(pg_header).csv" to_file \
332 9042 aaronmk
pg_export_table_no_header "$@"
333 9014 aaronmk
}
334
335 13166 aaronmk
pg_dump() # usage: database={...|} [schema=...] [struct=1 | data=1] [owners=1] \
336
# [compress=1] [create_schema=] [users=1] pg_dump [opts...] >out
337
# database='': entire cluster
338 10764 aaronmk
{
339 13166 aaronmk
	echo_func;kw_params database struct data owners compress create_schema users
340
	: "${database?}"
341 10775 aaronmk
	local create_schema="${create_schema-1}"
342 10764 aaronmk
343
	# subset
344
	if test "$schema"; then set -- --schema="\"$schema\"" "$@"; fi
345 13166 aaronmk
	if test "$struct"; then set -- "$@" --schema-only; fi
346
	if test "$data"  ; then set -- "$@" --data-only  ; fi
347 10764 aaronmk
348 13166 aaronmk
	if test "$database"; then # just one DB
349
		# format
350
		if test ! "$owners"; then set -- "$@" --no-owner   ; fi
351
		if test "$compress"; then set -- "$@" --format=custom --compress=9
352
							 else set -- "$@" --format=plain --inserts
353 10774 aaronmk
		fi
354
355 13166 aaronmk
		(
356
			# filter output
357
			if test ! "$create_schema"; then
358
				fd=1 redirs= filter_fd sed 's/^CREATE SCHEMA/--&/'
359
			fi
360
361
			pattern='^pg_dump: No matching tables were found$' ignore_err_msg \
362 12193 aaronmk
pg_cmd "$@"
363 13166 aaronmk
		)
364
	else # entire cluster
365
		# subset
366
		if test "$users"; then set -- "$@" --globals-only; fi
367
368
		(cd /; as_root=1 "pg_cmd" pg_dumpall "$@")
369
	fi
370 10764 aaronmk
}
371
372 12800 aaronmk
pg_schema_exists() # usage: schema=... pg_schema_exists
373 11855 aaronmk
{
374
	echo_func; : "${schema:?}"; mk_schema_esc
375 12800 aaronmk
	pattern='cannot create temporary relation in non-temporary schema' \
376 12829 aaronmk
ignore_e=3 log++ stderr_matches psql <<<"CREATE TEMP TABLE $schema_esc.t ()"
377 11855 aaronmk
}
378
379 11859 aaronmk
pg_require_schema() # usage: schema=... pg_require_schema
380
{
381
	echo_func; : "${schema:?}"
382 12806 aaronmk
	pg_schema_exists || die "schema $schema does not exist"
383 11859 aaronmk
}
384
385 12800 aaronmk
pg_table_exists() # usage: [schema=...] table=... pg_table_exists
386 11768 aaronmk
{
387
	echo_func; : "${table:?}"; mk_table_esc
388 12865 aaronmk
	! pattern='relation .* does not exist' \
389 12829 aaronmk
ignore_e=3 log++ stderr_matches psql <<<"SELECT NULL FROM $table_esc LIMIT 0"
390 11768 aaronmk
}
391
392 9014 aaronmk
fi