/
qf_base.go
359 lines (333 loc) · 8.37 KB
/
qf_base.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
package qf
import (
"fmt"
"github.com/UritMedical/qf/util/qreflect"
"gorm.io/gorm"
"reflect"
"strings"
)
//
// BaseBll
// @Description: 提供业务基础通用方法
//
type BaseBll struct {
pkg string // 业务所在的包名
name string // 业务名称
qfGroup string // 框架路径组
subGroup string // 自定义路径组
sub IBll // 子接口
dalMap DalMap // 该业务的所有数据访问层
}
func (bll *BaseBll) set(sub IBll, qfGroup, subGroup string) {
// 反射子类
t := reflect.TypeOf(sub).Elem()
// 初始化
bll.sub = sub
bll.pkg = strings.ToLower(t.PkgPath())
bll.name = strings.ToLower(t.Name())
bll.qfGroup = strings.ToLower(qfGroup)
bll.subGroup = strings.ToLower(subGroup)
}
func (bll *BaseBll) key() string {
return fmt.Sprintf("%s.%s", bll.pkg, bll.name)
}
func (bll *BaseBll) regApi(bind func(key string, handler ApiHandler)) {
api := ApiMap{
bllName: bll.key(),
dict: map[EApiKind]map[string]ApiHandler{},
}
bll.sub.RegApi(api)
for kind, routers := range api.dict {
for relative, handler := range routers {
bind(bll.buildPathKey(kind, relative), handler)
}
}
}
func (bll *BaseBll) regMsg(bind func(key string, handler MessageHandler)) {
msg := MessageMap{
bllName: bll.key(),
dict: map[EApiKind]map[string]MessageHandler{},
}
bll.sub.RegMsg(msg)
for kind, routers := range msg.dict {
for relative, handler := range routers {
bind(bll.buildPathKey(kind, relative), handler)
}
}
}
func (bll *BaseBll) regDal(db *gorm.DB) {
bll.dalMap = DalMap{
bllName: bll.key(),
dict: map[IDal]interface{}{},
}
bll.sub.RegDal(bll.dalMap)
for d, model := range bll.dalMap.dict {
d.init(db, model, false)
}
}
func (bll *BaseBll) reMigrator(db *gorm.DB) {
for d, model := range bll.dalMap.dict {
d.init(db, model, true)
}
}
func (bll *BaseBll) regError(bind func(code int, error string)) {
err := FaultMap{
bllName: bll.key(),
dict: map[int]string{},
}
bll.sub.RegFault(err)
for code, msg := range err.dict {
bind(code, msg)
}
}
func (bll *BaseBll) regRef(getApi func(key string) ApiHandler) {
ref := RefMap{
getApi: func(kind EApiKind, relative string) ApiHandler {
return getApi(bll.buildPathKey(kind, relative))
},
}
bll.sub.RegRef(ref)
}
func (bll *BaseBll) buildPathKey(kind EApiKind, relative string) string {
gp := bll.qfGroup
if strings.HasPrefix(strings.ToLower(bll.pkg), "github.com/uritmedical/qf") {
gp = bll.qfGroup + "/qf"
}
path := fmt.Sprintf("%s/%s/%s", gp, bll.subGroup, relative)
path = strings.Replace(path, "//", "/", -1)
path = strings.TrimRight(path, "/")
return fmt.Sprintf("%s:/%s", kind.HttpMethod(), path)
}
//
// Debug
// @Description: 日志调试
// @param content 需要发送的调试信息
//
func (bll *BaseBll) Debug(info string) {
fmt.Println(info)
}
////
//// GetConfig
//// @Description:
//// @return map[string]interface{}
////
//func (bll *BaseBll) GetConfig() map[string]interface{} {
// return bll.config.GetConfig(fmt.Sprintf("%s.%s", bll.pkg, bll.name))
//}
//
////
//// SetConfig
//// @Description:
//// @param value
//// @return bool
//// @return error
////
//func (bll *BaseBll) SetConfig(value map[string]interface{}) (bool, error) {
// return bll.config.SetConfig(fmt.Sprintf("%s.%s", bll.pkg, bll.name), value)
//}
//
// BaseDal
// @Description: 基础数据访问方法
//
type BaseDal struct {
db *gorm.DB
tableName string
}
//
// init
// @Description: 初始化数据库
// @param db
// @param model
// @param migrator
//
func (b *BaseDal) init(db *gorm.DB, model interface{}, migrator bool) {
b.db = db
// 根据实体名称,生成数据库
if model != nil {
b.tableName = buildTableName(model)
// 自动生成表
if migrator {
// 每次都生成
err := db.Table(b.tableName).AutoMigrate(model)
if err != nil {
panic(fmt.Sprintf("AutoMigrate %s failed: %s", b.tableName, err.Error()))
}
} else {
// 仅第一次生成
if db.Migrator().HasTable(b.tableName) == false {
err := db.Table(b.tableName).AutoMigrate(model)
if err != nil {
panic(fmt.Sprintf("AutoMigrate %s failed: %s", b.tableName, err.Error()))
}
}
}
}
}
//
// DB
// @Description: 返回对应表的数据控制器
// @return *gorm.DB
//
func (b *BaseDal) DB() *gorm.DB {
if b.tableName == "" {
return b.db
}
return b.db.Table(b.tableName)
}
//
// Create
// @Description: 新增内容
// @param content 包含了内容结构的实体对象
// @return IError 异常
//
func (b *BaseDal) Create(content interface{}) IError {
ref := qreflect.New(content)
if ref.Get("LastTime") == "0001-01-01 00:00:00" {
_ = ref.Set("LastTime", NowDateTime())
}
// 提交
result := b.DB().Create(content)
if result.RowsAffected > 0 {
return nil
}
if result.Error != nil {
return Error(ErrorCodeSaveFailure, result.Error.Error())
}
return nil
}
//
// Save
// @Description: 保存内容(存在更新、不存在则新增)
// @param content 包含了内容结构的实体对象
// @return IError 异常
//
func (b *BaseDal) Save(content interface{}) IError {
ref := qreflect.New(content)
if ref.Get("LastTime") == "0001-01-01 00:00:00" {
_ = ref.Set("LastTime", NowDateTime())
}
// 提交
result := b.DB().Save(content)
if result.RowsAffected > 0 {
return nil
}
if result.Error != nil {
return Error(ErrorCodeSaveFailure, result.Error.Error())
}
return nil
}
//
// Delete
// @Description: 删除内容
// @param id 唯一号
// @return IError 异常
//
func (b *BaseDal) Delete(id uint64) IError {
result := b.DB().Delete(&BaseModel{Id: id})
if result.RowsAffected == 0 {
return Error(ErrorCodeRecordNotFound, fmt.Sprintf("delete failed, id=%d does not exist", id))
}
if result.Error != nil {
return Error(ErrorCodeDeleteFailure, result.Error.Error())
}
return nil
}
//
// GetModel
// @Description: 获取单条数据
// @param id 唯一号
// @param dest 目标实体结构
// @return IError 返回异常
//
func (b *BaseDal) GetModel(id uint64, dest interface{}) IError {
result := b.DB().Where("Id = ?", id).Find(dest)
// 如果异常或者未查询到任何数据
if result.Error != nil {
return Error(ErrorCodeRecordNotFound, result.Error.Error())
}
return nil
}
//
// GetSummary
// @Description: 仅获取单条摘要
// @param id
// @return IError
//
func (b *BaseDal) GetSummary(id uint64, dest interface{}) IError {
result := b.DB().Where("Id = ?", id).Omit("FullInfo").Find(dest)
// 如果异常或者未查询到任何数据
if result.Error != nil {
return Error(ErrorCodeRecordNotFound, result.Error.Error())
}
return nil
}
//
// GetList
// @Description: 按唯一号区间,获取一组列表
// @param startId 起始编号
// @param maxCount 最大获取数
// @param dest 目标列表
// @return IError 返回异常
//
func (b *BaseDal) GetList(startId uint64, maxCount uint, dest interface{}) IError {
result := b.DB().Limit(int(maxCount)).Offset(int(startId)).Find(dest)
if result.Error != nil {
return Error(ErrorCodeRecordNotFound, result.Error.Error())
}
return nil
}
//
// GetListByIN
// @Description: 获取指定Id列表的一组数据列表
// @param ids Id列表
// @param dest
// @return IError
//
func (b *BaseDal) GetListByIN(ids []uint64, dest interface{}) IError {
result := b.DB().Where("Id IN (?)", ids).Find(dest)
if result.Error != nil {
return Error(ErrorCodeRecordNotFound, result.Error.Error())
}
return nil
}
//
// GetConditions
// @Description: 通过自定义条件获取数据
// @param dest 结构体/列表
// @param query 条件
// @param args 条件参数
// @return IError
//
func (b *BaseDal) GetConditions(dest interface{}, query interface{}, args ...interface{}) IError {
result := b.DB().Where(query, args...).Find(dest)
if result.Error != nil {
return Error(ErrorCodeRecordNotFound, result.Error.Error())
}
return nil
}
//
// GetCount
// @Description: GetCount
// @param query 查询条件,如:a = ? and b = ?
// @param args 条件对应的值
// @return int64 查询到的记录数
//
func (b *BaseDal) GetCount(query interface{}, args ...interface{}) int64 {
count := int64(0)
b.DB().Where(query, args).Count(&count)
return count
}
//
// CheckExists
// @Description: 检查内容是否存在
// @param id 唯一号
// @return bool true存在 false不存在
//
func (b *BaseDal) CheckExists(id uint64) bool {
count := int64(0)
result := b.DB().Where("Id = ?", id).Count(&count)
if count > 0 && result.Error == nil {
return true
}
return false
}