func ExampleTx_CopyFile() { // Open the database. db, _ := bolt.Open(tempfile(), 0666, nil) defer os.Remove(db.Path()) defer db.Close() // Create a bucket and a key. db.Update(func(tx *bolt.Tx) error { tx.CreateBucket([]byte("widgets")) tx.Bucket([]byte("widgets")).Put([]byte("foo"), []byte("bar")) return nil }) // Copy the database to another file. toFile := tempfile() db.View(func(tx *bolt.Tx) error { return tx.CopyFile(toFile, 0666) }) defer os.Remove(toFile) // Open the cloned database. db2, _ := bolt.Open(toFile, 0666, nil) defer db2.Close() // Ensure that the key exists in the copy. db2.View(func(tx *bolt.Tx) error { value := tx.Bucket([]byte("widgets")).Get([]byte("foo")) fmt.Printf("The value for 'foo' in the clone is: %s\n", value) return nil }) // Output: // The value for 'foo' in the clone is: bar }
// Run executes the command. func (cmd *InfoCommand) Run(args ...string) error { // Parse flags. fs := flag.NewFlagSet("", flag.ContinueOnError) help := fs.Bool("h", false, "") if err := fs.Parse(args); err != nil { return err } else if *help { fmt.Fprintln(cmd.Stderr, cmd.Usage()) return ErrUsage } // Require database path. path := fs.Arg(0) if path == "" { return ErrPathRequired } else if _, err := os.Stat(path); os.IsNotExist(err) { return ErrFileNotFound } // Open the database. db, err := bolt.Open(path, 0666, nil) if err != nil { return err } defer db.Close() // Print basic database info. info := db.Info() fmt.Fprintf(cmd.Stdout, "Page Size: %d\n", info.PageSize) return nil }
func newBoltDBStable(path string, logger log.Logger) (*boltDBStable, error) { fullPath := fmt.Sprintf("%s%s", path, "/raftdb") // create if the directory doesnt exist err := os.MkdirAll(path, os.FileMode(0700)) if err != nil { return nil, err } db, err := bolt.Open(fullPath, 0600, nil) if err != nil { return nil, err } stable := &boltDBStable{ db: db, keyMap: make(map[runtimeKey][]byte), logger: logger, } // init stable err = stable.init() if err != nil { stable.Close() return nil, err } return stable, nil }
func ExampleTx_Rollback() { // Open the database. db, _ := bolt.Open(tempfile(), 0666, nil) defer os.Remove(db.Path()) defer db.Close() // Create a bucket. db.Update(func(tx *bolt.Tx) error { _, err := tx.CreateBucket([]byte("widgets")) return err }) // Set a value for a key. db.Update(func(tx *bolt.Tx) error { return tx.Bucket([]byte("widgets")).Put([]byte("foo"), []byte("bar")) }) // Update the key but rollback the transaction so it never saves. tx, _ := db.Begin(true) b := tx.Bucket([]byte("widgets")) b.Put([]byte("foo"), []byte("baz")) tx.Rollback() // Ensure that our original value is still set. db.View(func(tx *bolt.Tx) error { value := tx.Bucket([]byte("widgets")).Get([]byte("foo")) fmt.Printf("The value for 'foo' is still: %s\n", value) return nil }) // Output: // The value for 'foo' is still: bar }
func ExampleDB_Batch() { // Open the database. db, _ := bolt.Open(tempfile(), 0666, nil) defer os.Remove(db.Path()) defer db.Close() // Start our web server count := counter{db} srv := httptest.NewServer(count) defer srv.Close() // Decrease the batch size to make things more interesting. db.MaxBatchSize = 3 // Get every path multiple times concurrently. const clients = 10 paths := []string{ "/foo", "/bar", "/baz", "/quux", "/thud", "/xyzzy", } errors := make(chan error, clients) for i := 0; i < clients; i++ { go func(id int) { errors <- client(id, srv.URL, paths) }(i) } // Check all responses to make sure there's no error. for i := 0; i < clients; i++ { if err := <-errors; err != nil { fmt.Printf("client error: %v", err) return } } // Check the final result db.View(func(tx *bolt.Tx) error { b := tx.Bucket([]byte("hits")) c := b.Cursor() for k, v := c.First(); k != nil; k, v = c.Next() { fmt.Printf("hits to %s: %d\n", k, decode(v)) } return nil }) // Output: // hits to /bar: 10 // hits to /baz: 10 // hits to /foo: 10 // hits to /quux: 10 // hits to /thud: 10 // hits to /xyzzy: 10 }
// Run executes the command. func (cmd *CheckCommand) Run(args ...string) error { // Parse flags. fs := flag.NewFlagSet("", flag.ContinueOnError) help := fs.Bool("h", false, "") if err := fs.Parse(args); err != nil { return err } else if *help { fmt.Fprintln(cmd.Stderr, cmd.Usage()) return ErrUsage } // Require database path. path := fs.Arg(0) if path == "" { return ErrPathRequired } else if _, err := os.Stat(path); os.IsNotExist(err) { return ErrFileNotFound } // Open database. db, err := bolt.Open(path, 0666, nil) if err != nil { return err } defer db.Close() // Perform consistency check. return db.View(func(tx *bolt.Tx) error { var count int ch := tx.Check() loop: for { select { case err, ok := <-ch: if !ok { break loop } fmt.Fprintln(cmd.Stdout, err) count++ } } // Print summary of errors. if count > 0 { fmt.Fprintf(cmd.Stdout, "%d errors found\n", count) return ErrCorrupt } // Notify user that database is valid. fmt.Fprintln(cmd.Stdout, "OK") return nil }) }
// MustOpen creates a Bolt database in a temporary location. func MustOpen(mode os.FileMode, options *bolt.Options) *DB { // Create temporary path. f, _ := ioutil.TempFile("", "bolt-") f.Close() os.Remove(f.Name()) db, err := bolt.Open(f.Name(), mode, options) if err != nil { panic(err.Error()) } return &DB{DB: db, Path: f.Name()} }
// Run executes the "bench" command. func (cmd *BenchCommand) Run(args ...string) error { // Parse CLI arguments. options, err := cmd.ParseFlags(args) if err != nil { return err } // Remove path if "-work" is not set. Otherwise keep path. if options.Work { fmt.Fprintf(cmd.Stdout, "work: %s\n", options.Path) } else { defer os.Remove(options.Path) } // Create database. db, err := bolt.Open(options.Path, 0666, nil) if err != nil { return err } db.NoSync = options.NoSync defer db.Close() // Write to the database. var results BenchResults if err := cmd.runWrites(db, options, &results); err != nil { return fmt.Errorf("write: ", err) } // Read from the database. if err := cmd.runReads(db, options, &results); err != nil { return fmt.Errorf("bench: read: %s", err) } // Print results. fmt.Fprintf(os.Stderr, "# Write\t%v\t(%v/op)\t(%v op/sec)\n", results.WriteDuration, results.WriteOpDuration(), results.WriteOpsPerSecond()) fmt.Fprintf(os.Stderr, "# Read\t%v\t(%v/op)\t(%v op/sec)\n", results.ReadDuration, results.ReadOpDuration(), results.ReadOpsPerSecond()) fmt.Fprintln(os.Stderr, "") return nil }
func ExampleCursor_reverse() { // Open the database. db, _ := bolt.Open(tempfile(), 0666, nil) defer os.Remove(db.Path()) defer db.Close() // Start a read-write transaction. db.Update(func(tx *bolt.Tx) error { // Create a new bucket. tx.CreateBucket([]byte("animals")) // Insert data into a bucket. b := tx.Bucket([]byte("animals")) b.Put([]byte("dog"), []byte("fun")) b.Put([]byte("cat"), []byte("lame")) b.Put([]byte("liger"), []byte("awesome")) // Create a cursor for iteration. c := b.Cursor() // Iterate over items in reverse sorted key order. This starts // from the last key/value pair and updates the k/v variables to // the previous key/value on each iteration. // // The loop finishes at the beginning of the cursor when a nil key // is returned. for k, v := c.Last(); k != nil; k, v = c.Prev() { fmt.Printf("A %s is %s.\n", k, v) } return nil }) // Output: // A liger is awesome. // A dog is fun. // A cat is lame. }
// Ensure that the database can be copied to a file path. func TestTx_CopyFile(t *testing.T) { db := NewTestDB() defer db.Close() var dest = tempfile() db.Update(func(tx *bolt.Tx) error { tx.CreateBucket([]byte("widgets")) tx.Bucket([]byte("widgets")).Put([]byte("foo"), []byte("bar")) tx.Bucket([]byte("widgets")).Put([]byte("baz"), []byte("bat")) return nil }) ok(t, db.View(func(tx *bolt.Tx) error { return tx.CopyFile(dest, 0600) })) db2, err := bolt.Open(dest, 0600, nil) ok(t, err) defer db2.Close() db2.View(func(tx *bolt.Tx) error { equals(t, []byte("bar"), tx.Bucket([]byte("widgets")).Get([]byte("foo"))) equals(t, []byte("bat"), tx.Bucket([]byte("widgets")).Get([]byte("baz"))) return nil }) }
// Run executes the command. func (cmd *StatsCommand) Run(args ...string) error { // Parse flags. fs := flag.NewFlagSet("", flag.ContinueOnError) help := fs.Bool("h", false, "") if err := fs.Parse(args); err != nil { return err } else if *help { fmt.Fprintln(cmd.Stderr, cmd.Usage()) return ErrUsage } // Require database path. path, prefix := fs.Arg(0), fs.Arg(1) if path == "" { return ErrPathRequired } else if _, err := os.Stat(path); os.IsNotExist(err) { return ErrFileNotFound } // Open database. db, err := bolt.Open(path, 0666, nil) if err != nil { return err } defer db.Close() return db.View(func(tx *bolt.Tx) error { var s bolt.BucketStats var count int if err := tx.ForEach(func(name []byte, b *bolt.Bucket) error { if bytes.HasPrefix(name, []byte(prefix)) { s.Add(b.Stats()) count += 1 } return nil }); err != nil { return err } fmt.Fprintf(cmd.Stdout, "Aggregate statistics for %d buckets\n\n", count) fmt.Fprintln(cmd.Stdout, "Page count statistics") fmt.Fprintf(cmd.Stdout, "\tNumber of logical branch pages: %d\n", s.BranchPageN) fmt.Fprintf(cmd.Stdout, "\tNumber of physical branch overflow pages: %d\n", s.BranchOverflowN) fmt.Fprintf(cmd.Stdout, "\tNumber of logical leaf pages: %d\n", s.LeafPageN) fmt.Fprintf(cmd.Stdout, "\tNumber of physical leaf overflow pages: %d\n", s.LeafOverflowN) fmt.Fprintln(cmd.Stdout, "Tree statistics") fmt.Fprintf(cmd.Stdout, "\tNumber of keys/value pairs: %d\n", s.KeyN) fmt.Fprintf(cmd.Stdout, "\tNumber of levels in B+tree: %d\n", s.Depth) fmt.Fprintln(cmd.Stdout, "Page size utilization") fmt.Fprintf(cmd.Stdout, "\tBytes allocated for physical branch pages: %d\n", s.BranchAlloc) var percentage int if s.BranchAlloc != 0 { percentage = int(float32(s.BranchInuse) * 100.0 / float32(s.BranchAlloc)) } fmt.Fprintf(cmd.Stdout, "\tBytes actually used for branch data: %d (%d%%)\n", s.BranchInuse, percentage) fmt.Fprintf(cmd.Stdout, "\tBytes allocated for physical leaf pages: %d\n", s.LeafAlloc) percentage = 0 if s.LeafAlloc != 0 { percentage = int(float32(s.LeafInuse) * 100.0 / float32(s.LeafAlloc)) } fmt.Fprintf(cmd.Stdout, "\tBytes actually used for leaf data: %d (%d%%)\n", s.LeafInuse, percentage) fmt.Fprintln(cmd.Stdout, "Bucket statistics") fmt.Fprintf(cmd.Stdout, "\tTotal number of buckets: %d\n", s.BucketN) percentage = int(float32(s.InlineBucketN) * 100.0 / float32(s.BucketN)) fmt.Fprintf(cmd.Stdout, "\tTotal number on inlined buckets: %d (%d%%)\n", s.InlineBucketN, percentage) percentage = 0 if s.LeafInuse != 0 { percentage = int(float32(s.InlineBucketInuse) * 100.0 / float32(s.LeafInuse)) } fmt.Fprintf(cmd.Stdout, "\tBytes used for inlined buckets: %d (%d%%)\n", s.InlineBucketInuse, percentage) return nil }) }
// Run executes the command. func (cmd *PagesCommand) Run(args ...string) error { // Parse flags. fs := flag.NewFlagSet("", flag.ContinueOnError) help := fs.Bool("h", false, "") if err := fs.Parse(args); err != nil { return err } else if *help { fmt.Fprintln(cmd.Stderr, cmd.Usage()) return ErrUsage } // Require database path. path := fs.Arg(0) if path == "" { return ErrPathRequired } else if _, err := os.Stat(path); os.IsNotExist(err) { return ErrFileNotFound } // Open database. db, err := bolt.Open(path, 0666, nil) if err != nil { return err } defer func() { _ = db.Close() }() // Write header. fmt.Fprintln(cmd.Stdout, "ID TYPE ITEMS OVRFLW") fmt.Fprintln(cmd.Stdout, "======== ========== ====== ======") return db.Update(func(tx *bolt.Tx) error { var id int for { p, err := tx.Page(id) if err != nil { return &PageError{ID: id, Err: err} } else if p == nil { break } // Only display count and overflow if this is a non-free page. var count, overflow string if p.Type != "free" { count = strconv.Itoa(p.Count) if p.OverflowCount > 0 { overflow = strconv.Itoa(p.OverflowCount) } } // Print table row. fmt.Fprintf(cmd.Stdout, "%-8d %-10s %-6s %-6s\n", p.ID, p.Type, count, overflow) // Move to the next non-overflow page. id += 1 if p.Type != "free" { id += p.OverflowCount } } return nil }) }