package dept import ( "context" "database/sql" "errors" "fmt" "github.com/zeromicro/go-zero/core/stores/cache" "github.com/zeromicro/go-zero/core/stores/sqlx" ) var ErrUpdateConflict = errors.New("update conflict: data has been modified by another operation") var _ SysDeptModel = (*customSysDeptModel)(nil) type ( SysDeptModel interface { sysDeptModel FindAll(ctx context.Context) ([]*SysDept, error) UpdateWithOptLock(ctx context.Context, data *SysDept, expectedUpdateTime int64) error } customSysDeptModel struct { *defaultSysDeptModel } ) func NewSysDeptModel(conn sqlx.SqlConn, c cache.CacheConf, cachePrefix string, opts ...cache.Option) SysDeptModel { return &customSysDeptModel{ defaultSysDeptModel: newSysDeptModel(conn, c, cachePrefix, opts...), } } func (m *customSysDeptModel) FindAll(ctx context.Context) ([]*SysDept, error) { var list []*SysDept query := fmt.Sprintf("SELECT %s FROM %s ORDER BY `sort` ASC, `id` ASC", sysDeptRows, m.table) if err := m.QueryRowsNoCacheCtx(ctx, &list, query); err != nil { return nil, err } return list, nil } func (m *customSysDeptModel) UpdateWithOptLock(ctx context.Context, data *SysDept, expectedUpdateTime int64) error { sysDeptIdKey := fmt.Sprintf("%s%v", cacheSysDeptIdPrefix, data.Id) res, err := m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (sql.Result, error) { query := fmt.Sprintf("UPDATE %s SET `name`=?, `sort`=?, `deptType`=?, `remark`=?, `status`=?, `updateTime`=? WHERE `id`=? AND `updateTime`=?", m.table) return conn.ExecCtx(ctx, query, data.Name, data.Sort, data.DeptType, data.Remark, data.Status, data.UpdateTime, data.Id, expectedUpdateTime) }, sysDeptIdKey) if err != nil { return err } affected, _ := res.RowsAffected() if affected == 0 { return ErrUpdateConflict } return nil }