Small project for me to play around with boltdb. https://github.com/boltdb/bolt
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

90 lines
1.6 KiB

package main
import (
"bufio"
"fmt"
"log"
"os"
"github.com/boltdb/bolt"
)
const usage = "bdb <(w)rite|(r)ead|(b)uckets> <db>"
const queued = "queued"
func main() {
log.SetFlags(log.Lshortfile)
if len(os.Args) != 3 {
fmt.Fprintf(os.Stderr, "%s\n", usage)
os.Exit(1)
}
switch os.Args[1] {
case "write", "read", "w", "r", "buckets", "bkts", "b":
default:
fmt.Fprintf(os.Stderr, "%s\n", usage)
os.Exit(1)
}
db, err := bolt.Open(os.Args[2], 0600, nil)
if err != nil {
panic(err)
}
defer db.Close()
switch os.Args[1] {
case "write", "w":
err = db.Update(func(tx *bolt.Tx) error {
_, err := tx.CreateBucketIfNotExists([]byte(queued))
if err != nil {
return err
}
return nil
})
if err != nil {
panic(err)
}
err := db.Update(func(tx *bolt.Tx) error {
s := bufio.NewScanner(os.Stdin)
b := tx.Bucket([]byte(queued))
for s.Scan() {
err := b.Put(s.Bytes(), s.Bytes())
if err != nil {
return err
}
}
return s.Err()
})
if err != nil {
panic(err)
}
case "read", "r":
err = db.Update(func(tx *bolt.Tx) error {
_, err := tx.CreateBucketIfNotExists([]byte(queued))
if err != nil {
return err
}
return nil
})
if err != nil {
panic(err)
}
db.View(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte(queued))
c := b.Cursor()
for k, v := c.First(); k != nil; k, v = c.Next() {
fmt.Printf("key=%s, value=%s\n", k, v)
}
return nil
})
case "buckets", "bkts", "b":
db.View(func(tx *bolt.Tx) error {
return tx.ForEach(func(name []byte, _ *bolt.Bucket) error {
fmt.Printf("%s\n", name)
return nil
})
})
}
}