golang-im聊天
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. package repo
  2. import (
  3. "database/sql"
  4. "gim/pkg/db"
  5. "gim/pkg/gerrors"
  6. )
  7. const (
  8. SeqObjectTypeUser = 1 // 用户
  9. SeqObjectTypeRoom = 2 // 房间
  10. )
  11. type seqRepo struct{}
  12. var SeqRepo = new(seqRepo)
  13. // Incr 自增seq,并且获取自增后的值
  14. func (*seqRepo) Incr(objectType int, objectId int64) (int64, error) {
  15. tx := db.DB.Begin()
  16. defer tx.Rollback()
  17. var seq int64
  18. err := db.DB.Raw("select seq from seq where object_type = ? and object_id = ? for update", objectType, objectId).
  19. Row().Scan(&seq)
  20. if err != nil && err != sql.ErrNoRows {
  21. return 0, gerrors.WrapError(err)
  22. }
  23. if err == sql.ErrNoRows {
  24. err = db.DB.Exec("insert into seq (object_type,object_id,seq) values (?,?,?)", objectType, objectId, seq+1).Error
  25. if err != nil {
  26. return 0, gerrors.WrapError(err)
  27. }
  28. } else {
  29. err = db.DB.Exec("update seq set seq = seq + 1 where object_type = ? and object_id = ?", objectType, objectId).Error
  30. if err != nil {
  31. return 0, gerrors.WrapError(err)
  32. }
  33. }
  34. tx.Commit()
  35. return seq + 1, nil
  36. }