Skip to content

Instantly share code, notes, and snippets.

@viveksinghggits
Created July 15, 2020 09:02
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 viveksinghggits/c42fd8ae67a4e1abdf329a9011644fbc to your computer and use it in GitHub Desktop.
Save viveksinghggits/c42fd8ae67a4e1abdf329a9011644fbc to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"strconv"
"github.com/boltdb/bolt"
)
func main() {
db, err := bolt.Open("test.db", 0600, nil)
if err != nil {
fmt.Printf("Error %s\n", err.Error())
}
err = db.Update(func(tx *bolt.Tx) error {
_, err = tx.CreateBucketIfNotExists([]byte("dummy"))
return err
})
for i := 0; i < 5; i++ {
insert(db, strconv.Itoa(i), fmt.Sprintf("%s-%s", "vivek", strconv.Itoa(i)))
}
dbData := readAll(db)
resolve := someFunction(dbData)
fmt.Println("resolve that we have is ")
for k, v := range resolve {
fmt.Printf("key: %s value: %s\n", k, v)
}
for k, v := range resolve {
fmt.Printf("inserting key %s and value %s\n", k, v)
insert(db, k, string(v))
}
dbUpdated := readAll(db)
printMap(dbUpdated)
}
func printMap(a map[string][]byte) {
fmt.Println("Printing map")
for k, v := range a {
fmt.Printf("key: %s value: %s\n", k, v)
}
}
func someFunction(dbData map[string][]byte) map[string][]byte {
dbData["1"] = []byte("vivek-11")
return dbData
}
func insert(db *bolt.DB, k, v string) {
_ = db.Update(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte("dummy"))
err := b.Put([]byte(k), []byte(v))
return err
})
}
func readAll(db *bolt.DB) map[string][]byte {
lGraceP := map[string][]byte{}
db.View(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte("dummy"))
c := b.Cursor()
for k, v := c.First(); k != nil; k, v = c.Next() {
lGraceP[string(k)] = v
}
return nil
})
return lGraceP
}
@viveksinghggits
Copy link
Author

output

resolve that we have is 
key: 4 value: vivek-4
key: 0 value: vivek-0
key: 1 value: vivek-11
key: 2 value: vivek-2
key: 3 value: vivek-3
inserting key 0 and value vivek-0
inserting key 1 and value vivek-11
inserting key 2 and value 2vivek-
inserting key 3 and value 3vivek-
inserting key 4 and value 4vivek-
Printing map
key: 1 value: vivek-11
key: 2 value: 2vivek-
key: 3 value: 3vivek-
key: 4 value: 4vivek-
key: 0 value: vivek-0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment