-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhandler.go
310 lines (274 loc) · 8.16 KB
/
handler.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
package db_handler
import (
"encoding/json"
"fmt"
"github.com/go-redis/redis"
_ "github.com/go-sql-driver/mysql"
"github.com/go-xorm/xorm"
"reflect"
"time"
)
type DBHandler struct {
DB *xorm.Engine
dbConf *DbConfig
redisConf *RedisConfig
Redis *redis.Client
}
func generateDSN(conf *DbConfig) string {
return fmt.Sprintf("%s:%s@(%s:%d)/%s?charset=%s", conf.UserName, conf.Password, conf.Host, conf.Port, conf.DbName, conf.Charset)
}
func createDBConnection(dsn string, showSql bool) (*xorm.Engine, error) {
db, err := xorm.NewEngine("mysql", dsn)
if err != nil {
return nil, err
}
if err = db.Ping(); err != nil {
_ = db.Close()
return nil, err
}
if showSql {
db.ShowSQL(showSql)
}
return db, nil
}
func New(dbConf *DbConfig, redisConf *RedisConfig) (*DBHandler, error) {
var errs error
var client *redis.Client
var dsn string
var db *xorm.Engine
var handler *DBHandler
if dbConf == nil {
errs = fmt.Errorf("dataBase config is nil")
goto Error
}
dsn = generateDSN(dbConf)
db, errs = createDBConnection(dsn, dbConf.ShowLog)
if errs != nil {
goto Error
}
if redisConf != nil && redisConf.Host != "" {
client = redis.NewClient(&redis.Options{
Addr: fmt.Sprintf("%s:%d", redisConf.Host, redisConf.Port),
Password: redisConf.Password,
DB: redisConf.DB,
})
if _, errs = client.Ping().Result(); errs != nil {
goto Error
}
}
handler = &DBHandler{DB: db, dbConf: dbConf, Redis: client, redisConf: redisConf}
return handler, nil
Error:
return nil, errs
}
// find by id
func (db *DBHandler) Get(bean interface{}, name string, id interface{}) (bool, error) {
refValue := reflect.ValueOf(bean)
if refValue.Kind() != reflect.Ptr || refValue.Elem().Kind() != reflect.Struct {
return false, fmt.Errorf("struct pointer expected")
}
key := fmt.Sprintf("%s|%s|%v", db.dbConf.DbName, name, id)
// find from redis
if db.Redis != nil {
res, err := db.Redis.Get(key).Result()
if err == nil {
if res != "" {
err = json.Unmarshal([]byte(res), bean)
if err == nil {
// refresh expire
db.Redis.Set(key, res, time.Second*time.Duration(db.redisConf.Expire))
return true, nil
}
}
// del from redis
db.Redis.Del(key)
}
}
//find from db
has, err := db.DB.Table(name).Where("id=?", id).Get(bean)
if err == nil && has && db.Redis != nil {
// save to redis
r, err := json.Marshal(bean)
if err == nil {
db.Redis.Set(key, string(r), time.Second*time.Duration(db.redisConf.Expire))
}
}
return has, err
}
func (db *DBHandler) GetOne(bean interface{}, name string, field string, value interface{}, idName ...string) (bool, error) {
refValue := reflect.ValueOf(bean)
if refValue.Kind() != reflect.Ptr || refValue.Elem().Kind() != reflect.Struct {
return false, fmt.Errorf("struct pointer expected")
}
refValue = refValue.Elem()
key := fmt.Sprintf("%s|%s|%s|%v", db.dbConf.DbName, name, field, value)
//find from redis
if db.Redis != nil {
id, err := db.Redis.Get(key).Result()
if err == nil {
// 如果有id 走get方法
if id != "" {
has, err := db.Get(bean, name, id)
if err == nil && has {
return has, err
}
}
// 如果没有找到id,则删除该key
db.Redis.Del(key)
}
}
// find from db
has, err := db.DB.Table(name).Where(fmt.Sprintf("%s=?", field), value).Get(bean)
if err == nil && has && db.Redis != nil {
//save to redis
defaultIdName := "Id"
if idName != nil {
defaultIdName = idName[0]
}
camelId := ToCamelString(defaultIdName)
idValue := fmt.Sprintf("%v", refValue.FieldByName(camelId))
db.Redis.Set(key, idValue, time.Second*time.Duration(db.redisConf.Expire))
}
return has, err
}
func (db *DBHandler) List(bean interface{}, name string, condition *Condition) error {
session := db.DB.Table(name)
if condition.Where != "" {
if condition.Params != nil {
session = session.Where(condition.Where, condition.Params...)
} else {
session = session.Where(condition.Where)
}
}
if condition.Asc != nil {
session = session.Asc(condition.Asc...)
}
if condition.Desc != nil {
session = session.Desc(condition.Desc...)
}
if condition.Limit > 0 {
session = session.Limit(condition.Limit, condition.Offset)
}
return session.Find(bean)
}
func (db *DBHandler) ListAndCount(bean interface{}, name string, condition *Condition) (int64, error) {
session := db.DB.Table(name)
if condition.Where != "" {
if condition.Params != nil {
session = session.Where(condition.Where, condition.Params...)
} else {
session = session.Where(condition.Where)
}
}
if condition.Asc != nil {
session = session.Asc(condition.Asc...)
}
if condition.Desc != nil {
session = session.Desc(condition.Desc...)
}
if condition.Limit > 0 {
session = session.Limit(condition.Limit, condition.Offset)
}
return session.FindAndCount(bean)
}
func (db *DBHandler) Save(bean interface{}, name string, idName ...string) error {
value := reflect.ValueOf(bean)
if value.Kind() != reflect.Ptr || value.Elem().Kind() != reflect.Struct {
return fmt.Errorf("struct pointer expected")
}
defaultIdName := "Id"
if idName != nil {
defaultIdName = idName[0]
}
camelId := ToCamelString(defaultIdName)
snakeId := ToSnakeString(defaultIdName)
value = value.Elem()
idValue := fmt.Sprintf("%v", value.FieldByName(camelId))
var err error
if idValue == "0" {
//insert
_, err = db.DB.Table(name).Insert(bean)
if err != nil {
return err
}
} else {
//update
_, err = db.DB.Table(name).Where(fmt.Sprintf("%s=?", snakeId), idValue).AllCols().Update(bean)
if err != nil {
return err
}
}
idValue = fmt.Sprintf("%v", value.FieldByName(camelId))
//save to redis
if db.Redis != nil {
key := fmt.Sprintf("%s|%s|%v", db.dbConf.DbName, name, idValue)
r, err := json.Marshal(bean)
if err == nil {
db.Redis.Set(key, string(r), time.Second*time.Duration(db.redisConf.Expire))
}
}
return err
}
// delete by id
func (db *DBHandler) Del(bean interface{}, name string, id interface{}) error {
//delete from redis
_, err := db.DB.Table(name).Where("id=?", id).Delete(bean)
if db.Redis != nil {
key := fmt.Sprintf("%s|%s|%v", db.dbConf.DbName, name, id)
db.Redis.Del(key)
}
return err
}
// multiGet by column (default is id)
func (db *DBHandler) MultiGet(bean interface{}, name string, idList []interface{}, columnNames ...string) error {
column := "id"
if columnNames != nil {
column = columnNames[0]
}
// todo find from redis
err := db.DB.Table(name).In(column, idList...).Find(bean)
return err
}
func (db *DBHandler) Count(name string, condition *Condition) (int64, error) {
if condition == nil {
return db.DB.Table(name).Count()
}
return db.DB.Table(name).Where(condition.Where, condition.Params...).Count()
}
func (db *DBHandler) Sum(bean interface{}, name string, columnName string, condition *Condition) (float64, error) {
if condition == nil {
return db.DB.Table(name).Sum(bean, columnName)
}
return db.DB.Table(name).Where(condition.Where, condition.Params...).Sum(bean, columnName)
}
func (db *DBHandler) SumInt(bean interface{}, name string, columnName string, condition *Condition) (int64, error) {
if condition == nil {
return db.DB.Table(name).SumInt(bean, columnName)
}
return db.DB.Table(name).Where(condition.Where, condition.Params...).SumInt(bean, columnName)
}
func (db *DBHandler) Sums(bean interface{}, name string, condition *Condition, columnNames ...string) ([]float64, error) {
if condition == nil {
return db.DB.Table(name).Sums(bean, columnNames...)
}
return db.DB.Table(name).Where(condition.Where, condition.Params...).Sums(bean, columnNames...)
}
func (db *DBHandler) SumsInt(bean interface{}, name string, condition *Condition, columnNames ...string) ([]int64, error) {
if condition == nil {
return db.DB.Table(name).SumsInt(bean, columnNames...)
}
return db.DB.Table(name).Where(condition.Where, condition.Params...).SumsInt(bean, columnNames...)
}
func (db *DBHandler) Exec(sql string, params ...interface{}) error {
_, err := db.DB.Exec(sql, params)
return err
}
func (db *DBHandler) Query(sql string, params ...interface{}) ([]map[string]interface{}, error) {
return db.DB.QueryInterface(sql, params)
}
func (db *DBHandler) Flush() error {
if db.Redis != nil {
return db.Redis.FlushDB().Err()
}
return nil
}