-
Notifications
You must be signed in to change notification settings - Fork 90
/
dump.go
239 lines (196 loc) · 5.11 KB
/
dump.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
package mysqldump
import (
"database/sql"
"errors"
"os"
"path"
"strings"
"text/template"
"time"
)
type table struct {
Name string
SQL string
Values string
}
type dump struct {
DumpVersion string
ServerVersion string
Tables []*table
CompleteTime string
}
const version = "0.2.2"
const tmpl = `-- Go SQL Dump {{ .DumpVersion }}
--
-- ------------------------------------------------------
-- Server version {{ .ServerVersion }}
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
{{range .Tables}}
--
-- Table structure for table {{ .Name }}
--
DROP TABLE IF EXISTS {{ .Name }};
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
{{ .SQL }};
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table {{ .Name }}
--
LOCK TABLES {{ .Name }} WRITE;
/*!40000 ALTER TABLE {{ .Name }} DISABLE KEYS */;
{{ if .Values }}
INSERT INTO {{ .Name }} VALUES {{ .Values }};
{{ end }}
/*!40000 ALTER TABLE {{ .Name }} ENABLE KEYS */;
UNLOCK TABLES;
{{ end }}
-- Dump completed on {{ .CompleteTime }}
`
// Creates a MYSQL Dump based on the options supplied through the dumper.
func (d *Dumper) Dump() (string, error) {
name := time.Now().Format(d.format)
p := path.Join(d.dir, name+".sql")
// Check dump directory
if e, _ := exists(p); e {
return p, errors.New("Dump '" + name + "' already exists.")
}
// Create .sql file
f, err := os.Create(p)
if err != nil {
return p, err
}
defer f.Close()
data := dump{
DumpVersion: version,
Tables: make([]*table, 0),
}
// Get server version
if data.ServerVersion, err = getServerVersion(d.db); err != nil {
return p, err
}
// Get tables
tables, err := getTables(d.db)
if err != nil {
return p, err
}
// Get sql for each table
for _, name := range tables {
if t, err := createTable(d.db, name); err == nil {
data.Tables = append(data.Tables, t)
} else {
return p, err
}
}
// Set complete time
data.CompleteTime = time.Now().String()
// Write dump to file
t, err := template.New("mysqldump").Parse(tmpl)
if err != nil {
return p, err
}
if err = t.Execute(f, data); err != nil {
return p, err
}
return p, nil
}
func getTables(db *sql.DB) ([]string, error) {
tables := make([]string, 0)
// Get table list
rows, err := db.Query("SHOW TABLES")
if err != nil {
return tables, err
}
defer rows.Close()
// Read result
for rows.Next() {
var table sql.NullString
if err := rows.Scan(&table); err != nil {
return tables, err
}
tables = append(tables, table.String)
}
return tables, rows.Err()
}
func getServerVersion(db *sql.DB) (string, error) {
var server_version sql.NullString
if err := db.QueryRow("SELECT version()").Scan(&server_version); err != nil {
return "", err
}
return server_version.String, nil
}
func createTable(db *sql.DB, name string) (*table, error) {
var err error
t := &table{Name: name}
if t.SQL, err = createTableSQL(db, name); err != nil {
return nil, err
}
if t.Values, err = createTableValues(db, name); err != nil {
return nil, err
}
return t, nil
}
func createTableSQL(db *sql.DB, name string) (string, error) {
// Get table creation SQL
var table_return sql.NullString
var table_sql sql.NullString
err := db.QueryRow("SHOW CREATE TABLE "+name).Scan(&table_return, &table_sql)
if err != nil {
return "", err
}
if table_return.String != name {
return "", errors.New("Returned table is not the same as requested table")
}
return table_sql.String, nil
}
func createTableValues(db *sql.DB, name string) (string, error) {
// Get Data
rows, err := db.Query("SELECT * FROM " + name)
if err != nil {
return "", err
}
defer rows.Close()
// Get columns
columns, err := rows.Columns()
if err != nil {
return "", err
}
if len(columns) == 0 {
return "", errors.New("No columns in table " + name + ".")
}
// Read data
data_text := make([]string, 0)
for rows.Next() {
// Init temp data storage
//ptrs := make([]interface{}, len(columns))
//var ptrs []interface {} = make([]*sql.NullString, len(columns))
data := make([]*sql.NullString, len(columns))
ptrs := make([]interface{}, len(columns))
for i, _ := range data {
ptrs[i] = &data[i]
}
// Read data
if err := rows.Scan(ptrs...); err != nil {
return "", err
}
dataStrings := make([]string, len(columns))
for key, value := range data {
if value != nil && value.Valid {
dataStrings[key] = "'" + value.String + "'"
} else {
dataStrings[key] = "null"
}
}
data_text = append(data_text, "("+strings.Join(dataStrings, ",")+")")
}
return strings.Join(data_text, ","), rows.Err()
}