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
package rocket_m
import (
"git.hilo.cn/hilo-common/mylogrus"
"git.hilo.cn/hilo-common/resource/mysql"
"git.hilo.cn/hilo-common/utils"
"gorm.io/gorm"
"gorm.io/gorm/clause"
"runtime/debug"
"time"
)
type RocketInfo struct {
mysql.Entity
GroupId string
Period string
Round uint16
Stage uint16
Score uint32
}
func (ri *RocketInfo) Get(db *gorm.DB) error {
err := db.Where(ri).First(ri).Error
if err != nil {
if err == gorm.ErrRecordNotFound {
ri.ID = 0
return nil
} else {
return err
}
}
return nil
}
func (ri *RocketInfo) AddScore(db *gorm.DB) error {
return db.Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "group_id"}, {Name: "period"}},
DoUpdates: clause.Assignments(map[string]interface{}{
"score": gorm.Expr("score + ?", ri.Score)}),
}).Create(ri).Error
}
func (ri *RocketInfo) Save(db *gorm.DB) error {
return db.Save(ri).Error
}
// 周期是东3区的23点,即东8区的4点
func GetPeriod(t time.Time) string {
local := t.Local()
return local.Add(-time.Hour * 4).Format(utils.DATE_FORMAT)
}
type RocketStage struct {
Id uint16
Diamond uint32 // 升级需要的钻石数
}
func (rs *RocketStage) GetAll(db *gorm.DB) (map[uint16]uint32, error) {
rows := make([]RocketStage, 0)
if err := db.Find(&rows).Error; err != nil {
return nil, err
}
result := make(map[uint16]uint32, 0)
for _, i := range rows {
result[i.Id] = i.Diamond
}
return result, nil
}
//执行事务,遇到错误或异常则回滚 todo:应该移动到package mysql下
func DoTransaction(action func(db *gorm.DB) error) error {
begin := time.Now()
db := mysql.Db.Begin()
//异常回调
defer func() {
if err := recover(); err != nil {
//service.MyContext.Log.Info(string(debug.Stack()))
mylogrus.MyLog.Errorf("doTransactional SYSTEM ACTION PANIC: %v, stack: %v", err, string(debug.Stack()))
db.Rollback()
//为了防止给controller层造成数据错误,继续抛恐慌
panic(err)
}
}()
err := action(db)
if err != nil {
db.Rollback()
return err
}
//提交
db.Commit()
end := time.Now()
mylogrus.MyLog.Infof("transcation takes %s", end.Sub(begin).String())
return nil
}