Project

General

Profile

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

    
4
if self_not_included; then
5

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

    
15
quote='"'
16

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

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

    
23
mk_esc_name_alias schema_esc
24
mk_esc_name_alias table_esc
25

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

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

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

    
36
limit() # usage: "query... $([prefix=$'| |\n'] limit)"
37
{
38
	echo_func; kw_params prefix; local prefix="${prefix-
39
}"
40
	echo -n "${limit:+${prefix}LIMIT $limit}"
41
}
42

    
43
mk_select() # usage: {query=... | table=... [cols=...] [filter=...]} mk_select
44
{
45
	echo_func; kw_params query table cols filter; mk_table_esc
46
	echo "$(rtrim "${query:-SELECT ${cols:-*} ${cols:+
47
}FROM $table_esc
48
${filter:+WHERE $filter
49
}}")\
50
$(limit)"
51
}
52

    
53
# export func usage: export_func() { ...; mk_select_var; ... }
54
# caller usage: {query=... | table=... [cols=...] [filter=...]} export_func
55
# cmd line usage: [limit=...] caller
56
alias mk_select_var='declare query="$(mk_select)"'
57

    
58
fi # load new aliases
59
if self_being_included; then
60

    
61
mk_drop() # usage: table=... mk_drop|*sql_ANSI
62
{
63
	log++; echo_func; kw_params table; : "${table?}"; mk_table_esc
64
	echo "DROP TABLE IF EXISTS $table_esc"
65
}
66

    
67
mk_truncate() # usage: table=... mk_truncate|*sql_ANSI
68
{
69
	log++; echo_func; kw_params table; : "${table?}"; mk_table_esc
70
	echo "TRUNCATE $table_esc"
71
}
72

    
73

    
74
### MySQL
75

    
76
alias set_database=\
77
'if test "$schema"; then declare database="${database-$schema}"; fi'
78

    
79
fi # load new aliases
80
if self_being_included; then
81

    
82
# usage: mysql*() { ...; mysql_cmd "$@"; } (with alias)
83
function mysql_cmd() # usage: mysql*() { ...; mysql_cmd cmd "$@"; }
84
# auto-adds connection/login opts when specified
85
{
86
	echo_func
87
	local cmd="$1"; shift
88
	local ssh_server="$(localize_url "$ssh_server")"
89
	local server="$(localize_url "$server")"
90
	if test "$ssh_server"; then
91
		local ssh_dest="${ssh_dest-${ssh_user:+$ssh_user@}$ssh_server}"
92
	fi
93
	
94
	local var=ssh_dest; local_inv
95
	command "time" ${ssh_dest:+ssh "$ssh_dest" }"$cmd" \
96
${server:+ --host="$server" }${user:+--user="$user" } --password\
97
${password+="$password"} --quick "$@" # --quick: don't buffer entire result
98
}
99
alias mysql_cmd='mysql_cmd "$FUNCNAME"'
100

    
101
fi # load new aliases
102
if self_being_included; then
103

    
104
mysql() # usage: [output_data=1] [data_only=1] [log_queries=] mysql ...
105
{
106
	echo_func; kw_params output_data data_only query_verbosity
107
	if test "$data_only"; then local output_data="${output_data-1}"; fi
108
	local log_queries="${log_queries-1}"
109
	set_database
110
	
111
	set -- ${database:+--database="$database" }--local-infile=1 \
112
--${data_only:+skip-}column-names "$@"
113
	if test "$output_data"; then echo_stdin|mysql_cmd --batch "$@"
114
	else cmd_log_fd=1 mysql_cmd ${log_queries:+--verbose --verbose --verbose }\
115
"$@" # --verbose*3: echo runtimes
116
	fi
117
}
118

    
119
mysql_root() { echo_func; use_root; mysql "$@"; }
120

    
121
mysql_ANSI()
122
{
123
	echo_func
124
	(echo "SET sql_mode = 'ANSI';"; cat)|mysql "$@"
125
}
126

    
127
mysql_truncate() { echo_func; mk_truncate|mysql_ANSI; }
128

    
129
mysql_import() # usage: table=... [cols=...] [append=1] mysql_import <file
130
# without append=1, first ensures the table is empty
131
{
132
	echo_func
133
	mk_table_esc
134
	local mysql_load_data_format="${mysql_load_data_format-\
135
FIELDS TERMINATED BY ','
136
OPTIONALLY ENCLOSED BY '\"'
137
}"
138
	
139
	if test ! "$append"; then mysql_truncate; fi
140
	mysql_load_data_format="${mysql_load_data_format%
141
}"
142
	ssh2local # ssh does not tunnel nonstandard fds
143
	mysql_ANSI "$@" 40<&0 <<EOF
