-
Notifications
You must be signed in to change notification settings - Fork 3
/
sqlconn.go
410 lines (379 loc) · 11.3 KB
/
sqlconn.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
package sql
import (
"context"
"database/sql"
"os"
"runtime"
"strconv"
"time"
"github.com/abulo/ratel/v3/core/logger"
"github.com/abulo/ratel/v3/core/metric"
"github.com/abulo/ratel/v3/core/resource"
"github.com/abulo/ratel/v3/core/trace"
"github.com/opentracing/opentracing-go"
"github.com/opentracing/opentracing-go/ext"
"github.com/opentracing/opentracing-go/log"
"github.com/spf13/cast"
)
type (
// Session stands for raw connections or transaction sessions
Session interface {
MultiInsert(ctx context.Context, query string, args ...any) (int64, error)
Replace(ctx context.Context, query string, args ...any) (int64, error)
InsertUpdate(ctx context.Context, query string, args ...any) (int64, error)
Insert(ctx context.Context, query string, args ...any) (int64, error)
Update(ctx context.Context, query string, args ...any) (int64, error)
Delete(ctx context.Context, query string, args ...any) (int64, error)
Exec(ctx context.Context, query string, args ...any) (int64, error)
Count(ctx context.Context, query string, args ...any) (int64, error)
QueryRow(ctx context.Context, query string, args ...any) *Row
QueryRows(ctx context.Context, query string, args ...any) *Rows
ExecCtx(ctx context.Context, query string, args ...any) (sql.Result, error)
QueryCtx(ctx context.Context, query string, args ...any) (*sql.Rows, error)
}
// SqlConn only stands for raw connections, so Transact method can be called.
SqlConn interface {
Session
Transact(ctx context.Context, fn func(context.Context, Session) error) error
}
connProvider func() (*sql.DB, error)
// SqlOption defines the method to customize a sql connection.
SqlOption func(*commonSqlConn)
commonSqlConn struct {
connProv connProvider
// onError func(context.Context, error)
beginTx beginnable
brk resource.Breaker
accept func(error) bool
disableMetric bool // 关闭指标采集
disableTrace bool // 关闭链路追踪
disablePrepare bool // 关闭预处理
driverName string // 驱动
dbName string
addr string
}
beginnable func() (trans, error)
trans interface {
Session
Commit() error
Rollback() error
}
txSession struct {
*sql.Tx
disableMetric bool // 关闭指标采集
disableTrace bool // 关闭链路追踪
disablePrepare bool // 关闭预处理
driverName string // 驱动
dbName string
addr string
}
// sessionConn interface {
// Exec(query string, args ...any) (sql.Result, error)
// ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
// Query(query string, args ...any) (*sql.Rows, error)
// QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
// }
)
// NewSqlConn returns a SqlConn with given driver name and dns.
func NewSqlConn(driverName, dns string, pool *pool, opts ...SqlOption) SqlConn {
conn := &commonSqlConn{
disableTrace: pool.DisableTrace,
disableMetric: pool.DisableMetric,
driverName: pool.DriverName,
dbName: pool.DbName,
addr: pool.Addr,
connProv: func() (*sql.DB, error) {
return getSqlConn(driverName, dns, pool)
},
// 事务处理
beginTx: func() (trans, error) {
db, err := getSqlConn(driverName, dns, pool)
if err != nil {
return nil, err
}
tx, err := db.Begin()
if err != nil {
return nil, err
}
return txSession{
Tx: tx,
disableTrace: pool.DisableTrace,
disableMetric: pool.DisableMetric,
disablePrepare: pool.DisablePrepare,
driverName: pool.DriverName,
dbName: pool.DbName,
addr: pool.Addr,
}, nil
},
brk: resource.NewBreaker(),
}
for _, opt := range opts {
opt(conn)
}
return conn
}
// getCtx returns a context with a timeout.
func getCtx(ctx context.Context) context.Context {
if ctx == nil || ctx.Err() != nil {
ctx = context.TODO()
}
return ctx
}
func ResultAccept(err error) error {
if err == nil || err == sql.ErrNoRows || err == sql.ErrTxDone || err == context.Canceled {
return nil
}
return err
}
// Close closes the connection.
func (db *commonSqlConn) Close() error {
return nil
}
// MultiInsert 批量插入
func (db *commonSqlConn) MultiInsert(ctx context.Context, query string, args ...any) (int64, error) {
res, err := db.ExecCtx(ctx, query, args...)
if err != nil {
return 0, err
}
return res.RowsAffected()
}
// Replace 替换
func (db *commonSqlConn) Replace(ctx context.Context, query string, args ...any) (int64, error) {
res, err := db.ExecCtx(ctx, query, args...)
if err != nil {
return 0, err
}
return res.RowsAffected()
}
// InsertUpdate 插入或更新
func (db *commonSqlConn) InsertUpdate(ctx context.Context, query string, args ...any) (int64, error) {
res, err := db.ExecCtx(ctx, query, args...)
if err != nil {
return 0, err
}
return res.RowsAffected()
}
// Insert 插入
func (db *commonSqlConn) Insert(ctx context.Context, query string, args ...any) (int64, error) {
res, err := db.ExecCtx(ctx, query, args...)
if err != nil {
return 0, err
}
return res.LastInsertId()
}
// Update 更新
func (db *commonSqlConn) Update(ctx context.Context, query string, args ...any) (int64, error) {
res, err := db.ExecCtx(ctx, query, args...)
if err != nil {
return 0, err
}
return res.RowsAffected()
}
// Delete 删除
func (db *commonSqlConn) Delete(ctx context.Context, query string, args ...any) (int64, error) {
res, err := db.ExecCtx(ctx, query, args...)
if err != nil {
return 0, err
}
return res.RowsAffected()
}
// Exec executes a query without returning any rows.
func (db *commonSqlConn) Exec(ctx context.Context, query string, args ...any) (int64, error) {
res, err := db.ExecCtx(ctx, query, args...)
if err != nil {
return 0, err
}
return res.RowsAffected()
}
// QueryRow returns a single row from the database.
func (db *commonSqlConn) QueryRow(ctx context.Context, query string, args ...any) *Row {
res, err := db.QueryCtx(ctx, query, args...)
if err != nil {
return &Row{err: err}
}
return &Row{
rows: &Rows{rows: res},
err: err,
}
}
func (db *commonSqlConn) Count(ctx context.Context, query string, args ...any) (int64, error) {
res, err := db.QueryCtx(ctx, query, args...)
if err != nil {
return 0, err
}
result := &Row{
rows: &Rows{rows: res},
err: err,
}
d, err := result.ToMap()
if err != nil || d == nil {
return 0, err
}
if len(d) < 1 {
return 0, nil
}
v := d["_C"]
return strconv.ParseInt(v, 10, 0)
}
// QueryRow returns a single row from the database.
func (db *commonSqlConn) QueryRows(ctx context.Context, query string, args ...any) *Rows {
res, err := db.QueryCtx(ctx, query, args...)
if err != nil {
return &Rows{err: err}
}
return &Rows{
rows: res,
err: err,
}
}
// ExecCtx executes a query without returning any rows.
func (db *commonSqlConn) ExecCtx(ctx context.Context, query string, args ...any) (result sql.Result, err error) {
ctx = getCtx(ctx)
start := time.Now()
err = db.brk.DoWithAcceptable(func() error {
var conn *sql.DB
conn, err = db.connProv()
if err != nil {
return err
}
if !db.disableTrace {
call := Caller(7)
if parentSpan := trace.SpanFromContext(ctx); parentSpan != nil {
parentCtx := parentSpan.Context()
span := opentracing.StartSpan(db.driverName, opentracing.ChildOf(parentCtx))
ext.SpanKindRPCClient.Set(span)
hostName, err := os.Hostname()
if err != nil {
hostName = "unknown"
}
ext.PeerHostname.Set(span, hostName)
ext.PeerAddress.Set(span, db.addr)
ext.DBInstance.Set(span, db.dbName)
ext.DBStatement.Set(span, db.driverName)
sqlRaw, _ := Format(query, args...)
span.LogFields(log.String("sql", sqlRaw))
span.LogFields(log.Object("call", call))
defer span.Finish()
ctx = opentracing.ContextWithSpan(ctx, span)
}
}
if !db.disablePrepare {
var stmt *sql.Stmt
//添加预处理
stmt, err = conn.PrepareContext(ctx, query)
if err != nil {
return err
}
defer func() {
if err := stmt.Close(); err != nil {
logger.Logger.Error("Error closing stmt: ", err)
}
}()
result, err = stmt.ExecContext(ctx, args...)
} else {
result, err = conn.ExecContext(ctx, query, args...)
}
if !db.disableMetric {
cost := time.Since(start)
if err != nil {
metric.LibHandleCounter.WithLabelValues(db.driverName, db.dbName, db.addr, "ERR").Inc()
} else {
metric.LibHandleCounter.Inc(db.driverName, db.dbName, db.addr, "OK")
}
metric.LibHandleHistogram.WithLabelValues(db.driverName, db.dbName, db.addr).Observe(cost.Seconds())
}
return err
}, db.acceptable)
return
}
// QueryCtx executes a query that returns rows, typically a SELECT.
func (db *commonSqlConn) QueryCtx(ctx context.Context, query string, args ...any) (result *sql.Rows, err error) {
ctx = getCtx(ctx)
start := time.Now()
err = db.brk.DoWithAcceptable(func() error {
var conn *sql.DB
conn, err = db.connProv()
if err != nil {
return err
}
if !db.disableTrace {
call := Caller(7)
if parentSpan := trace.SpanFromContext(ctx); parentSpan != nil {
parentCtx := parentSpan.Context()
span := opentracing.StartSpan(db.driverName, opentracing.ChildOf(parentCtx))
ext.SpanKindRPCClient.Set(span)
hostName, err := os.Hostname()
if err != nil {
hostName = "unknown"
}
ext.PeerHostname.Set(span, hostName)
ext.PeerAddress.Set(span, db.addr)
ext.DBInstance.Set(span, db.dbName)
ext.DBStatement.Set(span, db.driverName)
sqlRaw, _ := Format(query, args...)
span.LogFields(log.String("sql", sqlRaw))
span.LogFields(log.Object("call", call))
defer span.Finish()
ctx = opentracing.ContextWithSpan(ctx, span)
}
}
if !db.disablePrepare {
var stmt *sql.Stmt
//添加预处理
stmt, err = conn.PrepareContext(ctx, query)
if err != nil {
return err
}
defer func() {
if err := stmt.Close(); err != nil {
logger.Logger.Error("Error closing stmt: ", err)
}
}()
result, err = stmt.QueryContext(ctx, args...)
} else {
result, err = conn.QueryContext(ctx, query, args...)
}
if !db.disableMetric {
cost := time.Since(start)
if err != nil {
metric.LibHandleCounter.WithLabelValues(db.driverName, db.dbName, db.addr, "ERR").Inc()
} else {
metric.LibHandleCounter.Inc(db.driverName, db.dbName, db.addr, "OK")
}
metric.LibHandleHistogram.WithLabelValues(db.driverName, db.dbName, db.addr).Observe(cost.Seconds())
}
return err
}, db.acceptable)
return
}
// acceptable returns true if the error is acceptable.
func (db *commonSqlConn) acceptable(err error) bool {
ok := err == nil || err == sql.ErrNoRows || err == sql.ErrTxDone || err == context.Canceled
if db.accept == nil {
return ok
}
return ok || db.accept(err)
}
func (db *commonSqlConn) Transact(ctx context.Context, fn func(context.Context, Session) error) (err error) {
ctx = getCtx(ctx)
err = db.brk.DoWithAcceptable(func() error {
pool := &pool{
DisableTrace: db.disableTrace,
DisableMetric: db.disableMetric,
DisablePrepare: db.disablePrepare,
DriverName: db.driverName,
DbName: db.dbName,
Addr: db.addr,
}
return transact(ctx, db, pool, db.beginTx, fn)
}, db.acceptable)
return
}
func Caller(skip int) map[string]string {
pc, file, lineNo, _ := runtime.Caller(skip)
name := runtime.FuncForPC(pc).Name()
return map[string]string{
"path": file + ":" + cast.ToString(lineNo),
"func": name,
}
}