84 lines
1.4 KiB
Go
84 lines
1.4 KiB
Go
package main
|
|
|
|
import (
|
|
"bufio"
|
|
"fmt"
|
|
"log"
|
|
"os"
|
|
|
|
"github.com/boltdb/bolt"
|
|
)
|
|
|
|
const usage = "bdb <(w)rite|(r)ead> <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":
|
|
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
|
|
})
|
|
}
|
|
}
|