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 9623 aaronmk
skip_table() # usage: create_table || table=... skip_table || return 0
32
{ 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 11356 aaronmk
	if test "$server";   then local PGHOST="$server";       export PGHOST; fi
277
	if test "$user";     then local PGUSER="$user";         export PGUSER; fi
278 12846 aaronmk
	if test "$password"; then local PGPASSWORD="$password"; log++ export PGPASSWORD;fi
279 11356 aaronmk
	if test "$database"; then local PGDATABASE="$database"; export PGDATABASE;fi
280 13340 aaronmk
	log++
281 9649 aaronmk
282 13183 aaronmk
	time if test "$as_root"; then sudo -u postgres "$@"; else command "$@"; fi
283 10763 aaronmk
}
284
alias pg_cmd='"pg_cmd" "${FUNCNAME%%__*}"'
285
286
fi # load new aliases
287
if self_being_included; then
288
289 13279 aaronmk
psql() # usage: [stdin=copy_pstdin_file|<(pstdin_cmd)] [output_data=1] psql \
290 12739 aaronmk
# <<<"cmds (eg. \copy from pstdin)"
291 13285 aaronmk
# $as_root: when on, avoids redirections as these are not passed through by sudo
292 11360 aaronmk
# SUDO_USER: when set, avoids outputting to /dev/fd/#, because this causes a
293
# "Permission denied" error when running as sudo on Linux
294 10763 aaronmk
{
295 12739 aaronmk
	echo_func; kw_params stdin output_data
296 13285 aaronmk
	local can_redir="$(! test "$as_root" && ! isset SUDO_USER; exit2bool)"
297
		echo_vars can_redir
298 13282 aaronmk
	if test "$stdin"; then
299
		test "$can_redir" || die 'custom $stdin not supported with sudo'
300
	fi
301 13280 aaronmk
	local verbose_="$(test "$can_redir" && can_log; exit2bool)"
302 12737 aaronmk
		echo_vars verbose_
303 13281 aaronmk
	local data2stdout="$(test "$output_data" -a "$can_redir"; exit2bool)"
304
		echo_vars data2stdout
305 10763 aaronmk
306 12737 aaronmk
	if test "$verbose_"; then set -- --echo-all --echo-hidden "$@"; fi
307 13286 aaronmk
	if test "$can_redir"; then
308
		local redirs=("${redirs[@]}" '40<&0' "0<${stdin:-&20}" '41>&1')
309
	fi
310 9646 aaronmk
	(
311 10295 aaronmk
		# hide stack traces/DETAIL sections of error messages at verbosity <2
312 12829 aaronmk
		if ! log++ can_log; then echo '\set VERBOSITY terse'; fi
313 12738 aaronmk
		if test "$verbose_"; then echo '\timing on'; fi
314
		echo "SET client_min_messages = \
315
$(if test "$verbose_"; then echo NOTICE; else echo WARNING; fi);"
316 9646 aaronmk
		cat
317 13283 aaronmk
	)|cmd_log_fd=${can_redir:+1} pg_cmd ${can_redir:+--file /dev/fd/40 }\
318 13281 aaronmk
${data2stdout:+--output /dev/fd/41 }--set ON_ERROR_STOP=1 --quiet "$@"\
319 13328 aaronmk
|| verbosity_min=2 die_error_hidden
320 9646 aaronmk
		# --output is for query *results*, not echoed statements
321
}
322
323 10755 aaronmk
pg_export() # usage: mk_select_opts... [pg_copy_format=CSV...] pg_export >out
324 9014 aaronmk
{
325
	echo_func
326 9463 aaronmk
	mk_select_var
327 9014 aaronmk
	local pg_copy_format="${pg_copy_format-CSV HEADER}"
328
329 12739 aaronmk
	output_data=1 psql "$@" <<<"COPY ($query) TO STDOUT $pg_copy_format;"
330 9014 aaronmk
}
331
332 9074 aaronmk
pg_header()
333 9014 aaronmk
{
334
	echo_func
335
	local pg_copy_format="CSV HEADER" limit=0
336 9083 aaronmk
	pg_export "$@"|echo_stdout
337 9014 aaronmk
}
338
339 9074 aaronmk
pg_export_table_no_header()
340 9014 aaronmk
{
341
	echo_func
342
	local pg_copy_format="CSV"
343 9083 aaronmk
	pg_export "$@"
344 9014 aaronmk
}
345
346 10825 aaronmk
pg_export_table_to_dir()
347
{
348
	echo_func
349
	local table="$1"; shift; mk_table_esc
350
	stdout="$exports_dir/$table.csv" to_file pg_export "$@"
351
}
352
353 9074 aaronmk
pg_export_table_to_dir_no_header()
354 9014 aaronmk
{
355
	echo_func
356
	local table="$1"; shift; mk_table_esc
357 9476 aaronmk
	stdout="$exports_dir/$table.no_header.cols=$(pg_header).csv" to_file \
358 9042 aaronmk
pg_export_table_no_header "$@"
359 9014 aaronmk
}
360
361 13262 aaronmk
## backups
362
363 13166 aaronmk
pg_dump() # usage: database={...|} [schema=...] [struct=1 | data=1] [owners=1] \
364
# [compress=1] [create_schema=] [users=1] pg_dump [opts...] >out
365
# database='': entire cluster
366 10764 aaronmk
{
367 13365 aaronmk
	echo_func; use_pg # import $pg_database
368
	kw_params database struct data owners compress create_schema users
369 13166 aaronmk
	: "${database?}"
370 10775 aaronmk
	local create_schema="${create_schema-1}"
371 10764 aaronmk
372
	# subset
373
	if test "$schema"; then set -- --schema="\"$schema\"" "$@"; fi
374 13166 aaronmk
	if test "$struct"; then set -- "$@" --schema-only; fi
375
	if test "$data"  ; then set -- "$@" --data-only  ; fi
376 10764 aaronmk
377 13166 aaronmk
	if test "$database"; then # just one DB
378
		# format
379
		if test ! "$owners"; then set -- "$@" --no-owner   ; fi
380
		if test "$compress"; then set -- "$@" --format=custom --compress=9
381
							 else set -- "$@" --format=plain --inserts
382 10774 aaronmk
		fi
383
384 13166 aaronmk
		(
385
			# filter output
386
			if test ! "$create_schema"; then
387
				fd=1 redirs= filter_fd sed 's/^CREATE SCHEMA/--&/'
388
			fi
389
390
			pattern='^pg_dump: No matching tables were found$' ignore_err_msg \
391 12193 aaronmk
pg_cmd "$@"
392 13166 aaronmk
		)
393
	else # entire cluster
394
		# subset
395
		if test "$users"; then set -- "$@" --globals-only; fi
396
397
		(cd /; as_root=1 "pg_cmd" pg_dumpall "$@")
398
	fi
399 10764 aaronmk
}
400
401 13262 aaronmk
## DB structure
402
403 13351 aaronmk
benign_does_not_exist_error() # usage: type=what benign_does_not_exist_error cmd
404
{
405
	log-- echo_func; : "${type:?}"
406 13354 aaronmk
	pattern="$type .* does not exist" benign_error=1 ignore_err_msg "$@"
407
		# no ignore_e=3, because this exit status also used for other errors
408 13351 aaronmk
}
409
410 13343 aaronmk
pg_schema_exists() # usage: schema=__ [benign_error=1] pg_schema_exists
411 11855 aaronmk
{
412 13339 aaronmk
	log-- echo_func; : "${schema:?}"; mk_schema_esc
413 13351 aaronmk
	# produces error both if true and if false
414 12800 aaronmk
	pattern='cannot create temporary relation in non-temporary schema' \
415 13351 aaronmk
ignore_e=3 type=schema stderr_matches benign_does_not_exist_error \
416
psql <<<"CREATE TEMP TABLE $schema_esc.t ()"
417 11855 aaronmk
}
418
419 13347 aaronmk
public_schema_exists() { log-- echo_func; schema=public pg_schema_exists; }
420
421 11859 aaronmk
pg_require_schema() # usage: schema=... pg_require_schema
422
{
423
	echo_func; : "${schema:?}"
424 12806 aaronmk
	pg_schema_exists || die "schema $schema does not exist"
425 11859 aaronmk
}
426
427 13343 aaronmk
pg_table_exists() # usage: [schema=__] table=__ [benign_error=1] pg_table_exists
428 11768 aaronmk
{
429
	echo_func; : "${table:?}"; mk_table_esc
430 12865 aaronmk
	! pattern='relation .* does not exist' \
431 12829 aaronmk
ignore_e=3 log++ stderr_matches psql <<<"SELECT NULL FROM $table_esc LIMIT 0"
432 11768 aaronmk
}
433
434 13262 aaronmk
## server admin
435
436
pg_ctl() # usage: pg_ctl {start|stop|restart|...}
437
{
438
	echo_func
439
	sudo service postgresql "$@"
440
}
441
442 13287 aaronmk
pg_start_backup() # requires config `wal_level = archive|hot_standby`
443
{ echo_func; as_root=1 psql <<<"SELECT pg_start_backup('backup', true);"; }
444
445
pg_stop_backup() # requires pg_start_backup() to have run
446
{ echo_func; as_root=1 psql <<<"SELECT pg_stop_backup();"; }
447
448 13264 aaronmk
pg_snapshot() # usage: [live=] [from=...] [to=...] pg_snapshot rsync_opts...
449 13262 aaronmk
{
450
	echo_func; kw_params from to; local from="${from:-/var/lib/postgresql}"
451 13288 aaronmk
452
	if pg_start_backup; then # perform online backup
453
		try db_copy "$@"
454
		pg_stop_backup
455
		end_try
456
	else ctl=pg_ctl db_snapshot "$@" # fall back to stopping server
457
	fi
458 13262 aaronmk
}
459
460 9014 aaronmk
fi