redis/v2/pipeline.go

91 lines
1.4 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
closed bool
2013-07-02 15:17:31 +04:00
}
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 {
c.closed = true
2013-07-02 15:17:31 +04:00
return nil
}
2013-09-29 11:17:39 +04:00
func (c *Pipeline) Discard() error {
if c.closed {
return errClosed
}
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 13:41:04 +04:00
// Exec always returns list of commands and error of the first failed
2013-09-29 11:17:39 +04:00
// command if any.
2013-09-29 12:06:49 +04:00
func (c *Pipeline) Exec() ([]Cmder, error) {
if c.closed {
return nil, errClosed
}
2013-09-29 12:06:49 +04:00
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 13:41:04 +04:00
setCmdsErr(cmds, err)
2013-09-29 12:06:49 +04:00
return cmds, err
2013-07-02 15:17:31 +04:00
}
2013-09-29 13:41:04 +04:00
if err := c.execCmds(cn, cmds); 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 13:41:04 +04:00
func (c *Pipeline) execCmds(cn *conn, cmds []Cmder) error {
2013-09-29 12:06:49 +04:00
err := c.writeCmd(cn, cmds...)
2013-07-02 15:17:31 +04:00
if err != nil {
2013-09-29 13:41:04 +04:00
setCmdsErr(cmds, err)
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 {
2014-01-06 18:06:30 +04:00
if err := cmd.parseReply(cn.rd); err != nil {
2013-09-29 12:06:49 +04:00
if firstCmdErr == nil {
firstCmdErr = err
2013-09-29 11:17:39 +04:00
}
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
}