Created
July 14, 2021 15:25
-
-
Save dtest11/3cd79a422d36fd9a66d43c110437808e to your computer and use it in GitHub Desktop.
boltdb loop cursor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"log" | |
"sort" | |
"strconv" | |
"github.com/boltdb/bolt" | |
) | |
func byteToInt(b []byte) int { | |
byteToInt, _ := strconv.Atoi(string(b)) | |
return byteToInt | |
} | |
func intToByte(b int) []byte { | |
pk := strconv.Itoa(b) | |
return []byte(pk) | |
} | |
const MaxLen = 5 | |
func main() { | |
db, err := bolt.Open("my.db", 0600, nil) | |
if err != nil { | |
log.Fatal(err) | |
} | |
defer db.Close() | |
//for i := 0; i < 10; i++ { | |
// db.Update(func(tx *bolt.Tx) error { | |
// b, _ := tx.CreateBucketIfNotExists([]byte("MyBucket")) | |
// id, _ := b.NextSequence() | |
// return b.Put(intToByte(int(id)), intToByte(int(id))) | |
// }) | |
//} | |
db.Update(func(tx *bolt.Tx) error { | |
b := tx.Bucket([]byte("MyBucket")) | |
c := b.Cursor() | |
var ids []int | |
for k, _ := c.First(); k != nil; k, _ = c.Next() { | |
//fmt.Printf("current key=%s, value=%s\n", k, v) | |
ids = append(ids, byteToInt(k)) | |
} | |
if len(ids) > MaxLen { | |
sort.Ints(ids) | |
ids = ids[:len(ids)-MaxLen] | |
for _, v := range ids { | |
if err := b.Delete(intToByte(v)); err != nil { | |
panic(err) | |
} | |
//fmt.Println("delete ", intToByte(v)) | |
} | |
} | |
id, _ := b.NextSequence() | |
return b.Put(intToByte(int(id)), intToByte(int(id))) | |
}) | |
db.View(func(tx *bolt.Tx) error { | |
b := tx.Bucket([]byte("MyBucket")) | |
c := b.Cursor() | |
for k, v := c.Last(); k != nil; k, v = c.Prev() { | |
fmt.Printf("current key=%s, value=%s\n", k, v) | |
} | |
return nil | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment