Skip to content

Commit

Permalink
feat(interal/client): scan
Browse files Browse the repository at this point in the history
  • Loading branch information
ken8203 committed May 11, 2023
1 parent bf84e7c commit a1b8931
Show file tree
Hide file tree
Showing 4 changed files with 57 additions and 0 deletions.
1 change: 1 addition & 0 deletions internal/client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ type Client interface {
Get(ctx context.Context, key []byte) ([]byte, error)
Delete(ctx context.Context, key []byte) error
TTL(ctx context.Context, key []byte) (uint64, error)
Scan(ctx context.Context, start []byte, limit int) ([]Entry, error)
Close(ctx context.Context) error
}

Expand Down
13 changes: 13 additions & 0 deletions internal/client/entry.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package client

type Entry struct {
K, V []byte
}

func (e Entry) Key() string {
return string(e.K)
}

func (e Entry) Value() string {
return string(e.V)
}
17 changes: 17 additions & 0 deletions internal/client/raw.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,23 @@ func (c *rawClient) TTL(ctx context.Context, key []byte) (uint64, error) {
return 0, nil
}

func (c *rawClient) Scan(ctx context.Context, start []byte, limit int) ([]Entry, error) {
keys, values, err := c.client.Scan(ctx, start, nil, limit)
if err != nil {
return nil, err
}

entries := make([]Entry, 0, len(keys))
for i, key := range keys {
entries[i] = Entry{
K: key,
V: values[i],
}
}

return entries, nil
}

func (c *rawClient) Close(ctx context.Context) error {
return c.client.Close()
}
26 changes: 26 additions & 0 deletions internal/client/txn.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,32 @@ func (c *txnClient) TTL(ctx context.Context, key []byte) (uint64, error) {
return 0, errors.New("TTL is not supported in txn mode")
}

func (c *txnClient) Scan(ctx context.Context, start []byte, limit int) ([]Entry, error) {
tx, err := c.client.Begin()
if err != nil {
return nil, err
}
defer tx.Commit(ctx)

it, err := tx.Iter(start, nil)
if err != nil {
return nil, err
}
defer it.Close()

var entries []Entry
for it.Valid() && limit > 0 {
entries = append(entries, Entry{
K: it.Key()[:],
V: it.Value()[:],
})
limit--
it.Next()
}

return entries, nil
}

func (c *txnClient) Close(ctx context.Context) error {
return c.client.Close()
}

0 comments on commit a1b8931

Please sign in to comment.