package sql import ( "cockData/server/log" "errors" "fmt" "gorm.io/gorm" "gorm.io/gorm/clause" "strings" "time" ) type RecordUser struct { gorm.Model PID string `gorm:"uniqueIndex;not null;comment:用户标识"` Name string `gorm:"not null;comment:用户昵称"` Avatar string `gorm:"not null;comment:用户头像"` Diamond int64 `gorm:"default:0;comment:钻石数量"` } func (r *RecordUser) TableName() string { return tableName("record_user") } func FindOrCreateUser(pID string, userName string, userAvatar string) (user RecordUser, err error) { user = RecordUser{ PID: pID, } err = _db.Where(&user).FirstOrCreate(&user).Error if err != nil { return } user.Name = userName user.Avatar = userAvatar if user.Name == "" { user.Name = fmt.Sprintf("Player-%d", user.ID) } if user.Avatar == "" { user.Avatar = "https://cxhy-cn.oss-cn-hangzhou.aliyuncs.com/H5Games/res/manga/IMG_2153.png" } err = _db.Save(&user).Error return } func GetUserInfo(userID uint) (createAt time.Time, curDiamond int64, err error) { user := RecordUser{Model: gorm.Model{ID: userID}} err = _db.Table(user.TableName()).Where(&user).First(&user).Error if err != nil { return } createAt = user.CreatedAt curDiamond = user.Diamond return } func ChangeDiamond(userID uint, diamond int64, reason string) (curDiamond int64, err error) { if strings.TrimSpace(reason) == "" { err = errors.New("钻石修改原因不可为空") log.Warnf("钻石修改原因为空 userID %d", userID) return } err = _db.Transaction(func(tx *gorm.DB) error { user := RecordUser{Model: gorm.Model{ID: userID}} err = tx.Clauses(clause.Locking{Strength: "UPDATE"}).Table(user.TableName()).Where(&user).First(&user).Error if err != nil { return err } record := RecordUserDiamond{UserID: userID} record.FormDiamond = user.Diamond record.Diamond = diamond user.Diamond += diamond err = tx.Save(&user).Error if err != nil { return err } record.ToDiamond = user.Diamond record.Reason = reason err = tx.Save(&record).Error if err != nil { return err } curDiamond = user.Diamond return nil }) return }