Project

General

Profile

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