Skip to content

Instantly share code, notes, and snippets.

@maddie
Last active September 2, 2020 09:12
Show Gist options
  • Save maddie/fecf3f33a132e4769e910b6a7093541d to your computer and use it in GitHub Desktop.
Save maddie/fecf3f33a132e4769e910b6a7093541d to your computer and use it in GitHub Desktop.
Migrate BadgerDB v1 to BadgerDB v2 programatically
package main
import (
"flag"
"log"
bv1 "github.com/dgraph-io/badger"
bv2 "github.com/dgraph-io/badger/v2"
)
var (
oldDir = flag.String("i", "", "input database (v1)")
newDir = flag.String("o", "", "output database (v2)")
)
// usage: go run main.go -i "v1 db path" -o "v2 db path"
func main() {
flag.Parse()
if *oldDir == "" {
log.Fatal("old database (v1) path cannot be empty")
}
if *newDir == "" {
log.Fatal("new database (v2) path cannot be empty")
}
v1opts := bv1.DefaultOptions(*oldDir)
odb, err := bv1.Open(v1opts)
if err != nil {
log.Fatal(err)
}
defer odb.Close()
v2opts := bv2.DefaultOptions(*newDir)
ndb, err := bv2.Open(v2opts)
if err != nil {
log.Fatal(err)
}
defer ndb.Close()
if err := ndb.Update(func(utxn *bv2.Txn) error {
return odb.View(func(vtxn *bv1.Txn) error {
it := vtxn.NewIterator(bv1.DefaultIteratorOptions)
defer it.Close()
if it.Rewind(); it.Valid() {
if err := it.Item().Value(func(val []byte) error {
return utxn.Set(it.Item().Key(), val)
}); err != nil {
return err
}
}
for {
if it.Next(); it.Valid() {
if err := it.Item().Value(func(val []byte) error {
return utxn.Set(it.Item().Key(), val)
}); err != nil {
return err
}
} else {
break
}
}
return nil
})
}); err != nil {
log.Fatal(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment