mysql.go 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package dao
  2. import (
  3. "context"
  4. "crypto/md5"
  5. "database/sql"
  6. "encoding/hex"
  7. "fmt"
  8. "go-common/app/job/live/gift/internal/model"
  9. "go-common/library/log"
  10. "strconv"
  11. )
  12. var (
  13. _getBag = "SELECT id,gift_num FROM user_gift_%s WHERE uid = ? AND gift_id = ? AND expireat = ? LIMIT 1"
  14. _getBagByID = "SELECT id,gift_num FROM user_gift_%s WHERE id = ?"
  15. _updateBagNum = "UPDATE user_gift_%s SET gift_num = gift_num + ? WHERE id = ?"
  16. _insertBag = "INSERT INTO user_gift_%s (uid,gift_id,gift_num,expireat) VALUES (?,?,?,?)"
  17. )
  18. // GetBag GetBag
  19. func (d *Dao) GetBag(ctx context.Context, uid, giftID, expireAt int64) (res *model.BagInfo, err error) {
  20. log.Info("GetBag,uid:%d,giftID:%d,expireAt:%d", uid, giftID, expireAt)
  21. row := d.db.QueryRow(ctx, fmt.Sprintf(_getBag, getPostFix(uid)), uid, giftID, expireAt)
  22. res = &model.BagInfo{}
  23. if err = row.Scan(&res.ID, &res.GiftNum); err != nil {
  24. if err == sql.ErrNoRows {
  25. err = nil
  26. return
  27. }
  28. log.Error("GetBag row.Scan error(%v)", err)
  29. }
  30. return
  31. }
  32. // UpdateBagNum UpdateBagNum
  33. func (d *Dao) UpdateBagNum(ctx context.Context, uid, id, num int64) (affected int64, err error) {
  34. log.Info("UpdateBagNum,uid:%d,id:%d,num:%d", uid, id, num)
  35. res, err := d.db.Exec(ctx, fmt.Sprintf(_updateBagNum, getPostFix(uid)), num, id)
  36. if err != nil {
  37. log.Error("UpdateBagNum error(%v)", err)
  38. return
  39. }
  40. return res.RowsAffected()
  41. }
  42. // AddBag AddBag
  43. func (d *Dao) AddBag(ctx context.Context, uid, giftID, giftNum, expireAt int64) (affected int64, err error) {
  44. log.Info("AddBag,uid:%d,giftID:%d,giftNum:%d,expireAt:%d", uid, giftID, giftNum, expireAt)
  45. res, err := d.db.Exec(ctx, fmt.Sprintf(_insertBag, getPostFix(uid)), uid, giftID, giftNum, expireAt)
  46. if err != nil {
  47. log.Error("AddBag error(%v)", err)
  48. return
  49. }
  50. return res.LastInsertId()
  51. }
  52. // GetBagByID GetBagByID
  53. func (d *Dao) GetBagByID(ctx context.Context, uid, id int64) (res *model.BagInfo, err error) {
  54. log.Info("GetBagByID,uid:%d,id:%d", uid, id)
  55. row := d.db.QueryRow(ctx, fmt.Sprintf(_getBagByID, getPostFix(uid)), id)
  56. res = &model.BagInfo{}
  57. if err = row.Scan(&res.ID, &res.GiftNum); err != nil {
  58. if err == sql.ErrNoRows {
  59. err = nil
  60. return
  61. }
  62. log.Error("GetBagByID row.Scan error(%v)", err)
  63. }
  64. return
  65. }
  66. func getPostFix(uid int64) string {
  67. uidStr := strconv.Itoa(int(uid))
  68. h := md5.New()
  69. h.Write([]byte(uidStr))
  70. md5Str := hex.EncodeToString(h.Sum(nil))
  71. return md5Str[0:1]
  72. }