Skip to content

Instantly share code, notes, and snippets.

@shafreeck
Last active May 9, 2020 07:52
Show Gist options
  • Save shafreeck/8ff7c637171d8c0f31509c48bfe1eaa7 to your computer and use it in GitHub Desktop.
Save shafreeck/8ff7c637171d8c0f31509c48bfe1eaa7 to your computer and use it in GitHub Desktop.
// test about the reverse iter
package main
import (
"context"
"flag"
"log"
"strings"
"github.com/pingcap/tidb/kv"
"github.com/pingcap/tidb/store/mockstore"
"github.com/pingcap/tidb/store/tikv"
)
// KV pairs
type KV struct {
Key string
Value string
}
// PutKeyValues write the key values into database
func PutKeyValues(s kv.Storage) {
txn, err := s.Begin()
if err != nil {
log.Fatal(err)
}
kvs := []*KV{
{"aaa", "1"},
{"bbb", "2"},
{"ccc", "3"},
{"ddd", "4"},
{"eee", "5"},
{"fff", "6"},
}
for _, kv := range kvs {
txn.Set([]byte(kv.Key), []byte(kv.Value))
}
if err := txn.Commit(context.Background()); err != nil {
log.Fatal(err)
}
}
// Reviter iterates the key values in the reverse order
func Reviter(s kv.Storage) {
txn, err := s.Begin()
if err != nil {
log.Fatal(err)
}
iter, err := txn.IterReverse([]byte("eee"))
if err != nil {
log.Fatal(err)
}
for iter.Valid() {
log.Println(string(iter.Key()), string(iter.Value()))
iter.Next()
}
txn.Commit(context.Background())
}
func main() {
var addr string
flag.StringVar(&addr, "addr", "tikv://127.0.0.1:2379", "tikv cluster address")
flag.Parse()
var store kv.Storage
var err error
open := tikv.Driver{}.Open
if strings.HasPrefix(addr, "mocktikv://") {
open = mockstore.MockDriver{}.Open
}
store, err = open(addr)
if err != nil {
log.Fatal(err)
}
PutKeyValues(store)
Reviter(store)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment