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
alias ssh2local='declare prefix=ssh_; import_vars; unset prefix
9
declare $(prefix=ssh_ get_prefix_vars); unset $(prefix=ssh_ get_prefix_vars)'
10
alias use_local='declare prefix=local_; import_vars; unset prefix'
11
alias use_remote='declare prefix=remote_; import_vars; unset prefix'
12
alias use_local_remote='{ use_remote; use_local; }'
13
	# *must* be run inside a function
14
alias use_root='declare prefix=root_; import_vars; unset prefix'
15

    
16
quote='"'
17

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

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

    
24
mk_esc_name_alias schema_esc
25
mk_esc_name_alias table_esc
26

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

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

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

    
35
# usage: (set_large_table; to_file db_cmd...) || return
36
alias set_large_table='declare del="${del-$(test "$limit"; exit2bool)}"
37
echo_vars del'
38

    
39
limit() # usage: "query... $([prefix=$'| |\n'] [limit|n=#] limit)"
40
{
41
	echo_func; kw_params prefix; local prefix="${prefix-
42
}"
43
	if isset n; then local limit="${limit-$n}"; fi
44
	echo -n "${limit:+${prefix}LIMIT $limit}"
45
}
46

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

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

    
64
# export func usage: export_func() { ...; mk_select_var; ... }
65
# caller usage: {query=... | table=... [cols=...] [filter=...]} export_func
66
# cmd line usage: [limit=...] caller
67
alias mk_select_var='declare query="$(mk_select)"'
68

    
69
fi # load new aliases
70
if self_being_included; then
71

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

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

    
84

    
85
### MySQL
86

    
87
alias set_database=\
88
'if test "$schema"; then declare database="${database-$schema}"; fi'
89

    
90
fi # load new aliases
91
if self_being_included; then
92

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

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

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

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

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

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

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

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

    
148
mysql_import() # usage: table=... [cols=...] [append=1] mysql_import <file
149
# without append=1, first ensures the table is empty
150
{
151
	echo_func
152
	mk_table_esc
153
	local mysql_load_data_format="${mysql_load_data_format-\
154
FIELDS TERMINATED BY ','
155
OPTIONALLY ENCLOSED BY '\"'
156
}"
157
	
158
	if test ! "$append"; then mysql_truncate; fi
159
	mysql_load_data_format="${mysql_load_data_format%
160
}"
161
	ssh2local # ssh does not tunnel nonstandard fds
162
	mysql "$@" 40<&0 <<EOF
163
LOAD DATA LOCAL INFILE '/dev/fd/40'
164
${append:+IGNORE }INTO TABLE $table_esc
165
$mysql_load_data_format
166
IGNORE 1 LINES
167
EOF
168
}
169

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

    
181
mysql_export_outfile() # supports CSV, but requires the FILE privilege
182
{
183
	echo_func
184
	: "${file:?}"
185
	mk_select_var
186
	local mysql_load_data_format="${mysql_load_data_format-\
187
FIELDS TERMINATED BY ','
188
OPTIONALLY ENCLOSED BY '\"'
189
}"
190
	
191
	local head="${query%%FROM*}" # includes trailing newline
192
	head="${head%
193
}"
194
	local tail="${query#$head}"
195
	mysql_load_data_format="${mysql_load_data_format%
196
}"
197
	mysql "$@" <<EOF
198
$head
199
INTO OUTFILE '$file'
200
$mysql_load_data_format
201
$tail
202
EOF
203
}
204

    
205
## backups
206

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

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

    
225
mysql_rm_privileged_statements()
226
{
227
	echo_func
228
	grep -vE -e '^/\*!40000 ALTER TABLE `.*` (DIS|EN)ABLE KEYS \*/;$' \
229
-e '^(UN)?LOCK TABLES( `.*` WRITE)?;$'
230
}
231

    
232
## permissions
233

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

    
243
## server admin
244

    
245
mysql_ctl() # usage: mysql_ctl {start|stop|restart|...}
246
{
247
	echo_func
248
	pattern='^stop: Unknown instance:' ignore_e=1 ignore_err_msg \
249
sudo service mysql "$@" # ignore errors if not running
250
}
251

    
252
mysql_snapshot() # usage: live=1 [from=...] [to=...] mysql_snapshot
253
{
254
	echo_func; kw_params from to
255
	local from="${from:-/var/lib/mysql}"; local to="${to:-$from.bak}"
256
	
257
	mysql_ctl stop
258
	local_dir="$from" remote_url="$to" try sudo upload
259
	mysql_ctl start
260
	rethrow
261
}
262

    
263

    
264
### PostgreSQL
265

    
266
alias use_pg='declare prefix=pg_; import_vars; unset prefix'
267

    
268
fi # load new aliases
269
if self_being_included; then
270

    
271
# usage: pg_*() { ...; pg_cmd "$@"; } (uses alias)
272
function pg_cmd() # usage for fn: pg_*() { ...; pg_cmd cmd "$@"; }
273
# auto-adds connection/login opts when specified
274
{
275
	echo_func; kw_params as_root
276
	
277
	use_pg
278
	log_local
279
	log- 2
280
	if test "$server";   then local PGHOST="$server";       export PGHOST; fi
281
	if test "$user";     then local PGUSER="$user";         export PGUSER; fi
282
	if test "$password"; then local PGPASSWORD="$password"; log++ export PGPASSWORD;fi
283
	if test "$database"; then local PGDATABASE="$database"; export PGDATABASE;fi
284
	log+ 2
285
	
286
	time if test "$as_root"; then sudo -u postgres "$@"; else command "$@"; fi
287
}
288
alias pg_cmd='"pg_cmd" "${FUNCNAME%%__*}"'
289

    
290
fi # load new aliases
291
if self_being_included; then
292

    
293
psql() # usage: [stdin=copy_pstdin_file] [output_data=1] psql \
294
# <<<"cmds (eg. \copy from pstdin)"
295
# SUDO_USER: when set, avoids outputting to /dev/fd/#, because this causes a
296
# "Permission denied" error when running as sudo on Linux
297
{
298
	echo_func; kw_params stdin output_data
299
	local bypass_ok="$(! isset SUDO_USER; exit2bool)"; echo_vars bypass_ok
300
	local verbose_="$(test "$bypass_ok" && can_log; exit2bool)"
301
		echo_vars verbose_
302
	local data_bypasses_filter="$(test "$output_data" -a "$bypass_ok";
303
		exit2bool)"; echo_vars data_bypasses_filter
