redis/pipeline.go

97 lines
1.6 KiB
Go
Raw Normal View History

package redis
2014-05-11 11:42:40 +04:00
// Not thread-safe.
type Pipeline struct {
2015-01-24 15:12:48 +03:00
commandable
2014-05-11 11:42:40 +04:00
2015-01-24 15:12:48 +03:00
cmds []Cmder
client *baseClient
2014-05-11 11:42:40 +04:00
closed bool
}
2014-05-11 11:42:40 +04:00
func (c *Client) Pipeline() *Pipeline {
2015-01-24 15:12:48 +03:00
pipe := &Pipeline{
client: &baseClient{
opt: c.opt,
connPool: c.connPool,
},
2015-01-24 15:12:48 +03:00
cmds: make([]Cmder, 0, 10),
2012-08-17 22:36:48 +04:00
}
2015-01-24 15:12:48 +03:00
pipe.commandable.process = pipe.process
return pipe
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
}
2015-01-24 15:12:48 +03:00
func (c *Pipeline) process(cmd Cmder) {
c.cmds = append(c.cmds, cmd)
}
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
2015-01-24 15:12:48 +03:00
c.cmds = make([]Cmder, 0, 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
}
2015-01-24 15:12:48 +03:00
cn, err := c.client.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 {
2015-01-24 15:12:48 +03:00
c.client.freeConn(cn, err)
2014-05-11 11:42:40 +04:00
return cmds, err
}
2015-01-24 15:12:48 +03:00
c.client.putConn(cn)
2014-05-11 11:42:40 +04:00
return cmds, nil
}
2014-05-11 11:42:40 +04:00
func (c *Pipeline) execCmds(cn *conn, cmds []Cmder) error {
2015-01-24 15:12:48 +03:00
if err := cn.writeCmds(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
}