redis/pipeline.go

92 lines
1.4 KiB
Go
Raw Normal View History

package redis
2014-05-11 11:42:40 +04:00
// Not thread-safe.
type Pipeline struct {
*Client
2014-05-11 11:42:40 +04:00
closed bool
}
2014-05-11 11:42:40 +04:00
func (c *Client) Pipeline() *Pipeline {
return &Pipeline{
Client: &Client{
2014-05-11 11:42:40 +04:00
baseClient: &baseClient{
opt: c.opt,
connPool: c.connPool,
cmds: make([]Cmder, 0),
},
},
2012-08-17 22:36:48 +04:00
}
2014-05-11 11:42:40 +04:00
}
2012-08-25 23:44:53 +04:00
2014-07-02 17:18:19 +04:00
func (c *Client) Pipelined(f func(*Pipeline) error) ([]Cmder, error) {
2014-05-11 11:42:40 +04:00
pc := c.Pipeline()
2014-07-02 17:18:19 +04:00
if err := f(pc); err != nil {
return nil, err
}
2014-05-11 11:42:40 +04:00
cmds, err := pc.Exec()
pc.Close()
return cmds, err
2012-08-17 22:36:48 +04:00
}
2014-05-11 11:42:40 +04:00
func (c *Pipeline) Close() error {
c.closed = true
return nil
}
2014-05-11 11:42:40 +04:00
func (c *Pipeline) Discard() error {
if c.closed {
return errClosed
}
c.cmds = c.cmds[:0]
return nil
2012-08-20 00:19:00 +04:00
}
2014-05-11 11:42:40 +04:00
// Exec always returns list of commands and error of the first failed
// command if any.
func (c *Pipeline) Exec() ([]Cmder, error) {
if c.closed {
return nil, errClosed
}
cmds := c.cmds
c.cmds = make([]Cmder, 0)
2012-08-25 23:44:53 +04:00
2014-05-11 11:42:40 +04:00
if len(cmds) == 0 {
return []Cmder{}, nil
2012-08-25 23:44:53 +04:00
}
2014-05-11 11:42:40 +04:00
cn, err := c.conn()
if err != nil {
2014-05-11 11:42:40 +04:00
setCmdsErr(cmds, err)
return cmds, err
}
2014-05-11 11:42:40 +04:00
if err := c.execCmds(cn, cmds); err != nil {
c.freeConn(cn, err)
return cmds, err
}
2014-05-11 11:42:40 +04:00
c.putConn(cn)
return cmds, nil
}
2014-05-11 11:42:40 +04:00
func (c *Pipeline) execCmds(cn *conn, cmds []Cmder) error {
2014-07-04 16:19:45 +04:00
if err := c.writeCmd(cn, cmds...); err != nil {
2014-05-11 11:42:40 +04:00
setCmdsErr(cmds, err)
return err
}
2014-05-11 11:42:40 +04:00
var firstCmdErr error
for _, cmd := range cmds {
if err := cmd.parseReply(cn.rd); err != nil {
if firstCmdErr == nil {
firstCmdErr = err
}
}
}
2014-05-11 11:42:40 +04:00
return firstCmdErr
}