seq.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package dao
  2. import (
  3. "context"
  4. "database/sql"
  5. "time"
  6. "go-common/app/service/main/seq-server/model"
  7. "go-common/library/log"
  8. )
  9. const (
  10. _allSQL = "SELECT id,max_seq,step,token,perch,ctime,mtime FROM business"
  11. _maxSeqSQL = "SELECT max_seq FROM business WHERE id=?"
  12. _upMaxSeqSQL = "UPDATE business SET max_seq=? WHERE id=? AND max_seq=?"
  13. _upMaxSeqTokenSQL = "UPDATE business SET max_seq=?,step=? WHERE id=? AND token=?"
  14. )
  15. // All get all seq
  16. func (d *Dao) All(c context.Context) (bs map[int64]*model.Business, err error) {
  17. rows, err := d.db.Query(c, _allSQL)
  18. if err != nil {
  19. log.Error("d.db.Query(%s) error(%v)", _allSQL, err)
  20. return
  21. }
  22. bs = make(map[int64]*model.Business)
  23. defer rows.Close()
  24. for rows.Next() {
  25. b := new(model.Business)
  26. if err = rows.Scan(&b.ID, &b.MaxSeq, &b.Step, &b.Token, &b.Perch, &b.CTime, &b.MTime); err != nil {
  27. log.Error("rows.Scan error(%v)")
  28. return
  29. }
  30. b.BenchTime = b.CTime.Time().UnixNano() / int64(time.Millisecond)
  31. b.LastTimestamp = time.Now().UnixNano() / int64(time.Millisecond)
  32. bs[b.ID] = b
  33. }
  34. return
  35. }
  36. // MaxSeq return current max seq.
  37. func (d *Dao) MaxSeq(c context.Context, businessID int64) (maxSeq int64, err error) {
  38. row := d.db.QueryRow(c, _maxSeqSQL, businessID)
  39. if err = row.Scan(&maxSeq); err != nil {
  40. if err == sql.ErrNoRows {
  41. err = nil
  42. } else {
  43. log.Error("row.Scan error(%v)", err)
  44. }
  45. }
  46. return
  47. }
  48. // UpMaxSeq update max seq by businessID.
  49. func (d *Dao) UpMaxSeq(c context.Context, businessID, maxSeq, lastSeq int64) (rows int64, err error) {
  50. res, err := d.db.Exec(c, _upMaxSeqSQL, maxSeq, businessID, lastSeq)
  51. if err != nil {
  52. log.Error("d.db.Exec(%s, %d, %d) error(%v)", _upMaxSeqSQL, maxSeq, businessID)
  53. return
  54. }
  55. return res.RowsAffected()
  56. }
  57. // UpMaxSeqToken update max seq by businessID and token.
  58. func (d *Dao) UpMaxSeqToken(c context.Context, businessID, maxSeq, step int64, token string) (rows int64, err error) {
  59. res, err := d.db.Exec(c, _upMaxSeqTokenSQL, maxSeq, step, businessID, token)
  60. if err != nil {
  61. log.Error("d.db.Exec(%s, %d, %d) error(%v)", _upMaxSeqSQL, maxSeq, businessID)
  62. return
  63. }
  64. return res.RowsAffected()
  65. }