code.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. package dao
  2. import (
  3. "context"
  4. xsql "database/sql"
  5. "go-common/app/service/main/coupon/model"
  6. "go-common/library/database/sql"
  7. "github.com/pkg/errors"
  8. )
  9. const (
  10. _couponCodeSQL = "SELECT id,batch_token,state,code,mid,coupon_type,ver FROM coupon_code WHERE code = ?;"
  11. _countCouponCountSQL = "SELECT COUNT(1) FROM coupon_code WHERE mid = ? AND batch_token = ?;"
  12. _updateCodeStateSQL = "UPDATE coupon_code SET state = ?, mid = ?,coupon_token = ?, ver = ver + 1 WHERE code = ? AND ver = ? AND state = 1;"
  13. )
  14. // CouponCode get open info by code.
  15. func (d *Dao) CouponCode(c context.Context, code string) (res *model.CouponCode, err error) {
  16. res = new(model.CouponCode)
  17. if err = d.db.QueryRow(c, _couponCodeSQL, code).
  18. Scan(&res.ID, &res.BatchToken, &res.State, &res.Code, &res.Mid, &res.CouponType, &res.Ver); err != nil {
  19. if err == sql.ErrNoRows {
  20. res = nil
  21. err = nil
  22. return
  23. }
  24. err = errors.Wrapf(err, "dao coupon code(%s)", code)
  25. }
  26. return
  27. }
  28. // CountCodeByMid get count code by mid.
  29. func (d *Dao) CountCodeByMid(c context.Context, mid int64, batckToken string) (count int64, err error) {
  30. if err = d.db.QueryRow(c, _countCouponCountSQL, mid, batckToken).Scan(&count); err != nil {
  31. err = errors.Wrapf(err, "dao count code")
  32. }
  33. return
  34. }
  35. // TxUpdateCodeState update code state.
  36. func (d *Dao) TxUpdateCodeState(tx *sql.Tx, a *model.CouponCode) (aff int64, err error) {
  37. var res xsql.Result
  38. if res, err = tx.Exec(_updateCodeStateSQL, a.State, a.Mid, a.CouponToken, a.Code, a.Ver); err != nil {
  39. err = errors.Wrapf(err, "dao update code state(%+v)", a)
  40. return
  41. }
  42. return res.RowsAffected()
  43. }