redis/v2/multi.go

126 lines
2.1 KiB
Go
Raw Normal View History

2013-07-02 15:17:31 +04:00
package redis
import (
2013-09-29 11:17:39 +04:00
"errors"
2013-07-02 15:17:31 +04:00
"fmt"
)
2013-09-29 11:17:39 +04:00
var errDiscard = errors.New("redis: Discard can be used only inside Exec")
// Not thread-safe.
type Multi struct {
2013-07-02 15:17:31 +04:00
*Client
}
2013-09-29 11:17:39 +04:00
func (c *Client) Multi() *Multi {
return &Multi{
2013-07-02 15:17:31 +04:00
Client: &Client{
baseClient: &baseClient{
2013-09-11 20:22:10 +04:00
opt: c.opt,
2013-07-02 15:17:31 +04:00
connPool: newSingleConnPool(c.connPool, nil, true),
},
},
2013-09-29 11:17:39 +04:00
}
2013-07-02 15:17:31 +04:00
}
2013-09-29 11:17:39 +04:00
func (c *Multi) Close() error {
2013-07-02 15:17:31 +04:00
c.Unwatch()
return c.Client.Close()
}
2013-09-29 11:17:39 +04:00
func (c *Multi) Watch(keys ...string) *StatusReq {
2013-07-02 15:17:31 +04:00
args := append([]string{"WATCH"}, keys...)
req := NewStatusReq(args...)
c.Process(req)
return req
}
2013-09-29 11:17:39 +04:00
func (c *Multi) Unwatch(keys ...string) *StatusReq {
2013-07-02 15:17:31 +04:00
args := append([]string{"UNWATCH"}, keys...)
req := NewStatusReq(args...)
c.Process(req)
return req
}
2013-09-29 11:17:39 +04:00
func (c *Multi) Discard() error {
2013-07-02 15:17:31 +04:00
if c.reqs == nil {
2013-09-29 11:17:39 +04:00
return errDiscard
2013-07-02 15:17:31 +04:00
}
c.reqs = c.reqs[:1]
2013-09-29 11:17:39 +04:00
return nil
2013-07-02 15:17:31 +04:00
}
2013-09-29 11:17:39 +04:00
func (c *Multi) Exec(f func()) ([]Req, error) {
2013-07-02 15:17:31 +04:00
c.reqs = []Req{NewStatusReq("MULTI")}
2013-09-29 11:17:39 +04:00
f()
c.reqs = append(c.reqs, NewIfaceSliceReq("EXEC"))
2013-07-02 15:17:31 +04:00
reqs := c.reqs
c.reqs = nil
if len(reqs) == 2 {
return []Req{}, nil
}
cn, err := c.conn()
if err != nil {
return nil, err
}
// Synchronize writes and reads to the connection using mutex.
err = c.execReqs(reqs, cn)
if err != nil {
c.removeConn(cn)
return nil, err
}
c.putConn(cn)
return reqs[1 : len(reqs)-1], nil
}
2013-09-29 11:17:39 +04:00
func (c *Multi) execReqs(reqs []Req, cn *conn) error {
2013-07-02 15:17:31 +04:00
err := c.writeReq(cn, reqs...)
if err != nil {
return err
}
statusReq := NewStatusReq()
// Omit last request (EXEC).
reqsLen := len(reqs) - 1
// Parse queued replies.
for i := 0; i < reqsLen; i++ {
_, err = statusReq.ParseReply(cn.Rd)
if err != nil {
return err
}
}
// Parse number of replies.
line, err := readLine(cn.Rd)
if err != nil {
return err
}
if line[0] != '*' {
2013-09-29 11:17:39 +04:00
return fmt.Errorf("redis: expected '*', but got line %q", line)
2013-07-02 15:17:31 +04:00
}
if len(line) == 3 && line[1] == '-' && line[2] == '1' {
return Nil
}
// Parse replies.
// Loop starts from 1 to omit first request (MULTI).
for i := 1; i < reqsLen; i++ {
req := reqs[i]
val, err := req.ParseReply(cn.Rd)
if err != nil {
req.SetErr(err)
} else {
req.SetVal(val)
}
}
return nil
}