-
Notifications
You must be signed in to change notification settings - Fork 0
/
mysql.go
317 lines (279 loc) · 7.83 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
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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
package nice
import (
"database/sql"
"errors"
"fmt"
_ "github.com/go-sql-driver/mysql"
"github.com/mitchellh/mapstructure"
"log"
"os"
"strconv"
"time"
)
// mysql is DB pool struct
type Mysql struct {
DriverName string
Master *sql.DB
Slave *sql.DB
Loger Logger
}
type MysqlConf struct {
//map类型
Master MysqlNode `yaml: "master"`
Slave MysqlNode `yaml: "slave"`
Database string `yaml: "database"`
Charset string `yaml: "charset"`
MaxLifetime string `yaml: "maxlifetime"`
}
type MysqlNode struct {
Host string `yaml: "host"`
User string `yaml: "user"`
Password string `yaml: "password"`
MaxOpen int `yaml: "maxopen"` //maxOpenConn
MaxIdle int `yaml: "maxidle"` //maxIdleConn
}
// Init DB pool
func NewMysql(config interface{}) *Mysql {
var err error
p := &Mysql{
DriverName: "mysql",
Loger: log.New(os.Stderr, "[Nice] ", log.LstdFlags),
}
conf := MysqlConf{}
err = mapstructure.Decode(config.(map[interface{}]interface{}), &conf)
p.Master, err = p.Connect(conf.Master, conf.Database, conf.Charset, conf.MaxLifetime)
if err != nil {
p.Loger.Panicln("Init mysql master pool failed.", err.Error())
}
if conf.Slave.Host != "" {
p.Slave, err = p.Connect(conf.Slave, conf.Database, conf.Charset, conf.MaxLifetime)
if err != nil {
return nil
}
} else {
p.Slave = p.Master
}
return p
}
func (p *Mysql) Connect(node MysqlNode, database, charset, MaxLifetime string) (*sql.DB, error) {
var err error
dsn := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=%s&autocommit=true", node.User, node.Password, node.Host, database, charset)
conn, err := sql.Open(p.DriverName, dsn)
if err != nil {
return nil, err
}
if err = conn.Ping(); err != nil {
return nil, err
}
conn.SetMaxOpenConns(node.MaxOpen)
conn.SetMaxIdleConns(node.MaxIdle)
mlt, _ := time.ParseDuration(MaxLifetime)
conn.SetConnMaxLifetime(mlt)
return conn, err
}
// Close pool
func (p *Mysql) Close() error {
p.Slave.Close()
return p.Master.Close()
}
// Get via pool
func (p *Mysql) Get(queryStr string, args ...interface{}) (map[string]interface{}, error) {
results, err := p.Query(queryStr, args...)
if err != nil {
return map[string]interface{}{}, err
}
if len(results) <= 0 {
return map[string]interface{}{}, sql.ErrNoRows
}
if len(results) > 1 {
return map[string]interface{}{}, errors.New("sql: more than one rows")
}
return results[0], nil
}
// Query via pool
func (p *Mysql) Query(sqlStr string, args ...interface{}) ([]map[string]interface{}, error) {
rows, err := p.Slave.Query(sqlStr, args...)
if err != nil {
p.Loger.Printf("query err: %v sql: %s", err, sqlStr)
return []map[string]interface{}{}, err
}
defer rows.Close()
columns, err := rows.ColumnTypes()
scanArgs := make([]interface{}, len(columns))
values := make([]sql.RawBytes, len(columns))
for i := range values {
scanArgs[i] = &values[i]
}
rowsMap := make([]map[string]interface{}, 0, 10)
for rows.Next() {
rows.Scan(scanArgs...)
rowMap := make(map[string]interface{})
for i, value := range values {
rowMap[columns[i].Name()] = bytes2RealType(value, columns[i])
}
rowsMap = append(rowsMap, rowMap)
}
if err = rows.Err(); err != nil {
return []map[string]interface{}{}, err
}
return rowsMap, nil
}
// QueryRow via pool
func (p *Mysql) QueryRow(sqlStr string, args ...interface{}) *sql.Row {
return p.Slave.QueryRow(sqlStr, args...)
}
func (p *Mysql) Exec(sqlStr string, args ...interface{}) (sql.Result, error) {
res, err := p.Master.Exec(sqlStr, args...)
if err != nil {
p.Loger.Printf("exec err: %v sql: %s", err, sqlStr)
}
return res, err
}
// Update via pool
func (p *Mysql) Update(updateStr string, args ...interface{}) (int64, error) {
result, err := p.Exec(updateStr, args...)
if err != nil {
return 0, err
}
affect, err := result.RowsAffected()
return affect, err
}
// Insert via pool
func (p *Mysql) Insert(insertStr string, args ...interface{}) (int64, error) {
result, err := p.Exec(insertStr, args...)
if err != nil {
return 0, err
}
lastId, err := result.LastInsertId()
return lastId, err
}
// Delete via pool
func (p *Mysql) Delete(deleteStr string, args ...interface{}) (int64, error) {
result, err := p.Exec(deleteStr, args...)
if err != nil {
return 0, err
}
affect, err := result.RowsAffected()
return affect, err
}
// SQLConnTransaction is for transaction connection
type SQLConnTransaction struct {
SQLTX *sql.Tx
Loger Logger
}
// Begin transaction
func (p *Mysql) Begin() (*SQLConnTransaction, error) {
var oneSQLConnTransaction = &SQLConnTransaction{}
var err error
if pingErr := p.Master.Ping(); pingErr == nil {
oneSQLConnTransaction.SQLTX, err = p.Master.Begin()
oneSQLConnTransaction.Loger = p.Loger
}
return oneSQLConnTransaction, err
}
// Rollback transaction
func (t *SQLConnTransaction) Rollback() error {
return t.SQLTX.Rollback()
}
// Commit transaction
func (t *SQLConnTransaction) Commit() error {
return t.SQLTX.Commit()
}
// Get via transaction
func (t *SQLConnTransaction) Get(queryStr string, args ...interface{}) (map[string]interface{}, error) {
results, err := t.Query(queryStr, args...)
if err != nil {
return map[string]interface{}{}, err
}
if len(results) <= 0 {
return map[string]interface{}{}, sql.ErrNoRows
}
if len(results) > 1 {
return map[string]interface{}{}, errors.New("sql: more than one rows")
}
return results[0], nil
}
// Query via transaction
func (t *SQLConnTransaction) Query(queryStr string, args ...interface{}) ([]map[string]interface{}, error) {
rows, err := t.SQLTX.Query(queryStr, args...)
if err != nil {
t.Loger.Printf("t query err: %v", err)
return []map[string]interface{}{}, err
}
defer rows.Close()
columns, err := rows.ColumnTypes()
scanArgs := make([]interface{}, len(columns))
values := make([]sql.RawBytes, len(columns))
for i := range values {
scanArgs[i] = &values[i]
}
rowsMap := make([]map[string]interface{}, 0, 10)
for rows.Next() {
rows.Scan(scanArgs...)
rowMap := make(map[string]interface{})
for i, value := range values {
rowMap[columns[i].Name()] = bytes2RealType(value, columns[i])
}
rowsMap = append(rowsMap, rowMap)
}
if err = rows.Err(); err != nil {
return []map[string]interface{}{}, err
}
return rowsMap, nil
}
func (t *SQLConnTransaction) Exec(sqlStr string, args ...interface{}) (sql.Result, error) {
res, err := t.SQLTX.Exec(sqlStr, args...)
if err != nil {
t.Loger.Printf("t exec err: %v", err)
}
return res, err
}
// Update via transaction
func (t *SQLConnTransaction) Update(updateStr string, args ...interface{}) (int64, error) {
result, err := t.Exec(updateStr, args...)
if err != nil {
return 0, err
}
affect, err := result.RowsAffected()
return affect, err
}
// Insert via transaction
func (t *SQLConnTransaction) Insert(insertStr string, args ...interface{}) (int64, error) {
result, err := t.Exec(insertStr, args...)
if err != nil {
return 0, err
}
lastId, err := result.LastInsertId()
return lastId, err
}
// Delete via transaction
func (t *SQLConnTransaction) Delete(deleteStr string, args ...interface{}) (int64, error) {
result, err := t.Exec(deleteStr, args...)
if err != nil {
return 0, err
}
affect, err := result.RowsAffected()
return affect, err
}
// bytes2RealType is to convert db type to code type
func bytes2RealType(src []byte, column *sql.ColumnType) interface{} {
srcStr := string(src)
var result interface{}
switch column.DatabaseTypeName() {
case "BIT", "TINYINT", "SMALLINT", "INT":
result, _ = strconv.ParseInt(srcStr, 10, 64)
case "BIGINT":
result, _ = strconv.ParseUint(srcStr, 10, 64)
case "CHAR", "VARCHAR",
"TINY TEXT", "TEXT", "MEDIUM TEXT", "LONG TEXT",
"TINY BLOB", "MEDIUM BLOB", "BLOB", "LONG BLOB",
"JSON", "ENUM", "SET",
"YEAR", "DATE", "TIME", "TIMESTAMP", "DATETIME":
result = srcStr
case "FLOAT", "DOUBLE", "DECIMAL":
result, _ = strconv.ParseFloat(srcStr, 64)
default:
result = nil
}
return result
}