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 use_local='declare prefix=local_; import_vars'
8
alias use_remote='declare prefix=remote_; import_vars'
9
alias use_local_remote='use_local; use_remote' # *must* be run inside a function
10

    
11
quote='"'
12

    
13
esc_name() { echo "$quote${1//$quote/$quote$quote}$quote"; }
14

    
15
mk_esc_name() { set_var "$1"_esc "$(esc_name "${!1}")"; }
16

    
17
alias mk_schema_esc='declare schema_esc; mk_esc_name schema'
18
alias mk_table_esc='declare table_esc; mk_esc_name table'
19

    
20
alias mk_select='mk_table_esc
21
declare query="${query:-SELECT * FROM $table_esc}${limit:+ LIMIT $limit}"'
22

    
23
fi # load new aliases
24
if self_being_included; then
25

    
26
log_sql() { test "$verbosity" -ge 2; }
27

    
28

    
29
### MySQL
30

    
31
# auto-adds connection/login opts when specified
32
mysql_cmd() # usage: mysql*() { ...; mysql_cmd "$@"; }
33
{
34
	echo_func
35
	local ssh_server="$(localize_url "$ssh_server")"
36
	local server="$(localize_url "$server")"
37
	if test "$ssh_server"; then
38
		local ssh_dest="${ssh_dest-${ssh_user:+$ssh_user@}$ssh_server}"
39
	fi
40
	if test "$schema"; then local database="${database-$schema}"; fi
41
	
42
	local var=ssh_dest; local_inv
43
	command ${ssh_dest:+ssh "$ssh_dest" }"${FUNCNAME[1]}" \
44
${server:+ --host="$server" }${user:+--user="$user" } --password\
45
${password+="$password"} ${database:+--databases "$database" --tables } "$@"
46
}
47

    
48
mysql() { echo_func; mysql_cmd --verbose "$@"; }
49

    
50
mysql_ANSI()
51
{
52
	echo_func
53
	(echo "SET sql_mode = 'ANSI';"; cat)|mysql "$@"
54
}
55

    
56
mysqldump() # usage: [schema=1 | data=1] mysqldump db [table...]
57
{
58
	echo_func
59
	mysql_cmd --quick --lock-tables=false --set-charset \
60
${postgres_compat:+--compatible=postgresql --add-locks=false }\
61
${schema:+--no-data }${data:+--no-create-info }"$@"
62
}
63

    
64
mysqldump_diffable()
65
{
66
	echo_func
67
	mysqldump "$@"|{ pipe_delay; sed 's/^(-- Dump completed).*$/\1/'; }
68
}
69

    
70

    
71
### PostgreSQL
72

    
73
pg_export()
74
{
75
	echo_func
76
	mk_select
77
	local pg_copy_format="${pg_copy_format-CSV HEADER}"
78
	
79
	psql "$@" <<<"COPY ($query) TO STDOUT $pg_copy_format;"
80
}
81

    
82
pg_header()
83
{
84
	echo_func
85
	local pg_copy_format="CSV HEADER" limit=0
86
	pg_export "$@"|echo_stdout
87
}
88

    
89
pg_export_table_no_header()
90
{
91
	echo_func
92
	local pg_copy_format="CSV"
93
	pg_export "$@"
94
}
95

    
96
pg_export_table_to_dir_no_header()
97
{
98
	echo_func
99
	local table="$1"; shift; mk_table_esc
100
	local cols="$(pg_header)"
101
	stdout="$exports_dir/$table.no_header.cols=$cols.csv" to_file \
102
pg_export_table_no_header "$@"
103
}
104

    
105
fi
(2-2/5)