-
Notifications
You must be signed in to change notification settings - Fork 0
/
sqlxx.go
220 lines (181 loc) · 5.12 KB
/
sqlxx.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
package sqlxx
import (
"context"
"database/sql"
"fmt"
"strings"
"time"
"github.com/jmoiron/sqlx"
"golang.org/x/xerrors"
)
type DB struct {
dbx *sqlx.DB
logger Logger
warnDuration time.Duration
warnRows int
hideParams bool
}
const (
DefaultWarnDuration = 150 * time.Millisecond
DefaultWarnRows = 1000
DefaultHideParams = false
CmdGet = "GET"
CmdSelect = "SELECT"
CmdQuery = "QUERY"
CmdExec = "EXEC"
CmdNamedExec = "N-EXEC"
)
type Option struct {
WarnDuration time.Duration
WarnRows int
HideParams bool
}
func New(db *sqlx.DB, l Logger, opts *Option) *DB {
var (
warnDuration time.Duration
warnRows int
hideParams bool
)
if opts != nil {
warnDuration = opts.WarnDuration
warnRows = opts.WarnRows
hideParams = opts.HideParams
} else {
warnDuration = DefaultWarnDuration
warnRows = DefaultWarnRows
hideParams = DefaultHideParams
}
return &DB{db, l, warnDuration, warnRows, hideParams}
}
type ctxKey string
const (
txCtxKey ctxKey = "tx-ctx-key"
)
type queryer interface {
QueryxContext(ctx context.Context, query string, args ...interface{}) (*sqlx.Rows, error)
GetContext(ctx context.Context, dest interface{}, query string, args ...interface{}) error
SelectContext(ctx context.Context, dest interface{}, query string, args ...interface{}) error
ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error)
NamedExecContext(ctx context.Context, query string, arg interface{}) (sql.Result, error)
}
func (db *DB) build(ctx context.Context) queryer {
if tx, ok := ctx.Value(txCtxKey).(*sqlx.Tx); ok {
return tx
}
return db.dbx
}
func newTxCtx(ctx context.Context, tx *sqlx.Tx) context.Context {
return context.WithValue(ctx, txCtxKey, tx)
}
func (db *DB) Query(ctx context.Context, query string, args ...interface{}) (*sqlx.Rows, error) {
start := time.Now()
rows, err := db.build(ctx).QueryxContext(ctx, query, args...)
clone := *rows
db.log(ctx, CmdQuery, query, args, err, countRows(&clone), time.Since(start))
return rows, err
}
func (db *DB) Get(ctx context.Context, dest interface{}, query string, args ...interface{}) error {
start := time.Now()
err := db.build(ctx).GetContext(ctx, dest, query, args...)
rows := 1
if err != nil {
rows = 0
}
db.log(ctx, CmdGet, query, args, err, rows, time.Since(start))
return err
}
func (db *DB) Select(ctx context.Context, dest interface{}, query string, args ...interface{}) error {
start := time.Now()
err := db.build(ctx).SelectContext(ctx, dest, query, args...)
db.log(ctx, CmdSelect, query, args, err, countRows(dest), time.Since(start))
return err
}
func (db *DB) Exec(ctx context.Context, query string, args ...interface{}) (sql.Result, error) {
start := time.Now()
res, err := db.build(ctx).ExecContext(ctx, query, args...)
db.log(ctx, CmdExec, query, args, err, countRows(res), time.Since(start))
return res, err
}
func (db *DB) NamedExec(ctx context.Context, query string, arg interface{}) (sql.Result, error) {
start := time.Now()
res, err := db.build(ctx).NamedExecContext(ctx, query, arg)
_, args, _ := sqlx.BindNamed(sqlx.NAMED, query, arg)
db.log(ctx, CmdNamedExec, query, args, err, countRows(res), time.Since(start))
return res, err
}
func (db *DB) log(ctx context.Context, cmd string, query string, args []interface{}, err error, rows int, d time.Duration) {
if db.logger == nil {
return
}
fn := db.loggerFunc(err, rows, d)
msg := db.makeLogMsg(cmd, query, args, rows, err, d)
fn(ctx, msg)
}
func (db *DB) loggerFunc(err error, rows int, d time.Duration) loggerFunc {
if db.logger == nil {
return nil
}
if err != nil && err != sql.ErrNoRows {
return db.logger.Warnf
} else if rows > db.warnRows {
return db.logger.Warnf
} else if d > db.warnDuration {
return db.logger.Warnf
}
return db.logger.Debugf
}
func (db *DB) makeLogMsg(cmd string, query string, args []interface{}, rows int, err error, elapsed time.Duration) string {
var b strings.Builder
b.Grow(1024)
b.WriteString("[" + cmd + "] ")
if err != nil && err != sql.ErrNoRows {
b.WriteString(err.Error())
b.WriteString(" ")
}
fmt.Fprintf(&b, "[%.2f ms] [%d rows] ", toMillisec(elapsed), rows)
b.WriteString(query)
if !db.hideParams {
b.WriteString(" ")
writeArgs(&b, args)
}
return b.String()
}
func (db *DB) Secret() *DB {
clone := db.clone()
clone.hideParams = true
return clone
}
func (db *DB) clone() *DB {
cloneDB := *db
return &cloneDB
}
type TxFunc func(context.Context) error
func (db *DB) RunInTx(ctx context.Context, txFn TxFunc) (err, rbErr error) {
if IsInTx(ctx) {
return txFn(ctx), nil
}
tx, err := db.dbx.Beginx()
if err != nil {
return err, nil
}
defer func() {
if pnc := recover(); pnc != nil {
rbErr = tx.Rollback()
if pncErr, ok := pnc.(error); ok {
err = pncErr
} else {
err = xerrors.Errorf("sqlxx: recovered: %v", pnc)
}
} else if err != nil {
rbErr = tx.Rollback()
} else if cmtErr := tx.Commit(); cmtErr != nil && cmtErr != sql.ErrTxDone {
err = cmtErr
}
}()
err = txFn(newTxCtx(ctx, tx))
return
}
func IsInTx(ctx context.Context) bool {
tx, ok := ctx.Value(txCtxKey).(*sqlx.Tx)
return ok && tx != nil
}