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 }