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";       export PGHOST; fi
277
	if test "$user";     then local PGUSER="$user";         export PGUSER; fi
278
	if test "$password"; then local PGPASSWORD="$password"; log++ export PGPASSWORD;fi
279
	if test "$database"; then local PGDATABASE="$database"; export PGDATABASE;fi
280
	log++
281
	
282
	time if test "$as_root"; then sudo -u postgres "$@"; else command "$@"; fi
283
}
284
alias pg_cmd='"pg_cmd" "${FUNCNAME%%__*}"'
285

    
286
fi # load new aliases
287
if self_being_included; then
288

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

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

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

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

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

    
361
## backups
362

    
363
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
{
367
	echo_func; use_pg # import $pg_database
368
	kw_params database struct data owners compress create_schema users
369
	: "${database?}"
370
	local create_schema="${create_schema-1}"
371
	
372
	# subset
373
	if test "$schema"; then set -- --schema="\"$schema\"" "$@"; fi
374
	if test "$struct"; then set -- "$@" --schema-only; fi
375
	if test "$data"  ; then set -- "$@" --data-only  ; fi
376
	
377
	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
		fi
383
		
384
		(
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
pg_cmd "$@"
392
		)
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
}
400

    
401
## DB structure
402

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

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

    
419
public_schema_exists() { log-- echo_func; schema=public pg_schema_exists; }
420

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

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

    
434
## server admin
435

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

    
442
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
pg_snapshot() # usage: [live=] [from=...] [to=...] pg_snapshot rsync_opts...
449
{
450
	echo_func; kw_params from to; local from="${from:-/var/lib/postgresql}"
451
	
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
}
459

    
460
fi
(4-4/11)