-
Notifications
You must be signed in to change notification settings - Fork 0
/
mysql.go
executable file
·233 lines (212 loc) · 6.23 KB
/
mysql.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
package lib
import (
"database/sql"
"database/sql/driver"
"errors"
"fmt"
"reflect"
"regexp"
"strconv"
"time"
"unicode"
"github.com/e421083458/gorm"
_ "github.com/e421083458/gorm/dialects/mysql"
)
func InitDBPool(path string) error {
//普通的db方式
DbConfMap := &MysqlMapConf{}
err := ParseConfig(path, DbConfMap)
if err != nil {
return err
}
if len(DbConfMap.List) == 0 {
fmt.Printf("[INFO] %s%s\n", time.Now().Format(TimeFormat), " empty mysql config.")
}
DBMapPool = map[string]*sql.DB{}
GORMMapPool = map[string]*gorm.DB{}
for confName, DbConf := range DbConfMap.List {
dbpool, err := sql.Open("mysql", DbConf.DataSourceName)
if err != nil {
return err
}
dbpool.SetMaxOpenConns(DbConf.MaxOpenConn)
dbpool.SetMaxIdleConns(DbConf.MaxIdleConn)
dbpool.SetConnMaxLifetime(time.Duration(DbConf.MaxConnLifeTime) * time.Second)
err = dbpool.Ping()
if err != nil {
return err
}
//gorm连接方式
dbgorm, err := gorm.Open("mysql", DbConf.DataSourceName)
if err != nil {
return err
}
dbgorm.SingularTable(true)
err = dbgorm.DB().Ping()
if err != nil {
return err
}
dbgorm.LogMode(true)
dbgorm.LogCtx(true)
dbgorm.SetLogger(&MysqlGormLogger{Trace: NewTrace()})
dbgorm.DB().SetMaxIdleConns(DbConf.MaxIdleConn)
dbgorm.DB().SetMaxOpenConns(DbConf.MaxOpenConn)
dbgorm.DB().SetConnMaxLifetime(time.Duration(DbConf.MaxConnLifeTime) * time.Second)
DBMapPool[confName] = dbpool
GORMMapPool[confName] = dbgorm
}
//手动配置连接
if dbpool, err := GetDBPool("default"); err == nil {
DBDefaultPool = dbpool
}
if dbpool, err := GetGormPool("default"); err == nil {
GORMDefaultPool = dbpool
}
return nil
}
func GetDBPool(name string) (*sql.DB, error) {
if dbpool, ok := DBMapPool[name]; ok {
return dbpool, nil
}
return nil, errors.New("get pool error")
}
func GetGormPool(name string) (*gorm.DB, error) {
if dbpool, ok := GORMMapPool[name]; ok {
return dbpool, nil
}
return nil, errors.New("get pool error")
}
func CloseDB() error {
for _, dbpool := range DBMapPool {
dbpool.Close()
}
for _, dbpool := range GORMMapPool {
dbpool.Close()
}
return nil
}
func DBPoolLogQuery(trace *TraceContext, sqlDb *sql.DB, query string, args ...interface{}) (*sql.Rows, error) {
startExecTime := time.Now()
rows, err := sqlDb.Query(query, args...)
endExecTime := time.Now()
if err != nil {
Log.TagError(trace, "_com_mysql_success", map[string]interface{}{
"sql": query,
"bind": args,
"proc_time": fmt.Sprintf("%f", endExecTime.Sub(startExecTime).Seconds()),
})
} else {
Log.TagInfo(trace, "_com_mysql_success", map[string]interface{}{
"sql": query,
"bind": args,
"proc_time": fmt.Sprintf("%f", endExecTime.Sub(startExecTime).Seconds()),
})
}
return rows, err
}
//mysql日志打印类
// Logger default logger
type MysqlGormLogger struct {
gorm.Logger
Trace *TraceContext
}
// Print format & print log
func (logger *MysqlGormLogger) Print(values ...interface{}) {
message := logger.LogFormatter(values...)
if message["level"] == "sql" {
Log.TagInfo(logger.Trace, "_com_mysql_success", message)
} else {
Log.TagInfo(logger.Trace, "_com_mysql_failure", message)
}
}
// LogCtx(true) 时会执行改方法
func (logger *MysqlGormLogger) CtxPrint(s *gorm.DB, values ...interface{}) {
ctx, ok := s.GetCtx()
trace := NewTrace()
if ok {
trace = ctx.(*TraceContext)
}
message := logger.LogFormatter(values...)
if message["level"] == "sql" {
Log.TagInfo(trace, "_com_mysql_success", message)
} else {
Log.TagInfo(trace, "_com_mysql_failure", message)
}
}
func (logger *MysqlGormLogger) LogFormatter(values ...interface{}) (messages map[string]interface{}) {
if len(values) > 1 {
var (
sql string
formattedValues []string
level = values[0]
currentTime = logger.NowFunc().Format("2006-01-02 15:04:05")
source = fmt.Sprintf("%v", values[1])
)
messages = map[string]interface{}{"level": level, "source": source, "current_time": currentTime}
if level == "sql" {
// duration
//messages = append(messages, fmt.Sprintf("%.2fms", float64(values[2].(time.Duration).Nanoseconds() / 1e4) / 100.0))
messages["proc_time"] = fmt.Sprintf("%fs", values[2].(time.Duration).Seconds())
// sql
for _, value := range values[4].([]interface{}) {
indirectValue := reflect.Indirect(reflect.ValueOf(value))
if indirectValue.IsValid() {
value = indirectValue.Interface()
if t, ok := value.(time.Time); ok {
formattedValues = append(formattedValues, fmt.Sprintf("'%v'", t.Format("2006-01-02 15:04:05")))
} else if b, ok := value.([]byte); ok {
if str := string(b); logger.isPrintable(str) {
formattedValues = append(formattedValues, fmt.Sprintf("'%v'", str))
} else {
formattedValues = append(formattedValues, "'<binary>'")
}
} else if r, ok := value.(driver.Valuer); ok {
if value, err := r.Value(); err == nil && value != nil {
formattedValues = append(formattedValues, fmt.Sprintf("'%v'", value))
} else {
formattedValues = append(formattedValues, "NULL")
}
} else {
formattedValues = append(formattedValues, fmt.Sprintf("'%v'", value))
}
} else {
formattedValues = append(formattedValues, "NULL")
}
}
// differentiate between $n placeholders or else treat like ?
if regexp.MustCompile(`\$\d+`).MatchString(values[3].(string)) {
sql = values[3].(string)
for index, value := range formattedValues {
placeholder := fmt.Sprintf(`\$%d([^\d]|$)`, index+1)
sql = regexp.MustCompile(placeholder).ReplaceAllString(sql, value+"$1")
}
} else {
formattedValuesLength := len(formattedValues)
for index, value := range regexp.MustCompile(`\?`).Split(values[3].(string), -1) {
sql += value
if index < formattedValuesLength {
sql += formattedValues[index]
}
}
}
messages["sql"] = sql
if len(values) > 5 {
messages["affected_row"] = strconv.FormatInt(values[5].(int64), 10)
}
} else {
messages["ext"] = values
}
}
return
}
func (logger *MysqlGormLogger) NowFunc() time.Time {
return time.Now()
}
func (logger *MysqlGormLogger) isPrintable(s string) bool {
for _, r := range s {
if !unicode.IsPrint(r) {
return false
}
}
return true
}