2013-07-02 15:17:31 +04:00
|
|
|
package redis
|
|
|
|
|
2013-09-29 11:17:39 +04:00
|
|
|
// Not thread-safe.
|
|
|
|
type Pipeline struct {
|
2013-07-02 15:17:31 +04:00
|
|
|
*Client
|
|
|
|
}
|
|
|
|
|
2013-09-29 11:17:39 +04:00
|
|
|
func (c *Client) Pipeline() *Pipeline {
|
|
|
|
return &Pipeline{
|
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: c.connPool,
|
|
|
|
|
|
|
|
reqs: make([]Req, 0),
|
|
|
|
},
|
|
|
|
},
|
|
|
|
}
|
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 *Client) Pipelined(f func(*Pipeline)) ([]Req, error) {
|
|
|
|
pc := c.Pipeline()
|
|
|
|
f(pc)
|
|
|
|
reqs, err := pc.Exec()
|
|
|
|
pc.Close()
|
|
|
|
return reqs, err
|
2013-07-02 15:17:31 +04:00
|
|
|
}
|
|
|
|
|
2013-09-29 11:17:39 +04:00
|
|
|
func (c *Pipeline) Close() error {
|
2013-07-02 15:17:31 +04:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2013-09-29 11:17:39 +04:00
|
|
|
func (c *Pipeline) Discard() error {
|
2013-07-02 15:17:31 +04:00
|
|
|
c.reqs = c.reqs[:0]
|
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
|
|
|
// Always returns list of commands and error of the first failed
|
|
|
|
// command if any.
|
|
|
|
func (c *Pipeline) Exec() ([]Req, error) {
|
2013-07-02 15:17:31 +04:00
|
|
|
reqs := c.reqs
|
|
|
|
c.reqs = make([]Req, 0)
|
|
|
|
|
|
|
|
if len(reqs) == 0 {
|
|
|
|
return []Req{}, nil
|
|
|
|
}
|
|
|
|
|
2013-09-17 11:35:52 +04:00
|
|
|
cn, err := c.conn()
|
2013-07-02 15:17:31 +04:00
|
|
|
if err != nil {
|
2013-09-29 11:17:39 +04:00
|
|
|
return reqs, err
|
2013-07-02 15:17:31 +04:00
|
|
|
}
|
|
|
|
|
2013-09-29 11:17:39 +04:00
|
|
|
if err := c.execReqs(reqs, cn); err != nil {
|
|
|
|
c.freeConn(cn, err)
|
|
|
|
return reqs, err
|
2013-07-02 15:17:31 +04:00
|
|
|
}
|
|
|
|
|
2013-09-17 11:35:52 +04:00
|
|
|
c.putConn(cn)
|
2013-07-02 15:17:31 +04:00
|
|
|
return reqs, nil
|
|
|
|
}
|
|
|
|
|
2013-09-29 11:17:39 +04:00
|
|
|
func (c *Pipeline) execReqs(reqs []Req, cn *conn) error {
|
2013-07-02 15:17:31 +04:00
|
|
|
err := c.writeReq(cn, reqs...)
|
|
|
|
if err != nil {
|
2013-09-29 11:17:39 +04:00
|
|
|
for _, req := range reqs {
|
|
|
|
req.SetErr(err)
|
|
|
|
}
|
2013-07-02 15:17:31 +04:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2013-09-29 11:17:39 +04:00
|
|
|
var firstReqErr error
|
|
|
|
for _, req := range reqs {
|
2013-07-02 15:17:31 +04:00
|
|
|
val, err := req.ParseReply(cn.Rd)
|
|
|
|
if err != nil {
|
|
|
|
req.SetErr(err)
|
2013-09-29 11:17:39 +04:00
|
|
|
if err != nil {
|
|
|
|
firstReqErr = err
|
|
|
|
}
|
2013-07-02 15:17:31 +04:00
|
|
|
} else {
|
|
|
|
req.SetVal(val)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2013-09-29 11:17:39 +04:00
|
|
|
return firstReqErr
|
2013-07-02 15:17:31 +04:00
|
|
|
}
|