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.

91 lines
1.6KB

  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "log"
  6. "os"
  7. "github.com/boltdb/bolt"
  8. )
  9. const usage = "bdb <(w)rite|(r)ead|(b)uckets> <db>"
  10. const queued = "queued"
  11. func main() {
  12. log.SetFlags(log.Lshortfile)
  13. if len(os.Args) != 3 {
  14. fmt.Fprintf(os.Stderr, "%s\n", usage)
  15. os.Exit(1)
  16. }
  17. switch os.Args[1] {
  18. case "write", "read", "w", "r", "buckets", "bkts", "b":
  19. default:
  20. fmt.Fprintf(os.Stderr, "%s\n", usage)
  21. os.Exit(1)
  22. }
  23. db, err := bolt.Open(os.Args[2], 0600, nil)
  24. if err != nil {
  25. panic(err)
  26. }
  27. defer db.Close()
  28. switch os.Args[1] {
  29. case "write", "w":
  30. err = db.Update(func(tx *bolt.Tx) error {
  31. _, err := tx.CreateBucketIfNotExists([]byte(queued))
  32. if err != nil {
  33. return err
  34. }
  35. return nil
  36. })
  37. if err != nil {
  38. panic(err)
  39. }
  40. err := db.Update(func(tx *bolt.Tx) error {
  41. s := bufio.NewScanner(os.Stdin)
  42. b := tx.Bucket([]byte(queued))
  43. for s.Scan() {
  44. err := b.Put(s.Bytes(), s.Bytes())
  45. if err != nil {
  46. return err
  47. }
  48. }
  49. return s.Err()
  50. })
  51. if err != nil {
  52. panic(err)
  53. }
  54. case "read", "r":
  55. err = db.Update(func(tx *bolt.Tx) error {
  56. _, err := tx.CreateBucketIfNotExists([]byte(queued))
  57. if err != nil {
  58. return err
  59. }
  60. return nil
  61. })
  62. if err != nil {
  63. panic(err)
  64. }
  65. db.View(func(tx *bolt.Tx) error {
  66. b := tx.Bucket([]byte(queued))
  67. c := b.Cursor()
  68. for k, v := c.First(); k != nil; k, v = c.Next() {
  69. fmt.Printf("key=%s, value=%s\n", k, v)
  70. }
  71. return nil
  72. })
  73. case "buckets", "bkts", "b":
  74. db.View(func(tx *bolt.Tx) error {
  75. return tx.ForEach(func(name []byte, _ *bolt.Bucket) error {
  76. fmt.Printf("%s\n", name)
  77. return nil
  78. })
  79. })
  80. }
  81. }