Project

General

Profile

1
#!/bin/bash -e
2
. "$(dirname "${BASH_SOURCE[0]}")"/util.sh
3
.rel sync.sh
4

    
5
if self_not_included; then
6

    
7
# using prefixed connection vars
8
# idempotent
9
alias ssh2local='declare prefix=ssh_; import_vars; unset prefix
10
declare $(prefix=ssh_ get_prefix_vars); unset $(prefix=ssh_ get_prefix_vars)'
11
alias use_local='declare prefix=local_; import_vars; unset prefix'
12
alias use_remote='declare prefix=remote_; import_vars; unset prefix'
13
alias use_local_remote='{ use_remote; use_local; }'
14
	# *must* be run inside a function
15
alias use_root='declare prefix=root_; import_vars; unset prefix'
16

    
17
quote='"'
18

    
19
esc_name() { echo "$quote${1//$quote/$quote$quote}$quote"; }
20

    
21
mk_esc_name_alias() # usage: mk_esc_name_alias schema_esc
22
{ alias mk_"$1"='declare '"$1"'="${'"$1"':-$(esc_name "$'"${1%_esc}"'")}"; '\
23
'echo_vars '"$1"; }
24

    
25
mk_esc_name_alias schema_esc
26
mk_esc_name_alias table_esc
27

    
28
fi # load new aliases
29
if self_being_included; then
30

    
31
skip_table() # usage: create_table || { table=... skip_table; return 0; }
32
{ what="table $table" already_exists_msg; }
33

    
34
: "${test=$(isset limit; exit2bool)}" # test mode when using limited # rows
35

    
36
# 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
limit() # usage: "query... $([prefix=$'| |\n'] [limit|n=#] limit)"
41
{
42
	echo_func; kw_params prefix; local prefix="${prefix-
43
}"
44
	if isset n; then local limit="${limit-$n}"; fi
45
	echo -n "${limit:+${prefix}LIMIT $limit}"
46
}
47

    
48
cols2list() # usage: cols2list col...
49
{ echo_func; cmd=esc_name foreach_arg; delim=', ' join "$@"; }
50

    
51
mk_select() # usage: {query=... | table=... [cols=...] [filter=...] \
52
# [order_by=...]} [limit|n=#] mk_select
53
{
54
	echo_func; kw_params query table cols filter; mk_table_esc
55
	if is_array cols    ; then cols="$(    cols2list "${cols[@]}"    )"; fi
56
	if is_array order_by; then order_by="$(cols2list "${order_by[@]}")"; fi
57
	echo "$(rtrim "${query:-SELECT ${cols:-*} ${cols:+
58
}FROM $table_esc
59
${filter:+WHERE $filter
60
}${order_by:+ORDER BY $order_by
61
}}")\
62
$(limit)"
63
}
64

    
65
# 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
fi # load new aliases
71
if self_being_included; then
72

    
73
mk_drop() # usage: table=... mk_drop|*sql_ANSI
74
{
75
	log_local; log++; echo_func; kw_params table; : "${table?}"; mk_table_esc
76
	echo "DROP TABLE IF EXISTS $table_esc"
77
}
78

    
79
mk_truncate() # usage: table=... mk_truncate|*sql_ANSI
80
{
81
	log_local; log++; echo_func; kw_params table; : "${table?}"; mk_table_esc
82
	echo "TRUNCATE $table_esc"
83
}
84

    
85

    
86
### MySQL
87

    
88
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
# usage: mysql*() { ...; mysql_cmd "$@"; } (with alias)
95
# caller usage: [ssh_server=...] [server=...] [user=...] [password=...] mysql*()
96
function mysql_cmd() # usage: mysql*() { ...; mysql_cmd cmd "$@"; }
97
# auto-adds connection/login opts when specified
98
{
99
	echo_func
100
	local cmd="$1"; shift
101
	local ssh_server="$(localize_url "$ssh_server")"
102
	local server="$(localize_url "$server")"
103
	if test "$ssh_server"; then
104
		local ssh_dest="${ssh_dest-${ssh_user:+$ssh_user@}$ssh_server}"
105
	fi
106
	
107
	local var=ssh_dest; local_inv
108
	command "time" ${ssh_dest:+ssh "$ssh_dest" }"$cmd" \
109
${server:+ --host="$server" }${user:+--user="$user" } --password\
110
${password+="$password"} --quick "$@" # --quick: don't buffer entire result
111
}
112
alias mysql_cmd='mysql_cmd "$FUNCNAME"'
113

    
114
fi # load new aliases
115
if self_being_included; then
116

    
117
function mysql() # usage: [database=...] [data_only=1] [log_queries=] mysql ...
118
{
119
	echo_func; kw_params output_data data_only query_verbosity
120
	if test "$data_only"; then local output_data="${output_data-1}"; fi
121
	local log_queries="${log_queries-1}"
122
	set_database
123
	
124
	set -- ${database:+--database="$database" }--local-infile=1 \
125
--${data_only:+skip-}column-names "$@"
126
	if test "$output_data"; then echo_stdin|mysql_cmd --batch "$@"
127
	else cmd_log_fd=1 mysql_cmd ${log_queries:+--verbose --verbose --verbose }\
128
"$@" # --verbose*3: echo runtimes
129
	fi
130
}
131

    
132
mysql_ANSI()
133
{
134
	echo_func
135
	(echo "SET sql_mode = 'ANSI';"; cat)|mysql "$@"
136
}
137

    
138
# always use ANSI mode, to support "" identifiers. `` *are* still supported in
139
# this mode, so it also works with SHOW CREATE TABLE output and dumpfiles.
140
alias mysql='mysql_ANSI'
141

    
142
fi # load new aliases
143
if self_being_included; then
144

    
145
mysql_root() { echo_func; use_root; mysql "$@"; }
146

    
147
mysql_truncate() { echo_func; mk_truncate|mysql; }
148

    
149
mysql_import() # usage: table=... [cols=...] [append=1] mysql_import <file
150
# without append=1, first ensures the table is empty
151
{
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
	if test ! "$append"; then mysql_truncate; fi
160
	mysql_load_data_format="${mysql_load_data_format%
161
}"
162
	ssh2local # ssh does not tunnel nonstandard fds
