-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdump.go
78 lines (68 loc) · 1.71 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
package main
import (
"encoding/json"
"fmt"
mysqlClient "github.com/go-mysql-org/go-mysql/client"
"github.com/go-mysql-org/go-mysql/mysql"
"strings"
)
func getClient() *mysqlClient.Conn {
connection, err := mysqlClient.Connect(config.Address, config.User, config.Password, "")
if err != nil {
panic(err)
}
err = connection.Ping()
if err != nil {
panic(err)
}
return connection
}
func Dump() {
connection := getClient()
log.Info("-dump is true, start dumping...")
for _, db := range config.Schemas {
for _, table := range db.Tables {
log.Infof("start dumping for %s.%s", db.Name, table.Name)
n := 0
var result mysql.Result
err := connection.ExecuteSelectStreaming(
fmt.Sprintf(
"SELECT %s FROM `%s`.`%s`",
strings.Join(table.ColumnNames, ","),
db.Name,
table.Name,
),
&result,
func(row []mysql.FieldValue) error {
data := map[string]any{}
for i, field := range row {
if field.Type == mysql.FieldValueTypeString {
data[table.ColumnNames[i]] = string(field.AsString())
} else {
data[table.ColumnNames[i]] = field.Value()
}
}
bytes, err := json.Marshal(data)
if err != nil {
log.Error("failed to parse row data to json", err)
}
table.Lock.Lock()
table.Buffer.WriteString(fmt.Sprintf("{\"index\":{\"_id\": %d}}\n", data["id"]))
table.Buffer.WriteString(string(bytes))
table.Buffer.WriteString("\n")
table.Lock.Unlock()
n++
if n%100000 == 0 {
BulkInsert(table)
log.Infof("synced %d rows", n)
}
return nil
}, nil)
if err != nil {
panic(err)
}
BulkInsert(table)
log.Infof("dump %s finished, tables: %s", db.Name, table.Name)
}
}
}