golang-im聊天
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

seq_repo.go 1018 B

2 years ago
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. }