-
Notifications
You must be signed in to change notification settings - Fork 6
/
mysql.go
129 lines (111 loc) · 3.21 KB
/
mysql.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
package etlutil
import (
"database/sql"
"fmt"
"strings"
"github.com/teambenny/goetl/etldata"
"github.com/teambenny/goetl/logger"
)
// MySQLInsertData abstracts building and executing a SQL INSERT
// statement for the given Data object.
//
// Note that the Data must be a valid JSON object
// (or an array of valid objects all with the same keys),
// where the keys are column names and the
// the values are SQL values to be inserted into those columns.
func MySQLInsertData(db *sql.DB, d etldata.Payload, tableName string, onDupKeyUpdate bool, onDupKeyFields []string, batchSize int) error {
objects, err := d.Objects()
if err != nil {
return err
}
if batchSize > 0 {
for i := 0; i < len(objects); i += batchSize {
maxIndex := i + batchSize
if maxIndex > len(objects) {
maxIndex = len(objects)
}
err = mysqlInsertObjects(db, objects[i:maxIndex], tableName, onDupKeyUpdate, onDupKeyFields)
if err != nil {
return err
}
}
return nil
}
return mysqlInsertObjects(db, objects, tableName, onDupKeyUpdate, onDupKeyFields)
}
func mysqlInsertObjects(db *sql.DB, objects []map[string]interface{}, tableName string, onDupKeyUpdate bool, onDupKeyFields []string) error {
logger.Info("MySQLInsertData: building INSERT for len(objects) =", len(objects))
insertSQL, vals := buildMySQLInsertSQL(objects, tableName, onDupKeyUpdate, onDupKeyFields)
logger.Debug("MySQLInsertData:", insertSQL)
logger.Debug("MySQLInsertData: values", vals)
stmt, err := db.Prepare(insertSQL)
if err != nil {
logger.Debug("MySQLInsertData: error preparing SQL")
return err
}
defer stmt.Close()
res, err := stmt.Exec(vals...)
if err != nil {
return err
}
lastID, err := res.LastInsertId()
if err != nil {
return err
}
rowCnt, err := res.RowsAffected()
if err != nil {
return err
}
logger.Info(fmt.Sprintf("MySQLInsertData: rows affected = %d, last insert ID = %d", rowCnt, lastID))
return nil
}
func buildMySQLInsertSQL(objects []map[string]interface{}, tableName string, onDupKeyUpdate bool, onDupKeyFields []string) (insertSQL string, vals []interface{}) {
cols := sortedColumns(objects)
// Format: INSERT INTO tablename(col1,col2) VALUES(?,?),(?,?)
insertPrefix := "INSERT IGNORE"
if onDupKeyUpdate {
insertPrefix = "INSERT"
}
insertSQL = fmt.Sprintf("%v INTO %v(%v) VALUES", insertPrefix, tableName, strings.Join(cols, ","))
// builds the (?,?) part
qs := "("
for i := 0; i < len(cols); i++ {
if i > 0 {
qs += ","
}
qs += "?"
}
qs += ")"
// append as many (?,?) parts as there are objects to insert
for i := 0; i < len(objects); i++ {
if i > 0 {
insertSQL += ","
}
insertSQL += qs
}
if onDupKeyUpdate {
// format: ON DUPLICATE KEY UPDATE a=VALUES(a), b=VALUES(b), c=VALUES(c)
insertSQL += " ON DUPLICATE KEY UPDATE "
// If this wasn't explicitly set, we want to update all columns
if len(onDupKeyFields) == 0 {
onDupKeyFields = cols
}
for i, c := range onDupKeyFields {
if i > 0 {
insertSQL += ","
}
insertSQL += "`" + c + "`=VALUES(`" + c + "`)"
}
}
vals = []interface{}{}
for _, obj := range objects {
for _, col := range cols {
if val, ok := obj[col]; ok {
vals = append(vals, val)
} else {
vals = append(vals, nil)
}
}
}
return
}