mysql.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package stat
  2. import (
  3. "context"
  4. "fmt"
  5. favmdl "go-common/app/service/main/favorite/model"
  6. "go-common/library/database/sql"
  7. "go-common/library/log"
  8. )
  9. const (
  10. _folderStatSharding int64 = 100
  11. // stat
  12. _statSQL = "SELECT play,fav,share from fav_folder_stat_%s WHERE fid=?"
  13. _upsertPlaySQL = "INSERT INTO fav_folder_stat_%s (fid,play) VALUES(?,?) ON DUPLICATE KEY UPDATE play=?"
  14. _upsertFavSQL = "INSERT INTO fav_folder_stat_%s (fid,fav) VALUES(?,?) ON DUPLICATE KEY UPDATE fav=?"
  15. _upsertShareSQL = "INSERT INTO fav_folder_stat_%s (fid,share) VALUES(?,?) ON DUPLICATE KEY UPDATE share=?"
  16. )
  17. // UpdateFav updates stat in db.
  18. func (d *Dao) UpdateFav(c context.Context, oid, count int64) (rows int64, err error) {
  19. fid, table := hit(oid)
  20. res, err := d.db.Exec(c, fmt.Sprintf(_upsertFavSQL, table), fid, count, count)
  21. if err != nil {
  22. log.Error("UpdateFav(%d,%d) error(%+v)", oid, count, err)
  23. return
  24. }
  25. rows, err = res.RowsAffected()
  26. return
  27. }
  28. // UpdateShare updates stat in db.
  29. func (d *Dao) UpdateShare(c context.Context, oid, count int64) (rows int64, err error) {
  30. fid, table := hit(oid)
  31. res, err := d.db.Exec(c, fmt.Sprintf(_upsertShareSQL, table), fid, count, count)
  32. if err != nil {
  33. log.Error("UpdateShare(%d,%d) error(%+v)", oid, count, err)
  34. return
  35. }
  36. rows, err = res.RowsAffected()
  37. return
  38. }
  39. // UpdatePlay updates stat in db.
  40. func (d *Dao) UpdatePlay(c context.Context, oid, count int64) (rows int64, err error) {
  41. fid, table := hit(oid)
  42. res, err := d.db.Exec(c, fmt.Sprintf(_upsertPlaySQL, table), fid, count, count)
  43. if err != nil {
  44. log.Error("UpdatePlay(%d) error(%+v)", oid, err)
  45. return
  46. }
  47. rows, err = res.RowsAffected()
  48. return
  49. }
  50. // Stat return stat count from mysql.
  51. func (d *Dao) Stat(c context.Context, oid int64) (f *favmdl.Folder, err error) {
  52. fid, table := hit(oid)
  53. f = &favmdl.Folder{}
  54. row := d.db.QueryRow(c, fmt.Sprintf(_statSQL, table), fid)
  55. if err = row.Scan(&f.PlayCount, &f.FavedCount, &f.ShareCount); err != nil {
  56. if err == sql.ErrNoRows {
  57. err = nil
  58. f = nil
  59. return
  60. }
  61. log.Error("Stat(%v) error(%+v)", f, err)
  62. }
  63. return
  64. }