mysql.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package dao
  2. import (
  3. "context"
  4. "fmt"
  5. "go-common/app/service/main/share/model"
  6. "go-common/library/database/sql"
  7. "go-common/library/log"
  8. "github.com/pkg/errors"
  9. )
  10. const (
  11. _shareSQL = "SELECT oid,tp,share FROM %s WHERE oid=? AND tp=?"
  12. _addShareSQL = "INSERT INTO %s(oid,tp,share) VALUES(?,?,1) ON DUPLICATE KEY UPDATE share=share+1"
  13. )
  14. func table(oid int64) string {
  15. return fmt.Sprintf("share_count_%02d", oid%100)
  16. }
  17. // Share get share
  18. func (d *Dao) Share(c context.Context, oid int64, tp int) (share *model.Share, err error) {
  19. row := d.db.QueryRow(c, fmt.Sprintf(_shareSQL, table(oid)), oid, tp)
  20. share = &model.Share{}
  21. if err = row.Scan(&share.OID, &share.Tp, &share.Count); err != nil {
  22. if err == sql.ErrNoRows {
  23. share = nil
  24. err = nil
  25. } else {
  26. err = errors.WithStack(err)
  27. }
  28. return
  29. }
  30. return
  31. }
  32. // AddShare add share
  33. func (d *Dao) AddShare(c context.Context, oid int64, tp int) (err error) {
  34. if _, err = d.db.Exec(c, fmt.Sprintf(_addShareSQL, table(oid)), oid, tp); err != nil {
  35. err = errors.Wrapf(err, "d.db.Exec(%s, %d, %d)", fmt.Sprintf(_addShareSQL, table(oid)), oid, tp)
  36. return
  37. }
  38. if _, ok := d.sources[oid]; ok && tp == model.ArchiveTyp {
  39. if _, err = d.db.Exec(c, fmt.Sprintf(_addShareSQL, table(d.c.Target)), d.c.Target, tp); err != nil {
  40. return
  41. }
  42. var share *model.Share
  43. if share, err = d.Share(c, d.c.Target, tp); err != nil {
  44. return
  45. }
  46. // pub msg
  47. if err = d.PubStatShare(c, model.ArchiveMsgTyp, d.c.Target, share.Count); err != nil {
  48. log.Error("s.dao.PubArchiveShare error(%v)", err)
  49. err = nil
  50. }
  51. d.asyncCache.Save(func() {
  52. if err = d.SetShareCache(context.Background(), d.c.Target, tp, share.Count); err != nil {
  53. log.Error("d.SetShareCache error(%v)", err)
  54. return
  55. }
  56. })
  57. }
  58. return
  59. }