ledisdb/server/command.go

112 lines
1.9 KiB
Go
Raw Normal View History

package server
2014-05-02 13:08:20 +04:00
2014-05-03 10:55:12 +04:00
import (
"fmt"
2014-05-20 04:41:24 +04:00
"github.com/siddontang/ledisdb/ledis"
"strconv"
2014-05-03 10:55:12 +04:00
"strings"
)
2014-05-02 13:08:20 +04:00
2014-08-25 10:18:23 +04:00
type CommandFunc func(c *client) error
2014-05-02 13:08:20 +04:00
var regCmds = map[string]CommandFunc{}
2014-05-03 10:55:12 +04:00
func register(name string, f CommandFunc) {
if _, ok := regCmds[strings.ToLower(name)]; ok {
panic(fmt.Sprintf("%s has been registered", name))
}
regCmds[name] = f
}
2014-08-25 10:18:23 +04:00
func pingCommand(c *client) error {
c.resp.writeStatus(PONG)
2014-05-03 10:55:12 +04:00
return nil
}
2014-08-25 10:18:23 +04:00
func echoCommand(c *client) error {
if len(c.args) != 1 {
2014-05-03 10:55:12 +04:00
return ErrCmdParams
}
2014-08-25 10:18:23 +04:00
c.resp.writeBulk(c.args[0])
2014-05-03 10:55:12 +04:00
return nil
}
2014-08-25 10:18:23 +04:00
func selectCommand(c *client) error {
if len(c.args) != 1 {
2014-05-20 04:41:24 +04:00
return ErrCmdParams
}
2014-08-25 10:18:23 +04:00
if index, err := strconv.Atoi(ledis.String(c.args[0])); err != nil {
2014-05-20 04:41:24 +04:00
return err
} else {
2014-09-02 13:55:12 +04:00
if c.db.IsTransaction() {
if err := c.tx.Select(index); err != nil {
return err
} else {
c.db = c.tx.DB
}
} else if c.db.IsInMulti() {
if err := c.script.Select(index); err != nil {
return err
} else {
c.db = c.script.DB
}
2014-05-20 04:41:24 +04:00
} else {
2014-09-02 13:55:12 +04:00
if db, err := c.ldb.Select(index); err != nil {
return err
} else {
c.db = db
}
2014-05-20 04:41:24 +04:00
}
2014-09-02 13:55:12 +04:00
c.resp.writeStatus(OK)
2014-05-20 04:41:24 +04:00
}
2014-08-25 10:18:23 +04:00
return nil
}
func infoCommand(c *client) error {
if len(c.args) > 1 {
return ErrSyntax
}
var section string
if len(c.args) == 1 {
section = strings.ToLower(ledis.String(c.args[0]))
}
buf := c.app.info.Dump(section)
c.resp.writeBulk(buf)
2014-05-20 04:41:24 +04:00
return nil
}
func flushallCommand(c *client) error {
err := c.ldb.FlushAll()
if err != nil {
return err
}
2014-08-25 10:18:23 +04:00
c.resp.writeStatus(OK)
return nil
}
func flushdbCommand(c *client) error {
_, err := c.db.FlushAll()
if err != nil {
return err
}
c.resp.writeStatus(OK)
return nil
}
func init() {
2014-05-03 10:55:12 +04:00
register("ping", pingCommand)
register("echo", echoCommand)
2014-05-20 04:41:24 +04:00
register("select", selectCommand)
2014-08-25 10:18:23 +04:00
register("info", infoCommand)
register("flushall", flushallCommand)
register("flushdb", flushdbCommand)
2014-05-03 10:55:12 +04:00
}