-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathexec.go
106 lines (85 loc) · 2.05 KB
/
exec.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
package sqlbuilder
import (
"database/sql"
"time"
)
//
// Author: 陈永佳 [email protected], [email protected]
//
type SQLPrepare interface {
Prepare(query string) (*sql.Stmt, error)
}
type Executor struct {
query string
DBPrepare SQLPrepare
logger func(sql string, args []interface{}) // 日志输出接口
slowThreshold time.Duration // 慢执行阀值
}
func newExecute(query string, prepare SQLPrepare) *Executor {
return &Executor{
query: query,
DBPrepare: prepare,
slowThreshold: 0,
}
}
func (slf *Executor) SetSlowExecThreshold(t time.Duration) *Executor {
slf.slowThreshold = t
return slf
}
func (slf *Executor) Logger(logger func(string, []interface{})) *Executor {
slf.logger = logger
return slf
}
func (slf *Executor) Exec(args ...interface{}) (sql.Result, error) {
start := time.Now()
defer slf.checkSlowExecution(start)
if nil != slf.logger {
slf.logger(slf.query, args)
}
stmt, pErr := slf.DBPrepare.Prepare(slf.query)
if nil != pErr {
return nil, pErr
}
defer stmt.Close()
return stmt.Exec(args...)
}
func (slf *Executor) Query(args ...interface{}) (*sql.Rows, error) {
start := time.Now()
defer slf.checkSlowExecution(start)
if nil != slf.logger {
slf.logger(slf.query, args)
}
stmt, pErr := slf.DBPrepare.Prepare(slf.query)
if nil != pErr {
return nil, pErr
}
defer stmt.Close()
return stmt.Query(args...)
}
func (slf *Executor) Exists(args ...interface{}) (bool, error) {
start := time.Now()
defer slf.checkSlowExecution(start)
if nil != slf.logger {
slf.logger(slf.query, args)
}
stmt, pErr := slf.DBPrepare.Prepare(slf.query)
if nil != pErr {
return false, pErr
}
defer stmt.Close()
rs, qErr := stmt.Query(args...)
if nil != qErr {
return false, qErr
}
defer rs.Close()
return rs.Next(), nil
}
func (slf *Executor) checkSlowExecution(start time.Time) {
if slf.slowThreshold <= 0 {
return
}
takes := time.Now().Sub(start)
if takes > slf.slowThreshold {
slf.logger(slf.query, []interface{}{"takes=" + takes.String()})
}
}