163
	mysql "$@" 40<&0 <<EOF
164
LOAD DATA LOCAL INFILE '/dev/fd/40'
165
${append:+IGNORE }INTO TABLE $table_esc
166
$mysql_load_data_format
167
IGNORE 1 LINES
168
EOF
169
}
170

    
171
mysql_export() # does not support CSV
172
# caller usage: [database=...] {query=... | table=... [cols=...] [filter=...]} \
173
# mysql_export
174
# cmd line usage: [limit=...] caller
175
{
176
	echo_func
177
	mk_select_var
178
	
179
	output_data=1 mysql "$@" <<<"$query"
180
}
181

    
182
mysql_export_outfile() # supports CSV, but requires the FILE privilege
183
{
184
	echo_func
185
	: "${file:?}"
186
	mk_select_var
187
	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
	head="${head%
194
}"
195
	local tail="${query#$head}"
196
	mysql_load_data_format="${mysql_load_data_format%
197
}"
198
	mysql "$@" <<EOF
199
$head
200
INTO OUTFILE '$file'
201
$mysql_load_data_format
202
$tail
203
EOF
204
}
205

    
206
## backups
207

    
208
mysqldump() # usage: [schema=1 | data=1] [create_db=1] mysqldump db [table...]
209
{
210
	echo_func
211
	echo_vars schema data create_db
212
	
213
	local var=create_db; local_inv
214
	mysql_cmd ${database:+--databases "$database" ${no_create_db:+--tables }} \
215
--lock-tables=false --set-charset \
216
${postgres_compat:+${data:+--compatible=postgresql }--add-locks=false }\
217
${schema:+--no-data }${data:+--no-create-info }"$@"
218
}
219

    
220
mysqldump_diffable()
221
{
222
	echo_func
223
	mysqldump "$@"|{ pipe_delay; echo_run sed 's/^(-- Dump completed).*$/\1/'; }
224
}
225

    
226
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

    
233
## permissions
234

    
235
mysql_seal_table() # usage: table=... user=... mysql_seal_table
236
# prevents further modifications to a table by a user
237
{
238
	echo_func; kw_params table user; : "${table:?}" "${user:?}"; mk_table_esc
239
	
240
	benign_error=1 mysql_root <<<"REVOKE ALL PRIVILEGES ON $table FROM '$user'@'%'" || true
241
	benign_error=1 mysql_root <<<"REVOKE GRANT OPTION   ON $table FROM '$user'@'%'" || true
242
}
243

    
244
## server admin
245

    
246
mysql_ctl() # usage: mysql_ctl {start|stop|restart|...}
247
{
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

    
253
mysql_snapshot() # usage: [live=] [from=...] [to=...] mysql_snapshot rsync_opts
254
{
255
	echo_func; kw_params from to; local from="${from:-/var/lib/mysql}"
256
	ctl=mysql_ctl db_snapshot "$@"
257
}
258

    
259

    
260
### PostgreSQL
261

    
262
alias use_pg='declare prefix=pg_; import_vars; unset prefix'
263

    
264
fi # load new aliases
265
if self_being_included; then
266

    
267
# 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
{
271
	echo_func; kw_params as_root
272
	
273
	use_pg
274
	log_local
275
	log--
276
	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
	log++
283
	
284
	time if test "$as_root"; then sudo -u postgres "$@"; else command "$@"; fi
285
}
286
alias pg_cmd='"pg_cmd" "${FUNCNAME%%__*}"'
287

    
288
fi # load new aliases
289
if self_being_included; then
290

    
291
psql() # usage: [stdin=copy_pstdin_file|<(pstdin_cmd)] [output_data=1] psql \
292
# <<<"cmds (eg. \copy from pstdin)"
293
# $as_root: when on, avoids redirections as these are not passed through by sudo
294
# SUDO_USER: when set, avoids outputting to /dev/fd/#, because this causes a
295
# "Permission denied" error when running as sudo on Linux
296
{
297
	echo_func; kw_params stdin output_data
298
	local can_redir="$(! test "$as_root" && ! isset SUDO_USER; exit2bool)"
299
		echo_vars can_redir
300
	if test "$stdin"; then
301
		test "$can_redir" || die 'custom $stdin not supported with sudo'
302
	fi
303
	local verbose_="$(test "$can_redir" && can_log; exit2bool)"
304
		echo_vars verbose_
305
	local data2stdout="$(test "$output_data" -a "$can_redir"; exit2bool)"
306
		echo_vars data2stdout
307
	
308
	if test "$verbose_"; then set -- --echo-all --echo-hidden "$@"; fi
309
	if test "$can_redir"; then
310
		local redirs=("${redirs[@]}" '40<&0' "0<${stdin:-&20}" '41>&1')
311
	fi
312
	(
313
		# hide stack traces/DETAIL sections of error messages at verbosity <2
314
		if ! log++ can_log; then echo '\set VERBOSITY terse'; fi
315
		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
		cat
319
	)|cmd_log_fd=${can_redir:+1} pg_cmd ${can_redir:+--file /dev/fd/40 }\
320
${data2stdout:+--output /dev/fd/41 }--set ON_ERROR_STOP=1 --quiet "$@"\
321
|| verbosity_min=2 die_error_hidden
322
		# --output is for query *results*, not echoed statements
323
}
324

    
325
pg_export() # usage: mk_select_opts... [pg_copy_format=CSV...] pg_export >out
326
{
327
	echo_func
328
	mk_select_var
329
	local pg_copy_format="${pg_copy_format-CSV HEADER}"
330
	
331
	output_data=1 psql "$@" <<<"COPY ($query) TO STDOUT $pg_copy_format;"
332
}
333

    
334
pg_header()
335
{
336
	echo_func
337
	local pg_copy_format="CSV HEADER" limit=0
338
	pg_export "$@"|echo_stdout
339
}
340

    
341
pg_export_table_no_header()
342
{
343
	echo_func
344
	local pg_copy_format="CSV"
345
	pg_export "$@"
346
}
347

    
348
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
pg_export_table_to_dir_no_header()
356
{
357
	echo_func
358
	local table="$1"; shift; mk_table_esc
359
	stdout="$exports_dir/$table.no_header.cols=$(pg_header).csv" to_file \
360
pg_export_table_no_header "$@"
361
}
362

    
363
## backups
364

    
365
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
{
369
	echo_func; use_pg # import $pg_database
370
	kw_params database struct data owners compress create_schema users
371
	: "${database?}"
372
	local create_schema="${create_schema-1}"
373
	
374
	# subset
375
	if test "$schema"; then set -- --schema="\"$schema\"" "$@"; fi
376
	if test "$struct"; then set -- "$@" --schema-only; fi
377
	if test "$data"  ; then set -- "$@" --data-only  ; fi
378
	
379
	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
		fi
385
		
386
		(
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
pg_cmd "$@"
394
		)
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
}
402

    
403
## DB structure
404

    
405
benign_does_not_exist_error() # usage: type=what benign_does_not_exist_error cmd
406
{
407
	log-- echo_func; : "${type:?}"
408
	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
}
411

    
412
pg_schema_exists() # usage: schema=__ [benign_error=1] pg_schema_exists
413
{
414
	log-- echo_func; : "${schema:?}"; mk_schema_esc
415
	# produces error both if true and if false
416
	pattern='cannot create temporary relation in non-temporary schema' \
417
ignore_e=3 type=schema stderr_matches benign_does_not_exist_error \
418
psql <<<"CREATE TEMP TABLE $schema_esc.t ()"
419
}
420

    
421
public_schema_exists() { log-- echo_func; schema=public pg_schema_exists; }
422

    
423
pg_require_schema() # usage: schema=... pg_require_schema
424
{
425
	echo_func; : "${schema:?}"
426
	pg_schema_exists || die "schema $schema does not exist"
427
}
428

    
429
pg_table_exists() # usage: [schema=__] table=__ [benign_error=1] pg_table_exists
430
{
431
	echo_func; : "${table:?}"; mk_table_esc
432
	! pattern='relation .* does not exist' \
433
ignore_e=3 log++ stderr_matches psql <<<"SELECT NULL FROM $table_esc LIMIT 0"
434
}
435

    
436
## server admin
437

    
438
pg_ctl() # usage: pg_ctl {start|stop|restart|...}
439
{
440
	echo_func
441
	sudo service postgresql "$@"
442
}
443

    
444
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
pg_snapshot() # usage: [live=] [from=...] [to=...] pg_snapshot rsync_opts...
451
{
452
	echo_func; kw_params from to; local from="${from:-/var/lib/postgresql}"
453
	
454
	if pg_start_backup; then # perform online backup
455
		try db_copy "$@"
456
		pg_stop_backup
457
		end_try
458
	else ctl=pg_ctl db_snapshot "$@" # fall back to stopping server
459
	fi
460
}
461

    
462
fi
(4-4/11)