Documentation
¶
Index ¶
- Constants
- Variables
- func Assert(condition bool, msg string, v ...any)
- type Bucket
- func (b *Bucket) AssertAppendOptimized()
- func (b *Bucket) Cursor() *Cursor
- func (b *Bucket) Delete(key []byte) (err error)
- func (b *Bucket) FillPercent() float64
- func (b *Bucket) ForEach(fn func(k, v []byte) error) error
- func (b *Bucket) Get(key []byte) []byte
- func (b *Bucket) Inspect() BucketStructure
- func (b *Bucket) Name() string
- func (b *Bucket) Put(key []byte, value []byte) (err error)
- func (b *Bucket) SetAppendOptimized()
- func (b *Bucket) SetAppendRightMinKeys(minKeys int)
- func (b *Bucket) SetBranchNodeSize(maxBytes int)
- func (b *Bucket) SetFillPercent(fillPercent float64)
- func (b *Bucket) SetLeafNodeSize(maxBytes int)
- func (b *Bucket) SetMode(mode BucketMode)
- func (b *Bucket) Stats() BucketStats
- func (b *Bucket) Tx() *Tx
- func (b *Bucket) Writable() bool
- type BucketMode
- type BucketStats
- type BucketStructure
- type CheckOption
- type Cursor
- func (c *Cursor) Bucket() *Bucket
- func (c *Cursor) Delete() error
- func (c *Cursor) First() (key []byte, value []byte)
- func (c *Cursor) Last() (key []byte, value []byte)
- func (c *Cursor) Next() (key []byte, value []byte)
- func (c *Cursor) Prev() (key []byte, value []byte)
- func (c *Cursor) Seek(seek []byte) (key []byte, value []byte)
- type DB
- func (db *DB) Batch(fn func(*Tx) error) error
- func (db *DB) Begin(writable bool) (t *Tx, err error)
- func (db *DB) Close() error
- func (db *DB) GoString() string
- func (db *DB) Info() *Info
- func (db *DB) IsReadOnly() bool
- func (db *DB) Logger() Logger
- func (db *DB) Restore(r io.Reader) error
- func (db *DB) Stats() Stats
- func (db *DB) String() string
- func (db *DB) Update(fn func(*Tx) error) error
- func (db *DB) View(fn func(*Tx) error) error
- type DefaultLogger
- func (l *DefaultLogger) Debug(v ...interface{})
- func (l *DefaultLogger) Debugf(format string, v ...interface{})
- func (l *DefaultLogger) EnableDebug()
- func (l *DefaultLogger) EnableTimestamps()
- func (l *DefaultLogger) Error(v ...interface{})
- func (l *DefaultLogger) Errorf(format string, v ...interface{})
- func (l *DefaultLogger) Fatal(v ...interface{})
- func (l *DefaultLogger) Fatalf(format string, v ...interface{})
- func (l *DefaultLogger) Info(v ...interface{})
- func (l *DefaultLogger) Infof(format string, v ...interface{})
- func (l *DefaultLogger) Panic(v ...interface{})
- func (l *DefaultLogger) Panicf(format string, v ...interface{})
- func (l *DefaultLogger) Warning(v ...interface{})
- func (l *DefaultLogger) Warningf(format string, v ...interface{})
- type Info
- type KVStringer
- type Logger
- type Options
- type Stats
- type Tx
- func (tx *Tx) Bucket(name []byte) *Bucket
- func (tx *Tx) Check(options ...CheckOption) <-chan error
- func (tx *Tx) Commit() (err error)
- func (tx *Tx) Copy(w io.Writer) error
- func (tx *Tx) CopyFile(path string, mode os.FileMode) error
- func (tx *Tx) CreateBucket(name []byte) (*Bucket, error)
- func (tx *Tx) CreateBucketIfNotExists(name []byte) (*Bucket, error)
- func (tx *Tx) Cursor() *Cursor
- func (tx *Tx) DB() *DB
- func (tx *Tx) DeleteBucket(name []byte) error
- func (tx *Tx) ForEach(fn func(name []byte, b *Bucket) error) error
- func (tx *Tx) Inspect() BucketStructure
- func (tx *Tx) OnCommit(fn func())
- func (tx *Tx) Rollback() error
- func (tx *Tx) Size() int64
- func (tx *Tx) Stats() TxStats
- func (tx *Tx) Writable() bool
- func (tx *Tx) WriteTo(w io.Writer) (n int64, err error)
- type TxStats
- func (s *TxStats) GetCommitTime() time.Duration
- func (s *TxStats) GetCursorCount() int64
- func (s *TxStats) GetDirtyNodeCount() int64
- func (s *TxStats) GetNodeCount() int64
- func (s *TxStats) GetNodeDeref() int64
- func (s *TxStats) GetRebalance() int64
- func (s *TxStats) GetRebalanceTime() time.Duration
- func (s *TxStats) GetSpill() int64
- func (s *TxStats) GetSpillTime() time.Duration
- func (s *TxStats) GetSplit() int64
- func (s *TxStats) GetWrite() int64
- func (s *TxStats) GetWriteBytes() int64
- func (s *TxStats) GetWriteTime() time.Duration
- func (s *TxStats) IncCommitTime(delta time.Duration) time.Duration
- func (s *TxStats) IncCursorCount(delta int64) int64
- func (s *TxStats) IncDirtyNodeCount(delta int64) int64
- func (s *TxStats) IncNodeCount(delta int64) int64
- func (s *TxStats) IncNodeDeref(delta int64) int64
- func (s *TxStats) IncRebalance(delta int64) int64
- func (s *TxStats) IncRebalanceTime(delta time.Duration) time.Duration
- func (s *TxStats) IncSpill(delta int64) int64
- func (s *TxStats) IncSpillTime(delta time.Duration) time.Duration
- func (s *TxStats) IncSplit(delta int64) int64
- func (s *TxStats) IncWrite(delta int64) int64
- func (s *TxStats) IncWriteBytes(delta int64) int64
- func (s *TxStats) IncWriteTime(delta time.Duration) time.Duration
- func (s *TxStats) Sub(other *TxStats) TxStats
Examples ¶
Constants ¶
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 ( DefaultMaxBatchSize int = 1000 DefaultMaxBatchDelay = 10 * time.Millisecond )
Default values if not set in a DB instance.
const DefaultFillPercent = 0.5
DefaultFillPercent is the percentage that split nodes are filled.
Variables ¶
var DefaultOptions = &Options{}
DefaultOptions represent the options used if nil options are passed into Open().
Functions ¶
Types ¶
type Bucket ¶
type Bucket struct {
// contains filtered or unexported fields
}
Bucket is a tx-local handle to one top-level B+tree. A Bucket is never shared across transactions.
func (*Bucket) AssertAppendOptimized ¶ added in v0.4.3
func (b *Bucket) AssertAppendOptimized()
func (*Bucket) Delete ¶
Delete removes a key from the bucket.
Example ¶
// Open the database.
db, err := bolt.Open(tempfile(), 0600, nil)
if err != nil {
log.Fatal(err)
}
// 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 (*Bucket) FillPercent ¶
FillPercent returns the target fill percentage used when splitting BTree nodes.
func (*Bucket) ForEach ¶
ForEach executes a function for each key/value pair in a bucket.
Example ¶
// Open the database.
db, err := bolt.Open(tempfile(), 0600, nil)
if err != nil {
log.Fatal(err)
}
// 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.
func (*Bucket) Inspect ¶
func (b *Bucket) Inspect() BucketStructure
Inspect returns the structure of the bucket.
func (*Bucket) Put ¶
Put sets the value for a key in the bucket.
Example ¶
// Open the database.
db, err := bolt.Open(tempfile(), 0600, nil)
if err != nil {
log.Fatal(err)
}
// 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 (*Bucket) SetAppendOptimized ¶ added in v0.4.0
func (b *Bucket) SetAppendOptimized()
SetAppendOptimized enables append-oriented splitting for monotonically increasing keys.
func (*Bucket) SetAppendRightMinKeys ¶ added in v0.4.0
SetAppendRightMinKeys sets the minimum number of entries kept in the right node after an append split. Values below one are clamped to one. On writable transactions the setting is committed as bucket metadata and reused by later transactions.
func (*Bucket) SetBranchNodeSize ¶ added in v0.4.0
SetBranchNodeSize sets the branch-node split threshold for this bucket. Non-positive values keep the existing threshold. On writable transactions the setting is committed as bucket metadata and reused by later transactions.
func (*Bucket) SetFillPercent ¶ added in v0.4.0
SetFillPercent sets the target fill percentage used when splitting BTree nodes. Values outside the supported range are clamped.
func (*Bucket) SetLeafNodeSize ¶ added in v0.4.0
SetLeafNodeSize sets the leaf-node split threshold for this bucket. Non-positive values keep the existing threshold. On writable transactions the setting is committed as bucket metadata and reused by later transactions.
func (*Bucket) SetMode ¶ added in v0.4.0
func (b *Bucket) SetMode(mode BucketMode)
SetMode sets the bucket's split/rebalance policy. On writable transactions the setting is committed as bucket metadata and reused by later transactions.
type BucketMode ¶ added in v0.4.0
type BucketMode uint8
BucketMode controls the split/rebalance policy used by a bucket.
const ( // BucketModeBTree uses the general-purpose B+tree split/rebalance policy. BucketModeBTree BucketMode = iota // BucketModeAppend optimizes for monotonically increasing keys. Splits keep // the left node full and leave a small right node for future appends. BucketModeAppend )
type BucketStats ¶
type BucketStats struct {
// Tree statistics.
KeyN int // number of keys/value pairs
Depth int // number of levels in B+tree
// Page size utilization.
BranchInuse int // bytes actually used for branch data
LeafInuse int // bytes actually used for leaf data
}
BucketStats records statistics about resources used by a bucket.
func (*BucketStats) Add ¶
func (s *BucketStats) Add(other BucketStats)
type BucketStructure ¶
type BucketStructure struct {
Name string `json:"name"`
KeyN int `json:"keyN"`
Children []BucketStructure `json:"buckets,omitempty"`
}
BucketStructure records the structure of a bucket.
type CheckOption ¶
type CheckOption func(options *checkConfig)
CheckOption configures Tx.Check.
func WithKVStringer ¶
func WithKVStringer(kvStringer KVStringer) CheckOption
WithKVStringer sets a human-readable renderer for keys/values in error messages.
func WithPageId ¶
func WithPageId(pageId uint64) CheckOption
WithPageId is retained for API compatibility; it is a no-op in the page-less engine.
type Cursor ¶
type Cursor struct {
// contains filtered or unexported fields
}
Cursor represents an iterator that can traverse over all key/value pairs in a bucket in lexicographical order.
It has two modes:
- tree mode (bucket != nil): walks a single bucket's B+tree (via Bucket.Cursor());
- directory mode (bucket == nil, dir set): enumerates the top-level bucket NAMES in sorted order. Produced by Tx.Cursor(); used by snapshot/Hash/defrag-style callers that iterate all top-level buckets deterministically.
Example ¶
// Open the database.
db, err := bolt.Open(tempfile(), 0600, nil)
if err != nil {
log.Fatal(err)
}
// Start a read-write transaction.
if err := db.Update(func(tx *bolt.Tx) error {
// Create a new bucket.
b, err := tx.CreateBucket([]byte("animals"))
if err != nil {
return err
}
// Insert data into a bucket.
if err := b.Put([]byte("dog"), []byte("fun")); err != nil {
log.Fatal(err)
}
if err := b.Put([]byte("cat"), []byte("lame")); err != nil {
log.Fatal(err)
}
if err := b.Put([]byte("liger"), []byte("awesome")); err != nil {
log.Fatal(err)
}
// Create a cursor for iteration.
c := b.Cursor()
// Iterate over items in sorted key order. This starts from the
// first key/value pair and updates the k/v variables to the
// next key/value on each iteration.
//
// The loop finishes at the end of the cursor when a nil key is returned.
for k, v := c.First(); k != nil; k, v = c.Next() {
fmt.Printf("A %s is %s.\n", k, v)
}
return nil
}); err != nil {
log.Fatal(err)
}
if err := db.Close(); err != nil {
log.Fatal(err)
}
Output: A cat is lame. A dog is fun. A liger is awesome.
Example (Reverse) ¶
// Open the database.
db, err := bolt.Open(tempfile(), 0600, nil)
if err != nil {
log.Fatal(err)
}
// Start a read-write transaction.
if err := db.Update(func(tx *bolt.Tx) error {
// Create a new bucket.
b, err := tx.CreateBucket([]byte("animals"))
if err != nil {
return err
}
// Insert data into a bucket.
if err := b.Put([]byte("dog"), []byte("fun")); err != nil {
log.Fatal(err)
}
if err := b.Put([]byte("cat"), []byte("lame")); err != nil {
log.Fatal(err)
}
if err := b.Put([]byte("liger"), []byte("awesome")); err != nil {
log.Fatal(err)
}
// Create a cursor for iteration.
c := b.Cursor()
// Iterate over items in reverse sorted key order. This starts
// from the last key/value pair and updates the k/v variables to
// the previous key/value on each iteration.
//
// The loop finishes at the beginning of the cursor when a nil key
// is returned.
for k, v := c.Last(); k != nil; k, v = c.Prev() {
fmt.Printf("A %s is %s.\n", k, v)
}
return nil
}); err != nil {
log.Fatal(err)
}
// Close the database to release the file lock.
if err := db.Close(); err != nil {
log.Fatal(err)
}
Output: A liger is awesome. A dog is fun. A cat is lame.
func (*Cursor) Bucket ¶
Bucket returns the bucket that this cursor was created from. Returns nil for a directory cursor (Tx.Cursor()).
func (*Cursor) First ¶
First moves the cursor to the first item in the bucket and returns its key and value.
func (*Cursor) Last ¶
Last moves the cursor to the last item in the bucket and returns its key and value.
func (*Cursor) Next ¶
Next moves the cursor to the next item in the bucket and returns its key and value.
type DB ¶
type DB struct {
// MaxBatchSize is the maximum size of a batch. Default value is
// copied from DefaultMaxBatchSize in Open.
//
// If <=0, disables batching.
//
// Do not change concurrently with calls to Batch.
MaxBatchSize int
// MaxBatchDelay is the maximum delay before a batch starts.
// Default value is copied from DefaultMaxBatchDelay in Open.
//
// If <=0, effectively disables batching.
//
// Do not change concurrently with calls to Batch.
MaxBatchDelay time.Duration
// contains filtered or unexported fields
}
DB represents a collection of top-level buckets held in memory. All data access is performed through transactions which can be obtained through the DB. All the functions on DB will return a ErrDatabaseNotOpen if accessed before Open() is called.
func Open ¶
Open creates and opens a database at the given path with a given file mode. If the file does not exist then it will be created automatically with a given file mode. Passing in nil options will cause Bolt to open the database with the default options.
func (*DB) Batch ¶
Batch calls fn as part of a batch. It behaves similar to Update, except concurrent Batch calls can be combined into a single Bolt transaction.
func (*DB) IsReadOnly ¶
func (*DB) Restore ¶
Restore reads a BMSP snapshot from r and rebuilds the database in memory. It must be called on a fresh/empty DB (e.g. right after Open). No durability is added: the snapshot is a bulk rehydration, not incremental persistence.
type DefaultLogger ¶
DefaultLogger is a default implementation of the Logger interface.
func (*DefaultLogger) Debug ¶
func (l *DefaultLogger) Debug(v ...interface{})
func (*DefaultLogger) Debugf ¶
func (l *DefaultLogger) Debugf(format string, v ...interface{})
func (*DefaultLogger) EnableDebug ¶
func (l *DefaultLogger) EnableDebug()
func (*DefaultLogger) EnableTimestamps ¶
func (l *DefaultLogger) EnableTimestamps()
func (*DefaultLogger) Error ¶
func (l *DefaultLogger) Error(v ...interface{})
func (*DefaultLogger) Errorf ¶
func (l *DefaultLogger) Errorf(format string, v ...interface{})
func (*DefaultLogger) Fatal ¶
func (l *DefaultLogger) Fatal(v ...interface{})
func (*DefaultLogger) Fatalf ¶
func (l *DefaultLogger) Fatalf(format string, v ...interface{})
func (*DefaultLogger) Info ¶
func (l *DefaultLogger) Info(v ...interface{})
func (*DefaultLogger) Infof ¶
func (l *DefaultLogger) Infof(format string, v ...interface{})
func (*DefaultLogger) Panic ¶
func (l *DefaultLogger) Panic(v ...interface{})
func (*DefaultLogger) Panicf ¶
func (l *DefaultLogger) Panicf(format string, v ...interface{})
func (*DefaultLogger) Warning ¶
func (l *DefaultLogger) Warning(v ...interface{})
func (*DefaultLogger) Warningf ¶
func (l *DefaultLogger) Warningf(format string, v ...interface{})
type KVStringer ¶
KVStringer renders keys/values for human-readable diagnostic messages.
func HexKVStringer ¶
func HexKVStringer() KVStringer
HexKVStringer serializes both key & value to hex representation.
type Logger ¶
type Logger interface {
Debug(v ...interface{})
Debugf(format string, v ...interface{})
Error(v ...interface{})
Errorf(format string, v ...interface{})
Info(v ...interface{})
Infof(format string, v ...interface{})
Warning(v ...interface{})
Warningf(format string, v ...interface{})
Fatal(v ...interface{})
Fatalf(format string, v ...interface{})
Panic(v ...interface{})
Panicf(format string, v ...interface{})
}
type Options ¶
type Options struct {
// ReadOnly opens the database in read-only mode.
ReadOnly bool
// Logger is the logger used for vmbolt.
Logger Logger
// NoStatistics turns off statistics collection.
NoStatistics bool
}
Options represents the options that can be set when opening a database.
type Stats ¶
type Stats struct {
// Put `TxStats` at the first field to ensure it's 64-bit aligned.
TxStats TxStats // global, ongoing stats.
// Transaction stats
TxN int // total number of started read transactions
OpenTxN int // number of currently open read transactions
}
Stats represents statistics about the database.
type Tx ¶
type Tx struct {
// contains filtered or unexported fields
}
Tx represents a read-only or read/write transaction on the database.
Every transaction pins one globally consistent dbState at Begin time. A write tx mutates tx-local buckets and publishes one new dbState atomically at commit.
func (*Tx) Check ¶
func (tx *Tx) Check(options ...CheckOption) <-chan error
Check performs structural consistency validation of the committed database snapshot pinned by this transaction (tx.base). It validates the immutable in-memory node graph directly via child pointers (no flat index).
Every detected inconsistency is streamed on the returned channel; the channel is closed when validation completes. A well-formed database yields no errors.
Concurrent calls on the same transaction are safe: the published snapshot is immutable, so each Check call walks it independently without locks.
Options: WithKVStringer customizes key/value rendering in error messages; WithPageId is accepted for API compatibility but is a no-op (the engine is page-less).
Scope: only the committed snapshot the transaction pinned is validated. Uncommitted, in-flight write-transaction mutations are NOT validated.
func (*Tx) CreateBucket ¶
CreateBucket creates a new top-level bucket and returns a tx-local handle to it.
func (*Tx) CreateBucketIfNotExists ¶
CreateBucketIfNotExists creates a new bucket if it doesn't already exist.
func (*Tx) Cursor ¶
Cursor returns a directory cursor over the top-level bucket names in sorted order. Tx关闭后调用会返回空Cursor,调用对应方法会Panic,和bbolt语义兼容
func (*Tx) DeleteBucket ¶
DeleteBucket deletes a top-level bucket.
func (*Tx) Inspect ¶
func (tx *Tx) Inspect() BucketStructure
Inspect returns the structure of the database: a synthetic "root" whose children are the top-level buckets.
func (*Tx) OnCommit ¶
func (tx *Tx) OnCommit(fn func())
OnCommit adds a handler function to be executed after the transaction successfully commits.
type TxStats ¶
type TxStats struct {
CursorCount int64
NodeCount int64
NodeDeref int64
Rebalance int64
RebalanceTime time.Duration
Split int64
Spill int64
SpillTime time.Duration
Write int64 // number of mutating operations applied to B+tree nodes
WriteBytes int64 // logical key/value bytes passed through Put
WriteTime time.Duration
DirtyNodeCount int64 // dirty nodes observed at commit
CommitTime time.Duration
}
TxStats represents statistics about the actions performed by the transaction.