sysDeptModel.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. package dept
  2. import (
  3. "context"
  4. "database/sql"
  5. "errors"
  6. "fmt"
  7. "github.com/zeromicro/go-zero/core/stores/cache"
  8. "github.com/zeromicro/go-zero/core/stores/sqlx"
  9. )
  10. var ErrUpdateConflict = errors.New("update conflict: data has been modified by another operation")
  11. var _ SysDeptModel = (*customSysDeptModel)(nil)
  12. type (
  13. SysDeptModel interface {
  14. sysDeptModel
  15. FindAll(ctx context.Context) ([]*SysDept, error)
  16. UpdateWithOptLock(ctx context.Context, data *SysDept, expectedUpdateTime int64) error
  17. }
  18. customSysDeptModel struct {
  19. *defaultSysDeptModel
  20. }
  21. )
  22. func NewSysDeptModel(conn sqlx.SqlConn, c cache.CacheConf, cachePrefix string, opts ...cache.Option) SysDeptModel {
  23. return &customSysDeptModel{
  24. defaultSysDeptModel: newSysDeptModel(conn, c, cachePrefix, opts...),
  25. }
  26. }
  27. func (m *customSysDeptModel) FindAll(ctx context.Context) ([]*SysDept, error) {
  28. var list []*SysDept
  29. query := fmt.Sprintf("SELECT %s FROM %s ORDER BY `sort` ASC, `id` ASC", sysDeptRows, m.table)
  30. if err := m.QueryRowsNoCacheCtx(ctx, &list, query); err != nil {
  31. return nil, err
  32. }
  33. return list, nil
  34. }
  35. func (m *customSysDeptModel) UpdateWithOptLock(ctx context.Context, data *SysDept, expectedUpdateTime int64) error {
  36. sysDeptIdKey := fmt.Sprintf("%s%v", cacheSysDeptIdPrefix, data.Id)
  37. res, err := m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (sql.Result, error) {
  38. query := fmt.Sprintf("UPDATE %s SET `name`=?, `sort`=?, `deptType`=?, `remark`=?, `status`=?, `updateTime`=? WHERE `id`=? AND `updateTime`=?", m.table)
  39. return conn.ExecCtx(ctx, query, data.Name, data.Sort, data.DeptType, data.Remark, data.Status, data.UpdateTime, data.Id, expectedUpdateTime)
  40. }, sysDeptIdKey)
  41. if err != nil {
  42. return err
  43. }
  44. affected, _ := res.RowsAffected()
  45. if affected == 0 {
  46. return ErrUpdateConflict
  47. }
  48. return nil
  49. }