tile38/controller/keys.go

100 lines
2.1 KiB
Go
Raw Normal View History

2016-03-05 02:08:16 +03:00
package controller
import (
"bytes"
"strings"
"time"
2016-07-10 05:44:28 +03:00
"github.com/tidwall/btree"
2016-03-29 01:22:30 +03:00
"github.com/tidwall/resp"
2016-07-12 22:18:16 +03:00
"github.com/tidwall/tile38/controller/glob"
2016-03-29 01:22:30 +03:00
"github.com/tidwall/tile38/controller/server"
2016-03-05 02:08:16 +03:00
)
2016-03-29 01:22:30 +03:00
func (c *Controller) cmdKeys(msg *server.Message) (res string, err error) {
var start = time.Now()
vs := msg.Values[1:]
2016-03-05 02:08:16 +03:00
var pattern string
2016-03-29 01:22:30 +03:00
var ok bool
if vs, pattern, ok = tokenval(vs); !ok || pattern == "" {
return "", errInvalidNumberOfArguments
2016-03-05 02:08:16 +03:00
}
2016-03-29 01:22:30 +03:00
if len(vs) != 0 {
return "", errInvalidNumberOfArguments
2016-03-05 02:08:16 +03:00
}
2016-03-29 01:22:30 +03:00
2016-03-05 02:08:16 +03:00
var wr = &bytes.Buffer{}
var once bool
2016-03-29 01:22:30 +03:00
if msg.OutputType == server.JSON {
wr.WriteString(`{"ok":true,"keys":[`)
}
2016-03-05 02:08:16 +03:00
var everything bool
var greater bool
var greaterPivot string
2016-03-29 01:22:30 +03:00
var vals []resp.Value
2016-03-05 02:08:16 +03:00
iterator := func(item btree.Item) bool {
key := item.(*collectionT).Key
var match bool
if everything {
match = true
} else if greater {
if !strings.HasPrefix(key, greaterPivot) {
return false
}
match = true
} else {
2016-07-12 22:18:16 +03:00
match, _ = glob.Match(pattern, key)
2016-03-05 02:08:16 +03:00
}
if match {
if once {
2016-03-29 01:22:30 +03:00
if msg.OutputType == server.JSON {
wr.WriteByte(',')
}
2016-03-05 02:08:16 +03:00
} else {
once = true
}
2016-03-29 01:22:30 +03:00
switch msg.OutputType {
case server.JSON:
wr.WriteString(jsonString(key))
case server.RESP:
vals = append(vals, resp.StringValue(key))
}
2016-03-05 02:08:16 +03:00
}
return true
}
if pattern == "*" {
everything = true
c.cols.Ascend(iterator)
} else {
if strings.HasSuffix(pattern, "*") {
greaterPivot = pattern[:len(pattern)-1]
2016-07-12 22:18:16 +03:00
if glob.IsGlob(greaterPivot) {
2016-03-05 02:08:16 +03:00
greater = false
c.cols.Ascend(iterator)
} else {
greater = true
c.cols.AscendGreaterOrEqual(&collectionT{Key: greaterPivot}, iterator)
}
2016-07-12 22:18:16 +03:00
} else if glob.IsGlob(pattern) {
2016-03-05 02:08:16 +03:00
greater = false
c.cols.Ascend(iterator)
} else {
greater = true
greaterPivot = pattern
c.cols.AscendGreaterOrEqual(&collectionT{Key: greaterPivot}, iterator)
}
}
2016-03-29 01:22:30 +03:00
if msg.OutputType == server.JSON {
wr.WriteString(`],"elapsed":"` + time.Now().Sub(start).String() + "\"}")
} else {
data, err := resp.ArrayValue(vals).MarshalRESP()
if err != nil {
return "", err
}
wr.Write(data)
}
return wr.String(), nil
2016-03-05 02:08:16 +03:00
}