-
Notifications
You must be signed in to change notification settings - Fork 1
/
db.go
335 lines (304 loc) · 8.5 KB
/
db.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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
package gomysql
import (
"context"
"database/sql"
"fmt"
"os"
"reflect"
"regexp"
"strings"
"sync"
"time"
"github.com/go-sql-driver/mysql"
)
type Db struct {
*sql.DB
conf string
Ctx context.Context
sc *Sqlconfig
f *os.File
mu *sync.RWMutex
maxpacket uint64
maxConn int
debug bool
}
func (d *Db) execError(err error, cmd string, args ...interface{}) {
if d.sc.WriteLogWhenFailed {
d.mu.Lock()
d.f.WriteString(fmt.Sprintf("-- %s, reason: %s\n", time.Now().Format("2006-01-02 15:04:05"), err.Error()))
d.f.WriteString(ToSql(cmd, args...) + ";\n")
d.f.Sync()
d.mu.Unlock()
}
}
func (d *Db) GetConnections() int {
return d.Stats().OpenConnections
}
func (d *Db) Use(dbname string, overWrite ...bool) (*Db, error) {
// 切换到新的库, 并产生一个新的db
ow := false
if len(overWrite) > 0 {
ow = overWrite[0]
}
err := d.CreateDatabase(dbname, ow)
if err != nil {
return d, err
}
d.Close()
s := &Sqlconfig{
UserName: d.sc.UserName,
Password: d.sc.Password,
Host: d.sc.Host,
Port: d.sc.Port,
DbName: dbname,
ClientFoundRows: d.sc.ClientFoundRows,
AllowCleartextPasswords: d.sc.AllowCleartextPasswords,
InterpolateParams: d.sc.InterpolateParams,
ColumnsWithAlias: d.sc.ColumnsWithAlias,
MultiStatements: d.sc.MultiStatements,
ParseTime: d.sc.ParseTime,
TLS: d.sc.TLS,
ReadTimeout: d.sc.ReadTimeout,
Timeout: d.sc.Timeout,
WriteTimeout: d.sc.WriteTimeout,
AllowOldPasswords: d.sc.AllowOldPasswords,
Charset: d.sc.Charset,
Loc: d.sc.Loc,
MaxAllowedPacket: d.sc.MaxAllowedPacket,
Collation: d.sc.Collation,
MaxOpenConns: d.sc.MaxOpenConns,
MaxIdleConns: d.sc.MaxIdleConns,
ConnMaxLifetime: d.sc.ConnMaxLifetime,
WriteLogWhenFailed: d.sc.WriteLogWhenFailed,
LogFile: d.sc.LogFile,
}
return s.conndb(s.GetMysqlDataSource())
}
func (d *Db) CreateDatabase(dbname string, overWrite bool) error {
if overWrite {
d.QueryRow("drop database " + dbname + " if exsits")
}
err := d.QueryRow("create database " + dbname).Err()
if err != nil && err.(*mysql.MySQLError).Number == 1007 {
return nil
}
return err
}
func (d *Db) Flush() {
if d.f != nil {
d.f.Sync()
d.f.Close()
}
}
func (d *Db) Update(cmd string, args ...interface{}) Result {
res := Result{}
if d.debug {
res.Sql = ToSql(cmd, args...)
}
result, err := d.ExecContext(d.Ctx, cmd, args...)
if err != nil {
res.Err = err
d.execError(err, res.Sql)
return res
}
res.RowsAffected, res.Err = result.RowsAffected()
return res
}
func (d *Db) Delete(cmd string, args ...interface{}) Result {
return d.Update(cmd, args...)
}
func (d *Db) Insert(cmd string, args ...interface{}) Result {
res := Result{}
if d.debug {
res.Sql = ToSql(cmd, args...)
}
result, err := d.ExecContext(d.Ctx, cmd, args...)
if err != nil {
res.Err = err
d.execError(err, res.Sql)
return res
}
res.LastInsertId, res.Err = result.LastInsertId()
return res
}
func (d *Db) InsertMany(cmd string, args ...interface{}) Result {
// sql: insert into test(id, name) values(?,?) args: interface{}... 1,'t1', 2, 't2', 3, 't3'
// 每次返回的是第一次插入的id
if args == nil {
return d.Insert(cmd)
}
newcmd, err := formatSql(cmd, args...)
if err != nil {
return Result{Err: err}
}
return d.Insert(newcmd, args...)
}
func (d *Db) GetRows(cmd string, args ...interface{}) (*sql.Rows, error) {
return d.QueryContext(d.Ctx, cmd, args...)
}
func (d *Db) GetOne(cmd string, args ...interface{}) *sql.Row {
return d.QueryRowContext(d.Ctx, cmd, args...)
}
func (d *Db) Select(dest interface{}, cmd string, args ...interface{}) Result {
// db.Select(&value, "select * from test")
// 传入切片的地址, 根据tag 的 db 自动补充,
// 最求性能建议还是使用 GetRows or GetOne
res := Result{}
if d.debug {
res.Sql = ToSql(cmd, args...)
}
rows, err := d.QueryContext(d.Ctx, cmd, args...)
if err != nil {
res.Err = err
return res
}
defer rows.Close()
// 需要设置的值
res.Err = fill(dest, rows)
return res
}
func (d *Db) InsertInterfaceWithID(dest interface{}, cmd string, args ...interface{}) Result {
// $key 和 $value 固定位置固定值
// db.InsertInterfaceWithID(&value, "insert into test($key) values($value)")
res := Result{
LastInsertIds: make([]int64, 0),
}
typ := reflect.TypeOf(dest)
value := reflect.ValueOf(dest)
if typ.Kind() == reflect.Ptr {
typ = typ.Elem()
value = value.Elem()
}
if typ.Kind() == reflect.Struct {
return d.insertInterface(dest, cmd, args...)
}
if typ.Kind() == reflect.Slice {
// 如果是切片, 那么每个值都做一次处理
length := value.Len()
if length == 1 {
return d.insertInterface(dest, cmd, args...)
}
for i := 0; i < length; i++ {
result := d.insertInterface(value.Index(i).Interface(), cmd, args...)
res.Sql += ";" + result.Sql
if result.Err != nil {
return result
}
res.LastInsertIds = append(res.LastInsertIds, result.LastInsertId)
}
} else {
res.Err = ErrNotSupport
}
return res
}
// 插入字段的占位符 $key, $value
func (d *Db) InsertInterfaceWithoutID(dest interface{}, cmd string, args ...interface{}) Result {
// $key 和 $value 固定位置固定值
// ID 自增的必须设置 default
// db.InsertInterfaceWithoutID(&value, "insert into test($key) values($value)")
res := Result{}
typ := reflect.TypeOf(dest)
value := reflect.ValueOf(dest)
if typ.Kind() == reflect.Ptr {
typ = typ.Elem()
value = value.Elem()
}
if typ.Kind() == reflect.Struct {
return d.insertInterface(dest, cmd, args...)
}
if typ.Kind() == reflect.Slice {
// 如果是切片, 那么每个值都做一次处理
length := value.Len()
if length == 1 {
return d.insertInterface(dest, cmd, args...)
}
arguments := make([]interface{}, 0)
for i := 0; i < length; i++ {
newcmd, newargs, err := insertInterfaceSql(value.Index(i).Interface(), cmd, args...)
if err != nil {
res.Err = err
return res
}
cmd = newcmd
arguments = append(arguments, newargs...)
}
return d.InsertMany(cmd, arguments...)
} else {
res.Err = ErrNotSupport
}
return res
}
func (d *Db) insertInterface(dest interface{}, cmd string, args ...interface{}) Result {
// 插入到args之前 dest 是struct或切片的指针
newcmd, newargs, err := insertInterfaceSql(dest, cmd, args...)
if err != nil {
return Result{Err: err}
}
return d.Insert(newcmd, newargs...)
}
// 还原sql
func ToSql(cmd string, args ...interface{}) string {
cmd = strings.Replace(cmd, "?", "%v", -1)
if len(args) > 0 {
newargs := make([]interface{}, 0, len(args))
for _, v := range args {
switch reflect.TypeOf(v).Kind() {
case reflect.Float32, reflect.Float64, reflect.Bool,
reflect.Int, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int8,
reflect.Uint, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint8:
v = fmt.Sprintf("%v", v)
default:
v = fmt.Sprintf("'%v'", v)
}
newargs = append(newargs, v)
}
return fmt.Sprintf(cmd, newargs...)
}
return cmd
}
func ToPGSql(cmd string, args ...interface{}) string {
rexp, _ := regexp.Compile(`\$(\d)+`)
cmd = rexp.ReplaceAllStringFunc(cmd, func(s string) string {
return "%v"
})
if len(args) > 0 {
newargs := make([]interface{}, 0, len(args))
for _, v := range args {
switch reflect.TypeOf(v).Kind() {
case reflect.Float32, reflect.Float64, reflect.Bool,
reflect.Int, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int8,
reflect.Uint, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint8:
v = fmt.Sprintf("%v", v)
default:
v = fmt.Sprintf("'%v'", v)
}
newargs = append(newargs, v)
}
return fmt.Sprintf(cmd, newargs...)
}
return cmd
}
// 还原sql
func InToSql(cmd string, args ...interface{}) string {
cmd, args, err := makeArgs(cmd, args...)
if err != nil {
return ""
}
cmd = strings.Replace(cmd, "?", "%v", -1)
if len(args) > 0 {
newargs := make([]interface{}, 0, len(args))
for _, v := range args {
v = fmt.Sprintf("'%v'", v)
newargs = append(newargs, v)
}
return fmt.Sprintf(cmd, newargs...)
}
return cmd
}
func (d *Db) UpdateInterface(dest interface{}, cmd string, args ...interface{}) Result {
newcmd, newargs, err := updateInterfaceSql(dest, cmd, args...)
if err != nil {
return Result{Err: err}
}
return d.Update(newcmd, newargs...)
}