Showing preview only (359K chars total). Download the full file or copy to clipboard to get everything.
Repository: boltdb/bolt
Branch: master
Commit: fd01fc79c553
Files: 39
Total size: 345.0 KB
Directory structure:
gitextract_kz6jb5aj/
├── .gitignore
├── LICENSE
├── Makefile
├── README.md
├── appveyor.yml
├── bolt_386.go
├── bolt_amd64.go
├── bolt_arm.go
├── bolt_arm64.go
├── bolt_linux.go
├── bolt_openbsd.go
├── bolt_ppc.go
├── bolt_ppc64.go
├── bolt_ppc64le.go
├── bolt_s390x.go
├── bolt_unix.go
├── bolt_unix_solaris.go
├── bolt_windows.go
├── boltsync_unix.go
├── bucket.go
├── bucket_test.go
├── cmd/
│ └── bolt/
│ ├── main.go
│ └── main_test.go
├── cursor.go
├── cursor_test.go
├── db.go
├── db_test.go
├── doc.go
├── errors.go
├── freelist.go
├── freelist_test.go
├── node.go
├── node_test.go
├── page.go
├── page_test.go
├── quick_test.go
├── simulation_test.go
├── tx.go
└── tx_test.go
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
*.prof
*.test
*.swp
/bin/
================================================
FILE: LICENSE
================================================
The MIT License (MIT)
Copyright (c) 2013 Ben Johnson
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
================================================
FILE: Makefile
================================================
BRANCH=`git rev-parse --abbrev-ref HEAD`
COMMIT=`git rev-parse --short HEAD`
GOLDFLAGS="-X main.branch $(BRANCH) -X main.commit $(COMMIT)"
default: build
race:
@go test -v -race -test.run="TestSimulate_(100op|1000op)"
# go get github.com/kisielk/errcheck
errcheck:
@errcheck -ignorepkg=bytes -ignore=os:Remove github.com/boltdb/bolt
test:
@go test -v -cover .
@go test -v ./cmd/bolt
.PHONY: fmt test
================================================
FILE: README.md
================================================
Bolt [](https://coveralls.io/r/boltdb/bolt?branch=master) [](https://godoc.org/github.com/boltdb/bolt) 
====
Bolt is a pure Go key/value store inspired by [Howard Chu's][hyc_symas]
[LMDB project][lmdb]. The goal of the project is to provide a simple,
fast, and reliable database for projects that don't require a full database
server such as Postgres or MySQL.
Since Bolt is meant to be used as such a low-level piece of functionality,
simplicity is key. The API will be small and only focus on getting values
and setting values. That's it.
[hyc_symas]: https://twitter.com/hyc_symas
[lmdb]: http://symas.com/mdb/
## Project Status
Bolt is stable, the API is fixed, and the file format is fixed. Full unit
test coverage and randomized black box testing are used to ensure database
consistency and thread safety. Bolt is currently used in high-load production
environments serving databases as large as 1TB. Many companies such as
Shopify and Heroku use Bolt-backed services every day.
## A message from the author
> The original goal of Bolt was to provide a simple pure Go key/value store and to
> not bloat the code with extraneous features. To that end, the project has been
> a success. However, this limited scope also means that the project is complete.
>
> Maintaining an open source database requires an immense amount of time and energy.
> Changes to the code can have unintended and sometimes catastrophic effects so
> even simple changes require hours and hours of careful testing and validation.
>
> Unfortunately I no longer have the time or energy to continue this work. Bolt is
> in a stable state and has years of successful production use. As such, I feel that
> leaving it in its current state is the most prudent course of action.
>
> If you are interested in using a more featureful version of Bolt, I suggest that
> you look at the CoreOS fork called [bbolt](https://github.com/coreos/bbolt).
- Ben Johnson ([@benbjohnson](https://twitter.com/benbjohnson))
## Table of Contents
- [Getting Started](#getting-started)
- [Installing](#installing)
- [Opening a database](#opening-a-database)
- [Transactions](#transactions)
- [Read-write transactions](#read-write-transactions)
- [Read-only transactions](#read-only-transactions)
- [Batch read-write transactions](#batch-read-write-transactions)
- [Managing transactions manually](#managing-transactions-manually)
- [Using buckets](#using-buckets)
- [Using key/value pairs](#using-keyvalue-pairs)
- [Autoincrementing integer for the bucket](#autoincrementing-integer-for-the-bucket)
- [Iterating over keys](#iterating-over-keys)
- [Prefix scans](#prefix-scans)
- [Range scans](#range-scans)
- [ForEach()](#foreach)
- [Nested buckets](#nested-buckets)
- [Database backups](#database-backups)
- [Statistics](#statistics)
- [Read-Only Mode](#read-only-mode)
- [Mobile Use (iOS/Android)](#mobile-use-iosandroid)
- [Resources](#resources)
- [Comparison with other databases](#comparison-with-other-databases)
- [Postgres, MySQL, & other relational databases](#postgres-mysql--other-relational-databases)
- [LevelDB, RocksDB](#leveldb-rocksdb)
- [LMDB](#lmdb)
- [Caveats & Limitations](#caveats--limitations)
- [Reading the Source](#reading-the-source)
- [Other Projects Using Bolt](#other-projects-using-bolt)
## Getting Started
### Installing
To start using Bolt, install Go and run `go get`:
```sh
$ go get github.com/boltdb/bolt/...
```
This will retrieve the library and install the `bolt` command line utility into
your `$GOBIN` path.
### Opening a database
The top-level object in Bolt is a `DB`. It is represented as a single file on
your disk and represents a consistent snapshot of your data.
To open your database, simply use the `bolt.Open()` function:
```go
package main
import (
"log"
"github.com/boltdb/bolt"
)
func main() {
// Open the my.db data file in your current directory.
// It will be created if it doesn't exist.
db, err := bolt.Open("my.db", 0600, nil)
if err != nil {
log.Fatal(err)
}
defer db.Close()
...
}
```
Please note that Bolt obtains a file lock on the data file so multiple processes
cannot open the same database at the same time. Opening an already open Bolt
database will cause it to hang until the other process closes it. To prevent
an indefinite wait you can pass a timeout option to the `Open()` function:
```go
db, err := bolt.Open("my.db", 0600, &bolt.Options{Timeout: 1 * time.Second})
```
### Transactions
Bolt allows only one read-write transaction at a time but allows as many
read-only transactions as you want at a time. Each transaction has a consistent
view of the data as it existed when the transaction started.
Individual transactions and all objects created from them (e.g. buckets, keys)
are not thread safe. To work with data in multiple goroutines you must start
a transaction for each one or use locking to ensure only one goroutine accesses
a transaction at a time. Creating transaction from the `DB` is thread safe.
Read-only transactions and read-write transactions should not depend on one
another and generally shouldn't be opened simultaneously in the same goroutine.
This can cause a deadlock as the read-write transaction needs to periodically
re-map the data file but it cannot do so while a read-only transaction is open.
#### Read-write transactions
To start a read-write transaction, you can use the `DB.Update()` function:
```go
err := db.Update(func(tx *bolt.Tx) error {
...
return nil
})
```
Inside the closure, you have a consistent view of the database. You commit the
transaction by returning `nil` at the end. You can also rollback the transaction
at any point by returning an error. All database operations are allowed inside
a read-write transaction.
Always check the return error as it will report any disk failures that can cause
your transaction to not complete. If you return an error within your closure
it will be passed through.
#### Read-only transactions
To start a read-only transaction, you can use the `DB.View()` function:
```go
err := db.View(func(tx *bolt.Tx) error {
...
return nil
})
```
You also get a consistent view of the database within this closure, however,
no mutating operations are allowed within a read-only transaction. You can only
retrieve buckets, retrieve values, and copy the database within a read-only
transaction.
#### Batch read-write transactions
Each `DB.Update()` waits for disk to commit the writes. This overhead
can be minimized by combining multiple updates with the `DB.Batch()`
function:
```go
err := db.Batch(func(tx *bolt.Tx) error {
...
return nil
})
```
Concurrent Batch calls are opportunistically combined into larger
transactions. Batch is only useful when there are multiple goroutines
calling it.
The trade-off is that `Batch` can call the given
function multiple times, if parts of the transaction fail. The
function must be idempotent and side effects must take effect only
after a successful return from `DB.Batch()`.
For example: don't display messages from inside the function, instead
set variables in the enclosing scope:
```go
var id uint64
err := db.Batch(func(tx *bolt.Tx) error {
// Find last key in bucket, decode as bigendian uint64, increment
// by one, encode back to []byte, and add new key.
...
id = newValue
return nil
})
if err != nil {
return ...
}
fmt.Println("Allocated ID %d", id)
```
#### Managing transactions manually
The `DB.View()` and `DB.Update()` functions are wrappers around the `DB.Begin()`
function. These helper functions will start the transaction, execute a function,
and then safely close your transaction if an error is returned. This is the
recommended way to use Bolt transactions.
However, sometimes you may want to manually start and end your transactions.
You can use the `DB.Begin()` function directly but **please** be sure to close
the transaction.
```go
// Start a writable transaction.
tx, err := db.Begin(true)
if err != nil {
return err
}
defer tx.Rollback()
// Use the transaction...
_, err := tx.CreateBucket([]byte("MyBucket"))
if err != nil {
return err
}
// Commit the transaction and check for error.
if err := tx.Commit(); err != nil {
return err
}
```
The first argument to `DB.Begin()` is a boolean stating if the transaction
should be writable.
### Using buckets
Buckets are collections of key/value pairs within the database. All keys in a
bucket must be unique. You can create a bucket using the `DB.CreateBucket()`
function:
```go
db.Update(func(tx *bolt.Tx) error {
b, err := tx.CreateBucket([]byte("MyBucket"))
if err != nil {
return fmt.Errorf("create bucket: %s", err)
}
return nil
})
```
You can also create a bucket only if it doesn't exist by using the
`Tx.CreateBucketIfNotExists()` function. It's a common pattern to call this
function for all your top-level buckets after you open your database so you can
guarantee that they exist for future transactions.
To delete a bucket, simply call the `Tx.DeleteBucket()` function.
### Using key/value pairs
To save a key/value pair to a bucket, use the `Bucket.Put()` function:
```go
db.Update(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte("MyBucket"))
err := b.Put([]byte("answer"), []byte("42"))
return err
})
```
This will set the value of the `"answer"` key to `"42"` in the `MyBucket`
bucket. To retrieve this value, we can use the `Bucket.Get()` function:
```go
db.View(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte("MyBucket"))
v := b.Get([]byte("answer"))
fmt.Printf("The answer is: %s\n", v)
return nil
})
```
The `Get()` function does not return an error because its operation is
guaranteed to work (unless there is some kind of system failure). If the key
exists then it will return its byte slice value. If it doesn't exist then it
will return `nil`. It's important to note that you can have a zero-length value
set to a key which is different than the key not existing.
Use the `Bucket.Delete()` function to delete a key from the bucket.
Please note that values returned from `Get()` are only valid while the
transaction is open. If you need to use a value outside of the transaction
then you must use `copy()` to copy it to another byte slice.
### Autoincrementing integer for the bucket
By using the `NextSequence()` function, you can let Bolt determine a sequence
which can be used as the unique identifier for your key/value pairs. See the
example below.
```go
// CreateUser saves u to the store. The new user ID is set on u once the data is persisted.
func (s *Store) CreateUser(u *User) error {
return s.db.Update(func(tx *bolt.Tx) error {
// Retrieve the users bucket.
// This should be created when the DB is first opened.
b := tx.Bucket([]byte("users"))
// Generate ID for the user.
// This returns an error only if the Tx is closed or not writeable.
// That can't happen in an Update() call so I ignore the error check.
id, _ := b.NextSequence()
u.ID = int(id)
// Marshal user data into bytes.
buf, err := json.Marshal(u)
if err != nil {
return err
}
// Persist bytes to users bucket.
return b.Put(itob(u.ID), buf)
})
}
// itob returns an 8-byte big endian representation of v.
func itob(v int) []byte {
b := make([]byte, 8)
binary.BigEndian.PutUint64(b, uint64(v))
return b
}
type User struct {
ID int
...
}
```
### Iterating over keys
Bolt stores its keys in byte-sorted order within a bucket. This makes sequential
iteration over these keys extremely fast. To iterate over keys we'll use a
`Cursor`:
```go
db.View(func(tx *bolt.Tx) error {
// Assume bucket exists and has keys
b := tx.Bucket([]byte("MyBucket"))
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
})
```
The cursor allows you to move to a specific point in the list of keys and move
forward or backward through the keys one at a time.
The following functions are available on the cursor:
```
First() Move to the first key.
Last() Move to the last key.
Seek() Move to a specific key.
Next() Move to the next key.
Prev() Move to the previous key.
```
Each of those functions has a return signature of `(key []byte, value []byte)`.
When you have iterated to the end of the cursor then `Next()` will return a
`nil` key. You must seek to a position using `First()`, `Last()`, or `Seek()`
before calling `Next()` or `Prev()`. If you do not seek to a position then
these functions will return a `nil` key.
During iteration, if the key is non-`nil` but the value is `nil`, that means
the key refers to a bucket rather than a value. Use `Bucket.Bucket()` to
access the sub-bucket.
#### Prefix scans
To iterate over a key prefix, you can combine `Seek()` and `bytes.HasPrefix()`:
```go
db.View(func(tx *bolt.Tx) error {
// Assume bucket exists and has keys
c := tx.Bucket([]byte("MyBucket")).Cursor()
prefix := []byte("1234")
for k, v := c.Seek(prefix); k != nil && bytes.HasPrefix(k, prefix); k, v = c.Next() {
fmt.Printf("key=%s, value=%s\n", k, v)
}
return nil
})
```
#### Range scans
Another common use case is scanning over a range such as a time range. If you
use a sortable time encoding such as RFC3339 then you can query a specific
date range like this:
```go
db.View(func(tx *bolt.Tx) error {
// Assume our events bucket exists and has RFC3339 encoded time keys.
c := tx.Bucket([]byte("Events")).Cursor()
// Our time range spans the 90's decade.
min := []byte("1990-01-01T00:00:00Z")
max := []byte("2000-01-01T00:00:00Z")
// Iterate over the 90's.
for k, v := c.Seek(min); k != nil && bytes.Compare(k, max) <= 0; k, v = c.Next() {
fmt.Printf("%s: %s\n", k, v)
}
return nil
})
```
Note that, while RFC3339 is sortable, the Golang implementation of RFC3339Nano does not use a fixed number of digits after the decimal point and is therefore not sortable.
#### ForEach()
You can also use the function `ForEach()` if you know you'll be iterating over
all the keys in a bucket:
```go
db.View(func(tx *bolt.Tx) error {
// Assume bucket exists and has keys
b := tx.Bucket([]byte("MyBucket"))
b.ForEach(func(k, v []byte) error {
fmt.Printf("key=%s, value=%s\n", k, v)
return nil
})
return nil
})
```
Please note that keys and values in `ForEach()` are only valid while
the transaction is open. If you need to use a key or value outside of
the transaction, you must use `copy()` to copy it to another byte
slice.
### Nested buckets
You can also store a bucket in a key to create nested buckets. The API is the
same as the bucket management API on the `DB` object:
```go
func (*Bucket) CreateBucket(key []byte) (*Bucket, error)
func (*Bucket) CreateBucketIfNotExists(key []byte) (*Bucket, error)
func (*Bucket) DeleteBucket(key []byte) error
```
Say you had a multi-tenant application where the root level bucket was the account bucket. Inside of this bucket was a sequence of accounts which themselves are buckets. And inside the sequence bucket you could have many buckets pertaining to the Account itself (Users, Notes, etc) isolating the information into logical groupings.
```go
// createUser creates a new user in the given account.
func createUser(accountID int, u *User) error {
// Start the transaction.
tx, err := db.Begin(true)
if err != nil {
return err
}
defer tx.Rollback()
// Retrieve the root bucket for the account.
// Assume this has already been created when the account was set up.
root := tx.Bucket([]byte(strconv.FormatUint(accountID, 10)))
// Setup the users bucket.
bkt, err := root.CreateBucketIfNotExists([]byte("USERS"))
if err != nil {
return err
}
// Generate an ID for the new user.
userID, err := bkt.NextSequence()
if err != nil {
return err
}
u.ID = userID
// Marshal and save the encoded user.
if buf, err := json.Marshal(u); err != nil {
return err
} else if err := bkt.Put([]byte(strconv.FormatUint(u.ID, 10)), buf); err != nil {
return err
}
// Commit the transaction.
if err := tx.Commit(); err != nil {
return err
}
return nil
}
```
### Database backups
Bolt is a single file so it's easy to backup. You can use the `Tx.WriteTo()`
function to write a consistent view of the database to a writer. If you call
this from a read-only transaction, it will perform a hot backup and not block
your other database reads and writes.
By default, it will use a regular file handle which will utilize the operating
system's page cache. See the [`Tx`](https://godoc.org/github.com/boltdb/bolt#Tx)
documentation for information about optimizing for larger-than-RAM datasets.
One common use case is to backup over HTTP so you can use tools like `cURL` to
do database backups:
```go
func BackupHandleFunc(w http.ResponseWriter, req *http.Request) {
err := db.View(func(tx *bolt.Tx) error {
w.Header().Set("Content-Type", "application/octet-stream")
w.Header().Set("Content-Disposition", `attachment; filename="my.db"`)
w.Header().Set("Content-Length", strconv.Itoa(int(tx.Size())))
_, err := tx.WriteTo(w)
return err
})
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
```
Then you can backup using this command:
```sh
$ curl http://localhost/backup > my.db
```
Or you can open your browser to `http://localhost/backup` and it will download
automatically.
If you want to backup to another file you can use the `Tx.CopyFile()` helper
function.
### Statistics
The database keeps a running count of many of the internal operations it
performs so you can better understand what's going on. By grabbing a snapshot
of these stats at two points in time we can see what operations were performed
in that time range.
For example, we could start a goroutine to log stats every 10 seconds:
```go
go func() {
// Grab the initial stats.
prev := db.Stats()
for {
// Wait for 10s.
time.Sleep(10 * time.Second)
// Grab the current stats and diff them.
stats := db.Stats()
diff := stats.Sub(&prev)
// Encode stats to JSON and print to STDERR.
json.NewEncoder(os.Stderr).Encode(diff)
// Save stats for the next loop.
prev = stats
}
}()
```
It's also useful to pipe these stats to a service such as statsd for monitoring
or to provide an HTTP endpoint that will perform a fixed-length sample.
### Read-Only Mode
Sometimes it is useful to create a shared, read-only Bolt database. To this,
set the `Options.ReadOnly` flag when opening your database. Read-only mode
uses a shared lock to allow multiple processes to read from the database but
it will block any processes from opening the database in read-write mode.
```go
db, err := bolt.Open("my.db", 0666, &bolt.Options{ReadOnly: true})
if err != nil {
log.Fatal(err)
}
```
### Mobile Use (iOS/Android)
Bolt is able to run on mobile devices by leveraging the binding feature of the
[gomobile](https://github.com/golang/mobile) tool. Create a struct that will
contain your database logic and a reference to a `*bolt.DB` with a initializing
constructor that takes in a filepath where the database file will be stored.
Neither Android nor iOS require extra permissions or cleanup from using this method.
```go
func NewBoltDB(filepath string) *BoltDB {
db, err := bolt.Open(filepath+"/demo.db", 0600, nil)
if err != nil {
log.Fatal(err)
}
return &BoltDB{db}
}
type BoltDB struct {
db *bolt.DB
...
}
func (b *BoltDB) Path() string {
return b.db.Path()
}
func (b *BoltDB) Close() {
b.db.Close()
}
```
Database logic should be defined as methods on this wrapper struct.
To initialize this struct from the native language (both platforms now sync
their local storage to the cloud. These snippets disable that functionality for the
database file):
#### Android
```java
String path;
if (android.os.Build.VERSION.SDK_INT >=android.os.Build.VERSION_CODES.LOLLIPOP){
path = getNoBackupFilesDir().getAbsolutePath();
} else{
path = getFilesDir().getAbsolutePath();
}
Boltmobiledemo.BoltDB boltDB = Boltmobiledemo.NewBoltDB(path)
```
#### iOS
```objc
- (void)demo {
NSString* path = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,
NSUserDomainMask,
YES) objectAtIndex:0];
GoBoltmobiledemoBoltDB * demo = GoBoltmobiledemoNewBoltDB(path);
[self addSkipBackupAttributeToItemAtPath:demo.path];
//Some DB Logic would go here
[demo close];
}
- (BOOL)addSkipBackupAttributeToItemAtPath:(NSString *) filePathString
{
NSURL* URL= [NSURL fileURLWithPath: filePathString];
assert([[NSFileManager defaultManager] fileExistsAtPath: [URL path]]);
NSError *error = nil;
BOOL success = [URL setResourceValue: [NSNumber numberWithBool: YES]
forKey: NSURLIsExcludedFromBackupKey error: &error];
if(!success){
NSLog(@"Error excluding %@ from backup %@", [URL lastPathComponent], error);
}
return success;
}
```
## Resources
For more information on getting started with Bolt, check out the following articles:
* [Intro to BoltDB: Painless Performant Persistence](http://npf.io/2014/07/intro-to-boltdb-painless-performant-persistence/) by [Nate Finch](https://github.com/natefinch).
* [Bolt -- an embedded key/value database for Go](https://www.progville.com/go/bolt-embedded-db-golang/) by Progville
## Comparison with other databases
### Postgres, MySQL, & other relational databases
Relational databases structure data into rows and are only accessible through
the use of SQL. This approach provides flexibility in how you store and query
your data but also incurs overhead in parsing and planning SQL statements. Bolt
accesses all data by a byte slice key. This makes Bolt fast to read and write
data by key but provides no built-in support for joining values together.
Most relational databases (with the exception of SQLite) are standalone servers
that run separately from your application. This gives your systems
flexibility to connect multiple application servers to a single database
server but also adds overhead in serializing and transporting data over the
network. Bolt runs as a library included in your application so all data access
has to go through your application's process. This brings data closer to your
application but limits multi-process access to the data.
### LevelDB, RocksDB
LevelDB and its derivatives (RocksDB, HyperLevelDB) are similar to Bolt in that
they are libraries bundled into the application, however, their underlying
structure is a log-structured merge-tree (LSM tree). An LSM tree optimizes
random writes by using a write ahead log and multi-tiered, sorted files called
SSTables. Bolt uses a B+tree internally and only a single file. Both approaches
have trade-offs.
If you require a high random write throughput (>10,000 w/sec) or you need to use
spinning disks then LevelDB could be a good choice. If your application is
read-heavy or does a lot of range scans then Bolt could be a good choice.
One other important consideration is that LevelDB does not have transactions.
It supports batch writing of key/values pairs and it supports read snapshots
but it will not give you the ability to do a compare-and-swap operation safely.
Bolt supports fully serializable ACID transactions.
### LMDB
Bolt was originally a port of LMDB so it is architecturally similar. Both use
a B+tree, have ACID semantics with fully serializable transactions, and support
lock-free MVCC using a single writer and multiple readers.
The two projects have somewhat diverged. LMDB heavily focuses on raw performance
while Bolt has focused on simplicity and ease of use. For example, LMDB allows
several unsafe actions such as direct writes for the sake of performance. Bolt
opts to disallow actions which can leave the database in a corrupted state. The
only exception to this in Bolt is `DB.NoSync`.
There are also a few differences in API. LMDB requires a maximum mmap size when
opening an `mdb_env` whereas Bolt will handle incremental mmap resizing
automatically. LMDB overloads the getter and setter functions with multiple
flags whereas Bolt splits these specialized cases into their own functions.
## Caveats & Limitations
It's important to pick the right tool for the job and Bolt is no exception.
Here are a few things to note when evaluating and using Bolt:
* Bolt is good for read intensive workloads. Sequential write performance is
also fast but random writes can be slow. You can use `DB.Batch()` or add a
write-ahead log to help mitigate this issue.
* Bolt uses a B+tree internally so there can be a lot of random page access.
SSDs provide a significant performance boost over spinning disks.
* Try to avoid long running read transactions. Bolt uses copy-on-write so
old pages cannot be reclaimed while an old transaction is using them.
* Byte slices returned from Bolt are only valid during a transaction. Once the
transaction has been committed or rolled back then the memory they point to
can be reused by a new page or can be unmapped from virtual memory and you'll
see an `unexpected fault address` panic when accessing it.
* Bolt uses an exclusive write lock on the database file so it cannot be
shared by multiple processes.
* Be careful when using `Bucket.FillPercent`. Setting a high fill percent for
buckets that have random inserts will cause your database to have very poor
page utilization.
* Use larger buckets in general. Smaller buckets causes poor page utilization
once they become larger than the page size (typically 4KB).
* Bulk loading a lot of random writes into a new bucket can be slow as the
page will not split until the transaction is committed. Randomly inserting
more than 100,000 key/value pairs into a single new bucket in a single
transaction is not advised.
* Bolt uses a memory-mapped file so the underlying operating system handles the
caching of the data. Typically, the OS will cache as much of the file as it
can in memory and will release memory as needed to other processes. This means
that Bolt can show very high memory usage when working with large databases.
However, this is expected and the OS will release memory as needed. Bolt can
handle databases much larger than the available physical RAM, provided its
memory-map fits in the process virtual address space. It may be problematic
on 32-bits systems.
* The data structures in the Bolt database are memory mapped so the data file
will be endian specific. This means that you cannot copy a Bolt file from a
little endian machine to a big endian machine and have it work. For most
users this is not a concern since most modern CPUs are little endian.
* Because of the way pages are laid out on disk, Bolt cannot truncate data files
and return free pages back to the disk. Instead, Bolt maintains a free list
of unused pages within its data file. These free pages can be reused by later
transactions. This works well for many use cases as databases generally tend
to grow. However, it's important to note that deleting large chunks of data
will not allow you to reclaim that space on disk.
For more information on page allocation, [see this comment][page-allocation].
[page-allocation]: https://github.com/boltdb/bolt/issues/308#issuecomment-74811638
## Reading the Source
Bolt is a relatively small code base (<3KLOC) for an embedded, serializable,
transactional key/value database so it can be a good starting point for people
interested in how databases work.
The best places to start are the main entry points into Bolt:
- `Open()` - Initializes the reference to the database. It's responsible for
creating the database if it doesn't exist, obtaining an exclusive lock on the
file, reading the meta pages, & memory-mapping the file.
- `DB.Begin()` - Starts a read-only or read-write transaction depending on the
value of the `writable` argument. This requires briefly obtaining the "meta"
lock to keep track of open transactions. Only one read-write transaction can
exist at a time so the "rwlock" is acquired during the life of a read-write
transaction.
- `Bucket.Put()` - Writes a key/value pair into a bucket. After validating the
arguments, a cursor is used to traverse the B+tree to the page and position
where they key & value will be written. Once the position is found, the bucket
materializes the underlying page and the page's parent pages into memory as
"nodes". These nodes are where mutations occur during read-write transactions.
These changes get flushed to disk during commit.
- `Bucket.Get()` - Retrieves a key/value pair from a bucket. This uses a cursor
to move to the page & position of a key/value pair. During a read-only
transaction, the key and value data is returned as a direct reference to the
underlying mmap file so there's no allocation overhead. For read-write
transactions, this data may reference the mmap file or one of the in-memory
node values.
- `Cursor` - This object is simply for traversing the B+tree of on-disk pages
or in-memory nodes. It can seek to a specific key, move to the first or last
value, or it can move forward or backward. The cursor handles the movement up
and down the B+tree transparently to the end user.
- `Tx.Commit()` - Converts the in-memory dirty nodes and the list of free pages
into pages to be written to disk. Writing to disk then occurs in two phases.
First, the dirty pages are written to disk and an `fsync()` occurs. Second, a
new meta page with an incremented transaction ID is written and another
`fsync()` occurs. This two phase write ensures that partially written data
pages are ignored in the event of a crash since the meta page pointing to them
is never written. Partially written meta pages are invalidated because they
are written with a checksum.
If you have additional notes that could be helpful for others, please submit
them via pull request.
## Other Projects Using Bolt
Below is a list of public, open source projects that use Bolt:
* [BoltDbWeb](https://github.com/evnix/boltdbweb) - A web based GUI for BoltDB files.
* [Operation Go: A Routine Mission](http://gocode.io) - An online programming game for Golang using Bolt for user accounts and a leaderboard.
* [Bazil](https://bazil.org/) - A file system that lets your data reside where it is most convenient for it to reside.
* [DVID](https://github.com/janelia-flyem/dvid) - Added Bolt as optional storage engine and testing it against Basho-tuned leveldb.
* [Skybox Analytics](https://github.com/skybox/skybox) - A standalone funnel analysis tool for web analytics.
* [Scuttlebutt](https://github.com/benbjohnson/scuttlebutt) - Uses Bolt to store and process all Twitter mentions of GitHub projects.
* [Wiki](https://github.com/peterhellberg/wiki) - A tiny wiki using Goji, BoltDB and Blackfriday.
* [ChainStore](https://github.com/pressly/chainstore) - Simple key-value interface to a variety of storage engines organized as a chain of operations.
* [MetricBase](https://github.com/msiebuhr/MetricBase) - Single-binary version of Graphite.
* [Gitchain](https://github.com/gitchain/gitchain) - Decentralized, peer-to-peer Git repositories aka "Git meets Bitcoin".
* [event-shuttle](https://github.com/sclasen/event-shuttle) - A Unix system service to collect and reliably deliver messages to Kafka.
* [ipxed](https://github.com/kelseyhightower/ipxed) - Web interface and api for ipxed.
* [BoltStore](https://github.com/yosssi/boltstore) - Session store using Bolt.
* [photosite/session](https://godoc.org/bitbucket.org/kardianos/photosite/session) - Sessions for a photo viewing site.
* [LedisDB](https://github.com/siddontang/ledisdb) - A high performance NoSQL, using Bolt as optional storage.
* [ipLocator](https://github.com/AndreasBriese/ipLocator) - A fast ip-geo-location-server using bolt with bloom filters.
* [cayley](https://github.com/google/cayley) - Cayley is an open-source graph database using Bolt as optional backend.
* [bleve](http://www.blevesearch.com/) - A pure Go search engine similar to ElasticSearch that uses Bolt as the default storage backend.
* [tentacool](https://github.com/optiflows/tentacool) - REST api server to manage system stuff (IP, DNS, Gateway...) on a linux server.
* [Seaweed File System](https://github.com/chrislusf/seaweedfs) - Highly scalable distributed key~file system with O(1) disk read.
* [InfluxDB](https://influxdata.com) - Scalable datastore for metrics, events, and real-time analytics.
* [Freehold](http://tshannon.bitbucket.org/freehold/) - An open, secure, and lightweight platform for your files and data.
* [Prometheus Annotation Server](https://github.com/oliver006/prom_annotation_server) - Annotation server for PromDash & Prometheus service monitoring system.
* [Consul](https://github.com/hashicorp/consul) - Consul is service discovery and configuration made easy. Distributed, highly available, and datacenter-aware.
* [Kala](https://github.com/ajvb/kala) - Kala is a modern job scheduler optimized to run on a single node. It is persistent, JSON over HTTP API, ISO 8601 duration notation, and dependent jobs.
* [drive](https://github.com/odeke-em/drive) - drive is an unofficial Google Drive command line client for \*NIX operating systems.
* [stow](https://github.com/djherbis/stow) - a persistence manager for objects
backed by boltdb.
* [buckets](https://github.com/joyrexus/buckets) - a bolt wrapper streamlining
simple tx and key scans.
* [mbuckets](https://github.com/abhigupta912/mbuckets) - A Bolt wrapper that allows easy operations on multi level (nested) buckets.
* [Request Baskets](https://github.com/darklynx/request-baskets) - A web service to collect arbitrary HTTP requests and inspect them via REST API or simple web UI, similar to [RequestBin](http://requestb.in/) service
* [Go Report Card](https://goreportcard.com/) - Go code quality report cards as a (free and open source) service.
* [Boltdb Boilerplate](https://github.com/bobintornado/boltdb-boilerplate) - Boilerplate wrapper around bolt aiming to make simple calls one-liners.
* [lru](https://github.com/crowdriff/lru) - Easy to use Bolt-backed Least-Recently-Used (LRU) read-through cache with chainable remote stores.
* [Storm](https://github.com/asdine/storm) - Simple and powerful ORM for BoltDB.
* [GoWebApp](https://github.com/josephspurrier/gowebapp) - A basic MVC web application in Go using BoltDB.
* [SimpleBolt](https://github.com/xyproto/simplebolt) - A simple way to use BoltDB. Deals mainly with strings.
* [Algernon](https://github.com/xyproto/algernon) - A HTTP/2 web server with built-in support for Lua. Uses BoltDB as the default database backend.
* [MuLiFS](https://github.com/dankomiocevic/mulifs) - Music Library Filesystem creates a filesystem to organise your music files.
* [GoShort](https://github.com/pankajkhairnar/goShort) - GoShort is a URL shortener written in Golang and BoltDB for persistent key/value storage and for routing it's using high performent HTTPRouter.
* [torrent](https://github.com/anacrolix/torrent) - Full-featured BitTorrent client package and utilities in Go. BoltDB is a storage backend in development.
* [gopherpit](https://github.com/gopherpit/gopherpit) - A web service to manage Go remote import paths with custom domains
* [bolter](https://github.com/hasit/bolter) - Command-line app for viewing BoltDB file in your terminal.
* [btcwallet](https://github.com/btcsuite/btcwallet) - A bitcoin wallet.
* [dcrwallet](https://github.com/decred/dcrwallet) - A wallet for the Decred cryptocurrency.
* [Ironsmith](https://github.com/timshannon/ironsmith) - A simple, script-driven continuous integration (build - > test -> release) tool, with no external dependencies
* [BoltHold](https://github.com/timshannon/bolthold) - An embeddable NoSQL store for Go types built on BoltDB
* [Ponzu CMS](https://ponzu-cms.org) - Headless CMS + automatic JSON API with auto-HTTPS, HTTP/2 Server Push, and flexible server framework.
If you are using Bolt in a project please send a pull request to add it to the list.
================================================
FILE: appveyor.yml
================================================
version: "{build}"
os: Windows Server 2012 R2
clone_folder: c:\gopath\src\github.com\boltdb\bolt
environment:
GOPATH: c:\gopath
install:
- echo %PATH%
- echo %GOPATH%
- go version
- go env
- go get -v -t ./...
build_script:
- go test -v ./...
================================================
FILE: bolt_386.go
================================================
package bolt
// maxMapSize represents the largest mmap size supported by Bolt.
const maxMapSize = 0x7FFFFFFF // 2GB
// maxAllocSize is the size used when creating array pointers.
const maxAllocSize = 0xFFFFFFF
// Are unaligned load/stores broken on this arch?
var brokenUnaligned = false
================================================
FILE: bolt_amd64.go
================================================
package bolt
// maxMapSize represents the largest mmap size supported by Bolt.
const maxMapSize = 0xFFFFFFFFFFFF // 256TB
// maxAllocSize is the size used when creating array pointers.
const maxAllocSize = 0x7FFFFFFF
// Are unaligned load/stores broken on this arch?
var brokenUnaligned = false
================================================
FILE: bolt_arm.go
================================================
package bolt
import "unsafe"
// maxMapSize represents the largest mmap size supported by Bolt.
const maxMapSize = 0x7FFFFFFF // 2GB
// maxAllocSize is the size used when creating array pointers.
const maxAllocSize = 0xFFFFFFF
// Are unaligned load/stores broken on this arch?
var brokenUnaligned bool
func init() {
// Simple check to see whether this arch handles unaligned load/stores
// correctly.
// ARM9 and older devices require load/stores to be from/to aligned
// addresses. If not, the lower 2 bits are cleared and that address is
// read in a jumbled up order.
// See http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.faqs/ka15414.html
raw := [6]byte{0xfe, 0xef, 0x11, 0x22, 0x22, 0x11}
val := *(*uint32)(unsafe.Pointer(uintptr(unsafe.Pointer(&raw)) + 2))
brokenUnaligned = val != 0x11222211
}
================================================
FILE: bolt_arm64.go
================================================
// +build arm64
package bolt
// maxMapSize represents the largest mmap size supported by Bolt.
const maxMapSize = 0xFFFFFFFFFFFF // 256TB
// maxAllocSize is the size used when creating array pointers.
const maxAllocSize = 0x7FFFFFFF
// Are unaligned load/stores broken on this arch?
var brokenUnaligned = false
================================================
FILE: bolt_linux.go
================================================
package bolt
import (
"syscall"
)
// fdatasync flushes written data to a file descriptor.
func fdatasync(db *DB) error {
return syscall.Fdatasync(int(db.file.Fd()))
}
================================================
FILE: bolt_openbsd.go
================================================
package bolt
import (
"syscall"
"unsafe"
)
const (
msAsync = 1 << iota // perform asynchronous writes
msSync // perform synchronous writes
msInvalidate // invalidate cached data
)
func msync(db *DB) error {
_, _, errno := syscall.Syscall(syscall.SYS_MSYNC, uintptr(unsafe.Pointer(db.data)), uintptr(db.datasz), msInvalidate)
if errno != 0 {
return errno
}
return nil
}
func fdatasync(db *DB) error {
if db.data != nil {
return msync(db)
}
return db.file.Sync()
}
================================================
FILE: bolt_ppc.go
================================================
// +build ppc
package bolt
// maxMapSize represents the largest mmap size supported by Bolt.
const maxMapSize = 0x7FFFFFFF // 2GB
// maxAllocSize is the size used when creating array pointers.
const maxAllocSize = 0xFFFFFFF
================================================
FILE: bolt_ppc64.go
================================================
// +build ppc64
package bolt
// maxMapSize represents the largest mmap size supported by Bolt.
const maxMapSize = 0xFFFFFFFFFFFF // 256TB
// maxAllocSize is the size used when creating array pointers.
const maxAllocSize = 0x7FFFFFFF
// Are unaligned load/stores broken on this arch?
var brokenUnaligned = false
================================================
FILE: bolt_ppc64le.go
================================================
// +build ppc64le
package bolt
// maxMapSize represents the largest mmap size supported by Bolt.
const maxMapSize = 0xFFFFFFFFFFFF // 256TB
// maxAllocSize is the size used when creating array pointers.
const maxAllocSize = 0x7FFFFFFF
// Are unaligned load/stores broken on this arch?
var brokenUnaligned = false
================================================
FILE: bolt_s390x.go
================================================
// +build s390x
package bolt
// maxMapSize represents the largest mmap size supported by Bolt.
const maxMapSize = 0xFFFFFFFFFFFF // 256TB
// maxAllocSize is the size used when creating array pointers.
const maxAllocSize = 0x7FFFFFFF
// Are unaligned load/stores broken on this arch?
var brokenUnaligned = false
================================================
FILE: bolt_unix.go
================================================
// +build !windows,!plan9,!solaris
package bolt
import (
"fmt"
"os"
"syscall"
"time"
"unsafe"
)
// flock acquires an advisory lock on a file descriptor.
func flock(db *DB, mode os.FileMode, exclusive bool, timeout time.Duration) error {
var t time.Time
for {
// If we're beyond our timeout then return an error.
// This can only occur after we've attempted a flock once.
if t.IsZero() {
t = time.Now()
} else if timeout > 0 && time.Since(t) > timeout {
return ErrTimeout
}
flag := syscall.LOCK_SH
if exclusive {
flag = syscall.LOCK_EX
}
// Otherwise attempt to obtain an exclusive lock.
err := syscall.Flock(int(db.file.Fd()), flag|syscall.LOCK_NB)
if err == nil {
return nil
} else if err != syscall.EWOULDBLOCK {
return err
}
// Wait for a bit and try again.
time.Sleep(50 * time.Millisecond)
}
}
// funlock releases an advisory lock on a file descriptor.
func funlock(db *DB) error {
return syscall.Flock(int(db.file.Fd()), syscall.LOCK_UN)
}
// mmap memory maps a DB's data file.
func mmap(db *DB, sz int) error {
// Map the data file to memory.
b, err := syscall.Mmap(int(db.file.Fd()), 0, sz, syscall.PROT_READ, syscall.MAP_SHARED|db.MmapFlags)
if err != nil {
return err
}
// Advise the kernel that the mmap is accessed randomly.
if err := madvise(b, syscall.MADV_RANDOM); err != nil {
return fmt.Errorf("madvise: %s", err)
}
// Save the original byte slice and convert to a byte array pointer.
db.dataref = b
db.data = (*[maxMapSize]byte)(unsafe.Pointer(&b[0]))
db.datasz = sz
return nil
}
// munmap unmaps a DB's data file from memory.
func munmap(db *DB) error {
// Ignore the unmap if we have no mapped data.
if db.dataref == nil {
return nil
}
// Unmap using the original byte slice.
err := syscall.Munmap(db.dataref)
db.dataref = nil
db.data = nil
db.datasz = 0
return err
}
// NOTE: This function is copied from stdlib because it is not available on darwin.
func madvise(b []byte, advice int) (err error) {
_, _, e1 := syscall.Syscall(syscall.SYS_MADVISE, uintptr(unsafe.Pointer(&b[0])), uintptr(len(b)), uintptr(advice))
if e1 != 0 {
err = e1
}
return
}
================================================
FILE: bolt_unix_solaris.go
================================================
package bolt
import (
"fmt"
"os"
"syscall"
"time"
"unsafe"
"golang.org/x/sys/unix"
)
// flock acquires an advisory lock on a file descriptor.
func flock(db *DB, mode os.FileMode, exclusive bool, timeout time.Duration) error {
var t time.Time
for {
// If we're beyond our timeout then return an error.
// This can only occur after we've attempted a flock once.
if t.IsZero() {
t = time.Now()
} else if timeout > 0 && time.Since(t) > timeout {
return ErrTimeout
}
var lock syscall.Flock_t
lock.Start = 0
lock.Len = 0
lock.Pid = 0
lock.Whence = 0
lock.Pid = 0
if exclusive {
lock.Type = syscall.F_WRLCK
} else {
lock.Type = syscall.F_RDLCK
}
err := syscall.FcntlFlock(db.file.Fd(), syscall.F_SETLK, &lock)
if err == nil {
return nil
} else if err != syscall.EAGAIN {
return err
}
// Wait for a bit and try again.
time.Sleep(50 * time.Millisecond)
}
}
// funlock releases an advisory lock on a file descriptor.
func funlock(db *DB) error {
var lock syscall.Flock_t
lock.Start = 0
lock.Len = 0
lock.Type = syscall.F_UNLCK
lock.Whence = 0
return syscall.FcntlFlock(uintptr(db.file.Fd()), syscall.F_SETLK, &lock)
}
// mmap memory maps a DB's data file.
func mmap(db *DB, sz int) error {
// Map the data file to memory.
b, err := unix.Mmap(int(db.file.Fd()), 0, sz, syscall.PROT_READ, syscall.MAP_SHARED|db.MmapFlags)
if err != nil {
return err
}
// Advise the kernel that the mmap is accessed randomly.
if err := unix.Madvise(b, syscall.MADV_RANDOM); err != nil {
return fmt.Errorf("madvise: %s", err)
}
// Save the original byte slice and convert to a byte array pointer.
db.dataref = b
db.data = (*[maxMapSize]byte)(unsafe.Pointer(&b[0]))
db.datasz = sz
return nil
}
// munmap unmaps a DB's data file from memory.
func munmap(db *DB) error {
// Ignore the unmap if we have no mapped data.
if db.dataref == nil {
return nil
}
// Unmap using the original byte slice.
err := unix.Munmap(db.dataref)
db.dataref = nil
db.data = nil
db.datasz = 0
return err
}
================================================
FILE: bolt_windows.go
================================================
package bolt
import (
"fmt"
"os"
"syscall"
"time"
"unsafe"
)
// LockFileEx code derived from golang build filemutex_windows.go @ v1.5.1
var (
modkernel32 = syscall.NewLazyDLL("kernel32.dll")
procLockFileEx = modkernel32.NewProc("LockFileEx")
procUnlockFileEx = modkernel32.NewProc("UnlockFileEx")
)
const (
lockExt = ".lock"
// see https://msdn.microsoft.com/en-us/library/windows/desktop/aa365203(v=vs.85).aspx
flagLockExclusive = 2
flagLockFailImmediately = 1
// see https://msdn.microsoft.com/en-us/library/windows/desktop/ms681382(v=vs.85).aspx
errLockViolation syscall.Errno = 0x21
)
func lockFileEx(h syscall.Handle, flags, reserved, locklow, lockhigh uint32, ol *syscall.Overlapped) (err error) {
r, _, err := procLockFileEx.Call(uintptr(h), uintptr(flags), uintptr(reserved), uintptr(locklow), uintptr(lockhigh), uintptr(unsafe.Pointer(ol)))
if r == 0 {
return err
}
return nil
}
func unlockFileEx(h syscall.Handle, reserved, locklow, lockhigh uint32, ol *syscall.Overlapped) (err error) {
r, _, err := procUnlockFileEx.Call(uintptr(h), uintptr(reserved), uintptr(locklow), uintptr(lockhigh), uintptr(unsafe.Pointer(ol)), 0)
if r == 0 {
return err
}
return nil
}
// fdatasync flushes written data to a file descriptor.
func fdatasync(db *DB) error {
return db.file.Sync()
}
// flock acquires an advisory lock on a file descriptor.
func flock(db *DB, mode os.FileMode, exclusive bool, timeout time.Duration) error {
// Create a separate lock file on windows because a process
// cannot share an exclusive lock on the same file. This is
// needed during Tx.WriteTo().
f, err := os.OpenFile(db.path+lockExt, os.O_CREATE, mode)
if err != nil {
return err
}
db.lockfile = f
var t time.Time
for {
// If we're beyond our timeout then return an error.
// This can only occur after we've attempted a flock once.
if t.IsZero() {
t = time.Now()
} else if timeout > 0 && time.Since(t) > timeout {
return ErrTimeout
}
var flag uint32 = flagLockFailImmediately
if exclusive {
flag |= flagLockExclusive
}
err := lockFileEx(syscall.Handle(db.lockfile.Fd()), flag, 0, 1, 0, &syscall.Overlapped{})
if err == nil {
return nil
} else if err != errLockViolation {
return err
}
// Wait for a bit and try again.
time.Sleep(50 * time.Millisecond)
}
}
// funlock releases an advisory lock on a file descriptor.
func funlock(db *DB) error {
err := unlockFileEx(syscall.Handle(db.lockfile.Fd()), 0, 1, 0, &syscall.Overlapped{})
db.lockfile.Close()
os.Remove(db.path + lockExt)
return err
}
// mmap memory maps a DB's data file.
// Based on: https://github.com/edsrzf/mmap-go
func mmap(db *DB, sz int) error {
if !db.readOnly {
// Truncate the database to the size of the mmap.
if err := db.file.Truncate(int64(sz)); err != nil {
return fmt.Errorf("truncate: %s", err)
}
}
// Open a file mapping handle.
sizelo := uint32(sz >> 32)
sizehi := uint32(sz) & 0xffffffff
h, errno := syscall.CreateFileMapping(syscall.Handle(db.file.Fd()), nil, syscall.PAGE_READONLY, sizelo, sizehi, nil)
if h == 0 {
return os.NewSyscallError("CreateFileMapping", errno)
}
// Create the memory map.
addr, errno := syscall.MapViewOfFile(h, syscall.FILE_MAP_READ, 0, 0, uintptr(sz))
if addr == 0 {
return os.NewSyscallError("MapViewOfFile", errno)
}
// Close mapping handle.
if err := syscall.CloseHandle(syscall.Handle(h)); err != nil {
return os.NewSyscallError("CloseHandle", err)
}
// Convert to a byte array.
db.data = ((*[maxMapSize]byte)(unsafe.Pointer(addr)))
db.datasz = sz
return nil
}
// munmap unmaps a pointer from a file.
// Based on: https://github.com/edsrzf/mmap-go
func munmap(db *DB) error {
if db.data == nil {
return nil
}
addr := (uintptr)(unsafe.Pointer(&db.data[0]))
if err := syscall.UnmapViewOfFile(addr); err != nil {
return os.NewSyscallError("UnmapViewOfFile", err)
}
return nil
}
================================================
FILE: boltsync_unix.go
================================================
// +build !windows,!plan9,!linux,!openbsd
package bolt
// fdatasync flushes written data to a file descriptor.
func fdatasync(db *DB) error {
return db.file.Sync()
}
================================================
FILE: bucket.go
================================================
package bolt
import (
"bytes"
"fmt"
"unsafe"
)
const (
// MaxKeySize is the maximum length of a key, in bytes.
MaxKeySize = 32768
// MaxValueSize is the maximum length of a value, in bytes.
MaxValueSize = (1 << 31) - 2
)
const (
maxUint = ^uint(0)
minUint = 0
maxInt = int(^uint(0) >> 1)
minInt = -maxInt - 1
)
const bucketHeaderSize = int(unsafe.Sizeof(bucket{}))
const (
minFillPercent = 0.1
maxFillPercent = 1.0
)
// DefaultFillPercent is the percentage that split pages are filled.
// This value can be changed by setting Bucket.FillPercent.
const DefaultFillPercent = 0.5
// Bucket represents a collection of key/value pairs inside the database.
type Bucket struct {
*bucket
tx *Tx // the associated transaction
buckets map[string]*Bucket // subbucket cache
page *page // inline page reference
rootNode *node // materialized node for the root page.
nodes map[pgid]*node // node cache
// Sets the threshold for filling nodes when they split. By default,
// the bucket will fill to 50% but it can be useful to increase this
// amount if you know that your write workloads are mostly append-only.
//
// This is non-persisted across transactions so it must be set in every Tx.
FillPercent float64
}
// bucket represents the on-file representation of a bucket.
// This is stored as the "value" of a bucket key. If the bucket is small enough,
// then its root page can be stored inline in the "value", after the bucket
// header. In the case of inline buckets, the "root" will be 0.
type bucket struct {
root pgid // page id of the bucket's root-level page
sequence uint64 // monotonically incrementing, used by NextSequence()
}
// newBucket returns a new bucket associated with a transaction.
func newBucket(tx *Tx) Bucket {
var b = Bucket{tx: tx, FillPercent: DefaultFillPercent}
if tx.writable {
b.buckets = make(map[string]*Bucket)
b.nodes = make(map[pgid]*node)
}
return b
}
// Tx returns the tx of the bucket.
func (b *Bucket) Tx() *Tx {
return b.tx
}
// Root returns the root of the bucket.
func (b *Bucket) Root() pgid {
return b.root
}
// Writable returns whether the bucket is writable.
func (b *Bucket) Writable() bool {
return b.tx.writable
}
// Cursor creates a cursor associated with the bucket.
// The cursor is only valid as long as the transaction is open.
// Do not use a cursor after the transaction is closed.
func (b *Bucket) Cursor() *Cursor {
// Update transaction statistics.
b.tx.stats.CursorCount++
// Allocate and return a cursor.
return &Cursor{
bucket: b,
stack: make([]elemRef, 0),
}
}
// Bucket retrieves a nested bucket by name.
// Returns nil if the bucket does not exist.
// The bucket instance is only valid for the lifetime of the transaction.
func (b *Bucket) Bucket(name []byte) *Bucket {
if b.buckets != nil {
if child := b.buckets[string(name)]; child != nil {
return child
}
}
// Move cursor to key.
c := b.Cursor()
k, v, flags := c.seek(name)
// Return nil if the key doesn't exist or it is not a bucket.
if !bytes.Equal(name, k) || (flags&bucketLeafFlag) == 0 {
return nil
}
// Otherwise create a bucket and cache it.
var child = b.openBucket(v)
if b.buckets != nil {
b.buckets[string(name)] = child
}
return child
}
// Helper method that re-interprets a sub-bucket value
// from a parent into a Bucket
func (b *Bucket) openBucket(value []byte) *Bucket {
var child = newBucket(b.tx)
// If unaligned load/stores are broken on this arch and value is
// unaligned simply clone to an aligned byte array.
unaligned := brokenUnaligned && uintptr(unsafe.Pointer(&value[0]))&3 != 0
if unaligned {
value = cloneBytes(value)
}
// If this is a writable transaction then we need to copy the bucket entry.
// Read-only transactions can point directly at the mmap entry.
if b.tx.writable && !unaligned {
child.bucket = &bucket{}
*child.bucket = *(*bucket)(unsafe.Pointer(&value[0]))
} else {
child.bucket = (*bucket)(unsafe.Pointer(&value[0]))
}
// Save a reference to the inline page if the bucket is inline.
if child.root == 0 {
child.page = (*page)(unsafe.Pointer(&value[bucketHeaderSize]))
}
return &child
}
// CreateBucket creates a new bucket at the given key and returns the new bucket.
// Returns an error if the key already exists, if the bucket name is blank, or if the bucket name is too long.
// The bucket instance is only valid for the lifetime of the transaction.
func (b *Bucket) CreateBucket(key []byte) (*Bucket, error) {
if b.tx.db == nil {
return nil, ErrTxClosed
} else if !b.tx.writable {
return nil, ErrTxNotWritable
} else if len(key) == 0 {
return nil, ErrBucketNameRequired
}
// Move cursor to correct position.
c := b.Cursor()
k, _, flags := c.seek(key)
// Return an error if there is an existing key.
if bytes.Equal(key, k) {
if (flags & bucketLeafFlag) != 0 {
return nil, ErrBucketExists
}
return nil, ErrIncompatibleValue
}
// Create empty, inline bucket.
var bucket = Bucket{
bucket: &bucket{},
rootNode: &node{isLeaf: true},
FillPercent: DefaultFillPercent,
}
var value = bucket.write()
// Insert into node.
key = cloneBytes(key)
c.node().put(key, key, value, 0, bucketLeafFlag)
// Since subbuckets are not allowed on inline buckets, we need to
// dereference the inline page, if it exists. This will cause the bucket
// to be treated as a regular, non-inline bucket for the rest of the tx.
b.page = nil
return b.Bucket(key), nil
}
// CreateBucketIfNotExists creates a new bucket if it doesn't already exist and returns a reference to it.
// Returns an error if the bucket name is blank, or if the bucket name is too long.
// The bucket instance is only valid for the lifetime of the transaction.
func (b *Bucket) CreateBucketIfNotExists(key []byte) (*Bucket, error) {
child, err := b.CreateBucket(key)
if err == ErrBucketExists {
return b.Bucket(key), nil
} else if err != nil {
return nil, err
}
return child, nil
}
// DeleteBucket deletes a bucket at the given key.
// Returns an error if the bucket does not exists, or if the key represents a non-bucket value.
func (b *Bucket) DeleteBucket(key []byte) error {
if b.tx.db == nil {
return ErrTxClosed
} else if !b.Writable() {
return ErrTxNotWritable
}
// Move cursor to correct position.
c := b.Cursor()
k, _, flags := c.seek(key)
// Return an error if bucket doesn't exist or is not a bucket.
if !bytes.Equal(key, k) {
return ErrBucketNotFound
} else if (flags & bucketLeafFlag) == 0 {
return ErrIncompatibleValue
}
// Recursively delete all child buckets.
child := b.Bucket(key)
err := child.ForEach(func(k, v []byte) error {
if v == nil {
if err := child.DeleteBucket(k); err != nil {
return fmt.Errorf("delete bucket: %s", err)
}
}
return nil
})
if err != nil {
return err
}
// Remove cached copy.
delete(b.buckets, string(key))
// Release all bucket pages to freelist.
child.nodes = nil
child.rootNode = nil
child.free()
// Delete the node if we have a matching key.
c.node().del(key)
return nil
}
// Get retrieves the value for a key in the bucket.
// Returns a nil value if the key does not exist or if the key is a nested bucket.
// The returned value is only valid for the life of the transaction.
func (b *Bucket) Get(key []byte) []byte {
k, v, flags := b.Cursor().seek(key)
// Return nil if this is a bucket.
if (flags & bucketLeafFlag) != 0 {
return nil
}
// If our target node isn't the same key as what's passed in then return nil.
if !bytes.Equal(key, k) {
return nil
}
return v
}
// Put sets the value for a key in the bucket.
// If the key exist then its previous value will be overwritten.
// Supplied value must remain valid for the life of the transaction.
// Returns an error if the bucket was created from a read-only transaction, if the key is blank, if the key is too large, or if the value is too large.
func (b *Bucket) Put(key []byte, value []byte) error {
if b.tx.db == nil {
return ErrTxClosed
} else if !b.Writable() {
return ErrTxNotWritable
} else if len(key) == 0 {
return ErrKeyRequired
} else if len(key) > MaxKeySize {
return ErrKeyTooLarge
} else if int64(len(value)) > MaxValueSize {
return ErrValueTooLarge
}
// Move cursor to correct position.
c := b.Cursor()
k, _, flags := c.seek(key)
// Return an error if there is an existing key with a bucket value.
if bytes.Equal(key, k) && (flags&bucketLeafFlag) != 0 {
return ErrIncompatibleValue
}
// Insert into node.
key = cloneBytes(key)
c.node().put(key, key, value, 0, 0)
return nil
}
// Delete removes a key from the bucket.
// If the key does not exist then nothing is done and a nil error is returned.
// Returns an error if the bucket was created from a read-only transaction.
func (b *Bucket) Delete(key []byte) error {
if b.tx.db == nil {
return ErrTxClosed
} else if !b.Writable() {
return ErrTxNotWritable
}
// Move cursor to correct position.
c := b.Cursor()
_, _, flags := c.seek(key)
// Return an error if there is already existing bucket value.
if (flags & bucketLeafFlag) != 0 {
return ErrIncompatibleValue
}
// Delete the node if we have a matching key.
c.node().del(key)
return nil
}
// Sequence returns the current integer for the bucket without incrementing it.
func (b *Bucket) Sequence() uint64 { return b.bucket.sequence }
// SetSequence updates the sequence number for the bucket.
func (b *Bucket) SetSequence(v uint64) error {
if b.tx.db == nil {
return ErrTxClosed
} else if !b.Writable() {
return ErrTxNotWritable
}
// Materialize the root node if it hasn't been already so that the
// bucket will be saved during commit.
if b.rootNode == nil {
_ = b.node(b.root, nil)
}
// Increment and return the sequence.
b.bucket.sequence = v
return nil
}
// NextSequence returns an autoincrementing integer for the bucket.
func (b *Bucket) NextSequence() (uint64, error) {
if b.tx.db == nil {
return 0, ErrTxClosed
} else if !b.Writable() {
return 0, ErrTxNotWritable
}
// Materialize the root node if it hasn't been already so that the
// bucket will be saved during commit.
if b.rootNode == nil {
_ = b.node(b.root, nil)
}
// Increment and return the sequence.
b.bucket.sequence++
return b.bucket.sequence, nil
}
// ForEach executes a function for each key/value pair in a bucket.
// If the provided function returns an error then the iteration is stopped and
// the error is returned to the caller. The provided function must not modify
// the bucket; this will result in undefined behavior.
func (b *Bucket) ForEach(fn func(k, v []byte) error) error {
if b.tx.db == nil {
return ErrTxClosed
}
c := b.Cursor()
for k, v := c.First(); k != nil; k, v = c.Next() {
if err := fn(k, v); err != nil {
return err
}
}
return nil
}
// Stat returns stats on a bucket.
func (b *Bucket) Stats() BucketStats {
var s, subStats BucketStats
pageSize := b.tx.db.pageSize
s.BucketN += 1
if b.root == 0 {
s.InlineBucketN += 1
}
b.forEachPage(func(p *page, depth int) {
if (p.flags & leafPageFlag) != 0 {
s.KeyN += int(p.count)
// used totals the used bytes for the page
used := pageHeaderSize
if p.count != 0 {
// If page has any elements, add all element headers.
used += leafPageElementSize * int(p.count-1)
// Add all element key, value sizes.
// The computation takes advantage of the fact that the position
// of the last element's key/value equals to the total of the sizes
// of all previous elements' keys and values.
// It also includes the last element's header.
lastElement := p.leafPageElement(p.count - 1)
used += int(lastElement.pos + lastElement.ksize + lastElement.vsize)
}
if b.root == 0 {
// For inlined bucket just update the inline stats
s.InlineBucketInuse += used
} else {
// For non-inlined bucket update all the leaf stats
s.LeafPageN++
s.LeafInuse += used
s.LeafOverflowN += int(p.overflow)
// Collect stats from sub-buckets.
// Do that by iterating over all element headers
// looking for the ones with the bucketLeafFlag.
for i := uint16(0); i < p.count; i++ {
e := p.leafPageElement(i)
if (e.flags & bucketLeafFlag) != 0 {
// For any bucket element, open the element value
// and recursively call Stats on the contained bucket.
subStats.Add(b.openBucket(e.value()).Stats())
}
}
}
} else if (p.flags & branchPageFlag) != 0 {
s.BranchPageN++
lastElement := p.branchPageElement(p.count - 1)
// used totals the used bytes for the page
// Add header and all element headers.
used := pageHeaderSize + (branchPageElementSize * int(p.count-1))
// Add size of all keys and values.
// Again, use the fact that last element's position equals to
// the total of key, value sizes of all previous elements.
used += int(lastElement.pos + lastElement.ksize)
s.BranchInuse += used
s.BranchOverflowN += int(p.overflow)
}
// Keep track of maximum page depth.
if depth+1 > s.Depth {
s.Depth = (depth + 1)
}
})
// Alloc stats can be computed from page counts and pageSize.
s.BranchAlloc = (s.BranchPageN + s.BranchOverflowN) * pageSize
s.LeafAlloc = (s.LeafPageN + s.LeafOverflowN) * pageSize
// Add the max depth of sub-buckets to get total nested depth.
s.Depth += subStats.Depth
// Add the stats for all sub-buckets
s.Add(subStats)
return s
}
// forEachPage iterates over every page in a bucket, including inline pages.
func (b *Bucket) forEachPage(fn func(*page, int)) {
// If we have an inline page then just use that.
if b.page != nil {
fn(b.page, 0)
return
}
// Otherwise traverse the page hierarchy.
b.tx.forEachPage(b.root, 0, fn)
}
// forEachPageNode iterates over every page (or node) in a bucket.
// This also includes inline pages.
func (b *Bucket) forEachPageNode(fn func(*page, *node, int)) {
// If we have an inline page or root node then just use that.
if b.page != nil {
fn(b.page, nil, 0)
return
}
b._forEachPageNode(b.root, 0, fn)
}
func (b *Bucket) _forEachPageNode(pgid pgid, depth int, fn func(*page, *node, int)) {
var p, n = b.pageNode(pgid)
// Execute function.
fn(p, n, depth)
// Recursively loop over children.
if p != nil {
if (p.flags & branchPageFlag) != 0 {
for i := 0; i < int(p.count); i++ {
elem := p.branchPageElement(uint16(i))
b._forEachPageNode(elem.pgid, depth+1, fn)
}
}
} else {
if !n.isLeaf {
for _, inode := range n.inodes {
b._forEachPageNode(inode.pgid, depth+1, fn)
}
}
}
}
// spill writes all the nodes for this bucket to dirty pages.
func (b *Bucket) spill() error {
// Spill all child buckets first.
for name, child := range b.buckets {
// If the child bucket is small enough and it has no child buckets then
// write it inline into the parent bucket's page. Otherwise spill it
// like a normal bucket and make the parent value a pointer to the page.
var value []byte
if child.inlineable() {
child.free()
value = child.write()
} else {
if err := child.spill(); err != nil {
return err
}
// Update the child bucket header in this bucket.
value = make([]byte, unsafe.Sizeof(bucket{}))
var bucket = (*bucket)(unsafe.Pointer(&value[0]))
*bucket = *child.bucket
}
// Skip writing the bucket if there are no materialized nodes.
if child.rootNode == nil {
continue
}
// Update parent node.
var c = b.Cursor()
k, _, flags := c.seek([]byte(name))
if !bytes.Equal([]byte(name), k) {
panic(fmt.Sprintf("misplaced bucket header: %x -> %x", []byte(name), k))
}
if flags&bucketLeafFlag == 0 {
panic(fmt.Sprintf("unexpected bucket header flag: %x", flags))
}
c.node().put([]byte(name), []byte(name), value, 0, bucketLeafFlag)
}
// Ignore if there's not a materialized root node.
if b.rootNode == nil {
return nil
}
// Spill nodes.
if err := b.rootNode.spill(); err != nil {
return err
}
b.rootNode = b.rootNode.root()
// Update the root node for this bucket.
if b.rootNode.pgid >= b.tx.meta.pgid {
panic(fmt.Sprintf("pgid (%d) above high water mark (%d)", b.rootNode.pgid, b.tx.meta.pgid))
}
b.root = b.rootNode.pgid
return nil
}
// inlineable returns true if a bucket is small enough to be written inline
// and if it contains no subbuckets. Otherwise returns false.
func (b *Bucket) inlineable() bool {
var n = b.rootNode
// Bucket must only contain a single leaf node.
if n == nil || !n.isLeaf {
return false
}
// Bucket is not inlineable if it contains subbuckets or if it goes beyond
// our threshold for inline bucket size.
var size = pageHeaderSize
for _, inode := range n.inodes {
size += leafPageElementSize + len(inode.key) + len(inode.value)
if inode.flags&bucketLeafFlag != 0 {
return false
} else if size > b.maxInlineBucketSize() {
return false
}
}
return true
}
// Returns the maximum total size of a bucket to make it a candidate for inlining.
func (b *Bucket) maxInlineBucketSize() int {
return b.tx.db.pageSize / 4
}
// write allocates and writes a bucket to a byte slice.
func (b *Bucket) write() []byte {
// Allocate the appropriate size.
var n = b.rootNode
var value = make([]byte, bucketHeaderSize+n.size())
// Write a bucket header.
var bucket = (*bucket)(unsafe.Pointer(&value[0]))
*bucket = *b.bucket
// Convert byte slice to a fake page and write the root node.
var p = (*page)(unsafe.Pointer(&value[bucketHeaderSize]))
n.write(p)
return value
}
// rebalance attempts to balance all nodes.
func (b *Bucket) rebalance() {
for _, n := range b.nodes {
n.rebalance()
}
for _, child := range b.buckets {
child.rebalance()
}
}
// node creates a node from a page and associates it with a given parent.
func (b *Bucket) node(pgid pgid, parent *node) *node {
_assert(b.nodes != nil, "nodes map expected")
// Retrieve node if it's already been created.
if n := b.nodes[pgid]; n != nil {
return n
}
// Otherwise create a node and cache it.
n := &node{bucket: b, parent: parent}
if parent == nil {
b.rootNode = n
} else {
parent.children = append(parent.children, n)
}
// Use the inline page if this is an inline bucket.
var p = b.page
if p == nil {
p = b.tx.page(pgid)
}
// Read the page into the node and cache it.
n.read(p)
b.nodes[pgid] = n
// Update statistics.
b.tx.stats.NodeCount++
return n
}
// free recursively frees all pages in the bucket.
func (b *Bucket) free() {
if b.root == 0 {
return
}
var tx = b.tx
b.forEachPageNode(func(p *page, n *node, _ int) {
if p != nil {
tx.db.freelist.free(tx.meta.txid, p)
} else {
n.free()
}
})
b.root = 0
}
// dereference removes all references to the old mmap.
func (b *Bucket) dereference() {
if b.rootNode != nil {
b.rootNode.root().dereference()
}
for _, child := range b.buckets {
child.dereference()
}
}
// pageNode returns the in-memory node, if it exists.
// Otherwise returns the underlying page.
func (b *Bucket) pageNode(id pgid) (*page, *node) {
// Inline buckets have a fake page embedded in their value so treat them
// differently. We'll return the rootNode (if available) or the fake page.
if b.root == 0 {
if id != 0 {
panic(fmt.Sprintf("inline bucket non-zero page access(2): %d != 0", id))
}
if b.rootNode != nil {
return nil, b.rootNode
}
return b.page, nil
}
// Check the node cache for non-inline buckets.
if b.nodes != nil {
if n := b.nodes[id]; n != nil {
return nil, n
}
}
// Finally lookup the page from the transaction if no node is materialized.
return b.tx.page(id), nil
}
// BucketStats records statistics about resources used by a bucket.
type BucketStats struct {
// Page count statistics.
BranchPageN int // number of logical branch pages
BranchOverflowN int // number of physical branch overflow pages
LeafPageN int // number of logical leaf pages
LeafOverflowN int // number of physical leaf overflow pages
// Tree statistics.
KeyN int // number of keys/value pairs
Depth int // number of levels in B+tree
// Page size utilization.
BranchAlloc int // bytes allocated for physical branch pages
BranchInuse int // bytes actually used for branch data
LeafAlloc int // bytes allocated for physical leaf pages
LeafInuse int // bytes actually used for leaf data
// Bucket statistics
BucketN int // total number of buckets including the top bucket
InlineBucketN int // total number on inlined buckets
InlineBucketInuse int // bytes used for inlined buckets (also accounted for in LeafInuse)
}
func (s *BucketStats) Add(other BucketStats) {
s.BranchPageN += other.BranchPageN
s.BranchOverflowN += other.BranchOverflowN
s.LeafPageN += other.LeafPageN
s.LeafOverflowN += other.LeafOverflowN
s.KeyN += other.KeyN
if s.Depth < other.Depth {
s.Depth = other.Depth
}
s.BranchAlloc += other.BranchAlloc
s.BranchInuse += other.BranchInuse
s.LeafAlloc += other.LeafAlloc
s.LeafInuse += other.LeafInuse
s.BucketN += other.BucketN
s.InlineBucketN += other.InlineBucketN
s.InlineBucketInuse += other.InlineBucketInuse
}
// cloneBytes returns a copy of a given slice.
func cloneBytes(v []byte) []byte {
var clone = make([]byte, len(v))
copy(clone, v)
return clone
}
================================================
FILE: bucket_test.go
================================================
package bolt_test
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"log"
"math/rand"
"os"
"strconv"
"strings"
"testing"
"testing/quick"
"github.com/boltdb/bolt"
)
// Ensure that a bucket that gets a non-existent key returns nil.
func TestBucket_Get_NonExistent(t *testing.T) {
db := MustOpenDB()
defer db.MustClose()
if err := db.Update(func(tx *bolt.Tx) error {
b, err := tx.CreateBucket([]byte("widgets"))
if err != nil {
t.Fatal(err)
}
if v := b.Get([]byte("foo")); v != nil {
t.Fatal("expected nil value")
}
return nil
}); err != nil {
t.Fatal(err)
}
}
// Ensure that a bucket can read a value that is not flushed yet.
func TestBucket_Get_FromNode(t *testing.T) {
db := MustOpenDB()
defer db.MustClose()
if err := db.Update(func(tx *bolt.Tx) error {
b, err := tx.CreateBucket([]byte("widgets"))
if err != nil {
t.Fatal(err)
}
if err := b.Put([]byte("foo"), []byte("bar")); err != nil {
t.Fatal(err)
}
if v := b.Get([]byte("foo")); !bytes.Equal(v, []byte("bar")) {
t.Fatalf("unexpected value: %v", v)
}
return nil
}); err != nil {
t.Fatal(err)
}
}
// Ensure that a bucket retrieved via Get() returns a nil.
func TestBucket_Get_IncompatibleValue(t *testing.T) {
db := MustOpenDB()
defer db.MustClose()
if err := db.Update(func(tx *bolt.Tx) error {
_, err := tx.CreateBucket([]byte("widgets"))
if err != nil {
t.Fatal(err)
}
if _, err := tx.Bucket([]byte("widgets")).CreateBucket([]byte("foo")); err != nil {
t.Fatal(err)
}
if tx.Bucket([]byte("widgets")).Get([]byte("foo")) != nil {
t.Fatal("expected nil value")
}
return nil
}); err != nil {
t.Fatal(err)
}
}
// Ensure that a slice returned from a bucket has a capacity equal to its length.
// This also allows slices to be appended to since it will require a realloc by Go.
//
// https://github.com/boltdb/bolt/issues/544
func TestBucket_Get_Capacity(t *testing.T) {
db := MustOpenDB()
defer db.MustClose()
// Write key to a bucket.
if err := db.Update(func(tx *bolt.Tx) error {
b, err := tx.CreateBucket([]byte("bucket"))
if err != nil {
return err
}
return b.Put([]byte("key"), []byte("val"))
}); err != nil {
t.Fatal(err)
}
// Retrieve value and attempt to append to it.
if err := db.Update(func(tx *bolt.Tx) error {
k, v := tx.Bucket([]byte("bucket")).Cursor().First()
// Verify capacity.
if len(k) != cap(k) {
t.Fatalf("unexpected key slice capacity: %d", cap(k))
} else if len(v) != cap(v) {
t.Fatalf("unexpected value slice capacity: %d", cap(v))
}
// Ensure slice can be appended to without a segfault.
k = append(k, []byte("123")...)
v = append(v, []byte("123")...)
return nil
}); err != nil {
t.Fatal(err)
}
}
// Ensure that a bucket can write a key/value.
func TestBucket_Put(t *testing.T) {
db := MustOpenDB()
defer db.MustClose()
if err := db.Update(func(tx *bolt.Tx) error {
b, err := tx.CreateBucket([]byte("widgets"))
if err != nil {
t.Fatal(err)
}
if err := b.Put([]byte("foo"), []byte("bar")); err != nil {
t.Fatal(err)
}
v := tx.Bucket([]byte("widgets")).Get([]byte("foo"))
if !bytes.Equal([]byte("bar"), v) {
t.Fatalf("unexpected value: %v", v)
}
return nil
}); err != nil {
t.Fatal(err)
}
}
// Ensure that a bucket can rewrite a key in the same transaction.
func TestBucket_Put_Repeat(t *testing.T) {
db := MustOpenDB()
defer db.MustClose()
if err := db.Update(func(tx *bolt.Tx) error {
b, err := tx.CreateBucket([]byte("widgets"))
if err != nil {
t.Fatal(err)
}
if err := b.Put([]byte("foo"), []byte("bar")); err != nil {
t.Fatal(err)
}
if err := b.Put([]byte("foo"), []byte("baz")); err != nil {
t.Fatal(err)
}
value := tx.Bucket([]byte("widgets")).Get([]byte("foo"))
if !bytes.Equal([]byte("baz"), value) {
t.Fatalf("unexpected value: %v", value)
}
return nil
}); err != nil {
t.Fatal(err)
}
}
// Ensure that a bucket can write a bunch of large values.
func TestBucket_Put_Large(t *testing.T) {
db := MustOpenDB()
defer db.MustClose()
count, factor := 100, 200
if err := db.Update(func(tx *bolt.Tx) error {
b, err := tx.CreateBucket([]byte("widgets"))
if err != nil {
t.Fatal(err)
}
for i := 1; i < count; i++ {
if err := b.Put([]byte(strings.Repeat("0", i*factor)), []byte(strings.Repeat("X", (count-i)*factor))); err != nil {
t.Fatal(err)
}
}
return nil
}); err != nil {
t.Fatal(err)
}
if err := db.View(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte("widgets"))
for i := 1; i < count; i++ {
value := b.Get([]byte(strings.Repeat("0", i*factor)))
if !bytes.Equal(value, []byte(strings.Repeat("X", (count-i)*factor))) {
t.Fatalf("unexpected value: %v", value)
}
}
return nil
}); err != nil {
t.Fatal(err)
}
}
// Ensure that a database can perform multiple large appends safely.
func TestDB_Put_VeryLarge(t *testing.T) {
if testing.Short() {
t.Skip("skipping test in short mode.")
}
n, batchN := 400000, 200000
ksize, vsize := 8, 500
db := MustOpenDB()
defer db.MustClose()
for i := 0; i < n; i += batchN {
if err := db.Update(func(tx *bolt.Tx) error {
b, err := tx.CreateBucketIfNotExists([]byte("widgets"))
if err != nil {
t.Fatal(err)
}
for j := 0; j < batchN; j++ {
k, v := make([]byte, ksize), make([]byte, vsize)
binary.BigEndian.PutUint32(k, uint32(i+j))
if err := b.Put(k, v); err != nil {
t.Fatal(err)
}
}
return nil
}); err != nil {
t.Fatal(err)
}
}
}
// Ensure that a setting a value on a key with a bucket value returns an error.
func TestBucket_Put_IncompatibleValue(t *testing.T) {
db := MustOpenDB()
defer db.MustClose()
if err := db.Update(func(tx *bolt.Tx) error {
b0, err := tx.CreateBucket([]byte("widgets"))
if err != nil {
t.Fatal(err)
}
if _, err := tx.Bucket([]byte("widgets")).CreateBucket([]byte("foo")); err != nil {
t.Fatal(err)
}
if err := b0.Put([]byte("foo"), []byte("bar")); err != bolt.ErrIncompatibleValue {
t.Fatalf("unexpected error: %s", err)
}
return nil
}); err != nil {
t.Fatal(err)
}
}
// Ensure that a setting a value while the transaction is closed returns an error.
func TestBucket_Put_Closed(t *testing.T) {
db := MustOpenDB()
defer db.MustClose()
tx, err := db.Begin(true)
if err != nil {
t.Fatal(err)
}
b, err := tx.CreateBucket([]byte("widgets"))
if err != nil {
t.Fatal(err)
}
if err := tx.Rollback(); err != nil {
t.Fatal(err)
}
if err := b.Put([]byte("foo"), []byte("bar")); err != bolt.ErrTxClosed {
t.Fatalf("unexpected error: %s", err)
}
}
// Ensure that setting a value on a read-only bucket returns an error.
func TestBucket_Put_ReadOnly(t *testing.T) {
db := MustOpenDB()
defer db.MustClose()
if err := db.Update(func(tx *bolt.Tx) error {
if _, err := tx.CreateBucket([]byte("widgets")); err != nil {
t.Fatal(err)
}
return nil
}); err != nil {
t.Fatal(err)
}
if err := db.View(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte("widgets"))
if err := b.Put([]byte("foo"), []byte("bar")); err != bolt.ErrTxNotWritable {
t.Fatalf("unexpected error: %s", err)
}
return nil
}); err != nil {
t.Fatal(err)
}
}
// Ensure that a bucket can delete an existing key.
func TestBucket_Delete(t *testing.T) {
db := MustOpenDB()
defer db.MustClose()
if err := db.Update(func(tx *bolt.Tx) error {
b, err := tx.CreateBucket([]byte("widgets"))
if err != nil {
t.Fatal(err)
}
if err := b.Put([]byte("foo"), []byte("bar")); err != nil {
t.Fatal(err)
}
if err := b.Delete([]byte("foo")); err != nil {
t.Fatal(err)
}
if v := b.Get([]byte("foo")); v != nil {
t.Fatalf("unexpected value: %v", v)
}
return nil
}); err != nil {
t.Fatal(err)
}
}
// Ensure that deleting a large set of keys will work correctly.
func TestBucket_Delete_Large(t *testing.T) {
db := MustOpenDB()
defer db.MustClose()
if err := db.Update(func(tx *bolt.Tx) error {
b, err := tx.CreateBucket([]byte("widgets"))
if err != nil {
t.Fatal(err)
}
for i := 0; i < 100; i++ {
if err := b.Put([]byte(strconv.Itoa(i)), []byte(strings.Repeat("*", 1024))); err != nil {
t.Fatal(err)
}
}
return nil
}); err != nil {
t.Fatal(err)
}
if err := db.Update(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte("widgets"))
for i := 0; i < 100; i++ {
if err := b.Delete([]byte(strconv.Itoa(i))); err != nil {
t.Fatal(err)
}
}
return nil
}); err != nil {
t.Fatal(err)
}
if err := db.View(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte("widgets"))
for i := 0; i < 100; i++ {
if v := b.Get([]byte(strconv.Itoa(i))); v != nil {
t.Fatalf("unexpected value: %v, i=%d", v, i)
}
}
return nil
}); err != nil {
t.Fatal(err)
}
}
// Deleting a very large list of keys will cause the freelist to use overflow.
func TestBucket_Delete_FreelistOverflow(t *testing.T) {
if testing.Short() {
t.Skip("skipping test in short mode.")
}
db := MustOpenDB()
defer db.MustClose()
k := make([]byte, 16)
for i := uint64(0); i < 10000; i++ {
if err := db.Update(func(tx *bolt.Tx) error {
b, err := tx.CreateBucketIfNotExists([]byte("0"))
if err != nil {
t.Fatalf("bucket error: %s", err)
}
for j := uint64(0); j < 1000; j++ {
binary.BigEndian.PutUint64(k[:8], i)
binary.BigEndian.PutUint64(k[8:], j)
if err := b.Put(k, nil); err != nil {
t.Fatalf("put error: %s", err)
}
}
return nil
}); err != nil {
t.Fatal(err)
}
}
// Delete all of them in one large transaction
if err := db.Update(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte("0"))
c := b.Cursor()
for k, _ := c.First(); k != nil; k, _ = c.Next() {
if err := c.Delete(); err != nil {
t.Fatal(err)
}
}
return nil
}); err != nil {
t.Fatal(err)
}
}
// Ensure that accessing and updating nested buckets is ok across transactions.
func TestBucket_Nested(t *testing.T) {
db := MustOpenDB()
defer db.MustClose()
if err := db.Update(func(tx *bolt.Tx) error {
// Create a widgets bucket.
b, err := tx.CreateBucket([]byte("widgets"))
if err != nil {
t.Fatal(err)
}
// Create a widgets/foo bucket.
_, err = b.CreateBucket([]byte("foo"))
if err != nil {
t.Fatal(err)
}
// Create a widgets/bar key.
if err := b.Put([]byte("bar"), []byte("0000")); err != nil {
t.Fatal(err)
}
return nil
}); err != nil {
t.Fatal(err)
}
db.MustCheck()
// Update widgets/bar.
if err := db.Update(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte("widgets"))
if err := b.Put([]byte("bar"), []byte("xxxx")); err != nil {
t.Fatal(err)
}
return nil
}); err != nil {
t.Fatal(err)
}
db.MustCheck()
// Cause a split.
if err := db.Update(func(tx *bolt.Tx) error {
var b = tx.Bucket([]byte("widgets"))
for i := 0; i < 10000; i++ {
if err := b.Put([]byte(strconv.Itoa(i)), []byte(strconv.Itoa(i))); err != nil {
t.Fatal(err)
}
}
return nil
}); err != nil {
t.Fatal(err)
}
db.MustCheck()
// Insert into widgets/foo/baz.
if err := db.Update(func(tx *bolt.Tx) error {
var b = tx.Bucket([]byte("widgets"))
if err := b.Bucket([]byte("foo")).Put([]byte("baz"), []byte("yyyy")); err != nil {
t.Fatal(err)
}
return nil
}); err != nil {
t.Fatal(err)
}
db.MustCheck()
// Verify.
if err := db.View(func(tx *bolt.Tx) error {
var b = tx.Bucket([]byte("widgets"))
if v := b.Bucket([]byte("foo")).Get([]byte("baz")); !bytes.Equal(v, []byte("yyyy")) {
t.Fatalf("unexpected value: %v", v)
}
if v := b.Get([]byte("bar")); !bytes.Equal(v, []byte("xxxx")) {
t.Fatalf("unexpected value: %v", v)
}
for i := 0; i < 10000; i++ {
if v := b.Get([]byte(strconv.Itoa(i))); !bytes.Equal(v, []byte(strconv.Itoa(i))) {
t.Fatalf("unexpected value: %v", v)
}
}
return nil
}); err != nil {
t.Fatal(err)
}
}
// Ensure that deleting a bucket using Delete() returns an error.
func TestBucket_Delete_Bucket(t *testing.T) {
db := MustOpenDB()
defer db.MustClose()
if err := db.Update(func(tx *bolt.Tx) error {
b, err := tx.CreateBucket([]byte("widgets"))
if err != nil {
t.Fatal(err)
}
if _, err := b.CreateBucket([]byte("foo")); err != nil {
t.Fatal(err)
}
if err := b.Delete([]byte("foo")); err != bolt.ErrIncompatibleValue {
t.Fatalf("unexpected error: %s", err)
}
return nil
}); err != nil {
t.Fatal(err)
}
}
// Ensure that deleting a key on a read-only bucket returns an error.
func TestBucket_Delete_ReadOnly(t *testing.T) {
db := MustOpenDB()
defer db.MustClose()
if err := db.Update(func(tx *bolt.Tx) error {
if _, err := tx.CreateBucket([]byte("widgets")); err != nil {
t.Fatal(err)
}
return nil
}); err != nil {
t.Fatal(err)
}
if err := db.View(func(tx *bolt.Tx) error {
if err := tx.Bucket([]byte("widgets")).Delete([]byte("foo")); err != bolt.ErrTxNotWritable {
t.Fatalf("unexpected error: %s", err)
}
return nil
}); err != nil {
t.Fatal(err)
}
}
// Ensure that a deleting value while the transaction is closed returns an error.
func TestBucket_Delete_Closed(t *testing.T) {
db := MustOpenDB()
defer db.MustClose()
tx, err := db.Begin(true)
if err != nil {
t.Fatal(err)
}
b, err := tx.CreateBucket([]byte("widgets"))
if err != nil {
t.Fatal(err)
}
if err := tx.Rollback(); err != nil {
t.Fatal(err)
}
if err := b.Delete([]byte("foo")); err != bolt.ErrTxClosed {
t.Fatalf("unexpected error: %s", err)
}
}
// Ensure that deleting a bucket causes nested buckets to be deleted.
func TestBucket_DeleteBucket_Nested(t *testing.T) {
db := MustOpenDB()
defer db.MustClose()
if err := db.Update(func(tx *bolt.Tx) error {
widgets, err := tx.CreateBucket([]byte("widgets"))
if err != nil {
t.Fatal(err)
}
foo, err := widgets.CreateBucket([]byte("foo"))
if err != nil {
t.Fatal(err)
}
bar, err := foo.CreateBucket([]byte("bar"))
if err != nil {
t.Fatal(err)
}
if err := bar.Put([]byte("baz"), []byte("bat")); err != nil {
t.Fatal(err)
}
if err := tx.Bucket([]byte("widgets")).DeleteBucket([]byte("foo")); err != nil {
t.Fatal(err)
}
return nil
}); err != nil {
t.Fatal(err)
}
}
// Ensure that deleting a bucket causes nested buckets to be deleted after they have been committed.
func TestBucket_DeleteBucket_Nested2(t *testing.T) {
db := MustOpenDB()
defer db.MustClose()
if err := db.Update(func(tx *bolt.Tx) error {
widgets, err := tx.CreateBucket([]byte("widgets"))
if err != nil {
t.Fatal(err)
}
foo, err := widgets.CreateBucket([]byte("foo"))
if err != nil {
t.Fatal(err)
}
bar, err := foo.CreateBucket([]byte("bar"))
if err != nil {
t.Fatal(err)
}
if err := bar.Put([]byte("baz"), []byte("bat")); err != nil {
t.Fatal(err)
}
return nil
}); err != nil {
t.Fatal(err)
}
if err := db.Update(func(tx *bolt.Tx) error {
widgets := tx.Bucket([]byte("widgets"))
if widgets == nil {
t.Fatal("expected widgets bucket")
}
foo := widgets.Bucket([]byte("foo"))
if foo == nil {
t.Fatal("expected foo bucket")
}
bar := foo.Bucket([]byte("bar"))
if bar == nil {
t.Fatal("expected bar bucket")
}
if v := bar.Get([]byte("baz")); !bytes.Equal(v, []byte("bat")) {
t.Fatalf("unexpected value: %v", v)
}
if err := tx.DeleteBucket([]byte("widgets")); err != nil {
t.Fatal(err)
}
return nil
}); err != nil {
t.Fatal(err)
}
if err := db.View(func(tx *bolt.Tx) error {
if tx.Bucket([]byte("widgets")) != nil {
t.Fatal("expected bucket to be deleted")
}
return nil
}); err != nil {
t.Fatal(err)
}
}
// Ensure that deleting a child bucket with multiple pages causes all pages to get collected.
// NOTE: Consistency check in bolt_test.DB.Close() will panic if pages not freed properly.
func TestBucket_DeleteBucket_Large(t *testing.T) {
db := MustOpenDB()
defer db.MustClose()
if err := db.Update(func(tx *bolt.Tx) error {
widgets, err := tx.CreateBucket([]byte("widgets"))
if err != nil {
t.Fatal(err)
}
foo, err := widgets.CreateBucket([]byte("foo"))
if err != nil {
t.Fatal(err)
}
for i := 0; i < 1000; i++ {
if err := foo.Put([]byte(fmt.Sprintf("%d", i)), []byte(fmt.Sprintf("%0100d", i))); err != nil {
t.Fatal(err)
}
}
return nil
}); err != nil {
t.Fatal(err)
}
if err := db.Update(func(tx *bolt.Tx) error {
if err := tx.DeleteBucket([]byte("widgets")); err != nil {
t.Fatal(err)
}
return nil
}); err != nil {
t.Fatal(err)
}
}
// Ensure that a simple value retrieved via Bucket() returns a nil.
func TestBucket_Bucket_IncompatibleValue(t *testing.T) {
db := MustOpenDB()
defer db.MustClose()
if err := db.Update(func(tx *bolt.Tx) error {
widgets, err := tx.CreateBucket([]byte("widgets"))
if err != nil {
t.Fatal(err)
}
if err := widgets.Put([]byte("foo"), []byte("bar")); err != nil {
t.Fatal(err)
}
if b := tx.Bucket([]byte("widgets")).Bucket([]byte("foo")); b != nil {
t.Fatal("expected nil bucket")
}
return nil
}); err != nil {
t.Fatal(err)
}
}
// Ensure that creating a bucket on an existing non-bucket key returns an error.
func TestBucket_CreateBucket_IncompatibleValue(t *testing.T) {
db := MustOpenDB()
defer db.MustClose()
if err := db.Update(func(tx *bolt.Tx) error {
widgets, err := tx.CreateBucket([]byte("widgets"))
if err != nil {
t.Fatal(err)
}
if err := widgets.Put([]byte("foo"), []byte("bar")); err != nil {
t.Fatal(err)
}
if _, err := widgets.CreateBucket([]byte("foo")); err != bolt.ErrIncompatibleValue {
t.Fatalf("unexpected error: %s", err)
}
return nil
}); err != nil {
t.Fatal(err)
}
}
// Ensure that deleting a bucket on an existing non-bucket key returns an error.
func TestBucket_DeleteBucket_IncompatibleValue(t *testing.T) {
db := MustOpenDB()
defer db.MustClose()
if err := db.Update(func(tx *bolt.Tx) error {
widgets, err := tx.CreateBucket([]byte("widgets"))
if err != nil {
t.Fatal(err)
}
if err := widgets.Put([]byte("foo"), []byte("bar")); err != nil {
t.Fatal(err)
}
if err := tx.Bucket([]byte("widgets")).DeleteBucket([]byte("foo")); err != bolt.ErrIncompatibleValue {
t.Fatalf("unexpected error: %s", err)
}
return nil
}); err != nil {
t.Fatal(err)
}
}
// Ensure bucket can set and update its sequence number.
func TestBucket_Sequence(t *testing.T) {
db := MustOpenDB()
defer db.MustClose()
if err := db.Update(func(tx *bolt.Tx) error {
bkt, err := tx.CreateBucket([]byte("0"))
if err != nil {
t.Fatal(err)
}
// Retrieve sequence.
if v := bkt.Sequence(); v != 0 {
t.Fatalf("unexpected sequence: %d", v)
}
// Update sequence.
if err := bkt.SetSequence(1000); err != nil {
t.Fatal(err)
}
// Read sequence again.
if v := bkt.Sequence(); v != 1000 {
t.Fatalf("unexpected sequence: %d", v)
}
return nil
}); err != nil {
t.Fatal(err)
}
// Verify sequence in separate transaction.
if err := db.View(func(tx *bolt.Tx) error {
if v := tx.Bucket([]byte("0")).Sequence(); v != 1000 {
t.Fatalf("unexpected sequence: %d", v)
}
return nil
}); err != nil {
t.Fatal(err)
}
}
// Ensure that a bucket can return an autoincrementing sequence.
func TestBucket_NextSequence(t *testing.T) {
db := MustOpenDB()
defer db.MustClose()
if err := db.Update(func(tx *bolt.Tx) error {
widgets, err := tx.CreateBucket([]byte("widgets"))
if err != nil {
t.Fatal(err)
}
woojits, err := tx.CreateBucket([]byte("woojits"))
if err != nil {
t.Fatal(err)
}
// Make sure sequence increments.
if seq, err := widgets.NextSequence(); err != nil {
t.Fatal(err)
} else if seq != 1 {
t.Fatalf("unexpecte sequence: %d", seq)
}
if seq, err := widgets.NextSequence(); err != nil {
t.Fatal(err)
} else if seq != 2 {
t.Fatalf("unexpected sequence: %d", seq)
}
// Buckets should be separate.
if seq, err := woojits.NextSequence(); err != nil {
t.Fatal(err)
} else if seq != 1 {
t.Fatalf("unexpected sequence: %d", 1)
}
return nil
}); err != nil {
t.Fatal(err)
}
}
// Ensure that a bucket will persist an autoincrementing sequence even if its
// the only thing updated on the bucket.
// https://github.com/boltdb/bolt/issues/296
func TestBucket_NextSequence_Persist(t *testing.T) {
db := MustOpenDB()
defer db.MustClose()
if err := db.Update(func(tx *bolt.Tx) error {
if _, err := tx.CreateBucket([]byte("widgets")); err != nil {
t.Fatal(err)
}
return nil
}); err != nil {
t.Fatal(err)
}
if err := db.Update(func(tx *bolt.Tx) error {
if _, err := tx.Bucket([]byte("widgets")).NextSequence(); err != nil {
t.Fatal(err)
}
return nil
}); err != nil {
t.Fatal(err)
}
if err := db.Update(func(tx *bolt.Tx) error {
seq, err := tx.Bucket([]byte("widgets")).NextSequence()
if err != nil {
t.Fatalf("unexpected error: %s", err)
} else if seq != 2 {
t.Fatalf("unexpected sequence: %d", seq)
}
return nil
}); err != nil {
t.Fatal(err)
}
}
// Ensure that retrieving the next sequence on a read-only bucket returns an error.
func TestBucket_NextSequence_ReadOnly(t *testing.T) {
db := MustOpenDB()
defer db.MustClose()
if err := db.Update(func(tx *bolt.Tx) error {
if _, err := tx.CreateBucket([]byte("widgets")); err != nil {
t.Fatal(err)
}
return nil
}); err != nil {
t.Fatal(err)
}
if err := db.View(func(tx *bolt.Tx) error {
_, err := tx.Bucket([]byte("widgets")).NextSequence()
if err != bolt.ErrTxNotWritable {
t.Fatalf("unexpected error: %s", err)
}
return nil
}); err != nil {
t.Fatal(err)
}
}
// Ensure that retrieving the next sequence for a bucket on a closed database return an error.
func TestBucket_NextSequence_Closed(t *testing.T) {
db := MustOpenDB()
defer db.MustClose()
tx, err := db.Begin(true)
if err != nil {
t.Fatal(err)
}
b, err := tx.CreateBucket([]byte("widgets"))
if err != nil {
t.Fatal(err)
}
if err := tx.Rollback(); err != nil {
t.Fatal(err)
}
if _, err := b.NextSequence(); err != bolt.ErrTxClosed {
t.Fatal(err)
}
}
// Ensure a user can loop over all key/value pairs in a bucket.
func TestBucket_ForEach(t *testing.T) {
db := MustOpenDB()
defer db.MustClose()
if err := db.Update(func(tx *bolt.Tx) error {
b, err := tx.CreateBucket([]byte("widgets"))
if err != nil {
t.Fatal(err)
}
if err := b.Put([]byte("foo"), []byte("0000")); err != nil {
t.Fatal(err)
}
if err := b.Put([]byte("baz"), []byte("0001")); err != nil {
t.Fatal(err)
}
if err := b.Put([]byte("bar"), []byte("0002")); err != nil {
t.Fatal(err)
}
var index int
if err := b.ForEach(func(k, v []byte) error {
switch index {
case 0:
if !bytes.Equal(k, []byte("bar")) {
t.Fatalf("unexpected key: %v", k)
} else if !bytes.Equal(v, []byte("0002")) {
t.Fatalf("unexpected value: %v", v)
}
case 1:
if !bytes.Equal(k, []byte("baz")) {
t.Fatalf("unexpected key: %v", k)
} else if !bytes.Equal(v, []byte("0001")) {
t.Fatalf("unexpected value: %v", v)
}
case 2:
if !bytes.Equal(k, []byte("foo")) {
t.Fatalf("unexpected key: %v", k)
} else if !bytes.Equal(v, []byte("0000")) {
t.Fatalf("unexpected value: %v", v)
}
}
index++
return nil
}); err != nil {
t.Fatal(err)
}
if index != 3 {
t.Fatalf("unexpected index: %d", index)
}
return nil
}); err != nil {
t.Fatal(err)
}
}
// Ensure a database can stop iteration early.
func TestBucket_ForEach_ShortCircuit(t *testing.T) {
db := MustOpenDB()
defer db.MustClose()
if err := db.Update(func(tx *bolt.Tx) error {
b, err := tx.CreateBucket([]byte("widgets"))
if err != nil {
t.Fatal(err)
}
if err := b.Put([]byte("bar"), []byte("0000")); err != nil {
t.Fatal(err)
}
if err := b.Put([]byte("baz"), []byte("0000")); err != nil {
t.Fatal(err)
}
if err := b.Put([]byte("foo"), []byte("0000")); err != nil {
t.Fatal(err)
}
var index int
if err := tx.Bucket([]byte("widgets")).ForEach(func(k, v []byte) error {
index++
if bytes.Equal(k, []byte("baz")) {
return errors.New("marker")
}
return nil
}); err == nil || err.Error() != "marker" {
t.Fatalf("unexpected error: %s", err)
}
if index != 2 {
t.Fatalf("unexpected index: %d", index)
}
return nil
}); err != nil {
t.Fatal(err)
}
}
// Ensure that looping over a bucket on a closed database returns an error.
func TestBucket_ForEach_Closed(t *testing.T) {
db := MustOpenDB()
defer db.MustClose()
tx, err := db.Begin(true)
if err != nil {
t.Fatal(err)
}
b, err := tx.CreateBucket([]byte("widgets"))
if err != nil {
t.Fatal(err)
}
if err := tx.Rollback(); err != nil {
t.Fatal(err)
}
if err := b.ForEach(func(k, v []byte) error { return nil }); err != bolt.ErrTxClosed {
t.Fatalf("unexpected error: %s", err)
}
}
// Ensure that an error is returned when inserting with an empty key.
func TestBucket_Put_EmptyKey(t *testing.T) {
db := MustOpenDB()
defer db.MustClose()
if err := db.Update(func(tx *bolt.Tx) error {
b, err := tx.CreateBucket([]byte("widgets"))
if err != nil {
t.Fatal(err)
}
if err := b.Put([]byte(""), []byte("bar")); err != bolt.ErrKeyRequired {
t.Fatalf("unexpected error: %s", err)
}
if err := b.Put(nil, []byte("bar")); err != bolt.ErrKeyRequired {
t.Fatalf("unexpected error: %s", err)
}
return nil
}); err != nil {
t.Fatal(err)
}
}
// Ensure that an error is returned when inserting with a key that's too large.
func TestBucket_Put_KeyTooLarge(t *testing.T) {
db := MustOpenDB()
defer db.MustClose()
if err := db.Update(func(tx *bolt.Tx) error {
b, err := tx.CreateBucket([]byte("widgets"))
if err != nil {
t.Fatal(err)
}
if err := b.Put(make([]byte, 32769), []byte("bar")); err != bolt.ErrKeyTooLarge {
t.Fatalf("unexpected error: %s", err)
}
return nil
}); err != nil {
t.Fatal(err)
}
}
// Ensure that an error is returned when inserting a value that's too large.
func TestBucket_Put_ValueTooLarge(t *testing.T) {
// Skip this test on DroneCI because the machine is resource constrained.
if os.Getenv("DRONE") == "true" {
t.Skip("not enough RAM for test")
}
db := MustOpenDB()
defer db.MustClose()
if err := db.Update(func(tx *bolt.Tx) error {
b, err := tx.CreateBucket([]byte("widgets"))
if err != nil {
t.Fatal(err)
}
if err := b.Put([]byte("foo"), make([]byte, bolt.MaxValueSize+1)); err != bolt.ErrValueTooLarge {
t.Fatalf("unexpected error: %s", err)
}
return nil
}); err != nil {
t.Fatal(err)
}
}
// Ensure a bucket can calculate stats.
func TestBucket_Stats(t *testing.T) {
db := MustOpenDB()
defer db.MustClose()
// Add bucket with fewer keys but one big value.
bigKey := []byte("really-big-value")
for i := 0; i < 500; i++ {
if err := db.Update(func(tx *bolt.Tx) error {
b, err := tx.CreateBucketIfNotExists([]byte("woojits"))
if err != nil {
t.Fatal(err)
}
if err := b.Put([]byte(fmt.Sprintf("%03d", i)), []byte(strconv.Itoa(i))); err != nil {
t.Fatal(err)
}
return nil
}); err != nil {
t.Fatal(err)
}
}
if err := db.Update(func(tx *bolt.Tx) error {
if err := tx.Bucket([]byte("woojits")).Put(bigKey, []byte(strings.Repeat("*", 10000))); err != nil {
t.Fatal(err)
}
return nil
}); err != nil {
t.Fatal(err)
}
db.MustCheck()
if err := db.View(func(tx *bolt.Tx) error {
stats := tx.Bucket([]byte("woojits")).Stats()
if stats.BranchPageN != 1 {
t.Fatalf("unexpected BranchPageN: %d", stats.BranchPageN)
} else if stats.BranchOverflowN != 0 {
t.Fatalf("unexpected BranchOverflowN: %d", stats.BranchOverflowN)
} else if stats.LeafPageN != 7 {
t.Fatalf("unexpected LeafPageN: %d", stats.LeafPageN)
} else if stats.LeafOverflowN != 2 {
t.Fatalf("unexpected LeafOverflowN: %d", stats.LeafOverflowN)
} else if stats.KeyN != 501 {
t.Fatalf("unexpected KeyN: %d", stats.KeyN)
} else if stats.Depth != 2 {
t.Fatalf("unexpected Depth: %d", stats.Depth)
}
branchInuse := 16 // branch page header
branchInuse += 7 * 16 // branch elements
branchInuse += 7 * 3 // branch keys (6 3-byte keys)
if stats.BranchInuse != branchInuse {
t.Fatalf("unexpected BranchInuse: %d", stats.BranchInuse)
}
leafInuse := 7 * 16 // leaf page header
leafInuse += 501 * 16 // leaf elements
leafInuse += 500*3 + len(bigKey) // leaf keys
leafInuse += 1*10 + 2*90 + 3*400 + 10000 // leaf values
if stats.LeafInuse != leafInuse {
t.Fatalf("unexpected LeafInuse: %d", stats.LeafInuse)
}
// Only check allocations for 4KB pages.
if os.Getpagesize() == 4096 {
if stats.BranchAlloc != 4096 {
t.Fatalf("unexpected BranchAlloc: %d", stats.BranchAlloc)
} else if stats.LeafAlloc != 36864 {
t.Fatalf("unexpected LeafAlloc: %d", stats.LeafAlloc)
}
}
if stats.BucketN != 1 {
t.Fatalf("unexpected BucketN: %d", stats.BucketN)
} else if stats.InlineBucketN != 0 {
t.Fatalf("unexpected InlineBucketN: %d", stats.InlineBucketN)
} else if stats.InlineBucketInuse != 0 {
t.Fatalf("unexpected InlineBucketInuse: %d", stats.InlineBucketInuse)
}
return nil
}); err != nil {
t.Fatal(err)
}
}
// Ensure a bucket with random insertion utilizes fill percentage correctly.
func TestBucket_Stats_RandomFill(t *testing.T) {
if testing.Short() {
t.Skip("skipping test in short mode.")
} else if os.Getpagesize() != 4096 {
t.Skip("invalid page size for test")
}
db := MustOpenDB()
defer db.MustClose()
// Add a set of values in random order. It will be the same random
// order so we can maintain consistency between test runs.
var count int
rand := rand.New(rand.NewSource(42))
for _, i := range rand.Perm(1000) {
if err := db.Update(func(tx *bolt.Tx) error {
b, err := tx.CreateBucketIfNotExists([]byte("woojits"))
if err != nil {
t.Fatal(err)
}
b.FillPercent = 0.9
for _, j := range rand.Perm(100) {
index := (j * 10000) + i
if err := b.Put([]byte(fmt.Sprintf("%d000000000000000", index)), []byte("0000000000")); err != nil {
t.Fatal(err)
}
count++
}
return nil
}); err != nil {
t.Fatal(err)
}
}
db.MustCheck()
if err := db.View(func(tx *bolt.Tx) error {
stats := tx.Bucket([]byte("woojits")).Stats()
if stats.KeyN != 100000 {
t.Fatalf("unexpected KeyN: %d", stats.KeyN)
}
if stats.BranchPageN != 98 {
t.Fatalf("unexpected BranchPageN: %d", stats.BranchPageN)
} else if stats.BranchOverflowN != 0 {
t.Fatalf("unexpected BranchOverflowN: %d", stats.BranchOverflowN)
} else if stats.BranchInuse != 130984 {
t.Fatalf("unexpected BranchInuse: %d", stats.BranchInuse)
} else if stats.BranchAlloc != 401408 {
t.Fatalf("unexpected BranchAlloc: %d", stats.BranchAlloc)
}
if stats.LeafPageN != 3412 {
t.Fatalf("unexpected LeafPageN: %d", stats.LeafPageN)
} else if stats.LeafOverflowN != 0 {
t.Fatalf("unexpected LeafOverflowN: %d", stats.LeafOverflowN)
} else if stats.LeafInuse != 4742482 {
t.Fatalf("unexpected LeafInuse: %d", stats.LeafInuse)
} else if stats.LeafAlloc != 13975552 {
t.Fatalf("unexpected LeafAlloc: %d", stats.LeafAlloc)
}
return nil
}); err != nil {
t.Fatal(err)
}
}
// Ensure a bucket can calculate stats.
func TestBucket_Stats_Small(t *testing.T) {
db := MustOpenDB()
defer db.MustClose()
if err := db.Update(func(tx *bolt.Tx) error {
// Add a bucket that fits on a single root leaf.
b, err := tx.CreateBucket([]byte("whozawhats"))
if err != nil {
t.Fatal(err)
}
if err := b.Put([]byte("foo"), []byte("bar")); err != nil {
t.Fatal(err)
}
return nil
}); err != nil {
t.Fatal(err)
}
db.MustCheck()
if err := db.View(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte("whozawhats"))
stats := b.Stats()
if stats.BranchPageN != 0 {
t.Fatalf("unexpected BranchPageN: %d", stats.BranchPageN)
} else if stats.BranchOverflowN != 0 {
t.Fatalf("unexpected BranchOverflowN: %d", stats.BranchOverflowN)
} else if stats.LeafPageN != 0 {
t.Fatalf("unexpected LeafPageN: %d", stats.LeafPageN)
} else if stats.LeafOverflowN != 0 {
t.Fatalf("unexpected LeafOverflowN: %d", stats.LeafOverflowN)
} else if stats.KeyN != 1 {
t.Fatalf("unexpected KeyN: %d", stats.KeyN)
} else if stats.Depth != 1 {
t.Fatalf("unexpected Depth: %d", stats.Depth)
} else if stats.BranchInuse != 0 {
t.Fatalf("unexpected BranchInuse: %d", stats.BranchInuse)
} else if stats.LeafInuse != 0 {
t.Fatalf("unexpected LeafInuse: %d", stats.LeafInuse)
}
if os.Getpagesize() == 4096 {
if stats.BranchAlloc != 0 {
t.Fatalf("unexpected BranchAlloc: %d", stats.BranchAlloc)
} else if stats.LeafAlloc != 0 {
t.Fatalf("unexpected LeafAlloc: %d", stats.LeafAlloc)
}
}
if stats.BucketN != 1 {
t.Fatalf("unexpected BucketN: %d", stats.BucketN)
} else if stats.InlineBucketN != 1 {
t.Fatalf("unexpected InlineBucketN: %d", stats.InlineBucketN)
} else if stats.InlineBucketInuse != 16+16+6 {
t.Fatalf("unexpected InlineBucketInuse: %d", stats.InlineBucketInuse)
}
return nil
}); err != nil {
t.Fatal(err)
}
}
func TestBucket_Stats_EmptyBucket(t *testing.T) {
db := MustOpenDB()
defer db.MustClose()
if err := db.Update(func(tx *bolt.Tx) error {
// Add a bucket that fits on a single root leaf.
if _, err := tx.CreateBucket([]byte("whozawhats")); err != nil {
t.Fatal(err)
}
return nil
}); err != nil {
t.Fatal(err)
}
db.MustCheck()
if err := db.View(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte("whozawhats"))
stats := b.Stats()
if stats.BranchPageN != 0 {
t.Fatalf("unexpected BranchPageN: %d", stats.BranchPageN)
} else if stats.BranchOverflowN != 0 {
t.Fatalf("unexpected BranchOverflowN: %d", stats.BranchOverflowN)
} else if stats.LeafPageN != 0 {
t.Fatalf("unexpected LeafPageN: %d", stats.LeafPageN)
} else if stats.LeafOverflowN != 0 {
t.Fatalf("unexpected LeafOverflowN: %d", stats.LeafOverflowN)
} else if stats.KeyN != 0 {
t.Fatalf("unexpected KeyN: %d", stats.KeyN)
} else if stats.Depth != 1 {
t.Fatalf("unexpected Depth: %d", stats.Depth)
} else if stats.BranchInuse != 0 {
t.Fatalf("unexpected BranchInuse: %d", stats.BranchInuse)
} else if stats.LeafInuse != 0 {
t.Fatalf("unexpected LeafInuse: %d", stats.LeafInuse)
}
if os.Getpagesize() == 4096 {
if stats.BranchAlloc != 0 {
t.Fatalf("unexpected BranchAlloc: %d", stats.BranchAlloc)
} else if stats.LeafAlloc != 0 {
t.Fatalf("unexpected LeafAlloc: %d", stats.LeafAlloc)
}
}
if stats.BucketN != 1 {
t.Fatalf("unexpected BucketN: %d", stats.BucketN)
} else if stats.InlineBucketN != 1 {
t.Fatalf("unexpected InlineBucketN: %d", stats.InlineBucketN)
} else if stats.InlineBucketInuse != 16 {
t.Fatalf("unexpected InlineBucketInuse: %d", stats.InlineBucketInuse)
}
return nil
}); err != nil {
t.Fatal(err)
}
}
// Ensure a bucket can calculate stats.
func TestBucket_Stats_Nested(t *testing.T) {
db := MustOpenDB()
defer db.MustClose()
if err := db.Update(func(tx *bolt.Tx) error {
b, err := tx.CreateBucket([]byte("foo"))
if err != nil {
t.Fatal(err)
}
for i := 0; i < 100; i++ {
if err := b.Put([]byte(fmt.Sprintf("%02d", i)), []byte(fmt.Sprintf("%02d", i))); err != nil {
t.Fatal(err)
}
}
bar, err := b.CreateBucket([]byte("bar"))
if err != nil {
t.Fatal(err)
}
for i := 0; i < 10; i++ {
if err := bar.Put([]byte(strconv.Itoa(i)), []byte(strconv.Itoa(i))); err != nil {
t.Fatal(err)
}
}
baz, err := bar.CreateBucket([]byte("baz"))
if err != nil {
t.Fatal(err)
}
for i := 0; i < 10; i++ {
if err := baz.Put([]byte(strconv.Itoa(i)), []byte(strconv.Itoa(i))); err != nil {
t.Fatal(err)
}
}
return nil
}); err != nil {
t.Fatal(err)
}
db.MustCheck()
if err := db.View(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte("foo"))
stats := b.Stats()
if stats.BranchPageN != 0 {
t.Fatalf("unexpected BranchPageN: %d", stats.BranchPageN)
} else if stats.BranchOverflowN != 0 {
t.Fatalf("unexpected BranchOverflowN: %d", stats.BranchOverflowN)
} else if stats.LeafPageN != 2 {
t.Fatalf("unexpected LeafPageN: %d", stats.LeafPageN)
} else if stats.LeafOverflowN != 0 {
t.Fatalf("unexpected LeafOverflowN: %d", stats.LeafOverflowN)
} else if stats.KeyN != 122 {
t.Fatalf("unexpected KeyN: %d", stats.KeyN)
} else if stats.Depth != 3 {
t.Fatalf("unexpected Depth: %d", stats.Depth)
} else if stats.BranchInuse != 0 {
t.Fatalf("unexpected BranchInuse: %d", stats.BranchInuse)
}
foo := 16 // foo (pghdr)
foo += 101 * 16 // foo leaf elements
foo += 100*2 + 100*2 // foo leaf key/values
foo += 3 + 16 // foo -> bar key/value
bar := 16 // bar (pghdr)
bar += 11 * 16 // bar leaf elements
bar += 10 + 10 // bar leaf key/values
bar += 3 + 16 // bar -> baz key/value
baz := 16 // baz (inline) (pghdr)
baz += 10 * 16 // baz leaf elements
baz += 10 + 10 // baz leaf key/values
if stats.LeafInuse != foo+bar+baz {
t.Fatalf("unexpected LeafInuse: %d", stats.LeafInuse)
}
if os.Getpagesize() == 4096 {
if stats.BranchAlloc != 0 {
t.Fatalf("unexpected BranchAlloc: %d", stats.BranchAlloc)
} else if stats.LeafAlloc != 8192 {
t.Fatalf("unexpected LeafAlloc: %d", stats.LeafAlloc)
}
}
if stats.BucketN != 3 {
t.Fatalf("unexpected BucketN: %d", stats.BucketN)
} else if stats.InlineBucketN != 1 {
t.Fatalf("unexpected InlineBucketN: %d", stats.InlineBucketN)
} else if stats.InlineBucketInuse != baz {
t.Fatalf("unexpected InlineBucketInuse: %d", stats.InlineBucketInuse)
}
return nil
}); err != nil {
t.Fatal(err)
}
}
// Ensure a large bucket can calculate stats.
func TestBucket_Stats_Large(t *testing.T) {
if testing.Short() {
t.Skip("skipping test in short mode.")
}
db := MustOpenDB()
defer db.MustClose()
var index int
for i := 0; i < 100; i++ {
// Add bucket with lots of keys.
if err := db.Update(func(tx *bolt.Tx) error {
b, err := tx.CreateBucketIfNotExists([]byte("widgets"))
if err != nil {
t.Fatal(err)
}
for i := 0; i < 1000; i++ {
if err := b.Put([]byte(strconv.Itoa(index)), []byte(strconv.Itoa(index))); err != nil {
t.Fatal(err)
}
index++
}
return nil
}); err != nil {
t.Fatal(err)
}
}
db.MustCheck()
if err := db.View(func(tx *bolt.Tx) error {
stats := tx.Bucket([]byte("widgets")).Stats()
if stats.BranchPageN != 13 {
t.Fatalf("unexpected BranchPageN: %d", stats.BranchPageN)
} else if stats.BranchOverflowN != 0 {
t.Fatalf("unexpected BranchOverflowN: %d", stats.BranchOverflowN)
} else if stats.LeafPageN != 1196 {
t.Fatalf("unexpected LeafPageN: %d", stats.LeafPageN)
} else if stats.LeafOverflowN != 0 {
t.Fatalf("unexpected LeafOverflowN: %d", stats.LeafOverflowN)
} else if stats.KeyN != 100000 {
t.Fatalf("unexpected KeyN: %d", stats.KeyN)
} else if stats.Depth != 3 {
t.Fatalf("unexpected Depth: %d", stats.Depth)
} else if stats.BranchInuse != 25257 {
t.Fatalf("unexpected BranchInuse: %d", stats.BranchInuse)
} else if stats.LeafInuse != 2596916 {
t.Fatalf("unexpected LeafInuse: %d", stats.LeafInuse)
}
if os.Getpagesize() == 4096 {
if stats.BranchAlloc != 53248 {
t.Fatalf("unexpected BranchAlloc: %d", stats.BranchAlloc)
} else if stats.LeafAlloc != 4898816 {
t.Fatalf("unexpected LeafAlloc: %d", stats.LeafAlloc)
}
}
if stats.BucketN != 1 {
t.Fatalf("unexpected BucketN: %d", stats.BucketN)
} else if stats.InlineBucketN != 0 {
t.Fatalf("unexpected InlineBucketN: %d", stats.InlineBucketN)
} else if stats.InlineBucketInuse != 0 {
t.Fatalf("unexpected InlineBucketInuse: %d", stats.InlineBucketInuse)
}
return nil
}); err != nil {
t.Fatal(err)
}
}
// Ensure that a bucket can write random keys and values across multiple transactions.
func TestBucket_Put_Single(t *testing.T) {
if testing.Short() {
t.Skip("skipping test in short mode.")
}
index := 0
if err := quick.Check(func(items testdata) bool {
db := MustOpenDB()
defer db.MustClose()
m := make(map[string][]byte)
if err := db.Update(func(tx *bolt.Tx) error {
if _, err := tx.CreateBucket([]byte("widgets")); err != nil {
t.Fatal(err)
}
return nil
}); err != nil {
t.Fatal(err)
}
for _, item := range items {
if err := db.Update(func(tx *bolt.Tx) error {
if err := tx.Bucket([]byte("widgets")).Put(item.Key, item.Value); err != nil {
panic("put error: " + err.Error())
}
m[string(item.Key)] = item.Value
return nil
}); err != nil {
t.Fatal(err)
}
// Verify all key/values so far.
if err := db.View(func(tx *bolt.Tx) error {
i := 0
for k, v := range m {
value := tx.Bucket([]byte("widgets")).Get([]byte(k))
if !bytes.Equal(value, v) {
t.Logf("value mismatch [run %d] (%d of %d):\nkey: %x\ngot: %x\nexp: %x", index, i, len(m), []byte(k), value, v)
db.CopyTempFile()
t.FailNow()
}
i++
}
return nil
}); err != nil {
t.Fatal(err)
}
}
index++
return true
}, nil); err != nil {
t.Error(err)
}
}
// Ensure that a transaction can insert multiple key/value pairs at once.
func TestBucket_Put_Multiple(t *testing.T) {
if testing.Short() {
t.Skip("skipping test in short mode.")
}
if err := quick.Check(func(items testdata) bool {
db := MustOpenDB()
defer db.MustClose()
// Bulk insert all values.
if err := db.Update(func(tx *bolt.Tx) error {
if _, err := tx.CreateBucket([]byte("widgets")); err != nil {
t.Fatal(err)
}
return nil
}); err != nil {
t.Fatal(err)
}
if err := db.Update(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte("widgets"))
for _, item := range items {
if err := b.Put(item.Key, item.Value); err != nil {
t.Fatal(err)
}
}
return nil
}); err != nil {
t.Fatal(err)
}
// Verify all items exist.
if err := db.View(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte("widgets"))
for _, item := range items {
value := b.Get(item.Key)
if !bytes.Equal(item.Value, value) {
db.CopyTempFile()
t.Fatalf("exp=%x; got=%x", item.Value, value)
}
}
return nil
}); err != nil {
t.Fatal(err)
}
return true
}, qconfig()); err != nil {
t.Error(err)
}
}
// Ensure that a transaction can delete all key/value pairs and return to a single leaf page.
func TestBucket_Delete_Quick(t *testing.T) {
if testing.Short() {
t.Skip("skipping test in short mode.")
}
if err := quick.Check(func(items testdata) bool {
db := MustOpenDB()
defer db.MustClose()
// Bulk insert all values.
if err := db.Update(func(tx *bolt.Tx) error {
if _, err := tx.CreateBucket([]byte("widgets")); err != nil {
t.Fatal(err)
}
return nil
}); err != nil {
t.Fatal(err)
}
if err := db.Update(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte("widgets"))
for _, item := range items {
if err := b.Put(item.Key, item.Value); err != nil {
t.Fatal(err)
}
}
return nil
}); err != nil {
t.Fatal(err)
}
// Remove items one at a time and check consistency.
for _, item := range items {
if err := db.Update(func(tx *bolt.Tx) error {
return tx.Bucket([]byte("widgets")).Delete(item.Key)
}); err != nil {
t.Fatal(err)
}
}
// Anything before our deletion index should be nil.
if err := db.View(func(tx *bolt.Tx) error {
if err := tx.Bucket([]byte("widgets")).ForEach(func(k, v []byte) error {
t.Fatalf("bucket should be empty; found: %06x", trunc(k, 3))
return nil
}); err != nil {
t.Fatal(err)
}
return nil
}); err != nil {
t.Fatal(err)
}
return true
}, qconfig()); err != nil {
t.Error(err)
}
}
func ExampleBucket_Put() {
// Open the database.
db, err := bolt.Open(tempfile(), 0666, nil)
if err != nil {
log.Fatal(err)
}
defer os.Remove(db.Path())
// Start a write transaction.
if err := db.Update(func(tx *bolt.Tx) error {
// Create a bucket.
b, err := tx.CreateBucket([]byte("widgets"))
if err != nil {
return err
}
// Set the value "bar" for the key "foo".
if err := b.Put([]byte("foo"), []byte("bar")); err != nil {
return err
}
return nil
}); err != nil {
log.Fatal(err)
}
// Read value back in a different read-only transaction.
if err := db.View(func(tx *bolt.Tx) error {
value := tx.Bucket([]byte("widgets")).Get([]byte("foo"))
fmt.Printf("The value of 'foo' is: %s\n", value)
return nil
}); err != nil {
log.Fatal(err)
}
// Close database to release file lock.
if err := db.Close(); err != nil {
log.Fatal(err)
}
// Output:
// The value of 'foo' is: bar
}
func ExampleBucket_Delete() {
// Open the database.
db, err := bolt.Open(tempfile(), 0666, nil)
if err != nil {
log.Fatal(err)
}
defer os.Remove(db.Path())
// Start a write transaction.
if err := db.Update(func(tx *bolt.Tx) error {
// Create a bucket.
b, err := tx.CreateBucket([]byte("widgets"))
if err != nil {
return err
}
// Set the value "bar" for the key "foo".
if err := b.Put([]byte("foo"), []byte("bar")); err != nil {
return err
}
// Retrieve the key back from the database and verify it.
value := b.Get([]byte("foo"))
fmt.Printf("The value of 'foo' was: %s\n", value)
return nil
}); err != nil {
log.Fatal(err)
}
// Delete the key in a different write transaction.
if err := db.Update(func(tx *bolt.Tx) error {
return tx.Bucket([]byte("widgets")).Delete([]byte("foo"))
}); err != nil {
log.Fatal(err)
}
// Retrieve the key again.
if err := db.View(func(tx *bolt.Tx) error {
value := tx.Bucket([]byte("widgets")).Get([]byte("foo"))
if value == nil {
fmt.Printf("The value of 'foo' is now: nil\n")
}
return nil
}); err != nil {
log.Fatal(err)
}
// Close database to release file lock.
if err := db.Close(); err != nil {
log.Fatal(err)
}
// Output:
// The value of 'foo' was: bar
// The value of 'foo' is now: nil
}
func ExampleBucket_ForEach() {
// Open the database.
db, err := bolt.Open(tempfile(), 0666, nil)
if err != nil {
log.Fatal(err)
}
defer os.Remove(db.Path())
// Insert data into a bucket.
if err := db.Update(func(tx *bolt.Tx) error {
b, err := tx.CreateBucket([]byte("animals"))
if err != nil {
return err
}
if err := b.Put([]byte("dog"), []byte("fun")); err != nil {
return err
}
if err := b.Put([]byte("cat"), []byte("lame")); err != nil {
return err
}
if err := b.Put([]byte("liger"), []byte("awesome")); err != nil {
return err
}
// Iterate over items in sorted key order.
if err := b.ForEach(func(k, v []byte) error {
fmt.Printf("A %s is %s.\n", k, v)
return nil
}); err != nil {
return err
}
return nil
}); err != nil {
log.Fatal(err)
}
// Close database to release file lock.
if err := db.Close(); err != nil {
log.Fatal(err)
}
// Output:
// A cat is lame.
// A dog is fun.
// A liger is awesome.
}
================================================
FILE: cmd/bolt/main.go
================================================
package main
import (
"bytes"
"encoding/binary"
"errors"
"flag"
"fmt"
"io"
"io/ioutil"
"math/rand"
"os"
"runtime"
"runtime/pprof"
"strconv"
"strings"
"time"
"unicode"
"unicode/utf8"
"unsafe"
"github.com/boltdb/bolt"
)
var (
// ErrUsage is returned when a usage message was printed and the process
// should simply exit with an error.
ErrUsage = errors.New("usage")
// ErrUnknownCommand is returned when a CLI command is not specified.
ErrUnknownCommand = errors.New("unknown command")
// ErrPathRequired is returned when the path to a Bolt database is not specified.
ErrPathRequired = errors.New("path required")
// ErrFileNotFound is returned when a Bolt database does not exist.
ErrFileNotFound = errors.New("file not found")
// ErrInvalidValue is returned when a benchmark reads an unexpected value.
ErrInvalidValue = errors.New("invalid value")
// ErrCorrupt is returned when a checking a data file finds errors.
ErrCorrupt = errors.New("invalid value")
// ErrNonDivisibleBatchSize is returned when the batch size can't be evenly
// divided by the iteration count.
ErrNonDivisibleBatchSize = errors.New("number of iterations must be divisible by the batch size")
// ErrPageIDRequired is returned when a required page id is not specified.
ErrPageIDRequired = errors.New("page id required")
// ErrPageNotFound is returned when specifying a page above the high water mark.
ErrPageNotFound = errors.New("page not found")
// ErrPageFreed is returned when reading a page that has already been freed.
ErrPageFreed = errors.New("page freed")
)
// PageHeaderSize represents the size of the bolt.page header.
const PageHeaderSize = 16
func main() {
m := NewMain()
if err := m.Run(os.Args[1:]...); err == ErrUsage {
os.Exit(2)
} else if err != nil {
fmt.Println(err.Error())
os.Exit(1)
}
}
// Main represents the main program execution.
type Main struct {
Stdin io.Reader
Stdout io.Writer
Stderr io.Writer
}
// NewMain returns a new instance of Main connect to the standard input/output.
func NewMain() *Main {
return &Main{
Stdin: os.Stdin,
Stdout: os.Stdout,
Stderr: os.Stderr,
}
}
// Run executes the program.
func (m *Main) Run(args ...string) error {
// Require a command at the beginning.
if len(args) == 0 || strings.HasPrefix(args[0], "-") {
fmt.Fprintln(m.Stderr, m.Usage())
return ErrUsage
}
// Execute command.
switch args[0] {
case "help":
fmt.Fprintln(m.Stderr, m.Usage())
return ErrUsage
case "bench":
return newBenchCommand(m).Run(args[1:]...)
case "check":
return newCheckCommand(m).Run(args[1:]...)
case "compact":
return newCompactCommand(m).Run(args[1:]...)
case "dump":
return newDumpCommand(m).Run(args[1:]...)
case "info":
return newInfoCommand(m).Run(args[1:]...)
case "page":
return newPageCommand(m).Run(args[1:]...)
case "pages":
return newPagesCommand(m).Run(args[1:]...)
case "stats":
return newStatsCommand(m).Run(args[1:]...)
default:
return ErrUnknownCommand
}
}
// Usage returns the help message.
func (m *Main) Usage() string {
return strings.TrimLeft(`
Bolt is a tool for inspecting bolt databases.
Usage:
bolt command [arguments]
The commands are:
bench run synthetic benchmark against bolt
check verifies integrity of bolt database
compact copies a bolt database, compacting it in the process
info print basic info
help print this screen
pages print list of pages with their types
stats iterate over all pages and generate usage stats
Use "bolt [command] -h" for more information about a command.
`, "\n")
}
// CheckCommand represents the "check" command execution.
type CheckCommand struct {
Stdin io.Reader
Stdout io.Writer
Stderr io.Writer
}
// NewCheckCommand returns a CheckCommand.
func newCheckCommand(m *Main) *CheckCommand {
return &CheckCommand{
Stdin: m.Stdin,
Stdout: m.Stdout,
Stderr: m.Stderr,
}
}
// 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
})
}
// Usage returns the help message.
func (cmd *CheckCommand) Usage() string {
return strings.TrimLeft(`
usage: bolt check PATH
Check opens a database at PATH and runs an exhaustive check to verify that
all pages are accessible or are marked as freed. It also verifies that no
pages are double referenced.
Verification errors will stream out as they are found and the process will
return after all pages have been checked.
`, "\n")
}
// InfoCommand represents the "info" command execution.
type InfoCommand struct {
Stdin io.Reader
Stdout io.Writer
Stderr io.Writer
}
// NewInfoCommand returns a InfoCommand.
func newInfoCommand(m *Main) *InfoCommand {
return &InfoCommand{
Stdin: m.Stdin,
Stdout: m.Stdout,
Stderr: m.Stderr,
}
}
// 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
}
// Usage returns the help message.
func (cmd *InfoCommand) Usage() string {
return strings.TrimLeft(`
usage: bolt info PATH
Info prints basic information about the Bolt database at PATH.
`, "\n")
}
// DumpCommand represents the "dump" command execution.
type DumpCommand struct {
Stdin io.Reader
Stdout io.Writer
Stderr io.Writer
}
// newDumpCommand returns a DumpCommand.
func newDumpCommand(m *Main) *DumpCommand {
return &DumpCommand{
Stdin: m.Stdin,
Stdout: m.Stdout,
Stderr: m.Stderr,
}
}
// Run executes the command.
func (cmd *DumpCommand) 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 and page id.
path := fs.Arg(0)
if path == "" {
return ErrPathRequired
} else if _, err := os.Stat(path); os.IsNotExist(err) {
return ErrFileNotFound
}
// Read page ids.
pageIDs, err := atois(fs.Args()[1:])
if err != nil {
return err
} else if len(pageIDs) == 0 {
return ErrPageIDRequired
}
// Open database to retrieve page size.
pageSize, err := ReadPageSize(path)
if err != nil {
return err
}
// Open database file handler.
f, err := os.Open(path)
if err != nil {
return err
}
defer func() { _ = f.Close() }()
// Print each page listed.
for i, pageID := range pageIDs {
// Print a separator.
if i > 0 {
fmt.Fprintln(cmd.Stdout, "===============================================")
}
// Print page to stdout.
if err := cmd.PrintPage(cmd.Stdout, f, pageID, pageSize); err != nil {
return err
}
}
return nil
}
// PrintPage prints a given page as hexadecimal.
func (cmd *DumpCommand) PrintPage(w io.Writer, r io.ReaderAt, pageID int, pageSize int) error {
const bytesPerLineN = 16
// Read page into buffer.
buf := make([]byte, pageSize)
addr := pageID * pageSize
if n, err := r.ReadAt(buf, int64(addr)); err != nil {
return err
} else if n != pageSize {
return io.ErrUnexpectedEOF
}
// Write out to writer in 16-byte lines.
var prev []byte
var skipped bool
for offset := 0; offset < pageSize; offset += bytesPerLineN {
// Retrieve current 16-byte line.
line := buf[offset : offset+bytesPerLineN]
isLastLine := (offset == (pageSize - bytesPerLineN))
// If it's the same as the previous line then print a skip.
if bytes.Equal(line, prev) && !isLastLine {
if !skipped {
fmt.Fprintf(w, "%07x *\n", addr+offset)
skipped = true
}
} else {
// Print line as hexadecimal in 2-byte groups.
fmt.Fprintf(w, "%07x %04x %04x %04x %04x %04x %04x %04x %04x\n", addr+offset,
line[0:2], line[2:4], line[4:6], line[6:8],
line[8:10], line[10:12], line[12:14], line[14:16],
)
skipped = false
}
// Save the previous line.
prev = line
}
fmt.Fprint(w, "\n")
return nil
}
// Usage returns the help message.
func (cmd *DumpCommand) Usage() string {
return strings.TrimLeft(`
usage: bolt dump -page PAGEID PATH
Dump prints a hexadecimal dump of a single page.
`, "\n")
}
// PageCommand represents the "page" command execution.
type PageCommand struct {
Stdin io.Reader
Stdout io.Writer
Stderr io.Writer
}
// newPageCommand returns a PageCommand.
func newPageCommand(m *Main) *PageCommand {
return &PageCommand{
Stdin: m.Stdin,
Stdout: m.Stdout,
Stderr: m.Stderr,
}
}
// Run executes the command.
func (cmd *PageCommand) 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 and page id.
path := fs.Arg(0)
if path == "" {
return ErrPathRequired
} else if _, err := os.Stat(path); os.IsNotExist(err) {
return ErrFileNotFound
}
// Read page ids.
pageIDs, err := atois(fs.Args()[1:])
if err != nil {
return err
} else if len(pageIDs) == 0 {
return ErrPageIDRequired
}
// Open database file handler.
f, err := os.Open(path)
if err != nil {
return err
}
defer func() { _ = f.Close() }()
// Print each page listed.
for i, pageID := range pageIDs {
// Print a separator.
if i > 0 {
fmt.Fprintln(cmd.Stdout, "===============================================")
}
// Retrieve page info and page size.
p, buf, err := ReadPage(path, pageID)
if err != nil {
return err
}
// Print basic page info.
fmt.Fprintf(cmd.Stdout, "Page ID: %d\n", p.id)
fmt.Fprintf(cmd.Stdout, "Page Type: %s\n", p.Type())
fmt.Fprintf(cmd.Stdout, "Total Size: %d bytes\n", len(buf))
// Print type-specific data.
switch p.Type() {
case "meta":
err = cmd.PrintMeta(cmd.Stdout, buf)
case "leaf":
err = cmd.PrintLeaf(cmd.Stdout, buf)
case "branch":
err = cmd.PrintBranch(cmd.Stdout, buf)
case "freelist":
err = cmd.PrintFreelist(cmd.Stdout, buf)
}
if err != nil {
return err
}
}
return nil
}
// PrintMeta prints the data from the meta page.
func (cmd *PageCommand) PrintMeta(w io.Writer, buf []byte) error {
m := (*meta)(unsafe.Pointer(&buf[PageHeaderSize]))
fmt.Fprintf(w, "Version: %d\n", m.version)
fmt.Fprintf(w, "Page Size: %d bytes\n", m.pageSize)
fmt.Fprintf(w, "Flags: %08x\n", m.flags)
fmt.Fprintf(w, "Root: <pgid=%d>\n", m.root.root)
fmt.Fprintf(w, "Freelist: <pgid=%d>\n", m.freelist)
fmt.Fprintf(w, "HWM: <pgid=%d>\n", m.pgid)
fmt.Fprintf(w, "Txn ID: %d\n", m.txid)
fmt.Fprintf(w, "Checksum: %016x\n", m.checksum)
fmt.Fprintf(w, "\n")
return nil
}
// PrintLeaf prints the data for a leaf page.
func (cmd *PageCommand) PrintLeaf(w io.Writer, buf []byte) error {
p := (*page)(unsafe.Pointer(&buf[0]))
// Print number of items.
fmt.Fprintf(w, "Item Count: %d\n", p.count)
fmt.Fprintf(w, "\n")
// Print each key/value.
for i := uint16(0); i < p.count; i++ {
e := p.leafPageElement(i)
// Format key as string.
var k string
if isPrintable(string(e.key())) {
k = fmt.Sprintf("%q", string(e.key()))
} else {
k = fmt.Sprintf("%x", string(e.key()))
}
// Format value as string.
var v string
if (e.flags & uint32(bucketLeafFlag)) != 0 {
b := (*bucket)(unsafe.Pointer(&e.value()[0]))
v = fmt.Sprintf("<pgid=%d,seq=%d>", b.root, b.sequence)
} else if isPrintable(string(e.value())) {
v = fmt.Sprintf("%q", string(e.value()))
} else {
v = fmt.Sprintf("%x", string(e.value()))
}
fmt.Fprintf(w, "%s: %s\n", k, v)
}
fmt.Fprintf(w, "\n")
return nil
}
// PrintBranch prints the data for a leaf page.
func (cmd *PageCommand) PrintBranch(w io.Writer, buf []byte) error {
p := (*page)(unsafe.Pointer(&buf[0]))
// Print number of items.
fmt.Fprintf(w, "Item Count: %d\n", p.count)
fmt.Fprintf(w, "\n")
// Print each key/value.
for i := uint16(0); i < p.count; i++ {
e := p.branchPageElement(i)
// Format key as string.
var k string
if isPrintable(string(e.key())) {
k = fmt.Sprintf("%q", string(e.key()))
} else {
k = fmt.Sprintf("%x", string(e.key()))
}
fmt.Fprintf(w, "%s: <pgid=%d>\n", k, e.pgid)
}
fmt.Fprintf(w, "\n")
return nil
}
// PrintFreelist prints the data for a freelist page.
func (cmd *PageCommand) PrintFreelist(w io.Writer, buf []byte) error {
p := (*page)(unsafe.Pointer(&buf[0]))
// Print number of items.
fmt.Fprintf(w, "Item Count: %d\n", p.count)
fmt.Fprintf(w, "\n")
// Print each page in the freelist.
ids := (*[maxAllocSize]pgid)(unsafe.Pointer(&p.ptr))
for i := uint16(0); i < p.count; i++ {
fmt.Fprintf(w, "%d\n", ids[i])
}
fmt.Fprintf(w, "\n")
return nil
}
// PrintPage prints a given page as hexadecimal.
func (cmd *PageCommand) PrintPage(w io.Writer, r io.ReaderAt, pageID int, pageSize int) error {
const bytesPerLineN = 16
// Read page into buffer.
buf := make([]byte, pageSize)
addr := pageID * pageSize
if n, err := r.ReadAt(buf, int64(addr)); err != nil {
return err
} else if n != pageSize {
return io.ErrUnexpectedEOF
}
// Write out to writer in 16-byte lines.
var prev []byte
var skipped bool
for offset := 0; offset < pageSize; offset += bytesPerLineN {
// Retrieve current 16-byte line.
line := buf[offset : offset+bytesPerLineN]
isLastLine := (offset == (pageSize - bytesPerLineN))
// If it's the same as the previous line then print a skip.
if bytes.Equal(line, prev) && !isLastLine {
if !skipped {
fmt.Fprintf(w, "%07x *\n", addr+offset)
skipped = true
}
} else {
// Print line as hexadecimal in 2-byte groups.
fmt.Fprintf(w, "%07x %04x %04x %04x %04x %04x %04x %04x %04x\n", addr+offset,
line[0:2], line[2:4], line[4:6], line[6:8],
line[8:10], line[10:12], line[12:14], line[14:16],
)
skipped = false
}
// Save the previous line.
prev = line
}
fmt.Fprint(w, "\n")
return nil
}
// Usage returns the help message.
func (cmd *PageCommand) Usage() string {
return strings.TrimLeft(`
usage: bolt page -page PATH pageid [pageid...]
Page prints one or more pages in human readable format.
`, "\n")
}
// PagesCommand represents the "pages" command execution.
type PagesCommand struct {
Stdin io.Reader
Stdout io.Writer
Stderr io.Writer
}
// NewPagesCommand returns a PagesCommand.
func newPagesCommand(m *Main) *PagesCommand {
return &PagesCommand{
Stdin: m.Stdin,
Stdout: m.Stdout,
Stderr: m.Stderr,
}
}
// 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
})
}
// Usage returns the help message.
func (cmd *PagesCommand) Usage() string {
return strings.TrimLeft(`
usage: bolt pages PATH
Pages prints a table of pages with their type (meta, leaf, branch, freelist).
Leaf and branch pages will show a key count in the "items" column while the
freelist will show the number of free pages in the "items" column.
The "overflow" column shows the number of blocks that the page spills over
into. Normally there is no overflow but large keys and values can cause
a single page to take up multiple blocks.
`, "\n")
}
// StatsCommand represents the "stats" command execution.
type StatsCommand struct {
Stdin io.Reader
Stdout io.Writer
Stderr io.Writer
}
// NewStatsCommand returns a StatsCommand.
func newStatsCommand(m *Main) *StatsCommand {
return &StatsCommand{
Stdin: m.Stdin,
Stdout: m.Stdout,
Stderr: m.Stderr,
}
}
// 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 = 0
if s.BucketN != 0 {
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
})
}
// Usage returns the help message.
func (cmd *StatsCommand) Usage() string {
return strings.TrimLeft(`
usage: bolt stats PATH
Stats performs an extensive search of the database to track every page
reference. It starts at the current meta page and recursively iterates
through every accessible bucket.
The following errors can be reported:
already freed
The page is referenced more than once in the freelist.
unreachable unfreed
The page is not referenced by a bucket or in the freelist.
reachable freed
The page is referenced by a bucket but is also in the freelist.
out of bounds
A page is referenced that is above the high water mark.
multiple references
A page is referenced by more than one other page.
invalid type
The page type is not "meta", "leaf", "branch", or "freelist".
No errors should occur in your database. However, if for some reason you
experience corruption, please submit a ticket to the Bolt project page:
https://github.com/boltdb/bolt/issues
`, "\n")
}
var benchBucketName = []byte("bench")
// BenchCommand represents the "bench" command execution.
type BenchCommand struct {
Stdin io.Reader
Stdout io.Writer
Stderr io.Writer
}
// NewBenchCommand returns a BenchCommand using the
func newBenchCommand(m *Main) *BenchCommand {
return &BenchCommand{
Stdin: m.Stdin,
Stdout: m.Stdout,
Stderr: m.Stderr,
}
}
// 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: %v", 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
}
// ParseFlags parses the command line flags.
func (cmd *BenchCommand) ParseFlags(args []string) (*BenchOptions, error) {
var options BenchOptions
// Parse flagset.
fs := flag.NewFlagSet("", flag.ContinueOnError)
fs.StringVar(&options.ProfileMode, "profile-mode", "rw", "")
fs.StringVar(&options.WriteMode, "write-mode", "seq", "")
fs.StringVar(&options.ReadMode, "read-mode", "seq", "")
fs.IntVar(&options.Iterations, "count", 1000, "")
fs.IntVar(&options.BatchSize, "batch-size", 0, "")
fs.IntVar(&options.KeySize, "key-size", 8, "")
fs.IntVar(&options.ValueSize, "value-size", 32, "")
fs.StringVar(&options.CPUProfile, "cpuprofile", "", "")
fs.StringVar(&options.MemProfile, "memprofile", "", "")
fs.StringVar(&options.BlockProfile, "blockprofile", "", "")
fs.Float64Var(&options.FillPercent, "fill-percent", bolt.DefaultFillPercent, "")
fs.BoolVar(&options.NoSync, "no-sync", false, "")
fs.BoolVar(&options.Work, "work", false, "")
fs.StringVar(&options.Path, "path", "", "")
fs.SetOutput(cmd.Stderr)
if err := fs.Parse(args); err != nil {
return nil, err
}
// Set batch size to iteration size if not set.
// Require that batch size can be evenly divided by the iteration count.
if options.BatchSize == 0 {
options.BatchSize = options.Iterations
} else if options.Iterations%options.BatchSize != 0 {
return nil, ErrNonDivisibleBatchSize
}
// Generate temp path if one is not passed in.
if options.Path == "" {
f, err := ioutil.TempFile("", "bolt-bench-")
if err != nil {
return nil, fmt.Errorf("temp file: %s", err)
}
f.Close()
os.Remove(f.Name())
options.Path = f.Name()
}
return &options, nil
}
// Writes to the database.
func (cmd *BenchCommand) runWrites(db *bolt.DB, options *BenchOptions, results *BenchResults) error {
// Start profiling for writes.
if options.ProfileMode == "rw" || options.ProfileMode == "w" {
cmd.startProfiling(options)
}
t := time.Now()
var err error
switch options.WriteMode {
case "seq":
err = cmd.runWritesSequential(db, options, results)
case "rnd":
err = cmd.runWritesRandom(db, options, results)
case "seq-nest":
err = cmd.runWritesSequentialNested(db, options, results)
case "rnd-nest":
err = cmd.runWritesRandomNested(db, options, results)
default:
return fmt.Errorf("invalid write mode: %s", options.WriteMode)
}
// Save time to write.
results.WriteDuration = time.Since(t)
// Stop profiling for writes only.
if options.ProfileMode == "w" {
cmd.stopProfiling()
}
return err
}
func (cmd *BenchCommand) runWritesSequential(db *bolt.DB, options *BenchOptions, results *BenchResults) error {
var i = uint32(0)
return cmd.runWritesWithSource(db, options, results, func() uint32 { i++; return i })
}
func (cmd *BenchCommand) runWritesRandom(db *bolt.DB, options *BenchOptions, results *BenchResults) error {
r := rand.New(rand.NewSource(time.Now().UnixNano()))
return cmd.runWritesWithSource(db, options, results, func() uint32 { return r.Uint32() })
}
func (cmd *BenchCommand) runWritesSequentialNested(db *bolt.DB, options *BenchOptions, results *BenchResults) error {
var i = uint32(0)
return cmd.runWritesWithSource(db, options, results, func() uint32 { i++; return i })
}
func (cmd *BenchCommand) runWritesRandomNested(db *bolt.DB, options *BenchOptions, results *BenchResults) error {
r := rand.New(rand.NewSource(time.Now().UnixNano()))
return cmd.runWritesWithSource(db, options, results, func() uint32 { return r.Uint32() })
}
func (cmd *BenchCommand) runWritesWithSource(db *bolt.DB, options *BenchOptions, results *BenchResults, keySource func() uint32) error {
results.WriteOps = options.Iterations
for i := 0; i < options.Iterations; i += options.BatchSize {
if err := db.Update(func(tx *bolt.Tx) error {
b, _ := tx.CreateBucketIfNotExists(benchBucketName)
b.FillPercent = options.FillPercent
for j := 0; j < options.BatchSize; j++ {
key := make([]byte, options.KeySize)
value := make([]byte, options.ValueSize)
// Write key as uint32.
binary.BigEndian.PutUint32(key, keySource())
// Insert key/value.
if err := b.Put(key, value); err != nil {
return err
}
}
return nil
}); err != nil {
return err
}
}
return nil
}
func (cmd *BenchCommand) runWritesNestedWithSource(db *bolt.DB, options *BenchOptions, results *BenchResults, keySource func() uint32) error {
results.WriteOps = options.Iterations
for i := 0; i < options.Iterations; i += options.BatchSize {
if err := db.Update(func(tx *bolt.Tx) error {
top, err := tx.CreateBucketIfNotExists(benchBucketName)
if err != nil {
return err
}
top.FillPercent = options.FillPercent
// Create bucket key.
name := make([]byte, options.KeySize)
binary.BigEndian.PutUint32(name, keySource())
// Create bucket.
b, err := top.CreateBucketIfNotExists(name)
if err != nil {
return err
}
b.FillPercent = options.FillPercent
for j := 0; j < options.BatchSize; j++ {
var key = make([]byte, options.KeySize)
var value = make([]byte, options.ValueSize)
// Generate key as uint32.
binary.BigEndian.PutUint32(key, keySource())
// Insert value into subbucket.
if err := b.Put(key, value); err != nil {
return err
}
}
return nil
}); err != nil {
return err
}
}
return nil
}
// Reads from the database.
func (cmd *BenchCommand) runReads(db *bolt.DB, options *BenchOptions, results *BenchResults) error {
// Start profiling for reads.
if options.ProfileMode == "r" {
cmd.startProfiling(options)
}
t := time.Now()
var err error
switch options.ReadMode {
case "seq":
switch options.WriteMode {
case "seq-nest", "rnd-nest":
err = cmd.runReadsSequentialNested(db, options, results)
default:
err = cmd.runReadsSequential(db, options, results)
}
default:
return fmt.Errorf("invalid read mode: %s", options.ReadMode)
}
// Save read time.
results.ReadDuration = time.Since(t)
// Stop profiling for reads.
if options.ProfileMode == "rw" || options.ProfileMode == "r" {
cmd.stopProfiling()
}
return err
}
func (cmd *BenchCommand) runReadsSequential(db *bolt.DB, options *BenchOptions, results *BenchResults) error {
return db.View(func(tx *bolt.Tx) error {
t := time.Now()
for {
var count int
c := tx.Bucket(benchBucketName).Cursor()
for k, v := c.First(); k != nil; k, v = c.Next() {
if v == nil {
return errors.New("invalid value")
}
count++
}
if options.WriteMode == "seq" && count != options.Iterations {
return fmt.Errorf("read seq: iter mismatch: expected %d, got %d", options.Iterations, count)
}
results.ReadOps += count
// Make sure we do this for at least a second.
if time.Since(t) >= time.Second {
break
}
}
return nil
})
}
func (cmd *BenchCommand) runReadsSequentialNested(db *bolt.DB, options *BenchOptions, results *BenchResults) error {
return db.View(func(tx *bolt.Tx) error {
t := time.Now()
for {
var count int
var top = tx.Bucket(benchBucketName)
if err := top.ForEach(func(name, _ []byte) error {
c := top.Bucket(name).Cursor()
for k, v := c.First(); k != nil; k, v = c.Next() {
if v == nil {
return ErrInvalidValue
}
count++
}
return nil
}); err != nil {
return err
}
if options.WriteMode == "seq-nest" && count != options.Iterations {
return fmt.Errorf("read seq-nest: iter mismatch: expected %d, got %d", options.Iterations, count)
}
results.ReadOps += count
// Make sure we do this for at least a second.
if time.Since(t) >= time.Second {
break
}
}
return nil
})
}
// File handlers for the various profiles.
var cpuprofile, memprofile, blockprofile *os.File
// Starts all profiles set on the options.
func (cmd *BenchCommand) startProfiling(options *BenchOptions) {
var err error
// Start CPU profiling.
if options.CPUProfile != "" {
cpuprofile, err = os.Create(options.CPUProfile)
if err != nil {
fmt.Fprintf(cmd.Stderr, "bench: could not create cpu profile %q: %v\n", options.CPUProfile, err)
os.Exit(1)
}
pprof.StartCPUProfile(cpuprofile)
}
// Start memory profiling.
if options.MemProfile != "" {
memprofile, err = os.Create(options.MemProfile)
if err != nil {
fmt.Fprintf(cmd.Stderr, "bench: could not create memory profile %q: %v\n", options.MemProfile, err)
os.Exit(1)
}
runtime.MemProfileRate = 4096
}
// Start fatal profiling.
if options.BlockProfile != "" {
blockprofile, err = os.Create(options.BlockProfile)
if err != nil {
fmt.Fprintf(cmd.Stderr, "bench: could not create block profile %q: %v\n", options.BlockProfile, err)
os.Exit(1)
}
runtime.SetBlockProfileRate(1)
}
}
// Stops all profiles.
func (cmd *BenchCommand) stopProfiling() {
if cpuprofile != nil {
pprof.StopCPUProfile()
cpuprofile.Close()
cpuprofile = nil
}
if memprofile != nil {
pprof.Lookup("heap").WriteTo(memprofile, 0)
memprofile.Close()
memprofile = nil
}
if blockprofile != nil {
pprof.Lookup("block").WriteTo(blockprofile, 0)
blockprofile.Close()
blockprofile = nil
runtime.SetBlockProfileRate(0)
}
}
// BenchOptions represents the set of options that can be passed to "bolt bench".
type BenchOptions struct {
ProfileMode string
WriteMode string
ReadMode string
Iterations int
BatchSize int
KeySize int
ValueSize int
CPUProfile string
MemProfile string
BlockProfile string
StatsInterval time.Duration
FillPercent float64
NoSync bool
Work bool
Path string
}
// BenchResults represents the performance results of the benchmark.
type BenchResults struct {
WriteOps int
WriteDuration time.Duration
ReadOps int
ReadDuration time.Duration
}
// Returns the duration for a single write operation.
func (r *BenchResults) WriteOpDuration() time.Duration {
if r.WriteOps == 0 {
return 0
}
return r.WriteDuration / time.Duration(r.WriteOps)
}
// Returns average number of write operations that can be performed per second.
func (r *BenchResults) WriteOpsPerSecond() int {
var op = r.WriteOpDuration()
if op == 0 {
return 0
}
return int(time.Second) / int(op)
}
// Returns the duration for a single read operation.
func (r *BenchResults) ReadOpDuration() time.Duration {
if r.ReadOps == 0 {
return 0
}
return r.ReadDuration / time.Duration(r.ReadOps)
}
// Returns average number of read operations that can be performed per second.
func (r *BenchResults) ReadOpsPerSecond() int {
var op = r.ReadOpDuration()
if op == 0 {
return 0
}
return int(time.Second) / int(op)
}
type PageError struct {
ID int
Err error
}
func (e *PageError) Error() string {
return fmt.Sprintf("page error: id=%d, err=%s", e.ID, e.Err)
}
// isPrintable returns true if the string is valid unicode and contains only printable runes.
func isPrintable(s string) bool {
if !utf8.ValidString(s) {
return false
}
for _, ch := range s {
if !unicode.IsPrint(ch) {
return false
}
}
return true
}
// ReadPage reads page info & full page data from a path.
// This is not transactionally safe.
func ReadPage(path string, pageID int) (*page, []byte, error) {
// Find page size.
pageSize, err := ReadPageSize(path)
if err != nil {
return nil, nil, fmt.Errorf("read page size: %s", err)
}
// Open database file.
f, err := os.Open(path)
if err != nil {
return nil, nil, err
}
defer f.Close()
// Read one block into buffer.
buf := make([]byte, pageSize)
if n, err := f.ReadAt(buf, int64(pageID*pageSize)); err != nil {
return nil, nil, err
} else if n != len(buf) {
return nil, nil, io.ErrUnexpectedEOF
}
// Determine total number of blocks.
p := (*page)(unsafe.Pointer(&buf[0]))
overflowN := p.overflow
// Re-read entire page (with overflow) into buffer.
buf = make([]byte, (int(overflowN)+1)*pageSize)
if n, err := f.ReadAt(buf, int64(pageID*pageSize)); err != nil {
return nil, nil, err
} else if n != len(buf) {
return nil, nil, io.ErrUnexpectedEOF
}
p = (*page)(unsafe.Pointer(&buf[0]))
return p, buf, nil
}
// ReadPageSize reads page size a path.
// This is not transactionally safe.
func ReadPageSize(path string) (int, error) {
// Open database file.
f, err := os.Open(path)
if err != nil {
return 0, err
}
defer f.Close()
// Read 4KB chunk.
buf := make([]byte, 4096)
if _, err := io.ReadFull(f, buf); err != nil {
return 0, err
}
// Read page size from metadata.
m := (*meta)(unsafe.Pointer(&buf[PageHeaderSize]))
return int(m.pageSize), nil
}
// atois parses a slice of strings into integers.
func atois(strs []string) ([]int, error) {
var a []int
for _, str := range strs {
i, err := strconv.Atoi(str)
if err != nil {
return nil, err
}
a = append(a, i)
}
return a, nil
}
// DO NOT EDIT. Copied from the "bolt" package.
const maxAllocSize = 0xFFFFFFF
// DO NOT EDIT. Copied from the "bolt" package.
const (
branchPageFlag = 0x01
leafPageFlag = 0x02
metaPageFlag = 0x04
freelistPageFlag = 0x10
)
// DO NOT EDIT. Copied from the "bolt" package.
const bucketLeafFlag = 0x01
// DO NOT EDIT. Copied from the "bolt" package.
type pgid uint64
// DO NOT EDIT. Copied from the "bolt" package.
type txid uint64
// DO NOT EDIT. Copied from the "bolt" package.
type meta struct {
magic uint32
version uint32
pageSize uint32
flags uint32
root bucket
freelist pgid
pgid pgid
txid txid
checksum uint64
}
// DO NOT EDIT. Copied from the "bolt" package.
type bucket struct {
root pgid
sequence uint64
}
// DO NOT EDIT. Copied from the "bolt" package.
type page struct {
id pgid
flags uint16
count uint16
overflow uint32
ptr uintptr
}
// DO NOT EDIT. Copied from the "bolt" package.
func (p *page) Type() string {
if (p.flags & branchPageFlag) != 0 {
return "branch"
} else if (p.flags & leafPageFlag) != 0 {
return "leaf"
} else if (p.flags & metaPageFlag) != 0 {
return "meta"
} else if (p.flags & freelistPageFlag) != 0 {
return "freelist"
}
return fmt.Sprintf("unknown<%02x>", p.flags)
}
// DO NOT EDIT. Copied from the "bolt" package.
func (p *page) leafPageElement(index uint16) *leafPageElement {
n := &((*[0x7FFFFFF]leafPageElement)(unsafe.Pointer(&p.ptr)))[index]
return n
}
// DO NOT EDIT. Copied from the "bolt" package.
func (p *page) branchPageElement(index uint16) *branchPageElement {
return &((*[0x7FFFFFF]branchPageElement)(unsafe.Pointer(&p.ptr)))[index]
}
// DO NOT EDIT. Copied from the "bolt" package.
type branchPageElement struct {
pos uint32
ksize uint32
pgid pgid
}
// DO NOT EDIT. Copied from the "bolt" package.
func (n *branchPageElement) key() []byte {
buf := (*[maxAllocSize]byte)(unsafe.Pointer(n))
return buf[n.pos : n.pos+n.ksize]
}
// DO NOT EDIT. Copied from the "bolt" package.
type leafPageElement struct {
flags uint32
pos uint32
ksize uint32
vsize uint32
}
// DO NOT EDIT. Copied from the "bolt" package.
func (n *leafPageElement) key() []byte {
buf := (*[maxAllocSize]byte)(unsafe.Pointer(n))
return buf[n.pos : n.pos+n.ksize]
}
// DO NOT EDIT. Copied from the "bolt" package.
func (n *leafPageElement) value() []byte {
buf := (*[maxAllocSize]byte)(unsafe.Pointer(n))
return buf[n.pos+n.ksize : n.pos+n.ksize+n.vsize]
}
// CompactCommand represents the "compact" command execution.
type CompactCommand struct {
Stdin io.Reader
Stdout io.Writer
Stderr io.Writer
SrcPath string
DstPath string
TxMaxSize int64
}
// newCompactCommand returns a CompactCommand.
func newCompactCommand(m *Main) *CompactCommand {
return &CompactCommand{
Stdin: m.Stdin,
Stdout: m.Stdout,
Stderr: m.Stderr,
}
}
// Run executes the command.
func (cmd *CompactCommand) Run(args ...string) (err error) {
// Parse flags.
fs := flag.NewFlagSet("", flag.ContinueOnError)
fs.SetOutput(ioutil.Discard)
fs.StringVar(&cmd.DstPath, "o", "", "")
fs.Int64Var(&cmd.TxMaxSize, "tx-max-size", 65536, "")
if err := fs.Parse(args); err == flag.ErrHelp {
fmt.Fprintln(cmd.Stderr, cmd.Usage())
return ErrUsage
} else if err != nil {
return err
} else if cmd.DstPath == "" {
return fmt.Errorf("output file required")
}
// Require database paths.
cmd.SrcPath = fs.Arg(0)
if cmd.SrcPath == "" {
return ErrPathRequired
}
// Ensure source file exists.
fi, err := os.Stat(cmd.SrcPath)
if os.IsNotExist(err) {
return ErrFileNotFound
} else if err != nil {
return err
}
initialSize := fi.Size()
// Open source database.
src, err := bolt.Open(cmd.SrcPath, 0444, nil)
if err != nil {
return err
}
defer src.Close()
// Open destination database.
dst, err := bolt.Open(cmd.DstPath, fi.Mode(), nil)
if err != nil {
return err
}
defer dst.Close()
// Run compaction.
if err := cmd.compact(dst, src); err != nil {
return err
}
// Report stats on new size.
fi, err = os.Stat(cmd.DstPath)
if err != nil {
return err
} else if fi.Size() == 0 {
return fmt.Errorf("zero db size")
}
fmt.Fprintf(cmd.Stdout, "%d -> %d bytes (gain=%.2fx)\n", initialSize, fi.Size(), float64(initialSize)/float64(fi.Size()))
return nil
}
func (cmd *CompactCommand) compact(dst, src *bolt.DB) error {
// commit regularly, or we'll run out of memory for large datasets if using one transaction.
var size int64
tx, err := dst.Begin(true)
if err != nil {
return err
}
defer tx.Rollback()
if err := cmd.walk(src, func(keys [][]byte, k, v []byte, seq uint64) error {
// On each key/value, check if we have exceeded tx size.
sz := int64(len(k) + len(v))
if size+sz > cmd.TxMaxSize && cmd.TxMaxSize != 0 {
// Commit previous transaction.
if err := tx.Commit(); err != nil {
return err
}
// Start new transaction.
tx, err = dst.Begin(true)
if err != nil {
return err
}
size = 0
}
size += sz
// Create bucket on the root transaction if this is the first level.
nk := len(keys)
if nk == 0 {
bkt, err := tx.CreateBucket(k)
if err != nil {
return err
}
if err := bkt.SetSequence(seq); err != nil {
return err
}
return nil
}
// Create buckets on subsequent levels, if necessary.
b := tx.Bucket(keys[0])
if nk > 1 {
for _, k := range keys[1:] {
b = b.Bucket(k)
}
}
// If there is no value then this is a bucket call.
if v == nil {
bkt, err := b.CreateBucket(k)
if err != nil {
return err
}
if err := bkt.SetSequence(seq); err != nil {
return err
}
return nil
}
// Otherwise treat it as a key/value pair.
return b.Put(k, v)
}); err != nil {
return err
}
return tx.Commit()
}
// walkFunc is the type of the function called for keys (buckets and "normal"
// values) discovered by Walk. keys is the list of keys to descend to the bucket
// owning the discovered key/value pair k/v.
type walkFunc func(keys [][]byte, k, v []byte, seq uint64) error
// walk walks recursively the bolt database db, calling walkFn for each key it finds.
func (cmd *CompactCommand) walk(db *bolt.DB, walkFn walkFunc) error {
return db.View(func(tx *bolt.Tx) error {
return tx.ForEach(func(name []byte, b *bolt.Bucket) error {
return cmd.walkBucket(b, nil, name, nil, b.Sequence(), walkFn)
})
})
}
func (cmd *CompactCommand) walkBucket(b *bolt.Bucket, keypath [][]byte, k, v []byte, seq uint64, fn walkFunc) error {
// Execute callback.
if err := fn(keypath, k, v, seq); err != nil {
return err
}
// If this is not a bucket then stop.
if v != nil {
return nil
}
// Iterate over each child key/value.
keypath = append(keypath, k)
return b.ForEach(func(k, v []byte) error {
if v == nil {
bkt := b.Bucket(k)
return cmd.walkBucket(bkt, keypath, k, nil, bkt.Sequence(), fn)
}
return cmd.walkBucket(b, keypath, k, v, b.Sequence(), fn)
})
}
// Usage returns the help message.
func (cmd *CompactCommand) Usage() string {
return strings.TrimLeft(`
usage: bolt compact [options] -o DST SRC
Compact opens a database at SRC path and walks it recursively, copying keys
as they are found from all buckets, to a newly created database at DST path.
The original database is left untouched.
Additional options include:
-tx-max-size NUM
Specifies the maximum size of individual transactions.
Defaults to 64KB.
`, "\n")
}
================================================
FILE: cmd/bolt/main_test.go
================================================
package main_test
import (
"bytes"
crypto "crypto/rand"
"encoding/binary"
"fmt"
"io"
"io/ioutil"
"math/rand"
"os"
"strconv"
"testing"
"github.com/boltdb/bolt"
"github.com/boltdb/bolt/cmd/bolt"
)
// Ensure the "info" command can print information about a database.
func TestInfoCommand_Run(t *testing.T) {
db := MustOpen(0666, nil)
db.DB.Close()
defer db.Close()
// Run the info command.
m := NewMain()
if err := m.Run("info", db.Path); err != nil {
t.Fatal(err)
}
}
// Ensure the "stats" command executes correctly with an empty database.
func TestStatsCommand_Run_EmptyDatabase(t *testing.T) {
// Ignore
if os.Getpagesize() != 4096 {
t.Skip("system does not use 4KB page size")
}
db := MustOpen(0666, nil)
defer db.Close()
db.DB.Close()
// Generate expected result.
exp := "Aggregate statistics for 0 buckets\n\n" +
"Page count statistics\n" +
"\tNumber of logical branch pages: 0\n" +
"\tNumber of physical branch overflow pages: 0\n" +
"\tNumber of logical leaf pages: 0\n" +
"\tNumber of physical leaf overflow pages: 0\n" +
"Tree statistics\n" +
"\tNumber of keys/value pairs: 0\n" +
"\tNumber of levels in B+tree: 0\n" +
"Page size utilization\n" +
"\tBytes allocated for physical branch pages: 0\n" +
"\tBytes actually used for branch data: 0 (0%)\n" +
"\tBytes allocated for physical leaf pages: 0\n" +
"\tBytes actually used for leaf data: 0 (0%)\n" +
"Bucket statistics\n" +
"\tTotal number of buckets: 0\n" +
"\tTotal number on inlined buckets: 0 (0%)\n" +
"\tBytes used for inlined buckets: 0 (0%)\n"
// Run the command.
m := NewMain()
if err := m.Run("stats", db.Path); err != nil {
t.Fatal(err)
} else if m.Stdout.String() != exp {
t.Fatalf("unexpected stdout:\n\n%s", m.Stdout.String())
}
}
// Ensure the "stats" command can execute correctly.
func TestStatsCommand_Run(t *testing.T) {
// Ignore
if os.Getpagesize() != 4096 {
t.Skip("system does not use 4KB page size")
}
db := MustOpen(0666, nil)
defer db.Close()
if err := db.Update(func(tx *bolt.Tx) error {
// Create "foo" bucket.
b, err := tx.CreateBucket([]byte("foo"))
if err != nil {
return err
}
for i := 0; i < 10; i++ {
if err := b.Put([]byte(strconv.Itoa(i)), []byte(strconv.Itoa(i))); err != nil {
return err
}
}
// Create "bar" bucket.
b, err = tx.CreateBucket([]byte("bar"))
if err != nil {
return err
}
for i := 0; i < 100; i++ {
if err := b.Put([]byte(strconv.Itoa(i)), []byte(strconv.Itoa(i))); err != nil {
return err
}
}
// Create "baz" bucket.
b, err = tx.CreateBucket([]byte("baz"))
if err != nil {
return err
}
if err := b.Put([]byte("key"), []byte("value")); err != nil {
return err
}
return nil
}); err != nil {
t.Fatal(err)
}
db.DB.Close()
// Generate expected result.
exp := "Aggregate statistics for 3 buckets\n\n" +
"Page count statistics\n" +
"\tNumber of logical branch pages: 0\n" +
"\tNumber of physical branch overflow pages: 0\n" +
"\tNumber of logical leaf pages: 1\n" +
"\tNumber of physical leaf overflow pages: 0\n" +
"Tree statistics\n" +
"\tNumber of keys/value pairs: 111\n" +
"\tNumber of levels in B+tree: 1\n" +
"Page size utilization\n" +
"\tBytes allocated for physical branch pages: 0\n" +
"\tBytes actually used for branch data: 0 (0%)\n" +
"\tBytes allocated for physical leaf pages: 4096\n" +
"\tBytes actually used for leaf data: 1996 (48%)\n" +
"Bucket statistics\n" +
"\tTotal number of buckets: 3\n" +
"\tTotal number on inlined buckets: 2 (66%)\n" +
"\tBytes used for inlined buckets: 236 (11%)\n"
// Run the command.
m := NewMain()
if err := m.Run("stats", db.Path); err != nil {
t.Fatal(err)
} else if m.Stdout.String() != exp {
t.Fatalf("unexpected stdout:\n\n%s", m.Stdout.String())
}
}
// Main represents a test wrapper for main.Main that records output.
type Main struct {
*main.Main
Stdin bytes.Buffer
Stdout bytes.Buffer
Stderr bytes.Buffer
}
// NewMain returns a new instance of Main.
func NewMain() *Main {
m := &Main{Main: main.NewMain()}
m.Main.Stdin = &m.Stdin
m.Main.Stdout = &m.Stdout
m.Main.Stderr = &m.Stderr
return m
}
// 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()}
}
// DB is a test wrapper for bolt.DB.
type DB struct {
*bolt.DB
Path string
}
// Close closes and removes the database.
func (db *DB) Close() error {
defer os.Remove(db.Path)
return db.DB.Close()
}
func TestCompactCommand_Run(t *testing.T) {
var s int64
if err := binary.Read(crypto.Reader, binary.BigEndian, &s); err != nil {
t.Fatal(err)
}
rand.Seed(s)
dstdb := MustOpen(0666, nil)
dstdb.Close()
// fill the db
db := MustOpen(0666, nil)
if err := db.Update(func(tx *bolt.Tx) error {
n := 2 + rand.Intn(5)
for i := 0; i < n; i++ {
k := []byte(fmt.Sprintf("b%d", i))
b, err := tx.CreateBucketIfNotExists(k)
if err != nil {
return err
}
if err := b.SetSequence(uint64(i)); err != nil {
return err
}
if err := fillBucket(b, append(k, '.')); err != nil {
return err
}
}
return nil
}); err != nil {
db.Close()
t.Fatal(err)
}
// make the db grow by adding large values, and delete them.
if err := db.Update(func(tx *bolt.Tx) error {
b, err := tx.CreateBucketIfNotExists([]byte("large_vals"))
if err != nil {
return err
}
n := 5 + rand.Intn(5)
for i := 0; i < n; i++ {
v := make([]byte, 1000*1000*(1+rand.Intn(5)))
_, err := crypto.Read(v)
if err != nil {
return err
}
if err := b.Put([]byte(fmt.Sprintf("l%d", i)), v); err != nil {
return err
}
}
return nil
}); err != nil {
db.Close()
t.Fatal(err)
}
if err := db.Update(func(tx *bolt.Tx) error {
c := tx.Bucket([]byte("large_vals")).Cursor()
for k, _ := c.First(); k != nil; k, _ = c.Next() {
if err := c.Delete(); err != nil {
return err
}
}
return tx.DeleteBucket([]byte("large_vals"))
}); err != nil {
db.Close()
t.Fatal(err)
}
db.DB.Close()
defer db.Close()
defer dstdb.Close()
dbChk, err := chkdb(db.Path)
if err != nil {
t.Fatal(err)
}
m := NewMain()
if err := m.Run("compact", "-o", dstdb.Path, db.Path); err != nil {
t.Fatal(err)
}
dbChkAfterCompact, err := chkdb(db.Path)
if err != nil {
t.Fatal(err)
}
dstdbChk, err := chkdb(dstdb.Path)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(dbChk, dbChkAfterCompact) {
t.Error("the original db has been touched")
}
if !bytes.Equal(dbChk, dstdbChk) {
t.Error("the compacted db data isn't the same than the original db")
}
}
func fillBucket(b *bolt.Bucket, prefix []byte) error {
n := 10 + rand.Intn(50)
for i := 0; i < n; i++ {
v := make([]byte, 10*(1+rand.Intn(4)))
_, err := crypto.Read(v)
if err != nil {
return err
}
k := append(prefix, []byte(fmt.Sprintf("k%d", i))...)
if err := b.Put(k, v); err != nil {
return err
}
}
// limit depth of subbuckets
s := 2 + rand.Intn(4)
if len(prefix) > (2*s + 1) {
return nil
}
n = 1 + rand.Intn(3)
for i := 0; i < n; i++ {
k := append(prefix, []byte(fmt.Sprintf("b%d", i))...)
sb, err := b.CreateBucket(k)
if err != nil {
return err
}
if err := fillBucket(sb, append(k, '.')); err != nil {
return err
}
}
return nil
}
func chkdb(path string) ([]byte, error) {
db, err := bolt.Open(path, 0666, nil)
if err != nil {
return nil, err
}
defer db.Close()
var buf bytes.Buffer
err = db.View(func(tx *bolt.Tx) error {
return tx.ForEach(func(name []byte, b *bolt.Bucket) error {
return walkBucket(b, name, nil, &buf)
})
})
if err != nil {
return nil, err
}
return buf.Bytes(), nil
}
func walkBucket(parent *bolt.Bucket, k []byte, v []byte, w io.Writer) error {
if _, err := fmt.Fprintf(w, "%d:%x=%x\n", parent.Sequence(), k, v); err != nil {
return err
}
// not a bucket, exit.
if v != nil {
return nil
}
return parent.ForEach(func(k, v []byte) error {
if v == nil {
return walkBucket(parent.Bucket(k), k, nil, w)
}
return walkBucket(parent, k, v, w)
})
}
================================================
FILE: cursor.go
================================================
package bolt
import (
"bytes"
"fmt"
"sort"
)
// Cursor represents an iterator that can traverse over all key/value pairs in a bucket in sorted order.
// Cursors see nested buckets with value == nil.
// Cursors can be obtained from a transaction and are valid as long as the transaction is open.
//
// Keys and values returned from the cursor are only valid for the life of the transaction.
//
// Changing data while traversing with a cursor may cause it to be invalidated
// and return unexpected keys and/or values. You must reposition your cursor
// after mutating data.
type Cursor struct {
bucket *Bucket
stack []elemRef
}
// Bucket returns the bucket that this cursor was created from.
func (c *Cursor) Bucket() *Bucket {
return c.bucket
}
// First moves the cursor to the first item in the bucket and returns its key and value.
// If the bucket is empty then a nil key and value are returned.
// The returned key and value are only valid for the life of the transaction.
func (c *Cursor) First() (key []byte, value []byte) {
_assert(c.bucket.tx.db != nil, "tx closed")
c.stack = c.stack[:0]
p, n := c.bucket.pageNode(c.bucket.root)
c.stack = append(c.stack, elemRef{page: p, node: n, index: 0})
c.first()
// If we land on an empty page then move to the next value.
// https://github.com/boltdb/bolt/issues/450
if c.stack[len(c.stack)-1].count() == 0 {
c.next()
}
k, v, flags := c.keyValue()
if (flags & uint32(bucketLeafFlag)) != 0 {
return k, nil
}
return k, v
}
// Last moves the cursor to the last item in the bucket and returns its key and value.
// If the bucket is empty then a nil key and value are returned.
// The returned key and value are only valid for the life of the transaction.
func (c *Cursor) Last() (key []byte, value []byte) {
_assert(c.bucket.tx.db != nil, "tx closed")
c.stack = c.stack[:0]
p, n := c.bucket.pageNode(c.bucket.root)
ref := elemRef{page: p, node: n}
ref.index = ref.count() - 1
c.stack = append(c.stack, ref)
c.last()
k, v, flags := c.keyValue()
if (flags & uint32(bucketLeafFlag)) != 0 {
return k, nil
}
return k, v
}
// Next moves the cursor to the next item in the bucket and returns its key and value.
// If the cursor is at the end of the bucket then a nil key and value are returned.
// The returned key and value are only valid for the life of the transaction.
func (c *Cursor) Next() (key []byte, value []byte) {
_assert(c.bucket.tx.db != nil, "tx closed")
k, v, flags := c.next()
if (flags & uint32(bucketLeafFlag)) != 0 {
return k, nil
}
return k, v
}
// Prev moves the cursor to the previous item in the bucket and returns its key and value.
// If the cursor is at the beginning of the bucket then a nil key and value are returned.
// The returned key and value are only valid for the life of the transaction.
func (c *Cursor) Prev() (key []byte, value []byte) {
_assert(c.bucket.tx.db != nil, "tx closed")
// Attempt to move back one element until we're successful.
// Move up the stack as we hit the beginning of each page in our stack.
for i := len(c.stack) - 1; i >= 0; i-- {
elem := &c.stack[i]
if elem.index > 0 {
elem.index--
break
}
c.stack = c.stack[:i]
}
// If we've hit the end then return nil.
if len(c.stack) == 0 {
return nil, nil
}
// Move down the stack to find the last element of the last leaf under this branch.
c.last()
k, v, flags := c.keyValue()
if (flags & uint32(bucketLeafFlag)) != 0 {
return k, nil
}
return k, v
}
// Seek moves the cursor to a given key and returns it.
// If the key does not exist then the next key is used. If no keys
// follow, a nil key is returned.
// The returned key and value are only valid for the life of the transaction.
func (c *Cursor) Seek(seek []byte) (key []byte, value []byte) {
k, v, flags := c.seek(seek)
// If we ended up after the last element of a page then move to the next one.
if ref := &c.stack[len(c.stack)-1]; ref.index >= ref.count() {
k, v, flags = c.next()
}
if k == nil {
return nil, nil
} else if (flags & uint32(bucketLeafFlag)) != 0 {
return k, nil
}
return k, v
}
// Delete removes the current key/value under the cursor from the bucket.
// Delete fails if current key/value is a bucket or if the transaction is not writable.
func (c *Cursor) Delete() error {
if c.bucket.tx.db == nil {
return ErrTxClosed
} else if !c.bucket.Writable() {
return ErrTxNotWritable
}
key, _, flags := c.keyValue()
// Return an error if current value is a bucket.
if (flags & bucketLeafFlag) != 0 {
return ErrIncompatibleValue
}
c.node().del(key)
return nil
}
// seek moves the cursor to a given key and returns it.
// If the key does not exist then the next key is used.
func (c *Cursor) seek(seek []byte) (key []byte, value []byte, flags uint32) {
_assert(c.bucket.tx.db != nil, "tx closed")
// Start from root page/node and traverse to correct page.
c.stack = c.stack[:0]
c.search(seek, c.bucket.root)
ref := &c.stack[len(c.stack)-1]
// If the cursor is pointing to the end of page/node then return nil.
if ref.index >= ref.count() {
return nil, nil, 0
}
// If this is a bucket then return a nil value.
return c.keyValue()
}
// first moves the cursor to the first leaf element under the last page in the stack.
func (c *Cursor) first() {
for {
// Exit when we hit a leaf page.
var ref = &c.stack[len(c.stack)-1]
if ref.isLeaf() {
break
}
// Keep adding pages pointing to the first element to the stack.
var pgid pgid
if ref.node != nil {
pgid = ref.node.inodes[ref.index].pgid
} else {
pgid = ref.page.branchPageElement(uint16(ref.index)).pgid
}
p, n := c.bucket.pageNode(pgid)
c.stack = append(c.stack, elemRef{page: p, node: n, index: 0})
}
}
// last moves the cursor to the last leaf element under the last page in the stack.
func (c *Cursor) last() {
for {
// Exit when we hit a leaf page.
ref := &c.stack[len(c.stack)-1]
if ref.isLeaf() {
break
}
// Keep adding pages pointing to the last element in the stack.
var pgid pgid
if ref.node != nil {
pgid = ref.node.inodes[ref.index].pgid
} else {
pgid = ref.page.branchPageElement(uint16(ref.index)).pgid
}
p, n := c.bucket.pageNode(pgid)
var nextRef = elemRef{page: p, node: n}
nextRef.index = nextRef.count() - 1
c.stack = append(c.stack, nextRef)
}
}
// next moves to the next leaf element and returns the key and value.
// If the cursor is at the last leaf element then it stays there and returns nil.
func (c *Cursor) next() (key []byte, value []byte, flags uint32) {
for {
// Attempt to move over one element until we're successful.
// Move up the stack as we hit the end of each page in our stack.
var i int
for i = len(c.stack) - 1; i >= 0; i-- {
elem := &c.stack[i]
if elem.index < elem.count()-1 {
elem.index++
break
}
}
// If we've hit the root page then stop and return. This will leave the
// cursor on the last element of the last page.
if i == -1 {
return nil, nil, 0
}
// Otherwise start from where we left off in the stack and find the
// first element of the first leaf page.
c.stack = c.stack[:i+1]
c.first()
// If this is an empty page then restart and move back up the stack.
// https://github.com/boltdb/bolt/issues/450
if c.stack[len(c.stack)-1].count() == 0 {
continue
}
return c.keyValue()
}
}
// search recursively performs a binary search against a given page/node until it finds a given key.
func (c *Cursor) search(key []byte, pgid pgid) {
p, n := c.bucket.pageNode(pgid)
if p != nil && (p.flags&(branchPageFlag|leafPageFlag)) == 0 {
panic(fmt.Sprintf("invalid page type: %d: %x", p.id, p.flags))
}
e := elemRef{page: p, node: n}
c.stack = append(c.stack, e)
// If we're on a leaf page/node then find the specific node.
if e.isLeaf() {
c.nsearch(key)
return
}
if n != nil {
c.searchNode(key, n)
return
}
c.searchPage(key, p)
}
func (c *Cursor) searchNode(key []byte, n *node) {
var exact bool
index := sort.Search(len(n.inodes), func(i int) bool {
// TODO(benbjohnson): Optimize this range search. It's a bit hacky right now.
// sort.Search() finds the lowest index where f() != -1 but we need the highest index.
ret := bytes.Compare(n.inodes[i].key, key)
if ret == 0 {
exact = true
}
return ret != -1
})
if !exact && index > 0 {
index--
}
c.stack[len(c.stack)-1].index = index
// Recursively search to the next page.
c.search(key, n.inodes[index].pgid)
}
func (c *Cursor) searchPage(key []byte, p *page) {
// Binary search for the correct range.
inodes := p.branchPageElements()
var exact bool
index := sort.Search(int(p.count), func(i int) bool {
// TODO(benbjohnson): Optimize this range search. It's a bit hacky right now.
// sort.Search() finds the lowest index where f() != -1 but we need the highest index.
ret := bytes.Compare(inodes[i].key(), key)
if ret == 0 {
exact = true
}
return ret != -1
})
if !exact && index > 0 {
index--
}
c.stack[len(c.stack)-1].index = index
// Recursively search to the next page.
c.search(key, inodes[index].pgid)
}
// nsearch searches the leaf node on the top of the stack for a key.
func (c *Cursor) nsearch(key []byte) {
e := &c.stack[len(c.stack)-1]
p, n := e.page, e.node
// If we have a node then search its inodes.
if n != nil {
index := sort.Search(len(n.inodes), func(i int) bool {
return bytes.Compare(n.inodes[i].key, key) != -1
})
e.index = index
return
}
// If we have a page then search its leaf elements.
inodes := p.leafPageElements()
index := sort.Search(int(p.count), func(i int) bool {
return bytes.Compare(inodes[i].key(), key) != -1
})
e.index = index
}
// keyValue returns the key and value of the current leaf element.
func (c *Cursor) keyValue() ([]byte, []byte, uint32) {
ref := &c.stack[len(c.stack)-1]
if ref.count() == 0 || ref.index >= ref.count() {
return nil, nil, 0
}
// Retrieve value from node.
if ref.node != nil {
inode := &ref.node.inodes[ref.index]
return inode.key, inode.value, inode.flags
}
// Or retrieve value from page.
elem := ref.page.leafPageElement(uint16(ref.index))
return elem.key(), elem.value(), elem.flags
}
// node returns the node that the cursor is currently positioned on.
func (c *Cursor) node() *node {
_assert(len(c.stack) > 0, "accessing a node with a zero-length cursor stack")
// If the top of the stack is a leaf node then just return it.
if ref := &c.stack[len(c.stack)-1]; ref.node != nil && ref.isLeaf() {
return ref.node
}
// Start from root and traverse down the hierarchy.
var n = c.stack[0].node
if n == nil {
n = c.bucket.node(c.stack[0].page.id, nil)
}
for _, ref := range c.stack[:len(c.stack)-1] {
_assert(!n.isLeaf, "expected branch node")
n = n.childAt(int(ref.index))
}
_assert(n.isLeaf, "expected leaf node")
return n
}
// elemRef represents a reference to an element on a given page/node.
type elemRef struct {
page *page
node *node
index int
}
// isLeaf returns whether the ref is pointing at a leaf page/node.
func (r *elemRef) isLeaf() bool {
if r.node != nil {
return r.node.isLeaf
}
return (r.page.flags & leafPageFlag) != 0
}
// count returns the number of inodes or page elements.
func (r *elemRef) count() int {
if r.node != nil {
return len(r.node.inodes)
}
return int(r.page.count)
}
================================================
FILE: cursor_test.go
================================================
package bolt_test
import (
"bytes"
"encoding/binary"
"fmt"
"log"
"os"
"reflect"
"sort"
"testing"
"testing/quick"
"github.com/boltdb/bolt"
)
// Ensure that a cursor can return a reference to the bucket that created it.
func TestCursor_Bucket(t *testing.T) {
db := MustOpenDB()
defer db.MustClose()
if err := db.Update(func(tx *bolt.Tx) error {
b, err := tx.CreateBucket([]byte("widgets"))
if err != nil {
t.Fatal(err)
}
if cb := b.Cursor().Bucket(); !reflect.DeepEqual(cb, b) {
t.Fatal("cursor bucket mismatch")
}
return nil
}); err != nil {
t.Fatal(err)
}
}
// Ensure that a Tx cursor can seek to the appropriate keys.
func TestCursor_Seek(t *testing.T) {
db := MustOpenDB()
defer db.MustClose()
if err := db.Update(func(tx *bolt.Tx) error {
b, err := tx.CreateBucket([]byte("widgets"))
if err != nil {
t.Fatal(err)
}
if err := b.Put([]byte("foo"), []byte("0001")); err != nil {
t.Fatal(err)
}
if err := b.Put([]byte("bar"), []byte("0002")); err != nil {
t.Fatal(err)
}
if err := b.Put([]byte("baz"), []byte("0003")); err != nil {
t.Fatal(err)
}
if _, err := b.CreateBucket([]byte("bkt")); err != nil {
t.Fatal(err)
}
return nil
}); err != nil {
t.Fatal(err)
}
if err := db.View(func(tx *bolt.Tx) error {
c := tx.Bucket([]byte("widgets")).Cursor()
// Exact match should go to the key.
if k, v := c.Seek([]byte("bar")); !bytes.Equal(k, []byte("bar")) {
t.Fatalf("unexpected key: %v", k)
} else if !bytes.Equal(v, []byte("0002")) {
t.Fatalf("unexpected value: %v", v)
}
// Inexact match should go to the next key.
if k, v := c.Seek([]byte("bas")); !bytes.Equal(k, []byte("baz")) {
t.Fatalf("unexpected key: %v", k)
} else if !bytes.Equal(v, []byte("0003")) {
t.Fatalf("unexpected value: %v", v)
}
// Low key should go to the first key.
if k, v := c.Seek([]byte("")); !bytes.Equal(k, []byte("bar")) {
t.Fatalf("unexpected key: %v", k)
} else if !bytes.Equal(v, []byte("0002")) {
t.Fatalf("unexpected value: %v", v)
}
// High key should return no key.
if k, v := c.Seek([]byte("zzz")); k != nil {
t.Fatalf("expected nil key: %v", k)
} else if v != nil {
t.Fatalf("expected nil value: %v", v)
}
// Buckets should return their key but no value.
if k, v := c.Seek([]byte("bkt")); !bytes.Equal(k, []byte("bkt")) {
t.Fatalf("unexpected key: %v", k)
} else if v != nil {
t.Fatalf("expected nil value: %v", v)
}
return nil
}); err != nil {
t.Fatal(err)
}
}
func TestCursor_Delete(t *testing.T) {
db := MustOpenDB()
defer db.MustClose()
const count = 1000
// Insert every other key between 0 and $count.
if err := db.Update(func(tx *bolt.Tx) error {
b, err := tx.CreateBucket([]byte("widgets"))
if err != nil {
t.Fatal(err)
}
for i := 0; i < count; i += 1 {
k := make([]byte, 8)
binary.BigEndian.PutUint64(k, uint64(i))
if err := b.Put(k, make([]byte, 100)); err != nil {
t.Fatal(err)
}
}
if _, err := b.CreateBucket([]byte("sub")); err != nil {
t.Fatal(err)
}
return nil
}); err != nil {
t.Fatal(err)
}
if err := db.Update(func(tx *bolt.Tx) error {
c := tx.Bucket([]byte("widgets")).Cursor()
bound := make([]byte, 8)
binary.BigEndian.PutUint64(bound, uint64(count/2))
for key, _ := c.First(); bytes.Compare(key, bound) < 0; key, _ = c.Next() {
if err := c.Delete(); err != nil {
t.Fatal(err)
}
}
c.Seek([]byte("sub"))
if err := c.Delete(); err != bolt.ErrIncompatibleValue {
t.Fatalf("unexpected error: %s", err)
}
return nil
}); err != nil {
t.Fatal(err)
}
if err := db.View(func(tx *bolt.Tx) error {
stats := tx.Bucket([]byte("widgets")).Stats()
if stats.KeyN != count/2+1 {
t.Fatalf("unexpected KeyN: %d", stats.KeyN)
}
return nil
}); err != nil {
t.Fatal(err)
}
}
// Ensure that a Tx cursor can seek to the appropriate keys when there are a
// large number of keys. This test also checks that seek will always move
// forward to the next key.
//
// Related: https://github.com/boltdb/bolt/pull/187
func TestCursor_Seek_Large(t *testing.T) {
db := MustOpenDB()
defer db.MustClose()
var count = 10000
// Insert every other key between 0 and $count.
if err := db.Update(func(tx *bolt.Tx) error {
b, err := tx.CreateBucket([]byte("widgets"))
if err != nil {
t.Fatal(err)
}
for i := 0; i < count; i += 100 {
for j := i; j < i+100; j += 2 {
k := make([]byte, 8)
binary.BigEndian.PutUint64(k, uint64(j))
if err := b.Put(k, make([]byte, 100)); err != nil {
t.Fatal(err)
}
}
}
return nil
}); err != nil {
t.Fatal(err)
}
if err := db.View(func(tx *bolt.Tx) error {
c := tx.Bucket([]byte("widgets")).Cursor()
for i := 0; i < count; i++ {
seek := make([]byte, 8)
binary.BigEndian.PutUint64(seek, uint64(i))
k, _ := c.Seek(seek)
// The last seek is beyond the end of the the range so
// it should return nil.
if i == count-1 {
if k != nil {
t.Fatal("expected nil key")
}
continue
}
// Otherwise we should seek to the exact key or the next key.
num := binary.BigEndian.Uint64(k)
if i%2 == 0 {
if num != uint64(i) {
t.Fatalf("unexpected num: %d", num)
}
} else {
if num != uint64(i+1) {
t.Fatalf("unexpected num: %d", num)
}
}
}
return nil
}); err != nil {
t.Fatal(err)
}
}
// Ensure that a cursor can iterate over an empty bucket without error.
func TestCursor_EmptyBucket(t *testing.T) {
db := MustOpenDB()
defer db.MustClose()
if err := db.Update(func(tx *bolt.Tx) error {
_, err := tx.CreateBucket([]byte("widgets"))
return err
}); err != nil {
t.Fatal(err)
}
if err := db.View(func(tx *bolt.Tx) error {
c := tx.Bucket([]byte("widgets")).Cursor()
k, v := c.First()
if k != nil {
t.Fatalf("unexpected key: %v", k)
} else if v != nil {
t.Fatalf("unexpected value: %v", v)
}
return nil
}); err != nil {
t.Fatal(err)
}
}
// Ensure that a Tx cursor can reverse iterate over an empty bucket without error.
func TestCursor_EmptyBucketReverse(t *testing.T) {
db := MustOpenDB()
defer db.MustClose()
if err := db.Update(func(tx *bolt.Tx) error {
_, err := tx.CreateBucket([]byte("widgets"))
return err
}); err != nil {
t.Fatal(err)
}
if err := db.View(func(tx *bolt.Tx) error {
c := tx.Bucket([]byte("widgets")).Cursor()
k, v := c.Last()
if k != nil {
t.Fatalf("unexpected key: %v", k)
} else if v != nil {
t.Fatalf("unexpected value: %v", v)
}
return nil
}); err != nil {
t.Fatal(err)
}
}
// Ensure that a Tx cursor can iterate over a single root with a couple elements.
func TestCursor_Iterate_Leaf(t *testing.T) {
db := MustOpenDB()
defer db.MustClose()
if err := db.Update(func(tx *bolt.Tx) error {
b, err := tx.CreateBucket([]byte("widgets"))
if err != nil {
t.Fatal(err)
}
if err := b.Put([]byte("baz"), []byte{}); err != nil {
t.Fatal(err)
}
if err := b.Put([]byte("foo"), []byte{0}); err != nil {
t.Fatal(err)
}
if err := b.Put([]byte("bar"), []byte{1}); err != nil {
t.Fatal(err)
}
return nil
}); err != nil {
t.Fatal(err)
}
tx, err := db.Begin(false)
if err != nil {
t.Fatal(err)
}
defer func() { _ = tx.Rollback() }()
c := tx.Bucket([]byte("widgets")).Cursor()
k, v := c.First()
if !bytes.Equal(k, []byte("bar")) {
t.Fatalf("unexpected key: %v", k)
} else if !bytes.Equal(v, []byte{1}) {
t.Fatalf("unexpected value: %v", v)
}
k, v = c.Next()
if !bytes.Equal(k, []byte("baz")) {
t.Fatalf("unexpected key: %v", k)
} else if !bytes.Equal(v, []byte{}) {
t.Fatalf("unexpected value: %v", v)
}
k, v = c.Next()
if !bytes.Equal(k, []byte("foo")) {
t.Fatalf("unexpected key: %v", k)
} else if !bytes.Equal(v, []byte{0}) {
t.Fatalf("unexpected value: %v", v)
}
k, v = c.Next()
if k != nil {
t.Fatalf("expected nil key: %v", k)
} else if v != nil {
t.Fatalf("expected nil value: %v", v)
}
k, v = c.Next()
if k != nil {
t.Fatalf("expected nil key: %v", k)
} else if v != nil {
t.Fatalf("expected nil value: %v", v)
}
if err := tx.Rollback(); err != nil {
t.Fatal(err)
}
}
// Ensure that a Tx cursor can iterate in reverse over a single root with a couple elements.
func TestCursor_LeafRootReverse(t *testing.T) {
db := MustOpenDB()
defer db.MustClose()
if err := db.Update(func(tx *bolt.Tx) error {
b, err := tx.CreateBucket([]byte("widgets"))
if err != nil {
t.Fatal(err)
}
if err := b.Put([]byte("baz"), []byte{}); err != nil {
t.Fatal(err)
}
if err := b.Put([]byte("foo"), []byte{0}); err != nil {
t.Fatal(err)
}
if err := b.Put([]byte("bar"), []byte{1}); err != nil {
t.Fatal(err)
}
return nil
}); err != nil {
t.Fatal(err)
}
tx, err := db.Begin(false)
if err != nil {
t.Fatal(err)
}
c := tx.Bucket([]byte("widgets")).Cursor()
if k, v := c.Last(); !bytes.Equal(k, []byte("foo")) {
t.Fatalf("unexpected key: %v", k)
} else if !bytes.Equal(v, []byte{0}) {
t.Fatalf("unexpected value: %v", v)
}
if k, v := c.Prev(); !bytes.Equal(k, []byte("baz")) {
t.Fatalf("unexpected key: %v", k)
} else if !bytes.Equal(v, []byte{}) {
t.Fatalf("unexpected value: %v", v)
}
if k, v := c.Prev(); !bytes.Equal(k, []byte("bar")) {
t.Fatalf("unexpected key: %v", k)
} else if !bytes.Equal(v, []byte{1}) {
t.Fatalf("unexpected value: %v", v)
}
if k, v := c.Prev(); k != nil {
t.Fatalf("expected nil key: %v", k)
} else if v != nil {
t.Fatalf("expected nil value: %v", v)
}
if k, v := c.Prev(); k != nil {
t.Fatalf("expected nil key: %v", k)
} else if v != nil {
t.Fatalf("expected nil value: %v", v)
}
if err := tx.Rollback(); err != nil {
t.Fatal(err)
}
}
// Ensure that a Tx cursor can restart from the beginning.
func TestCursor_Restart(t *testing.T) {
db := MustOpenDB()
defer db.MustClose()
if err := db.Update(func(tx *bolt.Tx) error {
b, err := tx.CreateBucket([]byte("widgets"))
if err != nil {
t.Fatal(err)
}
if err := b.Put([]byte("bar"), []byte{}); err != nil {
t.Fatal(err)
}
if err := b.Put([]byte("foo"), []byte{}); err != nil {
t.Fatal(err)
}
return nil
}); err != nil {
t.Fatal(err)
}
tx, err := db.Begin(false)
if err != nil {
t.Fatal(err)
}
c := tx.Bucket([]byte("widgets")).Cursor()
if k, _ := c.First(); !bytes.Equal(k, []byte("bar")) {
t.Fatalf("unexpected key: %v", k)
}
if k, _ := c.Next(); !bytes.Equal(k, []byte("foo")) {
t.Fatalf("unexpected key: %v", k)
}
if k, _ := c.First(); !bytes.Equal(k, []byte("bar")) {
t.Fatalf("unexpected key: %v", k)
}
if k, _ := c.Next(); !bytes.Equal(k, []byte("foo")) {
t.Fatalf("unexpected key: %v", k)
}
if err := tx.Rollback(); err != nil {
t.Fatal(err)
}
}
// Ensure that a cursor can skip over empty pages that have been deleted.
func TestCursor_First_EmptyPages(t *testing.T) {
db := MustOpenDB()
defer db.MustClose()
// Create 1000 keys in the "widgets" bucket.
if err := db.Update(func(tx *bolt.Tx) error {
b, err := tx.CreateBucket([]byte("widgets"))
if err != nil {
t.Fatal(err)
}
for i := 0; i < 1000; i++ {
if err := b.Put(u64tob(uint64(i)), []byte{}); err != nil {
t.Fatal(err)
}
}
return nil
}); err != nil {
t.Fatal(err)
}
// Delete half the keys and then try to iterate.
if err := db.Update(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte("widgets"))
for i := 0; i < 600; i++ {
if err := b.Delete(u64tob(uint64(i))); err != nil {
t.Fatal(err)
}
}
c := b.Cursor()
var n int
for k, _ := c.First(); k != nil; k, _ = c.Next() {
n++
}
if n != 400 {
t.Fatalf("unexpected key count: %d", n)
}
return nil
}); err != nil {
t.Fatal(err)
}
}
// Ensure that a Tx can iterate over all elements in a bucket.
func TestCursor_QuickCheck(t *testing.T) {
f := func(items testdata) bool {
db := MustOpenDB()
defer db.MustClose()
// Bulk insert all values.
tx, err := db.Begin(true)
if err != nil {
t.Fatal(err)
}
b, err := tx.CreateBucket([]byte("widgets"))
if err != nil {
t.Fatal(err)
}
for _, item := range items {
if err := b.Put(item.Key, item.Value); err != nil {
t.Fatal(err)
}
}
if err := tx.Commit(); err != nil {
t.Fatal(err)
}
// Sort test data.
sort.Sort(items)
// Iterate over all items and check consistency.
var index = 0
tx, err = db.Begin(false)
if err != nil {
t.Fatal(err)
}
c := tx.Bucket([]byte("widgets")).Cursor()
for k, v := c.First(); k != nil && index < len(items); k, v = c.Next() {
if !bytes.Equal(k, items[index].Key) {
t.Fatalf("unexpected key: %v", k)
} else if !bytes.Equal(v, items[index].Value) {
t.Fatalf("unexpected value: %v", v)
}
index++
}
if len(items) != index {
t.Fatalf("unexpected item count: %v, expected %v", len(items), index)
}
if err := tx.Rollback(); err != nil {
t.Fatal(err)
}
return true
}
if err := quick.Check(f, qconfig()); err != nil {
t.Error(err)
}
}
// Ensure that a transaction can iterate over all elements in a bucket in reverse.
func TestCursor_QuickCheck_Reverse(t *testing.T) {
f := func(items testdata) bool {
db := MustOpenDB()
defer db.MustClose()
// Bulk insert all values.
tx, err := db.Begin(true)
if err != nil {
t.Fatal(err)
}
b, err := tx.CreateBucket([]byte("widgets"))
if err != nil {
t.Fatal(err)
}
for _, item := range items {
if err := b.Put(item.Key, item.Value); err != nil {
t.Fatal(err)
}
}
if err := tx.Commit(); err != nil {
t.Fatal(err)
}
// Sort test data.
sort.Sort(revtestdata(items))
// Iterate over all items and check consistency.
var index = 0
tx, err = db.Begin(false)
if err != nil {
t.Fatal(err)
}
c := tx.Bucket([]byte("widgets")).Cursor()
for k, v := c.Last(); k != nil && index < len(items); k, v = c.Prev() {
if !bytes.Equal(k, items[index].Key) {
t.Fatalf("unexpected key: %v", k)
} else if !bytes.Equal(v, items[index].Value) {
t.Fatalf("unexpected value: %v", v)
}
index++
}
if len(items) != index {
t.Fatalf("unexpected item count: %v, expected %v", len(items), index)
}
if err := tx.Rollback(); err != nil {
t.Fatal(err)
}
return true
}
if err := quick.Check(f, qconfig()); err != nil {
t.Error(err)
}
}
// Ensure that a Tx cursor can iterate over subbuckets.
func TestCursor_QuickCheck_BucketsOnly(t *testing.T) {
db := MustOpenDB()
defer db.MustClose()
if err := db.Update(func(tx *bolt.Tx) error {
b, err := tx.CreateBucket([]byte("widgets"))
if err != nil {
t.Fatal(err)
}
if _, err := b.CreateBucket([]byte("foo")); err != nil {
t.Fatal(err)
}
if _, err := b.CreateBucket([]byte("bar")); err != nil {
t.Fatal(err)
}
if _, err := b.CreateBucket([]byte("baz")); err != nil {
t.Fatal(err)
}
return nil
}); er
gitextract_kz6jb5aj/ ├── .gitignore ├── LICENSE ├── Makefile ├── README.md ├── appveyor.yml ├── bolt_386.go ├── bolt_amd64.go ├── bolt_arm.go ├── bolt_arm64.go ├── bolt_linux.go ├── bolt_openbsd.go ├── bolt_ppc.go ├── bolt_ppc64.go ├── bolt_ppc64le.go ├── bolt_s390x.go ├── bolt_unix.go ├── bolt_unix_solaris.go ├── bolt_windows.go ├── boltsync_unix.go ├── bucket.go ├── bucket_test.go ├── cmd/ │ └── bolt/ │ ├── main.go │ └── main_test.go ├── cursor.go ├── cursor_test.go ├── db.go ├── db_test.go ├── doc.go ├── errors.go ├── freelist.go ├── freelist_test.go ├── node.go ├── node_test.go ├── page.go ├── page_test.go ├── quick_test.go ├── simulation_test.go ├── tx.go └── tx_test.go
SYMBOL INDEX (599 symbols across 32 files)
FILE: bolt_386.go
constant maxMapSize (line 4) | maxMapSize = 0x7FFFFFFF
constant maxAllocSize (line 7) | maxAllocSize = 0xFFFFFFF
FILE: bolt_amd64.go
constant maxMapSize (line 4) | maxMapSize = 0xFFFFFFFFFFFF
constant maxAllocSize (line 7) | maxAllocSize = 0x7FFFFFFF
FILE: bolt_arm.go
constant maxMapSize (line 6) | maxMapSize = 0x7FFFFFFF
constant maxAllocSize (line 9) | maxAllocSize = 0xFFFFFFF
function init (line 14) | func init() {
FILE: bolt_arm64.go
constant maxMapSize (line 6) | maxMapSize = 0xFFFFFFFFFFFF
constant maxAllocSize (line 9) | maxAllocSize = 0x7FFFFFFF
FILE: bolt_linux.go
function fdatasync (line 8) | func fdatasync(db *DB) error {
FILE: bolt_openbsd.go
constant msAsync (line 9) | msAsync = 1 << iota
constant msSync (line 10) | msSync
constant msInvalidate (line 11) | msInvalidate
function msync (line 14) | func msync(db *DB) error {
function fdatasync (line 22) | func fdatasync(db *DB) error {
FILE: bolt_ppc.go
constant maxMapSize (line 6) | maxMapSize = 0x7FFFFFFF
constant maxAllocSize (line 9) | maxAllocSize = 0xFFFFFFF
FILE: bolt_ppc64.go
constant maxMapSize (line 6) | maxMapSize = 0xFFFFFFFFFFFF
constant maxAllocSize (line 9) | maxAllocSize = 0x7FFFFFFF
FILE: bolt_ppc64le.go
constant maxMapSize (line 6) | maxMapSize = 0xFFFFFFFFFFFF
constant maxAllocSize (line 9) | maxAllocSize = 0x7FFFFFFF
FILE: bolt_s390x.go
constant maxMapSize (line 6) | maxMapSize = 0xFFFFFFFFFFFF
constant maxAllocSize (line 9) | maxAllocSize = 0x7FFFFFFF
FILE: bolt_unix.go
function flock (line 14) | func flock(db *DB, mode os.FileMode, exclusive bool, timeout time.Durati...
function funlock (line 43) | func funlock(db *DB) error {
function mmap (line 48) | func mmap(db *DB, sz int) error {
function munmap (line 68) | func munmap(db *DB) error {
function madvise (line 83) | func madvise(b []byte, advice int) (err error) {
FILE: bolt_unix_solaris.go
function flock (line 14) | func flock(db *DB, mode os.FileMode, exclusive bool, timeout time.Durati...
function funlock (line 48) | func funlock(db *DB) error {
function mmap (line 58) | func mmap(db *DB, sz int) error {
function munmap (line 78) | func munmap(db *DB) error {
FILE: bolt_windows.go
constant lockExt (line 19) | lockExt = ".lock"
constant flagLockExclusive (line 22) | flagLockExclusive = 2
constant flagLockFailImmediately (line 23) | flagLockFailImmediately = 1
constant errLockViolation (line 26) | errLockViolation syscall.Errno = 0x21
function lockFileEx (line 29) | func lockFileEx(h syscall.Handle, flags, reserved, locklow, lockhigh uin...
function unlockFileEx (line 37) | func unlockFileEx(h syscall.Handle, reserved, locklow, lockhigh uint32, ...
function fdatasync (line 46) | func fdatasync(db *DB) error {
function flock (line 51) | func flock(db *DB, mode os.FileMode, exclusive bool, timeout time.Durati...
function funlock (line 89) | func funlock(db *DB) error {
function mmap (line 98) | func mmap(db *DB, sz int) error {
function munmap (line 134) | func munmap(db *DB) error {
FILE: boltsync_unix.go
function fdatasync (line 6) | func fdatasync(db *DB) error {
FILE: bucket.go
constant MaxKeySize (line 11) | MaxKeySize = 32768
constant MaxValueSize (line 14) | MaxValueSize = (1 << 31) - 2
constant maxUint (line 18) | maxUint = ^uint(0)
constant minUint (line 19) | minUint = 0
constant maxInt (line 20) | maxInt = int(^uint(0) >> 1)
constant minInt (line 21) | minInt = -maxInt - 1
constant bucketHeaderSize (line 24) | bucketHeaderSize = int(unsafe.Sizeof(bucket{}))
constant minFillPercent (line 27) | minFillPercent = 0.1
constant maxFillPercent (line 28) | maxFillPercent = 1.0
constant DefaultFillPercent (line 33) | DefaultFillPercent = 0.5
type Bucket (line 36) | type Bucket struct
method Tx (line 72) | func (b *Bucket) Tx() *Tx {
method Root (line 77) | func (b *Bucket) Root() pgid {
method Writable (line 82) | func (b *Bucket) Writable() bool {
method Cursor (line 89) | func (b *Bucket) Cursor() *Cursor {
method Bucket (line 103) | func (b *Bucket) Bucket(name []byte) *Bucket {
method openBucket (line 130) | func (b *Bucket) openBucket(value []byte) *Bucket {
method CreateBucket (line 161) | func (b *Bucket) CreateBucket(key []byte) (*Bucket, error) {
method CreateBucketIfNotExists (line 205) | func (b *Bucket) CreateBucketIfNotExists(key []byte) (*Bucket, error) {
method DeleteBucket (line 217) | func (b *Bucket) DeleteBucket(key []byte) error {
method Get (line 266) | func (b *Bucket) Get(key []byte) []byte {
method Put (line 285) | func (b *Bucket) Put(key []byte, value []byte) error {
method Delete (line 317) | func (b *Bucket) Delete(key []byte) error {
method Sequence (line 340) | func (b *Bucket) Sequence() uint64 { return b.bucket.sequence }
method SetSequence (line 343) | func (b *Bucket) SetSequence(v uint64) error {
method NextSequence (line 362) | func (b *Bucket) NextSequence() (uint64, error) {
method ForEach (line 384) | func (b *Bucket) ForEach(fn func(k, v []byte) error) error {
method Stats (line 398) | func (b *Bucket) Stats() BucketStats {
method forEachPage (line 480) | func (b *Bucket) forEachPage(fn func(*page, int)) {
method forEachPageNode (line 493) | func (b *Bucket) forEachPageNode(fn func(*page, *node, int)) {
method _forEachPageNode (line 502) | func (b *Bucket) _forEachPageNode(pgid pgid, depth int, fn func(*page,...
method spill (line 526) | func (b *Bucket) spill() error {
method inlineable (line 586) | func (b *Bucket) inlineable() bool {
method maxInlineBucketSize (line 611) | func (b *Bucket) maxInlineBucketSize() int {
method write (line 616) | func (b *Bucket) write() []byte {
method rebalance (line 633) | func (b *Bucket) rebalance() {
method node (line 643) | func (b *Bucket) node(pgid pgid, parent *node) *node {
method free (line 676) | func (b *Bucket) free() {
method dereference (line 693) | func (b *Bucket) dereference() {
method pageNode (line 705) | func (b *Bucket) pageNode(id pgid) (*page, *node) {
type bucket (line 56) | type bucket struct
function newBucket (line 62) | func newBucket(tx *Tx) Bucket {
type BucketStats (line 730) | type BucketStats struct
method Add (line 753) | func (s *BucketStats) Add(other BucketStats) {
function cloneBytes (line 773) | func cloneBytes(v []byte) []byte {
FILE: bucket_test.go
function TestBucket_Get_NonExistent (line 20) | func TestBucket_Get_NonExistent(t *testing.T) {
function TestBucket_Get_FromNode (line 39) | func TestBucket_Get_FromNode(t *testing.T) {
function TestBucket_Get_IncompatibleValue (line 61) | func TestBucket_Get_IncompatibleValue(t *testing.T) {
function TestBucket_Get_Capacity (line 87) | func TestBucket_Get_Capacity(t *testing.T) {
function TestBucket_Put (line 124) | func TestBucket_Put(t *testing.T) {
function TestBucket_Put_Repeat (line 147) | func TestBucket_Put_Repeat(t *testing.T) {
function TestBucket_Put_Large (line 173) | func TestBucket_Put_Large(t *testing.T) {
function TestDB_Put_VeryLarge (line 208) | func TestDB_Put_VeryLarge(t *testing.T) {
function TestBucket_Put_IncompatibleValue (line 240) | func TestBucket_Put_IncompatibleValue(t *testing.T) {
function TestBucket_Put_Closed (line 263) | func TestBucket_Put_Closed(t *testing.T) {
function TestBucket_Put_ReadOnly (line 286) | func TestBucket_Put_ReadOnly(t *testing.T) {
function TestBucket_Delete (line 311) | func TestBucket_Delete(t *testing.T) {
function TestBucket_Delete_Large (line 336) | func TestBucket_Delete_Large(t *testing.T) {
function TestBucket_Delete_FreelistOverflow (line 383) | func TestBucket_Delete_FreelistOverflow(t *testing.T) {
function TestBucket_Nested (line 429) | func TestBucket_Nested(t *testing.T) {
function TestBucket_Delete_Bucket (line 516) | func TestBucket_Delete_Bucket(t *testing.T) {
function TestBucket_Delete_ReadOnly (line 537) | func TestBucket_Delete_ReadOnly(t *testing.T) {
function TestBucket_Delete_Closed (line 561) | func TestBucket_Delete_Closed(t *testing.T) {
function TestBucket_DeleteBucket_Nested (line 584) | func TestBucket_DeleteBucket_Nested(t *testing.T) {
function TestBucket_DeleteBucket_Nested2 (line 616) | func TestBucket_DeleteBucket_Nested2(t *testing.T) {
function TestBucket_DeleteBucket_Large (line 683) | func TestBucket_DeleteBucket_Large(t *testing.T) {
function TestBucket_Bucket_IncompatibleValue (line 719) | func TestBucket_Bucket_IncompatibleValue(t *testing.T) {
function TestBucket_CreateBucket_IncompatibleValue (line 742) | func TestBucket_CreateBucket_IncompatibleValue(t *testing.T) {
function TestBucket_DeleteBucket_IncompatibleValue (line 764) | func TestBucket_DeleteBucket_IncompatibleValue(t *testing.T) {
function TestBucket_Sequence (line 786) | func TestBucket_Sequence(t *testing.T) {
function TestBucket_NextSequence (line 828) | func TestBucket_NextSequence(t *testing.T) {
function TestBucket_NextSequence_Persist (line 871) | func TestBucket_NextSequence_Persist(t *testing.T) {
function TestBucket_NextSequence_ReadOnly (line 907) | func TestBucket_NextSequence_ReadOnly(t *testing.T) {
function TestBucket_NextSequence_Closed (line 932) | func TestBucket_NextSequence_Closed(t *testing.T) {
function TestBucket_ForEach (line 952) | func TestBucket_ForEach(t *testing.T) {
function TestBucket_ForEach_ShortCircuit (line 1010) | func TestBucket_ForEach_ShortCircuit(t *testing.T) {
function TestBucket_ForEach_Closed (line 1049) | func TestBucket_ForEach_Closed(t *testing.T) {
function TestBucket_Put_EmptyKey (line 1073) | func TestBucket_Put_EmptyKey(t *testing.T) {
function TestBucket_Put_KeyTooLarge (line 1095) | func TestBucket_Put_KeyTooLarge(t *testing.T) {
function TestBucket_Put_ValueTooLarge (line 1113) | func TestBucket_Put_ValueTooLarge(t *testing.T) {
function TestBucket_Stats (line 1137) | func TestBucket_Stats(t *testing.T) {
function TestBucket_Stats_RandomFill (line 1224) | func TestBucket_Stats_RandomFill(t *testing.T) {
function TestBucket_Stats_Small (line 1292) | func TestBucket_Stats_Small(t *testing.T) {
function TestBucket_Stats_EmptyBucket (line 1356) | func TestBucket_Stats_EmptyBucket(t *testing.T) {
function TestBucket_Stats_Nested (line 1416) | func TestBucket_Stats_Nested(t *testing.T) {
function TestBucket_Stats_Large (line 1518) | func TestBucket_Stats_Large(t *testing.T) {
function TestBucket_Put_Single (line 1591) | func TestBucket_Put_Single(t *testing.T) {
function TestBucket_Put_Multiple (line 1649) | func TestBucket_Put_Multiple(t *testing.T) {
function TestBucket_Delete_Quick (line 1702) | func TestBucket_Delete_Quick(t *testing.T) {
function ExampleBucket_Put (line 1761) | func ExampleBucket_Put() {
function ExampleBucket_Delete (line 1804) | func ExampleBucket_Delete() {
function ExampleBucket_ForEach (line 1862) | func ExampleBucket_ForEach() {
FILE: cmd/bolt/main.go
constant PageHeaderSize (line 60) | PageHeaderSize = 16
function main (line 62) | func main() {
type Main (line 73) | type Main struct
method Run (line 89) | func (m *Main) Run(args ...string) error {
method Usage (line 123) | func (m *Main) Usage() string {
function NewMain (line 80) | func NewMain() *Main {
type CheckCommand (line 146) | type CheckCommand struct
method Run (line 162) | func (cmd *CheckCommand) Run(args ...string) error {
method Usage (line 217) | func (cmd *CheckCommand) Usage() string {
function newCheckCommand (line 153) | func newCheckCommand(m *Main) *CheckCommand {
type InfoCommand (line 231) | type InfoCommand struct
method Run (line 247) | func (cmd *InfoCommand) Run(args ...string) error {
method Usage (line 281) | func (cmd *InfoCommand) Usage() string {
function newInfoCommand (line 238) | func newInfoCommand(m *Main) *InfoCommand {
type DumpCommand (line 290) | type DumpCommand struct
method Run (line 306) | func (cmd *DumpCommand) Run(args ...string) error {
method PrintPage (line 363) | func (cmd *DumpCommand) PrintPage(w io.Writer, r io.ReaderAt, pageID i...
method Usage (line 408) | func (cmd *DumpCommand) Usage() string {
function newDumpCommand (line 297) | func newDumpCommand(m *Main) *DumpCommand {
type PageCommand (line 417) | type PageCommand struct
method Run (line 433) | func (cmd *PageCommand) Run(args ...string) error {
method PrintMeta (line 505) | func (cmd *PageCommand) PrintMeta(w io.Writer, buf []byte) error {
method PrintLeaf (line 520) | func (cmd *PageCommand) PrintLeaf(w io.Writer, buf []byte) error {
method PrintBranch (line 557) | func (cmd *PageCommand) PrintBranch(w io.Writer, buf []byte) error {
method PrintFreelist (line 583) | func (cmd *PageCommand) PrintFreelist(w io.Writer, buf []byte) error {
method PrintPage (line 600) | func (cmd *PageCommand) PrintPage(w io.Writer, r io.ReaderAt, pageID i...
method Usage (line 645) | func (cmd *PageCommand) Usage() string {
function newPageCommand (line 424) | func newPageCommand(m *Main) *PageCommand {
type PagesCommand (line 654) | type PagesCommand struct
method Run (line 670) | func (cmd *PagesCommand) Run(args ...string) error {
method Usage (line 733) | func (cmd *PagesCommand) Usage() string {
function newPagesCommand (line 661) | func newPagesCommand(m *Main) *PagesCommand {
type StatsCommand (line 748) | type StatsCommand struct
method Run (line 764) | func (cmd *StatsCommand) Run(args ...string) error {
method Usage (line 847) | func (cmd *StatsCommand) Usage() string {
function newStatsCommand (line 755) | func newStatsCommand(m *Main) *StatsCommand {
type BenchCommand (line 885) | type BenchCommand struct
method Run (line 901) | func (cmd *BenchCommand) Run(args ...string) error {
method ParseFlags (line 942) | func (cmd *BenchCommand) ParseFlags(args []string) (*BenchOptions, err...
method runWrites (line 989) | func (cmd *BenchCommand) runWrites(db *bolt.DB, options *BenchOptions,...
method runWritesSequential (line 1022) | func (cmd *BenchCommand) runWritesSequential(db *bolt.DB, options *Ben...
method runWritesRandom (line 1027) | func (cmd *BenchCommand) runWritesRandom(db *bolt.DB, options *BenchOp...
method runWritesSequentialNested (line 1032) | func (cmd *BenchCommand) runWritesSequentialNested(db *bolt.DB, option...
method runWritesRandomNested (line 1037) | func (cmd *BenchCommand) runWritesRandomNested(db *bolt.DB, options *B...
method runWritesWithSource (line 1042) | func (cmd *BenchCommand) runWritesWithSource(db *bolt.DB, options *Ben...
method runWritesNestedWithSource (line 1071) | func (cmd *BenchCommand) runWritesNestedWithSource(db *bolt.DB, option...
method runReads (line 1115) | func (cmd *BenchCommand) runReads(db *bolt.DB, options *BenchOptions, ...
method runReadsSequential (line 1147) | func (cmd *BenchCommand) runReadsSequential(db *bolt.DB, options *Benc...
method runReadsSequentialNested (line 1178) | func (cmd *BenchCommand) runReadsSequentialNested(db *bolt.DB, options...
method startProfiling (line 1218) | func (cmd *BenchCommand) startProfiling(options *BenchOptions) {
method stopProfiling (line 1253) | func (cmd *BenchCommand) stopProfiling() {
function newBenchCommand (line 892) | func newBenchCommand(m *Main) *BenchCommand {
type BenchOptions (line 1275) | type BenchOptions struct
type BenchResults (line 1294) | type BenchResults struct
method WriteOpDuration (line 1302) | func (r *BenchResults) WriteOpDuration() time.Duration {
method WriteOpsPerSecond (line 1310) | func (r *BenchResults) WriteOpsPerSecond() int {
method ReadOpDuration (line 1319) | func (r *BenchResults) ReadOpDuration() time.Duration {
method ReadOpsPerSecond (line 1327) | func (r *BenchResults) ReadOpsPerSecond() int {
type PageError (line 1335) | type PageError struct
method Error (line 1340) | func (e *PageError) Error() string {
function isPrintable (line 1345) | func isPrintable(s string) bool {
function ReadPage (line 1359) | func ReadPage(path string, pageID int) (*page, []byte, error) {
function ReadPageSize (line 1399) | func ReadPageSize(path string) (int, error) {
function atois (line 1419) | func atois(strs []string) ([]int, error) {
constant maxAllocSize (line 1432) | maxAllocSize = 0xFFFFFFF
constant branchPageFlag (line 1436) | branchPageFlag = 0x01
constant leafPageFlag (line 1437) | leafPageFlag = 0x02
constant metaPageFlag (line 1438) | metaPageFlag = 0x04
constant freelistPageFlag (line 1439) | freelistPageFlag = 0x10
constant bucketLeafFlag (line 1443) | bucketLeafFlag = 0x01
type pgid (line 1446) | type pgid
type txid (line 1449) | type txid
type meta (line 1452) | type meta struct
type bucket (line 1465) | type bucket struct
type page (line 1471) | type page struct
method Type (line 1480) | func (p *page) Type() string {
method leafPageElement (line 1494) | func (p *page) leafPageElement(index uint16) *leafPageElement {
method branchPageElement (line 1500) | func (p *page) branchPageElement(index uint16) *branchPageElement {
type branchPageElement (line 1505) | type branchPageElement struct
method key (line 1512) | func (n *branchPageElement) key() []byte {
type leafPageElement (line 1518) | type leafPageElement struct
method key (line 1526) | func (n *leafPageElement) key() []byte {
method value (line 1532) | func (n *leafPageElement) value() []byte {
type CompactCommand (line 1538) | type CompactCommand struct
method Run (line 1558) | func (cmd *CompactCommand) Run(args ...string) (err error) {
method compact (line 1619) | func (cmd *CompactCommand) compact(dst, src *bolt.DB) error {
method walk (line 1694) | func (cmd *CompactCommand) walk(db *bolt.DB, walkFn walkFunc) error {
method walkBucket (line 1702) | func (cmd *CompactCommand) walkBucket(b *bolt.Bucket, keypath [][]byte...
method Usage (line 1725) | func (cmd *CompactCommand) Usage() string {
function newCompactCommand (line 1549) | func newCompactCommand(m *Main) *CompactCommand {
type walkFunc (line 1691) | type walkFunc
FILE: cmd/bolt/main_test.go
function TestInfoCommand_Run (line 20) | func TestInfoCommand_Run(t *testing.T) {
function TestStatsCommand_Run_EmptyDatabase (line 33) | func TestStatsCommand_Run_EmptyDatabase(t *testing.T) {
function TestStatsCommand_Run (line 73) | func TestStatsCommand_Run(t *testing.T) {
type Main (line 150) | type Main struct
function NewMain (line 158) | func NewMain() *Main {
function MustOpen (line 167) | func MustOpen(mode os.FileMode, options *bolt.Options) *DB {
type DB (line 181) | type DB struct
method Close (line 187) | func (db *DB) Close() error {
function TestCompactCommand_Run (line 192) | func TestCompactCommand_Run(t *testing.T) {
function fillBucket (line 291) | func fillBucket(b *bolt.Bucket, prefix []byte) error {
function chkdb (line 323) | func chkdb(path string) ([]byte, error) {
function walkBucket (line 341) | func walkBucket(parent *bolt.Bucket, k []byte, v []byte, w io.Writer) er...
FILE: cursor.go
type Cursor (line 18) | type Cursor struct
method Bucket (line 24) | func (c *Cursor) Bucket() *Bucket {
method First (line 31) | func (c *Cursor) First() (key []byte, value []byte) {
method Last (line 55) | func (c *Cursor) Last() (key []byte, value []byte) {
method Next (line 73) | func (c *Cursor) Next() (key []byte, value []byte) {
method Prev (line 85) | func (c *Cursor) Prev() (key []byte, value []byte) {
method Seek (line 117) | func (c *Cursor) Seek(seek []byte) (key []byte, value []byte) {
method Delete (line 135) | func (c *Cursor) Delete() error {
method seek (line 154) | func (c *Cursor) seek(seek []byte) (key []byte, value []byte, flags ui...
method first (line 172) | func (c *Cursor) first() {
method last (line 193) | func (c *Cursor) last() {
method next (line 218) | func (c *Cursor) next() (key []byte, value []byte, flags uint32) {
method search (line 253) | func (c *Cursor) search(key []byte, pgid pgid) {
method searchNode (line 274) | func (c *Cursor) searchNode(key []byte, n *node) {
method searchPage (line 294) | func (c *Cursor) searchPage(key []byte, p *page) {
method nsearch (line 318) | func (c *Cursor) nsearch(key []byte) {
method keyValue (line 340) | func (c *Cursor) keyValue() ([]byte, []byte, uint32) {
method node (line 358) | func (c *Cursor) node() *node {
type elemRef (line 380) | type elemRef struct
method isLeaf (line 387) | func (r *elemRef) isLeaf() bool {
method count (line 395) | func (r *elemRef) count() int {
FILE: cursor_test.go
function TestCursor_Bucket (line 18) | func TestCursor_Bucket(t *testing.T) {
function TestCursor_Seek (line 36) | func TestCursor_Seek(t *testing.T) {
function TestCursor_Delete (line 106) | func TestCursor_Delete(t *testing.T) {
function TestCursor_Seek_Large (line 169) | func TestCursor_Seek_Large(t *testing.T) {
function TestCursor_EmptyBucket (line 233) | func TestCursor_EmptyBucket(t *testing.T) {
function TestCursor_EmptyBucketReverse (line 258) | func TestCursor_EmptyBucketReverse(t *testing.T) {
function TestCursor_Iterate_Leaf (line 283) | func TestCursor_Iterate_Leaf(t *testing.T) {
function TestCursor_LeafRootReverse (line 354) | func TestCursor_LeafRootReverse(t *testing.T) {
function TestCursor_Restart (line 418) | func TestCursor_Restart(t *testing.T) {
function TestCursor_First_EmptyPages (line 464) | func TestCursor_First_EmptyPages(t *testing.T) {
function TestCursor_QuickCheck (line 511) | func TestCursor_QuickCheck(t *testing.T) {
function TestCursor_QuickCheck_Reverse (line 569) | func TestCursor_QuickCheck_Reverse(t *testing.T) {
function TestCursor_QuickCheck_BucketsOnly (line 626) | func TestCursor_QuickCheck_BucketsOnly(t *testing.T) {
function TestCursor_QuickCheck_BucketsOnly_Reverse (line 668) | func TestCursor_QuickCheck_BucketsOnly_Reverse(t *testing.T) {
function ExampleCursor (line 709) | func ExampleCursor() {
function ExampleCursor_reverse (line 763) | func ExampleCursor_reverse() {
FILE: db.go
constant maxMmapStep (line 18) | maxMmapStep = 1 << 30
constant version (line 21) | version = 2
constant magic (line 24) | magic uint32 = 0xED0CDAED
constant IgnoreNoSync (line 30) | IgnoreNoSync = runtime.GOOS == "openbsd"
constant DefaultMaxBatchSize (line 34) | DefaultMaxBatchSize int = 1000
constant DefaultMaxBatchDelay (line 35) | DefaultMaxBatchDelay = 10 * time.Millisecond
constant DefaultAllocSize (line 36) | DefaultAllocSize = 16 * 1024 * 1024
type DB (line 45) | type DB struct
method Path (line 133) | func (db *DB) Path() string {
method GoString (line 138) | func (db *DB) GoString() string {
method String (line 143) | func (db *DB) String() string {
method mmap (line 245) | func (db *DB) mmap(minsz int) error {
method munmap (line 298) | func (db *DB) munmap() error {
method mmapSize (line 308) | func (db *DB) mmapSize(size int) (int, error) {
method init (line 343) | func (db *DB) init() error {
method Close (line 391) | func (db *DB) Close() error {
method close (line 404) | func (db *DB) close() error {
method Begin (line 459) | func (db *DB) Begin(writable bool) (*Tx, error) {
method beginTx (line 466) | func (db *DB) beginTx() (*Tx, error) {
method beginRWTx (line 504) | func (db *DB) beginRWTx() (*Tx, error) {
method removeTx (line 545) | func (db *DB) removeTx(tx *Tx) {
method Update (line 581) | func (db *DB) Update(fn func(*Tx) error) error {
method View (line 612) | func (db *DB) View(fn func(*Tx) error) error {
method Batch (line 660) | func (db *DB) Batch(fn func(*Tx) error) error {
method Sync (line 775) | func (db *DB) Sync() error { return fdatasync(db) }
method Stats (line 779) | func (db *DB) Stats() Stats {
method Info (line 787) | func (db *DB) Info() *Info {
method page (line 792) | func (db *DB) page(id pgid) *page {
method pageInBuffer (line 798) | func (db *DB) pageInBuffer(b []byte, id pgid) *page {
method meta (line 803) | func (db *DB) meta() *meta {
method allocate (line 827) | func (db *DB) allocate(count int) (*page, error) {
method grow (line 859) | func (db *DB) grow(sz int) error {
method IsReadOnly (line 890) | func (db *DB) IsReadOnly() bool {
function Open (line 150) | func Open(path string, mode os.FileMode, options *Options) (*DB, error) {
type call (line 685) | type call struct
type batch (line 690) | type batch struct
method trigger (line 698) | func (b *batch) trigger() {
method run (line 704) | func (b *batch) run() {
type panicked (line 751) | type panicked struct
method Error (line 755) | func (p panicked) Error() string {
function safelyCall (line 762) | func safelyCall(fn func(*Tx) error, tx *Tx) (err error) {
type Options (line 895) | type Options struct
type Stats (line 930) | type Stats struct
method Sub (line 947) | func (s *Stats) Sub(other *Stats) Stats {
method add (line 961) | func (s *Stats) add(other *Stats) {
type Info (line 965) | type Info struct
type meta (line 970) | type meta struct
method validate (line 983) | func (m *meta) validate() error {
method copy (line 995) | func (m *meta) copy(dest *meta) {
method write (line 1000) | func (m *meta) write(p *page) {
method sum64 (line 1018) | func (m *meta) sum64() uint64 {
function _assert (line 1025) | func _assert(condition bool, msg string, v ...interface{}) {
function warn (line 1031) | func warn(v ...interface{}) { fmt.Fprintln(os.Stderr, v...) }
function warnf (line 1032) | func warnf(msg string, v ...interface{}) { fmt.Fprintf(os.Stderr, msg+"\...
function printstack (line 1034) | func printstack() {
FILE: db_test.go
constant version (line 28) | version = 2
constant magic (line 31) | magic uint32 = 0xED0CDAED
constant pageSize (line 34) | pageSize = 4096
constant pageHeaderSize (line 37) | pageHeaderSize = 16
type meta (line 40) | type meta struct
function TestOpen (line 53) | func TestOpen(t *testing.T) {
function TestOpen_ErrPathRequired (line 72) | func TestOpen_ErrPathRequired(t *testing.T) {
function TestOpen_ErrNotExists (line 80) | func TestOpen_ErrNotExists(t *testing.T) {
function TestOpen_ErrInvalid (line 88) | func TestOpen_ErrInvalid(t *testing.T) {
function TestOpen_ErrVersionMismatch (line 109) | func TestOpen_ErrVersionMismatch(t *testing.T) {
function TestOpen_ErrChecksum (line 146) | func TestOpen_ErrChecksum(t *testing.T) {
function TestOpen_Size (line 184) | func TestOpen_Size(t *testing.T) {
function TestOpen_Size_Large (line 244) | func TestOpen_Size_Large(t *testing.T) {
function TestOpen_Check (line 311) | func TestOpen_Check(t *testing.T) {
function TestOpen_MetaInitWriteError (line 338) | func TestOpen_MetaInitWriteError(t *testing.T) {
function TestOpen_FileTooSmall (line 343) | func TestOpen_FileTooSmall(t *testing.T) {
function TestDB_Open_InitialMmapSize (line 369) | func TestDB_Open_InitialMmapSize(t *testing.T) {
function TestDB_Begin_ErrDatabaseNotOpen (line 426) | func TestDB_Begin_ErrDatabaseNotOpen(t *testing.T) {
function TestDB_BeginRW (line 434) | func TestDB_BeginRW(t *testing.T) {
function TestDB_BeginRW_Closed (line 457) | func TestDB_BeginRW_Closed(t *testing.T) {
function TestDB_Close_PendingTx_RW (line 464) | func TestDB_Close_PendingTx_RW(t *testing.T) { testDB_Close_PendingTx(t,...
function TestDB_Close_PendingTx_RO (line 465) | func TestDB_Close_PendingTx_RO(t *testing.T) { testDB_Close_PendingTx(t,...
function testDB_Close_PendingTx (line 468) | func testDB_Close_PendingTx(t *testing.T, writable bool) {
function TestDB_Update (line 510) | func TestDB_Update(t *testing.T) {
function TestDB_Update_Closed (line 546) | func TestDB_Update_Closed(t *testing.T) {
function TestDB_Update_ManualCommit (line 559) | func TestDB_Update_ManualCommit(t *testing.T) {
function TestDB_Update_ManualRollback (line 585) | func TestDB_Update_ManualRollback(t *testing.T) {
function TestDB_View_ManualCommit (line 611) | func TestDB_View_ManualCommit(t *testing.T) {
function TestDB_View_ManualRollback (line 637) | func TestDB_View_ManualRollback(t *testing.T) {
function TestDB_Update_Panic (line 663) | func TestDB_Update_Panic(t *testing.T) {
function TestDB_View_Error (line 707) | func TestDB_View_Error(t *testing.T) {
function TestDB_View_Panic (line 719) | func TestDB_View_Panic(t *testing.T) {
function TestDB_Stats (line 762) | func TestDB_Stats(t *testing.T) {
function TestDB_Consistency (line 783) | func TestDB_Consistency(t *testing.T) {
function TestDBStats_Sub (line 851) | func TestDBStats_Sub(t *testing.T) {
function TestDB_Batch (line 869) | func TestDB_Batch(t *testing.T) {
function TestDB_Batch_Panic (line 914) | func TestDB_Batch_Panic(t *testing.T) {
function TestDB_BatchFull (line 945) | func TestDB_BatchFull(t *testing.T) {
function TestDB_BatchTime (line 1004) | func TestDB_BatchTime(t *testing.T) {
function ExampleDB_Update (line 1051) | func ExampleDB_Update() {
function ExampleDB_View (line 1091) | func ExampleDB_View() {
function ExampleDB_Begin_ReadOnly (line 1134) | func ExampleDB_Begin_ReadOnly() {
function BenchmarkDBBatchAutomatic (line 1193) | func BenchmarkDBBatchAutomatic(b *testing.B) {
function BenchmarkDBBatchSingle (line 1238) | func BenchmarkDBBatchSingle(b *testing.B) {
function BenchmarkDBBatchManual10x100 (line 1282) | func BenchmarkDBBatchManual10x100(b *testing.B) {
function validateBatchBench (line 1331) | func validateBatchBench(b *testing.B, db *DB) {
type DB (line 1367) | type DB struct
method Close (line 1381) | func (db *DB) Close() error {
method MustClose (line 1396) | func (db *DB) MustClose() {
method PrintStats (line 1403) | func (db *DB) PrintStats() {
method MustCheck (line 1418) | func (db *DB) MustCheck() {
method CopyTempFile (line 1456) | func (db *DB) CopyTempFile() {
function MustOpenDB (line 1372) | func MustOpenDB() *DB {
function tempfile (line 1467) | func tempfile() string {
function mustContainKeys (line 1482) | func mustContainKeys(b *bolt.Bucket, m map[string]string) {
function trunc (line 1515) | func trunc(b []byte, length int) []byte {
function truncDuration (line 1522) | func truncDuration(d time.Duration) string {
function fileSize (line 1526) | func fileSize(path string) int64 {
function warn (line 1534) | func warn(v ...interface{}) { fmt.Fprintln(os.Stderr, v...) }
function warnf (line 1535) | func warnf(msg string, v ...interface{}) { fmt.Fprintf(os.Stderr, msg+"\...
function u64tob (line 1538) | func u64tob(v uint64) []byte {
function btou64 (line 1545) | func btou64(b []byte) uint64 { return binary.BigEndian.Uint64(b) }
FILE: freelist.go
type freelist (line 11) | type freelist struct
method size (line 26) | func (f *freelist) size() int {
method count (line 36) | func (f *freelist) count() int {
method free_count (line 41) | func (f *freelist) free_count() int {
method pending_count (line 46) | func (f *freelist) pending_count() int {
method copyall (line 56) | func (f *freelist) copyall(dst []pgid) {
method allocate (line 67) | func (f *freelist) allocate(n int) pgid {
method free (line 111) | func (f *freelist) free(txid txid, p *page) {
method release (line 132) | func (f *freelist) release(txid txid) {
method rollback (line 147) | func (f *freelist) rollback(txid txid) {
method freed (line 158) | func (f *freelist) freed(pgid pgid) bool {
method read (line 163) | func (f *freelist) read(p *page) {
method write (line 191) | func (f *freelist) write(p *page) error {
method reload (line 215) | func (f *freelist) reload(p *page) {
method reindex (line 242) | func (f *freelist) reindex() {
function newFreelist (line 18) | func newFreelist() *freelist {
FILE: freelist_test.go
function TestFreelist_free (line 12) | func TestFreelist_free(t *testing.T) {
function TestFreelist_free_overflow (line 21) | func TestFreelist_free_overflow(t *testing.T) {
function TestFreelist_release (line 30) | func TestFreelist_release(t *testing.T) {
function TestFreelist_allocate (line 48) | func TestFreelist_allocate(t *testing.T) {
function TestFreelist_read (line 90) | func TestFreelist_read(t *testing.T) {
function TestFreelist_write (line 113) | func TestFreelist_write(t *testing.T) {
function Benchmark_FreelistRelease10K (line 135) | func Benchmark_FreelistRelease10K(b *testing.B) { benchmark_FreelistR...
function Benchmark_FreelistRelease100K (line 136) | func Benchmark_FreelistRelease100K(b *testing.B) { benchmark_FreelistR...
function Benchmark_FreelistRelease1000K (line 137) | func Benchmark_FreelistRelease1000K(b *testing.B) { benchmark_FreelistR...
function Benchmark_FreelistRelease10000K (line 138) | func Benchmark_FreelistRelease10000K(b *testing.B) { benchmark_FreelistR...
function benchmark_FreelistRelease (line 140) | func benchmark_FreelistRelease(b *testing.B, size int) {
function randomPgids (line 150) | func randomPgids(n int) []pgid {
FILE: node.go
type node (line 11) | type node struct
method root (line 24) | func (n *node) root() *node {
method minKeys (line 32) | func (n *node) minKeys() int {
method size (line 40) | func (n *node) size() int {
method sizeLessThan (line 52) | func (n *node) sizeLessThan(v int) bool {
method pageElementSize (line 65) | func (n *node) pageElementSize() int {
method childAt (line 73) | func (n *node) childAt(index int) *node {
method childIndex (line 81) | func (n *node) childIndex(child *node) int {
method numChildren (line 87) | func (n *node) numChildren() int {
method nextSibling (line 92) | func (n *node) nextSibling() *node {
method prevSibling (line 104) | func (n *node) prevSibling() *node {
method put (line 116) | func (n *node) put(oldKey, newKey, value []byte, pgid pgid, flags uint...
method del (line 144) | func (n *node) del(key []byte) {
method read (line 161) | func (n *node) read(p *page) {
method write (line 191) | func (n *node) write(p *page) {
method split (line 250) | func (n *node) split(pageSize int) []*node {
method splitTwo (line 273) | func (n *node) splitTwo(pageSize int) (*node, *node) {
method splitIndex (line 315) | func (n *node) splitIndex(threshold int) (index, sz int) {
method spill (line 339) | func (n *node) spill() error {
method rebalance (line 409) | func (n *node) rebalance() {
method removeChild (line 512) | func (n *node) removeChild(target *node) {
method dereference (line 523) | func (n *node) dereference() {
method free (line 554) | func (n *node) free() {
type nodes (line 588) | type nodes
method Len (line 590) | func (s nodes) Len() int { return len(s) }
method Swap (line 591) | func (s nodes) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
method Less (line 592) | func (s nodes) Less(i, j int) bool { return bytes.Compare(s[i].inodes[...
type inode (line 597) | type inode struct
type inodes (line 604) | type inodes
FILE: node_test.go
function TestNode_put (line 9) | func TestNode_put(t *testing.T) {
function TestNode_read_LeafPage (line 34) | func TestNode_read_LeafPage(t *testing.T) {
function TestNode_write_LeafPage (line 71) | func TestNode_write_LeafPage(t *testing.T) {
function TestNode_split (line 103) | func TestNode_split(t *testing.T) {
function TestNode_split_MinKeys (line 128) | func TestNode_split_MinKeys(t *testing.T) {
function TestNode_split_SinglePage (line 142) | func TestNode_split_SinglePage(t *testing.T) {
FILE: page.go
constant pageHeaderSize (line 10) | pageHeaderSize = int(unsafe.Offsetof(((*page)(nil)).ptr))
constant minKeysPerPage (line 12) | minKeysPerPage = 2
constant branchPageElementSize (line 14) | branchPageElementSize = int(unsafe.Sizeof(branchPageElement{}))
constant leafPageElementSize (line 15) | leafPageElementSize = int(unsafe.Sizeof(leafPageElement{}))
constant branchPageFlag (line 18) | branchPageFlag = 0x01
constant leafPageFlag (line 19) | leafPageFlag = 0x02
constant metaPageFlag (line 20) | metaPageFlag = 0x04
constant freelistPageFlag (line 21) | freelistPageFlag = 0x10
constant bucketLeafFlag (line 25) | bucketLeafFlag = 0x01
type pgid (line 28) | type pgid
type page (line 30) | type page struct
method typ (line 39) | func (p *page) typ() string {
method meta (line 53) | func (p *page) meta() *meta {
method leafPageElement (line 58) | func (p *page) leafPageElement(index uint16) *leafPageElement {
method leafPageElements (line 64) | func (p *page) leafPageElements() []leafPageElement {
method branchPageElement (line 72) | func (p *page) branchPageElement(index uint16) *branchPageElement {
method branchPageElements (line 77) | func (p *page) branchPageElements() []branchPageElement {
method hexdump (line 85) | func (p *page) hexdump(n int) {
type pages (line 90) | type pages
method Len (line 92) | func (s pages) Len() int { return len(s) }
method Swap (line 93) | func (s pages) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
method Less (line 94) | func (s pages) Less(i, j int) bool { return s[i].id < s[j].id }
type branchPageElement (line 97) | type branchPageElement struct
method key (line 104) | func (n *branchPageElement) key() []byte {
type leafPageElement (line 110) | type leafPageElement struct
method key (line 118) | func (n *leafPageElement) key() []byte {
method value (line 124) | func (n *leafPageElement) value() []byte {
type PageInfo (line 130) | type PageInfo struct
type pgids (line 137) | type pgids
method Len (line 139) | func (s pgids) Len() int { return len(s) }
method Swap (line 140) | func (s pgids) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
method Less (line 141) | func (s pgids) Less(i, j int) bool { return s[i] < s[j] }
method merge (line 144) | func (a pgids) merge(b pgids) pgids {
function mergepgids (line 159) | func mergepgids(dst, a, b pgids) {
FILE: page_test.go
function TestPage_typ (line 11) | func TestPage_typ(t *testing.T) {
function TestPage_dump (line 30) | func TestPage_dump(t *testing.T) {
function TestPgids_merge (line 34) | func TestPgids_merge(t *testing.T) {
function TestPgids_merge_quick (line 50) | func TestPgids_merge_quick(t *testing.T) {
FILE: quick_test.go
function init (line 26) | func init() {
function qconfig (line 37) | func qconfig() *quick.Config {
type testdata (line 44) | type testdata
method Len (line 46) | func (t testdata) Len() int { return len(t) }
method Swap (line 47) | func (t testdata) Swap(i, j int) { t[i], t[j] = t[j], t[i] }
method Less (line 48) | func (t testdata) Less(i, j int) bool { return bytes.Compare(t[i].Key,...
method Generate (line 50) | func (t testdata) Generate(rand *rand.Rand, size int) reflect.Value {
type revtestdata (line 69) | type revtestdata
method Len (line 71) | func (t revtestdata) Len() int { return len(t) }
method Swap (line 72) | func (t revtestdata) Swap(i, j int) { t[i], t[j] = t[j], t[i] }
method Less (line 73) | func (t revtestdata) Less(i, j int) bool { return bytes.Compare(t[i].K...
type testdataitem (line 75) | type testdataitem struct
function randByteSlice (line 80) | func randByteSlice(rand *rand.Rand, minSize, maxSize int) []byte {
FILE: simulation_test.go
function TestSimulate_1op_1p (line 13) | func TestSimulate_1op_1p(t *testing.T) { testSimulate(t, 1, 1) }
function TestSimulate_10op_1p (line 14) | func TestSimulate_10op_1p(t *testing.T) { testSimulate(t, 10, 1) }
function TestSimulate_100op_1p (line 15) | func TestSimulate_100op_1p(t *testing.T) { testSimulate(t, 100, 1) }
function TestSimulate_1000op_1p (line 16) | func TestSimulate_1000op_1p(t *testing.T) { testSimulate(t, 1000, 1) }
function TestSimulate_10000op_1p (line 17) | func TestSimulate_10000op_1p(t *testing.T) { testSimulate(t, 10000, 1) }
function TestSimulate_10op_10p (line 19) | func TestSimulate_10op_10p(t *testing.T) { testSimulate(t, 10, 10) }
function TestSimulate_100op_10p (line 20) | func TestSimulate_100op_10p(t *testing.T) { testSimulate(t, 100, 10) }
function TestSimulate_1000op_10p (line 21) | func TestSimulate_1000op_10p(t *testing.T) { testSimulate(t, 1000, 10) }
function TestSimulate_10000op_10p (line 22) | func TestSimulate_10000op_10p(t *testing.T) { testSimulate(t, 10000, 10) }
function TestSimulate_100op_100p (line 24) | func TestSimulate_100op_100p(t *testing.T) { testSimulate(t, 100, 100) }
function TestSimulate_1000op_100p (line 25) | func TestSimulate_1000op_100p(t *testing.T) { testSimulate(t, 1000, 100) }
function TestSimulate_10000op_100p (line 26) | func TestSimulate_10000op_100p(t *testing.T) { testSimulate(t, 10000, 10...
function TestSimulate_10000op_1000p (line 28) | func TestSimulate_10000op_1000p(t *testing.T) { testSimulate(t, 10000, 1...
function testSimulate (line 31) | func testSimulate(t *testing.T, threadCount, parallelism int) {
type simulateHandler (line 122) | type simulateHandler
function simulateGetHandler (line 125) | func simulateGetHandler(tx *bolt.Tx, qdb *QuickDB) {
function simulatePutHandler (line 160) | func simulatePutHandler(tx *bolt.Tx, qdb *QuickDB) {
type QuickDB (line 198) | type QuickDB struct
method Get (line 209) | func (db *QuickDB) Get(keys [][]byte) []byte {
method Put (line 235) | func (db *QuickDB) Put(keys [][]byte, value []byte) {
method Rand (line 257) | func (db *QuickDB) Rand() [][]byte {
method rand (line 268) | func (db *QuickDB) rand(m map[string]interface{}, keys *[][]byte) {
method Copy (line 284) | func (db *QuickDB) Copy() *QuickDB {
method copy (line 290) | func (db *QuickDB) copy(m map[string]interface{}) map[string]interface...
function NewQuickDB (line 204) | func NewQuickDB() *QuickDB {
function randKey (line 303) | func randKey() []byte {
function randKeys (line 313) | func randKeys() [][]byte {
function randValue (line 322) | func randValue() []byte {
FILE: tx.go
type txid (line 14) | type txid
type Tx (line 24) | type Tx struct
method init (line 44) | func (tx *Tx) init(db *DB) {
method ID (line 65) | func (tx *Tx) ID() int {
method DB (line 70) | func (tx *Tx) DB() *DB {
method Size (line 75) | func (tx *Tx) Size() int64 {
method Writable (line 80) | func (tx *Tx) Writable() bool {
method Cursor (line 88) | func (tx *Tx) Cursor() *Cursor {
method Stats (line 93) | func (tx *Tx) Stats() TxStats {
method Bucket (line 100) | func (tx *Tx) Bucket(name []byte) *Bucket {
method CreateBucket (line 107) | func (tx *Tx) CreateBucket(name []byte) (*Bucket, error) {
method CreateBucketIfNotExists (line 114) | func (tx *Tx) CreateBucketIfNotExists(name []byte) (*Bucket, error) {
method DeleteBucket (line 120) | func (tx *Tx) DeleteBucket(name []byte) error {
method ForEach (line 127) | func (tx *Tx) ForEach(fn func(name []byte, b *Bucket) error) error {
method OnCommit (line 137) | func (tx *Tx) OnCommit(fn func()) {
method Commit (line 144) | func (tx *Tx) Commit() error {
method Rollback (line 240) | func (tx *Tx) Rollback() error {
method rollback (line 249) | func (tx *Tx) rollback() {
method close (line 260) | func (tx *Tx) close() {
method Copy (line 297) | func (tx *Tx) Copy(w io.Writer) error {
method WriteTo (line 304) | func (tx *Tx) WriteTo(w io.Writer) (n int64, err error) {
method CopyFile (line 355) | func (tx *Tx) CopyFile(path string, mode os.FileMode) error {
method Check (line 377) | func (tx *Tx) Check() <-chan error {
method check (line 383) | func (tx *Tx) check(ch chan error) {
method checkBucket (line 418) | func (tx *Tx) checkBucket(b *Bucket, reachable map[pgid]*page, freed m...
method allocate (line 457) | func (tx *Tx) allocate(count int) (*page, error) {
method write (line 474) | func (tx *Tx) write() error {
method writeMeta (line 547) | func (tx *Tx) writeMeta() error {
method page (line 571) | func (tx *Tx) page(id pgid) *page {
method forEachPage (line 584) | func (tx *Tx) forEachPage(pgid pgid, depth int, fn func(*page, int)) {
method Page (line 601) | func (tx *Tx) Page(id int) (*PageInfo, error) {
type TxStats (line 627) | type TxStats struct
method add (line 653) | func (s *TxStats) add(other *TxStats) {
method Sub (line 671) | func (s *TxStats) Sub(other *TxStats) TxStats {
FILE: tx_test.go
function TestTx_Commit_ErrTxClosed (line 15) | func TestTx_Commit_ErrTxClosed(t *testing.T) {
function TestTx_Rollback_ErrTxClosed (line 37) | func TestTx_Rollback_ErrTxClosed(t *testing.T) {
function TestTx_Commit_ErrTxNotWritable (line 55) | func TestTx_Commit_ErrTxNotWritable(t *testing.T) {
function TestTx_Cursor (line 68) | func TestTx_Cursor(t *testing.T) {
function TestTx_CreateBucket_ErrTxNotWritable (line 106) | func TestTx_CreateBucket_ErrTxNotWritable(t *testing.T) {
function TestTx_CreateBucket_ErrTxClosed (line 121) | func TestTx_CreateBucket_ErrTxClosed(t *testing.T) {
function TestTx_Bucket (line 138) | func TestTx_Bucket(t *testing.T) {
function TestTx_Get_NotFound (line 155) | func TestTx_Get_NotFound(t *testing.T) {
function TestTx_CreateBucket (line 177) | func TestTx_CreateBucket(t *testing.T) {
function TestTx_CreateBucketIfNotExists (line 206) | func TestTx_CreateBucketIfNotExists(t *testing.T) {
function TestTx_CreateBucketIfNotExists_ErrBucketNameRequired (line 241) | func TestTx_CreateBucketIfNotExists_ErrBucketNameRequired(t *testing.T) {
function TestTx_CreateBucket_ErrBucketExists (line 260) | func TestTx_CreateBucket_ErrBucketExists(t *testing.T) {
function TestTx_CreateBucket_ErrBucketNameRequired (line 286) | func TestTx_CreateBucket_ErrBucketNameRequired(t *testing.T) {
function TestTx_DeleteBucket (line 300) | func TestTx_DeleteBucket(t *testing.T) {
function TestTx_DeleteBucket_ErrTxClosed (line 347) | func TestTx_DeleteBucket_ErrTxClosed(t *testing.T) {
function TestTx_DeleteBucket_ReadOnly (line 363) | func TestTx_DeleteBucket_ReadOnly(t *testing.T) {
function TestTx_DeleteBucket_NotFound (line 377) | func TestTx_DeleteBucket_NotFound(t *testing.T) {
function TestTx_ForEach_NoError (line 392) | func TestTx_ForEach_NoError(t *testing.T) {
function TestTx_ForEach_WithError (line 416) | func TestTx_ForEach_WithError(t *testing.T) {
function TestTx_OnCommit (line 441) | func TestTx_OnCommit(t *testing.T) {
function TestTx_OnCommit_Rollback (line 461) | func TestTx_OnCommit_Rollback(t *testing.T) {
function TestTx_CopyFile (line 481) | func TestTx_CopyFile(t *testing.T) {
type failWriterError (line 530) | type failWriterError struct
method Error (line 532) | func (failWriterError) Error() string {
type failWriter (line 536) | type failWriter struct
method Write (line 541) | func (f *failWriter) Write(p []byte) (n int, err error) {
function TestTx_CopyFile_Error_Meta (line 552) | func TestTx_CopyFile_Error_Meta(t *testing.T) {
function TestTx_CopyFile_Error_Normal (line 579) | func TestTx_CopyFile_Error_Normal(t *testing.T) {
function ExampleTx_Rollback (line 605) | func ExampleTx_Rollback() {
function ExampleTx_CopyFile (line 659) | func ExampleTx_CopyFile() {
Condensed preview — 39 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (387K chars).
[
{
"path": ".gitignore",
"chars": 26,
"preview": "*.prof\n*.test\n*.swp\n/bin/\n"
},
{
"path": "LICENSE",
"chars": 1078,
"preview": "The MIT License (MIT)\n\nCopyright (c) 2013 Ben Johnson\n\nPermission is hereby granted, free of charge, to any person obtai"
},
{
"path": "Makefile",
"chars": 410,
"preview": "BRANCH=`git rev-parse --abbrev-ref HEAD`\nCOMMIT=`git rev-parse --short HEAD`\nGOLDFLAGS=\"-X main.branch $(BRANCH) -X main"
},
{
"path": "README.md",
"chars": 36553,
"preview": "Bolt [](https://coveralls.io/r/boltdb/"
},
{
"path": "appveyor.yml",
"chars": 262,
"preview": "version: \"{build}\"\n\nos: Windows Server 2012 R2\n\nclone_folder: c:\\gopath\\src\\github.com\\boltdb\\bolt\n\nenvironment:\n GOPAT"
},
{
"path": "bolt_386.go",
"chars": 291,
"preview": "package bolt\n\n// maxMapSize represents the largest mmap size supported by Bolt.\nconst maxMapSize = 0x7FFFFFFF // 2GB\n\n//"
},
{
"path": "bolt_amd64.go",
"chars": 298,
"preview": "package bolt\n\n// maxMapSize represents the largest mmap size supported by Bolt.\nconst maxMapSize = 0xFFFFFFFFFFFF // 256"
},
{
"path": "bolt_arm.go",
"chars": 831,
"preview": "package bolt\n\nimport \"unsafe\"\n\n// maxMapSize represents the largest mmap size supported by Bolt.\nconst maxMapSize = 0x7F"
},
{
"path": "bolt_arm64.go",
"chars": 315,
"preview": "// +build arm64\n\npackage bolt\n\n// maxMapSize represents the largest mmap size supported by Bolt.\nconst maxMapSize = 0xFF"
},
{
"path": "bolt_linux.go",
"chars": 171,
"preview": "package bolt\n\nimport (\n\t\"syscall\"\n)\n\n// fdatasync flushes written data to a file descriptor.\nfunc fdatasync(db *DB) erro"
},
{
"path": "bolt_openbsd.go",
"chars": 518,
"preview": "package bolt\n\nimport (\n\t\"syscall\"\n\t\"unsafe\"\n)\n\nconst (\n\tmsAsync = 1 << iota // perform asynchronous writes\n\tmsSync "
},
{
"path": "bolt_ppc.go",
"chars": 227,
"preview": "// +build ppc\n\npackage bolt\n\n// maxMapSize represents the largest mmap size supported by Bolt.\nconst maxMapSize = 0x7FFF"
},
{
"path": "bolt_ppc64.go",
"chars": 315,
"preview": "// +build ppc64\n\npackage bolt\n\n// maxMapSize represents the largest mmap size supported by Bolt.\nconst maxMapSize = 0xFF"
},
{
"path": "bolt_ppc64le.go",
"chars": 317,
"preview": "// +build ppc64le\n\npackage bolt\n\n// maxMapSize represents the largest mmap size supported by Bolt.\nconst maxMapSize = 0x"
},
{
"path": "bolt_s390x.go",
"chars": 315,
"preview": "// +build s390x\n\npackage bolt\n\n// maxMapSize represents the largest mmap size supported by Bolt.\nconst maxMapSize = 0xFF"
},
{
"path": "bolt_unix.go",
"chars": 2168,
"preview": "// +build !windows,!plan9,!solaris\n\npackage bolt\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"syscall\"\n\t\"time\"\n\t\"unsafe\"\n)\n\n// flock acquire"
},
{
"path": "bolt_unix_solaris.go",
"chars": 2059,
"preview": "package bolt\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"syscall\"\n\t\"time\"\n\t\"unsafe\"\n\n\t\"golang.org/x/sys/unix\"\n)\n\n// flock acquires an advis"
},
{
"path": "bolt_windows.go",
"chars": 3930,
"preview": "package bolt\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"syscall\"\n\t\"time\"\n\t\"unsafe\"\n)\n\n// LockFileEx code derived from golang build filemut"
},
{
"path": "boltsync_unix.go",
"chars": 169,
"preview": "// +build !windows,!plan9,!linux,!openbsd\n\npackage bolt\n\n// fdatasync flushes written data to a file descriptor.\nfunc fd"
},
{
"path": "bucket.go",
"chars": 21334,
"preview": "package bolt\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"unsafe\"\n)\n\nconst (\n\t// MaxKeySize is the maximum length of a key, in bytes.\n\tMa"
},
{
"path": "bucket_test.go",
"chars": 46996,
"preview": "package bolt_test\n\nimport (\n\t\"bytes\"\n\t\"encoding/binary\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log\"\n\t\"math/rand\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\""
},
{
"path": "cmd/bolt/main.go",
"chars": 43931,
"preview": "package main\n\nimport (\n\t\"bytes\"\n\t\"encoding/binary\"\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"math/rand\"\n\t\"os\"\n\t\"runt"
},
{
"path": "cmd/bolt/main_test.go",
"chars": 8300,
"preview": "package main_test\n\nimport (\n\t\"bytes\"\n\tcrypto \"crypto/rand\"\n\t\"encoding/binary\"\n\t\"fmt\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"math/rand\"\n\t\"o"
},
{
"path": "cursor.go",
"chars": 11359,
"preview": "package bolt\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"sort\"\n)\n\n// Cursor represents an iterator that can traverse over all key/value "
},
{
"path": "cursor_test.go",
"chars": 18841,
"preview": "package bolt_test\n\nimport (\n\t\"bytes\"\n\t\"encoding/binary\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"reflect\"\n\t\"sort\"\n\t\"testing\"\n\t\"testing/quic"
},
{
"path": "db.go",
"chars": 28244,
"preview": "package bolt\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"hash/fnv\"\n\t\"log\"\n\t\"os\"\n\t\"runtime\"\n\t\"runtime/debug\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n"
},
{
"path": "db_test.go",
"chars": 34495,
"preview": "package bolt_test\n\nimport (\n\t\"bytes\"\n\t\"encoding/binary\"\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"hash/fnv\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"os\"\n\t"
},
{
"path": "doc.go",
"chars": 1781,
"preview": "/*\nPackage bolt implements a low-level key/value store in pure Go. It supports\nfully serializable transactions, ACID sem"
},
{
"path": "errors.go",
"chars": 2743,
"preview": "package bolt\n\nimport \"errors\"\n\n// These errors can be returned when opening or calling methods on a DB.\nvar (\n\t// ErrDat"
},
{
"path": "freelist.go",
"chars": 6694,
"preview": "package bolt\n\nimport (\n\t\"fmt\"\n\t\"sort\"\n\t\"unsafe\"\n)\n\n// freelist represents a list of all pages that are available for all"
},
{
"path": "freelist_test.go",
"chars": 4295,
"preview": "package bolt\n\nimport (\n\t\"math/rand\"\n\t\"reflect\"\n\t\"sort\"\n\t\"testing\"\n\t\"unsafe\"\n)\n\n// Ensure that a page is added to a trans"
},
{
"path": "node.go",
"chars": 16157,
"preview": "package bolt\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"sort\"\n\t\"unsafe\"\n)\n\n// node represents an in-memory, deserialized page.\ntype nod"
},
{
"path": "node_test.go",
"chars": 5644,
"preview": "package bolt\n\nimport (\n\t\"testing\"\n\t\"unsafe\"\n)\n\n// Ensure that a node can insert a key/value.\nfunc TestNode_put(t *testin"
},
{
"path": "page.go",
"chars": 4889,
"preview": "package bolt\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"sort\"\n\t\"unsafe\"\n)\n\nconst pageHeaderSize = int(unsafe.Offsetof(((*page)(nil)).ptr))"
},
{
"path": "page_test.go",
"chars": 1782,
"preview": "package bolt\n\nimport (\n\t\"reflect\"\n\t\"sort\"\n\t\"testing\"\n\t\"testing/quick\"\n)\n\n// Ensure that the page type can be returned in"
},
{
"path": "quick_test.go",
"chars": 2467,
"preview": "package bolt_test\n\nimport (\n\t\"bytes\"\n\t\"flag\"\n\t\"fmt\"\n\t\"math/rand\"\n\t\"os\"\n\t\"reflect\"\n\t\"testing/quick\"\n\t\"time\"\n)\n\n// testing"
},
{
"path": "simulation_test.go",
"chars": 7699,
"preview": "package bolt_test\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"math/rand\"\n\t\"sync\"\n\t\"testing\"\n\n\t\"github.com/boltdb/bolt\"\n)\n\nfunc TestSimul"
},
{
"path": "tx.go",
"chars": 18683,
"preview": "package bolt\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"sort\"\n\t\"strings\"\n\t\"time\"\n\t\"unsafe\"\n)\n\n// txid represents the internal transa"
},
{
"path": "tx_test.go",
"chars": 16645,
"preview": "package bolt_test\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com/boltdb/bolt\"\n)\n\n// Ensure th"
}
]
About this extraction
This page contains the full source code of the boltdb/bolt GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 39 files (345.0 KB), approximately 101.9k tokens, and a symbol index with 599 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.