tile38/internal/controller/keys.go

95 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"
"github.com/tidwall/tile38/internal/glob"
"github.com/tidwall/tile38/internal/server"
2016-03-05 02:08:16 +03:00
)
2017-10-05 18:20:40 +03:00
func (c *Controller) cmdKeys(msg *server.Message) (res resp.Value, err error) {
2016-03-29 01:22:30 +03:00
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 == "" {
2017-10-05 18:20:40 +03:00
return server.NOMessage, errInvalidNumberOfArguments
2016-03-05 02:08:16 +03:00
}
2016-03-29 01:22:30 +03:00
if len(vs) != 0 {
2017-10-05 18:20:40 +03:00
return server.NOMessage, 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() + "\"}")
2017-10-05 18:20:40 +03:00
return resp.StringValue(wr.String()), nil
2016-03-29 01:22:30 +03:00
}
2017-10-05 18:20:40 +03:00
return resp.ArrayValue(vals), nil
2016-03-05 02:08:16 +03:00
}