group.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package dao
  2. import (
  3. "context"
  4. xsql "database/sql"
  5. "fmt"
  6. "go-common/app/service/openplatform/abtest/model"
  7. "go-common/library/database/sql"
  8. "github.com/pkg/errors"
  9. )
  10. const (
  11. _addGroup = "INSERT INTO abtest_group (`name`,`desc`,`is_deleted`)VALUES(?, ?, 0)"
  12. _listGroup = "SELECT `id`, `name`, `desc` FROM abtest_group WHERE `is_deleted` = 0 ORDER BY id"
  13. _updateGroup = "UPDATE abtest_group set `name` = ?, `desc` = ? where id = ?"
  14. _deleteGroup = "UPDATE abtest_group set `is_deleted` = 1 WHERE id = ?"
  15. )
  16. //AddGroup add a new group
  17. func (d *Dao) AddGroup(c context.Context, g model.Group) (i int, err error) {
  18. var (
  19. res xsql.Result
  20. )
  21. if res, err = d.db.Exec(c, _addGroup, g.Name, g.Desc); err != nil {
  22. err = errors.Wrap(err, fmt.Sprintf("[dao.group|AddGroup] d.db.Exec err: %v", err))
  23. return
  24. }
  25. return intConv(res.LastInsertId())
  26. }
  27. //UpdateGroup update group by id
  28. func (d *Dao) UpdateGroup(c context.Context, g model.Group) (i int, err error) {
  29. var (
  30. res xsql.Result
  31. )
  32. if res, err = d.db.Exec(c, _updateGroup, g.Name, g.Desc, g.ID); err != nil {
  33. err = errors.Wrap(err, fmt.Sprintf("[dao.group|UpdateGroup] d.db.Exec err: %v", err))
  34. return
  35. }
  36. return intConv(res.RowsAffected())
  37. }
  38. //DeleteGroup delete the group by id
  39. func (d *Dao) DeleteGroup(c context.Context, id int) (i int, err error) {
  40. var (
  41. res xsql.Result
  42. )
  43. if res, err = d.db.Exec(c, _deleteGroup, id); err != nil {
  44. err = errors.Wrap(err, fmt.Sprintf("[dao.group|DeleteGroup] d.db.Exec err: %v", err))
  45. return
  46. }
  47. return intConv(res.RowsAffected())
  48. }
  49. //ListGroup list all groups
  50. func (d *Dao) ListGroup(c context.Context) (res []*model.Group, err error) {
  51. var rows *sql.Rows
  52. if rows, err = d.db.Query(c, _listGroup); err != nil {
  53. err = errors.Wrap(err, fmt.Sprintf("[dao.group|ListGroup] d.db.Query err: %v", err))
  54. return
  55. }
  56. defer rows.Close()
  57. for rows.Next() {
  58. g := &model.Group{}
  59. if err = rows.Scan(&g.ID, &g.Name, &g.Desc); err != nil {
  60. err = errors.Wrap(err, fmt.Sprintf("[dao.group|ListGroup] d.db.Query err: %v", err))
  61. return
  62. }
  63. res = append(res, g)
  64. }
  65. return
  66. }
  67. func intConv(i int64, err error) (int, error) {
  68. if err != nil {
  69. return 0, err
  70. }
  71. return int(i), nil
  72. }