Skip to content

Instantly share code, notes, and snippets.

@armon
Created March 28, 2014 04:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save armon/9825666 to your computer and use it in GitHub Desktop.
Save armon/9825666 to your computer and use it in GitHub Desktop.
package main
import (
"encoding/binary"
"github.com/armon/gomdb"
)
func main() {
// Create the env
env, err := mdb.NewEnv()
if err != nil {
panic(err)
}
if err := env.SetMaxDBs(mdb.DBI(2)); err != nil {
panic(err)
}
// Increase the maximum map size
if err := env.SetMapSize(128 * 1024 * 1024); err != nil {
panic(err)
}
// Open the DB
if err := env.Open(".", mdb.NOTLS, 0755); err != nil {
panic(err)
}
tx, err := env.BeginTxn(nil, 0)
if err != nil {
panic(err)
}
dbi, err := tx.DBIOpen("logs", mdb.CREATE)
if err != nil {
panic(err)
}
data := make([]byte, 300)
var i uint64
for i = 1; i <= 110; i++ {
key := uint64ToBytes(i)
// Write to the table
if err := tx.Put(dbi, key, data, 0); err != nil {
panic(err)
}
}
if err := tx.Commit(); err != nil {
panic(err)
}
// Start write txn
tx, err = env.BeginTxn(nil, 0)
if err != nil {
panic(err)
}
// Open a cursor
cursor, err := tx.CursorOpen(dbi)
if err != nil {
panic(err)
}
var minIdx uint64 = 0
var maxIdx uint64 = 90
var key []byte
didDelete := false
for {
if didDelete {
key, _, err = cursor.Get(nil, mdb.GET_CURRENT)
didDelete = false
// LMDB will return EINVAL(22) for the GET_CURRENT op if
// there is no further keys. We treat this as no more
// keys being found.
if num, ok := err.(mdb.Errno); ok && num == 22 {
println("errno 22")
err = mdb.NotFound
}
} else {
key, _, err = cursor.Get(nil, mdb.NEXT)
}
if err == mdb.NotFound {
break
} else if err != nil {
panic(err)
}
// Check if the key is in the range
keyVal := bytesToUint64(key)
println(keyVal)
if keyVal < minIdx {
println("min")
println(minIdx)
continue
}
if keyVal > maxIdx {
println("max")
println(maxIdx)
break
}
// Attempt delete
if err := cursor.Del(0); err != nil {
panic(err)
}
didDelete = true
}
if err := tx.Commit(); err != nil {
panic(err)
}
}
// Converts bytes to an integer
func bytesToUint64(b []byte) uint64 {
return binary.BigEndian.Uint64(b)
}
// Converts a uint to a byte slice
func uint64ToBytes(u uint64) []byte {
buf := make([]byte, 8)
binary.BigEndian.PutUint64(buf, u)
return buf
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment