mysql_coin.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package dao
  2. import (
  3. "context"
  4. "database/sql"
  5. "fmt"
  6. xsql "go-common/library/database/sql"
  7. "go-common/library/log"
  8. )
  9. const (
  10. _shard = 50
  11. _multi = 100
  12. _selCoin = "SELECT coins FROM coins_%02d where mid=?"
  13. _txUpdateCoins = "INSERT INTO coins_%02d(mid,coins) VALUES(?,?) ON DUPLICATE KEY UPDATE coins=coins+?"
  14. )
  15. // UpdateCoin update user coins.
  16. func (d *Dao) UpdateCoin(c context.Context, mid int64, coin float64) (err error) {
  17. count := int64(coin * _multi)
  18. if _, err = d.coin.Exec(c, fmt.Sprintf(_txUpdateCoins, mid%_shard), mid, count, count); err != nil {
  19. PromError("db:UpdateCoin")
  20. log.Errorv(c, log.KV("log", "UpdateCoin"), log.KV("err", err))
  21. return
  22. }
  23. return
  24. }
  25. // TxUpdateCoins update coins
  26. func (d *Dao) TxUpdateCoins(c context.Context, tx *xsql.Tx, mid int64, coin float64) (err error) {
  27. count := int64(coin * _multi)
  28. _, err = tx.Exec(fmt.Sprintf(_txUpdateCoins, mid%_shard), mid, count, count)
  29. if err != nil {
  30. PromError("db:TxUpdateCoins")
  31. log.Errorv(c, log.KV("log", "TxUpdateCoins"), log.KV("err", err), log.KV("mid", mid))
  32. return
  33. }
  34. return
  35. }
  36. // TxUserCoin tx user coin
  37. func (d *Dao) TxUserCoin(c context.Context, tx *xsql.Tx, mid int64) (count float64, err error) {
  38. var coin int64
  39. row := tx.QueryRow(fmt.Sprintf(_selCoin, mid%_shard), mid)
  40. if err = row.Scan(&coin); err != nil {
  41. if err == sql.ErrNoRows {
  42. err = nil
  43. return
  44. }
  45. PromError("db:TxUserCoin")
  46. log.Errorv(c, log.KV("log", "TxUserCoin"), log.KV("err", err))
  47. }
  48. count = float64(coin) / _multi
  49. return
  50. }
  51. // RawUserCoin get user coins.
  52. func (d *Dao) RawUserCoin(c context.Context, mid int64) (res float64, err error) {
  53. var count int64
  54. row := d.coin.QueryRow(c, fmt.Sprintf(_selCoin, mid%_shard), mid)
  55. if err = row.Scan(&count); err != nil {
  56. if err == sql.ErrNoRows {
  57. err = nil
  58. return
  59. }
  60. PromError("db:Coins")
  61. log.Errorv(c, log.KV("log", "Coins"), log.KV("err", err))
  62. }
  63. res = float64(count) / _multi
  64. return
  65. }