304
	
305
	if test "$verbose_"; then set -- --echo-all --echo-hidden "$@"; fi
306
	local redirs=("${redirs[@]}" '40<&0' "0<${stdin:-&20}" '41>&1')
307
	(
308
		# hide stack traces/DETAIL sections of error messages at verbosity <2
309
		if ! log++ can_log; then echo '\set VERBOSITY terse'; fi
310
		if test "$verbose_"; then echo '\timing on'; fi
311
		echo "SET client_min_messages = \
312
$(if test "$verbose_"; then echo NOTICE; else echo WARNING; fi);"
313
		cat
314
	)|cmd_log_fd=${bypass_ok:+1} pg_cmd --file /dev/fd/40 \
315
${data_bypasses_filter:+--output /dev/fd/41 }--set ON_ERROR_STOP=1 --quiet "$@"\
316
|| verbosity_min=2 die_error_hidden
317
		# --output is for query *results*, not echoed statements
318
}
319

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

    
329
pg_header()
330
{
331
	echo_func
332
	local pg_copy_format="CSV HEADER" limit=0
333
	pg_export "$@"|echo_stdout
334
}
335

    
336
pg_export_table_no_header()
337
{
338
	echo_func
339
	local pg_copy_format="CSV"
340
	pg_export "$@"
341
}
342

    
343
pg_export_table_to_dir()
344
{
345
	echo_func
346
	local table="$1"; shift; mk_table_esc
347
	stdout="$exports_dir/$table.csv" to_file pg_export "$@"
348
}
349

    
350
pg_export_table_to_dir_no_header()
351
{
352
	echo_func
353
	local table="$1"; shift; mk_table_esc
354
	stdout="$exports_dir/$table.no_header.cols=$(pg_header).csv" to_file \
355
pg_export_table_no_header "$@"
356
}
357

    
358
pg_dump() # usage: database={...|} [schema=...] [struct=1 | data=1] [owners=1] \
359
# [compress=1] [create_schema=] [users=1] pg_dump [opts...] >out
360
# database='': entire cluster
361
{
362
	echo_func;kw_params database struct data owners compress create_schema users
363
	: "${database?}"
364
	local create_schema="${create_schema-1}"
365
	
366
	# subset
367
	if test "$schema"; then set -- --schema="\"$schema\"" "$@"; fi
368
	if test "$struct"; then set -- "$@" --schema-only; fi
369
	if test "$data"  ; then set -- "$@" --data-only  ; fi
370
	
371
	if test "$database"; then # just one DB
372
		# format
373
		if test ! "$owners"; then set -- "$@" --no-owner   ; fi
374
		if test "$compress"; then set -- "$@" --format=custom --compress=9
375
							 else set -- "$@" --format=plain --inserts
376
		fi
377
		
378
		(
379
			# filter output
380
			if test ! "$create_schema"; then
381
				fd=1 redirs= filter_fd sed 's/^CREATE SCHEMA/--&/'
382
			fi
383
			
384
			pattern='^pg_dump: No matching tables were found$' ignore_err_msg \
385
pg_cmd "$@"
386
		)
387
	else # entire cluster
388
		# subset
389
		if test "$users"; then set -- "$@" --globals-only; fi
390
		
391
		(cd /; as_root=1 "pg_cmd" pg_dumpall "$@")
392
	fi
393
}
394

    
395
pg_schema_exists() # usage: schema=... pg_schema_exists
396
{
397
	echo_func; : "${schema:?}"; mk_schema_esc
398
	pattern='cannot create temporary relation in non-temporary schema' \
399
ignore_e=3 log++ stderr_matches psql <<<"CREATE TEMP TABLE $schema_esc.t ()"
400
}
401

    
402
pg_require_schema() # usage: schema=... pg_require_schema
403
{
404
	echo_func; : "${schema:?}"
405
	pg_schema_exists || die "schema $schema does not exist"
406
}
407

    
408
pg_table_exists() # usage: [schema=...] table=... pg_table_exists
409
{
410
	echo_func; : "${table:?}"; mk_table_esc
411
	! pattern='relation .* does not exist' \
412
ignore_e=3 log++ stderr_matches psql <<<"SELECT NULL FROM $table_esc LIMIT 0"
413
}
414

    
415
fi
(4-4/11)