144
LOAD DATA LOCAL INFILE '/dev/fd/40'
145
${append:+IGNORE }INTO TABLE $table_esc
146
$mysql_load_data_format
147
IGNORE 1 LINES
148
EOF
149
}
150

    
151
mysql_export() # does not support CSV
152
# caller usage: {query=... | table=... [cols=...] [filter=...]} mysql_export
153
# cmd line usage: [limit=...] caller
154
{
155
	echo_func
156
	mk_select_var
157
	
158
	output_data=1 mysql_ANSI "$@" <<<"$query"
159
}
160

    
161
mysql_export_outfile() # supports CSV, but requires the FILE privilege
162
{
163
	echo_func
164
	: "${file:?}"
165
	mk_select_var
166
	local mysql_load_data_format="${mysql_load_data_format-\
167
FIELDS TERMINATED BY ','
168
OPTIONALLY ENCLOSED BY '\"'
169
}"
170
	
171
	local head="${query%%FROM*}" # includes trailing newline
172
	head="${head%
173
}"
174
	local tail="${query#$head}"
175
	mysql_load_data_format="${mysql_load_data_format%
176
}"
177
	mysql_ANSI "$@" <<EOF
178
$head
179
INTO OUTFILE '$file'
180
$mysql_load_data_format
181
$tail
182
EOF
183
}
184

    
185
mysqldump() # usage: [schema=1 | data=1] mysqldump db [table...]
186
{
187
	echo_func; kw_params schema data
188
	
189
	mysql_cmd ${database:+--databases "$database" --tables } \
190
--lock-tables=false --set-charset \
191
${postgres_compat:+--compatible=postgresql --add-locks=false }\
192
${schema:+--no-data }${data:+--no-create-info }"$@"
193
}
194

    
195
mysqldump_diffable()
196
{
197
	echo_func
198
	mysqldump "$@"|{ pipe_delay; echo_run sed 's/^(-- Dump completed).*$/\1/'; }
199
}
200

    
201
mysql_rm_privileged_statements()
202
{
203
	echo_func
204
	grep -vE -e '^/\*!40000 ALTER TABLE `.*` (DIS|EN)ABLE KEYS \*/;$' \
205
-e '^(UN)?LOCK TABLES( `.*` WRITE)?;$'
206
}
207

    
208
## permissions
209

    
210
mysql_seal_table() # usage: table=... user=... mysql_seal_table
211
# prevents further modifications to a table by a user
212
{
213
	echo_func; kw_params table user; : "${table:?}" "${user:?}"; mk_table_esc
214
	
215
	benign_error=1 mysql_root <<<"REVOKE ALL PRIVILEGES ON $table FROM '$user'@'%'" || true
216
	benign_error=1 mysql_root <<<"REVOKE GRANT OPTION   ON $table FROM '$user'@'%'" || true
217
}
218

    
219

    
220
### PostgreSQL
221

    
222
alias use_pg='declare prefix=pg_; import_vars; unset prefix'
223

    
224
fi # load new aliases
225
if self_being_included; then
226

    
227
psql() # usage: [stdin=copy_pstdin_file] psql <<<"cmds, e.g. \copy from pstdin"
228
{
229
	echo_func; kw_params stdin
230
	
231
	use_pg
232
	log+ -2
233
	local PGHOST="$server";       export PGHOST
234
	local PGUSER="$user";         export PGUSER
235
	local PGPASSWORD="$password"; export PGPASSWORD
236
	local PGDATABASE="$database"; export PGDATABASE
237
	log+ 2
238
	
239
	if can_log; then set -- --echo-all --echo-hidden "$@"; fi
240
	local redirs=("${redirs[@]}" '40<&0' "0<${stdin:-&20}" '41>&1')
241
	(
242
		if can_log; then cat <<'EOF'
243
\timing on
244
SET client_min_messages = NOTICE;
245
EOF
246
		fi
247
		cat
248
	)|cmd_log_fd=1 command psql --file /dev/fd/40 --output /dev/fd/41 \
249
--set ON_ERROR_STOP=1 --quiet "$@"
250
		# --output is for query *results*, not echoed statements
251
}
252

    
253
pg_export()
254
{
255
	echo_func
256
	mk_select_var
257
	local pg_copy_format="${pg_copy_format-CSV HEADER}"
258
	
259
	psql "$@" <<<"COPY ($query) TO STDOUT $pg_copy_format;"
260
}
261

    
262
pg_header()
263
{
264
	echo_func
265
	local pg_copy_format="CSV HEADER" limit=0
266
	pg_export "$@"|echo_stdout
267
}
268

    
269
pg_export_table_no_header()
270
{
271
	echo_func
272
	local pg_copy_format="CSV"
273
	pg_export "$@"
274
}
275

    
276
pg_export_table_to_dir_no_header()
277
{
278
	echo_func
279
	local table="$1"; shift; mk_table_esc
280
	stdout="$exports_dir/$table.no_header.cols=$(pg_header).csv" to_file \
281
pg_export_table_no_header "$@"
282
}
283

    
284
fi
(3-3/8)