redis/v2/pipeline.go

86 lines
1.3 KiB
Go
Raw Normal View History

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,
2013-09-29 12:06:49 +04:00
cmds: make([]Cmder, 0),
2013-07-02 15:17:31 +04:00
},
},
}
2013-09-29 11:17:39 +04:00
}
2013-07-02 15:17:31 +04:00
2013-09-29 12:06:49 +04:00
func (c *Client) Pipelined(f func(*Pipeline)) ([]Cmder, error) {
2013-09-29 11:17:39 +04:00
pc := c.Pipeline()
f(pc)
2013-09-29 12:06:49 +04:00
cmds, err := pc.Exec()
2013-09-29 11:17:39 +04:00
pc.Close()
2013-09-29 12:06:49 +04:00
return cmds, 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-09-29 12:06:49 +04:00
c.cmds = c.cmds[: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.
2013-09-29 12:06:49 +04:00
func (c *Pipeline) Exec() ([]Cmder, error) {
cmds := c.cmds
c.cmds = make([]Cmder, 0)
2013-07-02 15:17:31 +04:00
2013-09-29 12:06:49 +04:00
if len(cmds) == 0 {
return []Cmder{}, nil
2013-07-02 15:17:31 +04:00
}
cn, err := c.conn()
2013-07-02 15:17:31 +04:00
if err != nil {
2013-09-29 12:06:49 +04:00
return cmds, err
2013-07-02 15:17:31 +04:00
}
2013-09-29 12:06:49 +04:00
if err := c.execCmds(cmds, cn); err != nil {
2013-09-29 11:17:39 +04:00
c.freeConn(cn, err)
2013-09-29 12:06:49 +04:00
return cmds, err
2013-07-02 15:17:31 +04:00
}
c.putConn(cn)
2013-09-29 12:06:49 +04:00
return cmds, nil
2013-07-02 15:17:31 +04:00
}
2013-09-29 12:06:49 +04:00
func (c *Pipeline) execCmds(cmds []Cmder, cn *conn) error {
err := c.writeCmd(cn, cmds...)
2013-07-02 15:17:31 +04:00
if err != nil {
2013-09-29 12:06:49 +04:00
for _, cmd := range cmds {
cmd.setErr(err)
2013-09-29 11:17:39 +04:00
}
2013-07-02 15:17:31 +04:00
return err
}
2013-09-29 12:06:49 +04:00
var firstCmdErr error
for _, cmd := range cmds {
2013-09-29 12:11:18 +04:00
val, err := cmd.parseReply(cn.rd)
2013-07-02 15:17:31 +04:00
if err != nil {
2013-09-29 12:06:49 +04:00
cmd.setErr(err)
if firstCmdErr == nil {
firstCmdErr = err
2013-09-29 11:17:39 +04:00
}
2013-07-02 15:17:31 +04:00
} else {
2013-09-29 12:06:49 +04:00
cmd.setVal(val)
2013-07-02 15:17:31 +04:00
}
}
2013-09-29 12:06:49 +04:00
return firstCmdErr
2013-07-02 15:17:31 +04:00
}