Skip to content

Instantly share code, notes, and snippets.

@sathishweb
Last active February 2, 2021 05:33
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 sathishweb/be54a17a69c54818ab5ce46659d444d8 to your computer and use it in GitHub Desktop.
Save sathishweb/be54a17a69c54818ab5ce46659d444d8 to your computer and use it in GitHub Desktop.
// Test code to show the Badger MergeOperator merging the deleted previous value with the new added values
func add(originalValue, newValue []byte) []byte {
return append(originalValue, newValue...)
}
func main() {
opts := badger.DefaultOptions("./testdata")
db, err := badger.Open(opts)
if err != nil {
println("Error opening badger db" + err.Error())
return
}
defer db.Close()
m := db.GetMergeOperator([]byte("mykey"), add, 200*time.Millisecond)
m.Add([]byte("initial value."))
m.Add([]byte(" Additioal value."))
m.Stop()
time.Sleep(time.Second)
err = db.View(func(txn *badger.Txn) error {
item, err := txn.Get([]byte("mykey"))
if err != nil {
return err
}
item.Value(func(val []byte) error {
fmt.Printf("Value: %v\n", string(val)) //-->This prints the value "initial value. Additional value." as expected
return nil
})
return nil
})
// Delete the merged value
db.Update(func(txn *badger.Txn) error {
return txn.Delete([]byte("mykey"))
})
mnew := db.GetMergeOperator([]byte("mykey"), add, 200*time.Millisecond)
mnew.Add([]byte("new value."))
mnew.Add([]byte(" Additional new value."))
mnew.Stop()
time.Sleep(time.Second)
err = db.View(func(txn *badger.Txn) error {
item, err := txn.Get([]byte("mykey"))
if err != nil {
return err
}
item.Value(func(val []byte) error {
//-->I expect this to print only "new value. Additional new value." as the previous value is deleted.
// But, this prints "initial value. Additional value.new value. Additional new value"
fmt.Printf("Value: %v\n", string(val))
return nil
})
return nil
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment