/
main.go
422 lines (368 loc) · 9.51 KB
/
main.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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
package dbhelper
import (
"context"
"database/sql"
"errors"
"fmt"
"log"
"regexp"
"strconv"
"strings"
"time"
"github.com/go-sql-driver/mysql"
)
type DbRow interface {
Scan(dest ...any) error
}
// ctxKey 用于在上下文中记录事务对象的key。
type ctxKey struct{}
type ctxRef struct {
tx *sql.Tx
alive bool
}
func (cr *ctxRef) Commit() error {
if cr.alive {
if err := cr.tx.Commit(); err != nil {
return err
} else {
cr.alive = false
log.Printf("[DEBUG] Committed transaction\n")
return nil
}
} else {
return nil
}
}
func (cr *ctxRef) Close() error {
if cr.alive {
if err := cr.tx.Rollback(); err != nil {
return err
} else {
cr.alive = false
log.Printf("[DEBUG] Rollback transaction\n")
return nil
}
} else {
return nil
}
}
var (
db *sql.DB
SQL_ARG_PATTERN = regexp.MustCompile(`:[1|2|3|4|5|6|7|8|9](0|1|2|3|4|5|6|7|8|9)?`)
)
// InitMySqlDb 初始化MySql数据源。
func InitMySqlDb(addr, username, password, dbname string) error {
cfg := mysql.NewConfig()
cfg.Net = "tcp"
cfg.Addr = addr
cfg.User = username
cfg.Passwd = password
cfg.DBName = dbname
cfg.Loc = time.Local
cfg.ParseTime = true
if db_, err := sql.Open("mysql", cfg.FormatDSN()); err != nil {
return err
} else {
db_.SetConnMaxLifetime(300 * time.Second)
db_.SetMaxIdleConns(2)
if err := db_.Ping(); err != nil {
return err
}
db = db_
return nil
}
}
func logSql(query string, args []any) {
buf := make([]string, 0, 10)
buf = append(buf, query)
for i, arg := range args {
av := any(nil)
if ns, ok := arg.(sql.NullString); ok {
if ns.Valid {
av = ns.String
}
} else if ni, ok := arg.(sql.NullInt64); ok {
if ni.Valid {
av = ni.Int64
}
} else if ni, ok := arg.(sql.NullInt32); ok {
if ni.Valid {
av = ni.Int32
}
} else if ni, ok := arg.(sql.NullInt16); ok {
if ni.Valid {
av = ni.Int16
}
} else if ni, ok := arg.(sql.NullByte); ok {
if ni.Valid {
av = ni.Byte
}
} else if ni, ok := arg.(sql.NullFloat64); ok {
if ni.Valid {
av = ni.Float64
}
} else if ni, ok := arg.(sql.NullBool); ok {
if ni.Valid {
av = ni.Bool
}
} else if ni, ok := arg.(sql.NullTime); ok {
if ni.Valid {
av = ni.Time
}
} else {
av = arg
}
if t, ok := av.(time.Time); ok {
buf = append(buf, fmt.Sprintf(" [%d] %s", i+1, t.Format("2006-01-02T15:04:05-0700")))
} else if j, ok := av.(int64); ok {
buf = append(buf, fmt.Sprintf(" [%d] %d", i+1, j))
} else if j, ok := av.(int32); ok {
buf = append(buf, fmt.Sprintf(" [%d] %d", i+1, j))
} else if j, ok := av.(int); ok {
buf = append(buf, fmt.Sprintf(" [%d] %d", i+1, j))
} else if j, ok := av.(float64); ok {
buf = append(buf, fmt.Sprintf(" [%d] %.2f", i+1, j))
} else {
buf = append(buf, fmt.Sprintf(" [%d] %#v", i+1, av))
}
}
log.Printf("[DEBUG] Execute sql: %s\n", strings.Join(buf, "\n"))
}
func prepareSql(ctx context.Context, query string, args []any) (*sql.Stmt, []any) {
oargs := make([]any, 0, len(args))
oquery := SQL_ARG_PATTERN.ReplaceAllStringFunc(query, func(s string) string {
s0 := s[1:]
if v, err := strconv.ParseInt(s0, 10, 64); err != nil {
panic(fmt.Errorf("illegal sql arg: %#v", s0))
} else {
si := int(v)
if si <= len(args) {
oargs = append(oargs, args[si-1])
return "?"
} else {
panic(fmt.Errorf("no enough args, wants %d", si))
}
}
})
if cr, ok := ctx.Value(ctxKey{}).(*ctxRef); ok {
logSql("[TX] "+oquery, oargs)
if !cr.alive {
panic(fmt.Errorf("current transaction is not alive"))
}
if stmt, err := cr.tx.Prepare(oquery); err != nil {
panic(err)
} else {
return stmt, oargs
}
} else {
logSql(oquery, oargs)
if stmt, err := db.Prepare(oquery); err != nil {
panic(err)
} else {
return stmt, oargs
}
}
}
func BeginTx(ctx context.Context, serializable bool) context.Context {
isolation := sql.LevelDefault
if serializable {
isolation = sql.LevelSerializable
}
if tx, err := db.BeginTx(ctx, &sql.TxOptions{Isolation: isolation}); err != nil {
panic(err)
} else {
log.Printf("[DEBUG] Begin transaction\n")
return context.WithValue(ctx, ctxKey{}, &ctxRef{tx: tx, alive: true})
}
}
func CommitTx(ctx context.Context) {
if cr, ok := ctx.Value(ctxKey{}).(*ctxRef); ok {
if err := cr.Commit(); err != nil {
panic(err)
}
}
}
func CloseTx(ctx context.Context) {
if cr, ok := ctx.Value(ctxKey{}).(*ctxRef); ok {
cr.Close()
}
}
// Exec 执行指定的sql并返回受影响的行数。
func Exec[T int | int8 | int16 | int32 | int64](ctx context.Context, query string, args ...any) (T, error) {
stmt, args := prepareSql(ctx, query, args)
defer stmt.Close()
if r, err := stmt.ExecContext(ctx, args...); err != nil {
if me, ok := err.(*mysql.MySQLError); ok && me.Number == 1452 /*违反外键约束的错误*/ {
return 0, nil
} else {
return 0, err
}
} else {
result, err := r.RowsAffected()
return T(result), err
}
}
// ExecLastInsertId 执行指定的sql并返回插入的ID值。只要sql执行成功,即使未插入任何记录也不会返回错误。
func ExecLastInsertId[T int | int8 | int16 | int32 | int64](ctx context.Context, query string, args ...any) (T, error) {
stmt, args := prepareSql(ctx, query, args)
defer stmt.Close()
if r, err := stmt.ExecContext(ctx, args...); err != nil {
if me, ok := err.(*mysql.MySQLError); ok && me.Number == 1452 /*违反外键约束的错误*/ {
return 0, nil
} else {
return 0, err
}
} else {
if result, err := r.LastInsertId(); err != nil {
return 0, nil
} else {
return T(result), nil
}
}
}
func Query[T bool | int | int8 | int16 | int32 | int64 | string | time.Time | sql.NullInt64 | sql.NullBool | sql.NullTime](ctx context.Context, query string, args ...any) (T, error) {
stmt, args := prepareSql(ctx, query, args)
defer stmt.Close()
r := stmt.QueryRowContext(ctx, args...)
var result T
if err := r.Scan(&result); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return result, nil
} else {
return result, err
}
} else {
return result, err
}
}
type RowHandler[T any] interface {
Scan(sc DbRow) (*T, error)
}
func QueryObj[T any](ctx context.Context, query string, rh RowHandler[T], args ...any) (*T, error) {
stmt, args := prepareSql(ctx, query, args)
defer stmt.Close()
r := stmt.QueryRowContext(ctx, args...)
if result, err := rh.Scan(r); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, nil
} else {
return nil, err
}
} else {
return result, err
}
}
func QueryList[T bool | int | int8 | int16 | int32 | int64 | string | time.Time | sql.NullInt64 | sql.NullBool | sql.NullTime](ctx context.Context, query string, args ...any) ([]T, error) {
stmt, args := prepareSql(ctx, query, args)
defer stmt.Close()
if r, err := stmt.QueryContext(ctx, args...); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, nil
} else {
return nil, err
}
} else {
result := make([]T, 0, 10)
for r.Next() {
var item T
if err := r.Scan(&item); err != nil {
return result, err
} else {
result = append(result, item)
}
}
return result, nil
}
}
// QueryObjList 查询对象列表。
func QueryObjList[T any](ctx context.Context, query string, rh RowHandler[T], args ...any) ([]*T, error) {
stmt, args := prepareSql(ctx, query, args)
defer stmt.Close()
if r, err := stmt.QueryContext(ctx, args...); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, nil
} else {
return nil, err
}
} else {
result := make([]*T, 0, 10)
for r.Next() {
if item, err := rh.Scan(r); err != nil {
return result, err
} else {
result = append(result, item)
}
}
return result, nil
}
}
func QueryKeyValueMap[T bool | int | int8 | int16 | int32 | int64 | string](ctx context.Context, query string, args ...any) (map[string]T, error) {
if result, err := QueryObjList[KeyValuePairPo[T]](ctx, query, &KeyValuePairMapper[T]{}, args...); err != nil {
return nil, err
} else {
m := make(map[string]T, len(result))
for _, kv := range result {
m[kv.Key] = kv.Value
}
return m, nil
}
}
// insertBatch 批量插入记录。
// 返回成功插入的记录数。
func InsertBatch(ctx context.Context, query string, rows ...[]any) (int64, error) {
if tx, err := db.BeginTx(ctx, &sql.TxOptions{}); err != nil {
return 0, err
} else if stmt, err := tx.Prepare(query); err != nil {
return 0, err
} else {
c := int64(0)
re := error(nil)
for _, row := range rows {
if row == nil {
continue
}
if r, err := stmt.ExecContext(ctx, row...); err != nil {
if re != nil {
re = err
}
} else if c_, err := r.RowsAffected(); err != nil {
panic(err)
} else {
c += c_
}
}
return c, re
}
}
func JoinInString(args []string) string {
if len(args) == 0 {
return "('')"
} else {
sa := make([]string, 0, len(args))
for _, a := range args {
sa = append(sa, "'"+a+"'")
}
return "(" + strings.Join(sa, ",") + ")"
}
}
func JoinInInt[T int | int8 | int16 | int32 | int64](args []T) string {
if len(args) == 0 {
return "(0)"
} else {
sa := make([]string, 0, len(args))
for _, a := range args {
sa = append(sa, strconv.FormatInt(int64(a), 10))
}
return "(" + strings.Join(sa, ",") + ")"
}
}
type KeyValuePairPo[T bool | int | int8 | int16 | int32 | int64 | string] struct {
Key string
Value T
}
type KeyValuePairMapper[T bool | int | int8 | int16 | int32 | int64 | string] struct{}
func (m *KeyValuePairMapper[T]) Scan(r DbRow) (*KeyValuePairPo[T], error) {
result := &KeyValuePairPo[T]{}
err := r.Scan(&result.Key, &result.Value)
return result, err
}