Search and commands

↑ ↓ to select · Enter to open · Esc to close

Type to search packages.

database

v1.21.5
github.com/luxfi/database

Documentation

pkg.go.dev ↗

Table of contents

↓ to select · Enter to jump· Shift+Enter for source

114 matches

Top ↑

Package database provides enhanced database utilities with optimized internals.

Package database provides memory management utilities.

Constants

MaxExcessCapacityFactor (2 declarations)

const (
	// MaxExcessCapacityFactor is the factor above which capacity is considered excessive
	MaxExcessCapacityFactor = 4
	// CapacityReductionFactor is the factor by which to reduce capacity when it's excessive
	CapacityReductionFactor = 2
)

Uint64Size (4 declarations)

const (
	Uint64Size = 8 // bytes
	BoolSize   = 1 // bytes
	BoolFalse  = 0x00
	BoolTrue   = 0x01
)

Variables

ErrClosed (3 declarations)

var (
	ErrClosed      = errors.New("closed")
	ErrNotFound    = errors.New("not found")
	ErrReadOnlyTxn = errors.New("write attempted in read-only transaction")
)

common errors

Functions

AtomicClear

func AtomicClear(readerDB Iteratee, deleterDB KeyValueDeleter) error

AtomicClearPrefix

func AtomicClearPrefix(readerDB Iteratee, deleterDB KeyValueDeleter, prefix []byte) error

AtomicClearPrefix deletes from [deleterDB] all keys in [readerDB] that have the given [prefix].

Clear

func Clear(db Database, writeSize int) error

Remove all key-value pairs from [db]. Writes each batch when it reaches [writeSize].

ClearPrefix

func ClearPrefix(db Database, prefix []byte, writeSize int) error

Removes all keys with the given [prefix] from [db]. Writes each batch when it reaches [writeSize].

Count

func Count(db Iteratee) (int, error)

GetBool

func GetBool(db KeyValueReader, key []byte) (bool, error)

GetID

func GetID(db KeyValueReader, key []byte) (ids.ID, error)

GetTimestamp

func GetTimestamp(db KeyValueReader, key []byte) (time.Time, error)

GetUInt32

func GetUInt32(db KeyValueReader, key []byte) (uint32, error)

GetUInt64

func GetUInt64(db KeyValueReader, key []byte) (uint64, error)

IsEmpty

func IsEmpty(db Iteratee) (bool, error)

NewErrBackendDisabled

func NewErrBackendDisabled(backend string) error

NewErrBackendDisabled creates a new ErrBackendDisabled error

PackUInt32

func PackUInt32(val uint32) []byte

PackUInt64

func PackUInt64(val uint64) []byte

ParseID

func ParseID(b []byte) (ids.ID, error)

ParseTimestamp

func ParseTimestamp(b []byte) (time.Time, error)

ParseUInt32

func ParseUInt32(b []byte) (uint32, error)

ParseUInt64

func ParseUInt64(b []byte) (uint64, error)

PutBool

func PutBool(db KeyValueWriter, key []byte, b bool) error

PutID

func PutID(db KeyValueWriter, key []byte, val ids.ID) error

PutTimestamp

func PutTimestamp(db KeyValueWriter, key []byte, val time.Time) error

PutUInt32

func PutUInt32(db KeyValueWriter, key []byte, val uint32) error

PutUInt64

func PutUInt64(db KeyValueWriter, key []byte, val uint64) error

Size

func Size(db Iteratee) (int, error)

UnwrapTo

func UnwrapTo[T any](db Database) (T, bool)

UnwrapTo extracts the innermost database that implements T.

Types

BadgerDBWithCache

type BadgerDBWithCache struct {
	// contains filtered or unexported fields
}

BadgerDBWithCache wraps BadgerDB with caching and compression optimizations

NewBadgerDBWithCache

func NewBadgerDBWithCache(db Database, cacheSize int, compressionLevel zstd.EncoderLevel, maxDecompressedSize int64, maxConcurrency int, reg metric.Registry) (*BadgerDBWithCache, error)

NewBadgerDBWithCache creates a new BadgerDB wrapper with caching and compression

BadgerDBWithCache.Delete

func (bdb *BadgerDBWithCache) Delete(key []byte) error

Delete removes a key from the database and cache

BadgerDBWithCache.Get

func (bdb *BadgerDBWithCache) Get(key []byte) ([]byte, error)

Get retrieves a value from the database with caching

BadgerDBWithCache.Has

func (bdb *BadgerDBWithCache) Has(key []byte) (bool, error)

Has checks if a key exists in the database

BadgerDBWithCache.Put

func (bdb *BadgerDBWithCache) Put(key, value []byte) error

Put inserts a value into the database with caching and compression

Batch

type Batch interface {
	KeyValueWriterDeleter

	// Size retrieves the amount of data queued up for writing, this includes
	// the keys, values, and deleted keys.
	Size() int

	// Write flushes any accumulated data to disk.
	Write() error

	// Reset resets the batch for reuse.
	Reset()

	// Replay replays the batch contents in the same order they were written
	// to the batch.
	Replay(w KeyValueWriterDeleter) error

	// Inner returns a Batch writing to the inner database, if one exists. If
	// this batch is already writing to the base DB, then itself should be
	// returned.
	Inner() Batch
}

Batch is a write-only database that commits changes to its host database when Write is called. A batch cannot be used concurrently.

BatchOp

type BatchOp struct {
	Key    []byte
	Value  []byte
	Delete bool
}

BatchOps

type BatchOps struct {
	Ops []BatchOp
	// contains filtered or unexported fields
}

BatchOps.Delete

func (b *BatchOps) Delete(key []byte) error

BatchOps.Put

func (b *BatchOps) Put(key, value []byte) error

BatchOps.Replay

func (b *BatchOps) Replay(w KeyValueWriterDeleter) error

BatchOps.Reset

func (b *BatchOps) Reset()

BatchOps.Size

func (b *BatchOps) Size() int

BatchedDatabase

type BatchedDatabase struct {
	// contains filtered or unexported fields
}

BatchedDatabase provides batched operations with optimizations

NewBatchedDatabase

func NewBatchedDatabase(db Database, batchSize int, batchTimeout time.Duration, reg metric.Registry) *BatchedDatabase

NewBatchedDatabase creates a new batched database wrapper

BatchedDatabase.Close

func (b *BatchedDatabase) Close() error

Close closes the batched database and flushes any remaining operations

BatchedDatabase.Delete

func (b *BatchedDatabase) Delete(key []byte) error

Delete adds a delete operation to the batch

BatchedDatabase.Flush

func (b *BatchedDatabase) Flush() error

Flush forces a flush of all pending operations

BatchedDatabase.Put

func (b *BatchedDatabase) Put(key, value []byte) error

Put adds a put operation to the batch

Batcher

type Batcher interface {
	// NewBatch creates a write-only database that buffers changes to its host db
	// until a final write is called.
	NewBatch() Batch
}

Batcher wraps the NewBatch method of a backing data store.

Compacter

type Compacter interface {
	// Compact the underlying DB for the given key range.
	// Specifically, deleted and overwritten versions are discarded,
	// and the data is rearranged to reduce the cost of operations
	// needed to access the data. This operation should typically only
	// be invoked by users who understand the underlying implementation.
	//
	// A nil start is treated as a key before all keys in the DB.
	// And a nil limit is treated as a key after all keys in the DB.
	// Therefore if both are nil then it will compact entire DB.
	//
	// Note: [start] and [limit] are safe to modify and read after calling Compact.
	Compact(start []byte, limit []byte) error
}

Compacter wraps the Compact method of a backing data store.

Database

type Database interface {
	KeyValueReaderWriterDeleter
	Batcher
	Iteratee
	Compacter
	Syncer
	io.Closer
	HealthCheck(context.Context) (interface{}, error)

	// Backup performs a backup of the database to the provided writer.
	// This should be a consistent snapshot of the database state.
	// since: 0 for full backup, or the version of the last backup for incremental.
	// returns: the version (timestamp/sequence) of this backup, to be used for the next incremental.
	Backup(w io.Writer, since uint64) (uint64, error)

	// Load restores the database from the provided reader.
	// This will overwrite the current database state with the backup.
	// Note: The database should generally be empty or fresh when calling Load.
	Load(r io.Reader) error
}

Database contains all the methods required to allow handling different key-value data stores backing the database.

ErrBackendDisabled

type ErrBackendDisabled struct {
	Backend string
}

ErrBackendDisabled is returned when a database backend is disabled at compile time

ErrBackendDisabled.Error

func (e *ErrBackendDisabled) Error() string

HeightIndex

type HeightIndex interface {
	// Put inserts the value at the given height.
	//
	// Note: [value] is safe to modify and read after calling Put.
	//
	// If [value] is nil or an empty slice, then when it's retrieved
	// it may be nil or an empty slice.
	Put(height uint64, value []byte) error

	// Get retrieves the value at the given height.
	// Returns ErrNotFound if the height does not exist.
	//
	// The returned byte slice is safe to read, but cannot be modified.
	Get(height uint64) ([]byte, error)

	// Has retrieves if a value exists at the given height.
	Has(height uint64) (bool, error)

	// Delete removes the value at the given height.
	Delete(height uint64) error

	// Close releases any resources associated with the index.
	Close() error
}

HeightIndex provides height-based key-value storage for blockchain state. Heights are stored as big-endian uint64 keys for efficient range queries.

Iteratee

type Iteratee interface {
	// NewIterator creates an iterator over the entire keyspace contained within
	// the key-value database.
	NewIterator() Iterator

	// NewIteratorWithStart creates an iterator over a subset of database
	// content starting at a particular initial key.
	NewIteratorWithStart(start []byte) Iterator

	// NewIteratorWithPrefix creates an iterator over a subset of database
	// content with a particular key prefix.
	NewIteratorWithPrefix(prefix []byte) Iterator

	// NewIteratorWithStartAndPrefix creates an iterator over a subset of
	// database content with a particular key prefix starting at a specified
	// key.
	NewIteratorWithStartAndPrefix(start, prefix []byte) Iterator
}

Iteratee wraps the NewIterator methods of a backing data store.

Iterator

type Iterator interface {
	// Next moves the iterator to the next key/value pair. It returns whether
	// the iterator successfully moved to a new key/value pair.
	// The iterator may return false if the underlying database has been closed
	// before the iteration has completed, in which case future calls to Error()
	// must return [ErrClosed].
	Next() bool

	// Error returns any accumulated error. Exhausting all the key/value pairs
	// is not considered to be an error.
	// Error should be called after all key/value pairs have been exhausted ie.
	// after Next() has returned false.
	Error() error

	// Key returns the key of the current key/value pair, or nil if done.
	// If the database is closed, must still report the current contents.
	// Behavior is undefined after Release is called.
	Key() []byte

	// Value returns the value of the current key/value pair, or nil if done.
	// If the database is closed, must still report the current contents.
	// Behavior is undefined after Release is called.
	Value() []byte

	// Release releases associated resources. Release should always succeed and
	// can be called multiple times without causing error.
	Release()
}

Iterator iterates over a database's key/value pairs.

When it encounters an error any seek will return false and will yield no key/ value pairs. The error can be queried by calling the Error method. Calling Release is still necessary.

An iterator must be released after use, but it is not necessary to read an iterator until exhaustion. An iterator is not safe for concurrent use, but it is safe to use multiple iterators concurrently.

IteratorError

type IteratorError struct {
	Err error
}

IteratorError does nothing and returns the provided error

IteratorError.Error

func (i *IteratorError) Error() error

IteratorError.Key

func (*IteratorError) Key() []byte

IteratorError.Next

func (*IteratorError) Next() bool

IteratorError.Release

func (*IteratorError) Release()

IteratorError.Value

func (*IteratorError) Value() []byte

KeyValueDeleter

type KeyValueDeleter interface {
	// Delete removes the key from the key-value data store.
	//
	// Note: [key] is safe to modify and read after calling Delete.
	Delete(key []byte) error
}

KeyValueDeleter wraps the Delete method of a backing data store.

KeyValueReader

type KeyValueReader interface {
	// Has retrieves if a key is present in the key-value data store.
	//
	// Note: [key] is safe to modify and read after calling Has.
	Has(key []byte) (bool, error)

	// Get retrieves the given key if it's present in the key-value data store.
	// Returns ErrNotFound if the key is not present in the key-value data store.
	//
	// Note: [key] is safe to modify and read after calling Get.
	// The returned byte slice is safe to read, but cannot be modified.
	Get(key []byte) ([]byte, error)
}

KeyValueReader wraps the Has and Get method of a backing data store.

KeyValueReaderWriter

type KeyValueReaderWriter interface {
	KeyValueReader
	KeyValueWriter
}

KeyValueReaderWriter allows read/write access to a backing data store.

KeyValueReaderWriterDeleter

type KeyValueReaderWriterDeleter interface {
	KeyValueReader
	KeyValueWriter
	KeyValueDeleter
}

KeyValueReaderWriterDeleter allows read/write/delete access to a backing data store.

KeyValueWriter

type KeyValueWriter interface {
	// Put inserts the given value into the key-value data store.
	//
	// Note: [key] and [value] are safe to modify and read after calling Put.
	//
	// If [value] is nil or an empty slice, then when it's retrieved
	// it may be nil or an empty slice.
	//
	// Similarly, a nil [key] is treated the same as an empty slice.
	Put(key []byte, value []byte) error
}

KeyValueWriter wraps the Put method of a backing data store.

KeyValueWriterDeleter

type KeyValueWriterDeleter interface {
	KeyValueWriter
	KeyValueDeleter
}

KeyValueWriterDeleter allows write/delete access to a backing data store.

MemoryManager

type MemoryManager struct {
	// contains filtered or unexported fields
}

MemoryManager provides memory management utilities.

NewMemoryManager

func NewMemoryManager(allowedPercent float64, reg metric.Registry) (*MemoryManager, error)

NewMemoryManager creates a new memory manager with the specified percentage of system memory

MemoryManager.Allowed

func (mm *MemoryManager) Allowed() int64

Allowed returns the amount of memory allowed for use

MemoryManager.Available

func (mm *MemoryManager) Available() int64

Available returns the amount of memory available for allocation

MemoryManager.GetMemoryStats

func (mm *MemoryManager) GetMemoryStats() MemoryStats

GetMemoryStats returns current memory statistics

MemoryManager.Release

func (mm *MemoryManager) Release(size int64)

Release releases previously reserved memory

MemoryManager.ReleaseCritical

func (mm *MemoryManager) ReleaseCritical(size int64)

ReleaseCritical releases memory from the critical reserve pool

MemoryManager.Reserve

func (mm *MemoryManager) Reserve(size int64)

Reserve reserves memory, blocking until it's available

MemoryManager.ReserveCritical

func (mm *MemoryManager) ReserveCritical(size int64)

ReserveCritical reserves memory from the critical reserve pool This is for operations that must not fail due to memory limits

MemoryManager.TryReserve

func (mm *MemoryManager) TryReserve(size int64) bool

TryReserve attempts to reserve memory without blocking Returns true if successful, false otherwise

MemoryManager.Used

func (mm *MemoryManager) Used() int64

Used returns the amount of memory currently in use

MemoryManager.WithReserve

func (mm *MemoryManager) WithReserve(size int64, fn func() error) error

WithReserve executes a function with reserved memory

MemoryStats

type MemoryStats struct {
	Allowed   int64   // Allowed memory in bytes
	Used      int64   // Used memory in bytes
	Available int64   // Available memory in bytes
	System    uint64  // Total system memory in bytes
	Percent   float64 // Percentage of system memory allowed
}

MemoryStats holds memory statistics

ObjectPool

type ObjectPool[T any] struct {
	// contains filtered or unexported fields
}

ObjectPool provides an optimized object pool.

NewObjectPool

func NewObjectPool[T any](newFn func() T, size int64, mm *MemoryManager, reg metric.Registry) *ObjectPool[T]

NewObjectPool creates a new object pool with memory management

ObjectPool[T].Clear

func (op *ObjectPool[T]) Clear()

Clear clears the object pool

ObjectPool[T].Get

func (op *ObjectPool[T]) Get() T

Get acquires an object from the pool

ObjectPool[T].GetPoolSize

func (op *ObjectPool[T]) GetPoolSize() int64

GetPoolSize returns the approximate number of objects in the pool

ObjectPool[T].Put

func (op *ObjectPool[T]) Put(obj T)

Put returns an object to the pool

OpType

type OpType int

OpType represents the type of operation

PutOp (2 declarations)

const (
	PutOp OpType = iota
	DeleteOp
)

Operation

type Operation struct {
	Type  OpType
	Key   []byte
	Value []byte
}

Operation represents a database operation

PrefixDropper

type PrefixDropper interface {
	DropPrefix(prefixes ...[]byte) error
}

PrefixDropper is implemented by backends that can delete every key under a prefix as one operation, rather than iterating and deleting key by key.

Worth asking for rather than emulating: the loop has to hold or re-open an iterator while mutating the range it is iterating, which is the shape that backends define least consistently.

RangeIterator

type RangeIterator struct {
	// contains filtered or unexported fields
}

RangeIterator provides optimized range iteration

NewRangeIterator

func NewRangeIterator(db Database, start, end []byte, limit int, reverse bool, reg metric.Registry) *RangeIterator

NewRangeIterator creates a new range iterator

RangeIterator.Count

func (r *RangeIterator) Count() int

Count returns the number of items iterated

RangeIterator.Iterate

func (r *RangeIterator) Iterate(callback func(key, value []byte) error) error

Iterate iterates over the range and calls the callback for each key-value pair

Replicatable

type Replicatable interface {
	StartReplicator(ctx context.Context) error
}

Replicatable is an optional interface for databases that support streaming replication to remote storage (S3, etc.). The node checks for this after DB creation and starts replication if REPLICATE_S3_ENDPOINT is set.

Sequence

type Sequence interface {
	// Next returns the next id in the sequence.
	Next() (uint64, error)

	// Release returns the unused remainder of the reserved band.
	Release() error
}

Sequence hands out monotonically increasing uint64 ids that survive a restart. It is the crash-safe alternative to an in-memory counter: a counter re-initialised from "highest key seen" can re-issue an id that is already on disk after an unclean shutdown, silently overwriting the record stored under it. A Sequence reserves a band on disk before handing any id out, so the ids after a restart are always above the ids before it.

Release returns the unused remainder of the reserved band. Not calling it leaks that band — the ids are skipped, never reused — so it is a waste, not a correctness problem.

Sequencer

type Sequencer interface {
	GetSequence(key []byte, bandwidth uint64) (Sequence, error)
}

Sequencer is implemented by backends that can persist a Sequence.

bandwidth is how many ids are reserved on disk per refill: larger amortises the write across more Next calls, and costs that many skipped ids on an unclean shutdown.

Syncer

type Syncer interface {
	// Sync flushes all buffered writes to persistent storage.
	// This ensures that data written before Sync is called will
	// survive a crash or power failure. This is important for
	// databases configured with async writes for performance.
	//
	// Implementations should ensure all in-memory buffers (memtables,
	// write-ahead logs, etc.) are flushed to disk.
	Sync() error
}

Syncer wraps the Sync method of a backing data store.

TTLWriter

type TTLWriter interface {
	PutWithTTL(key, value []byte, ttl time.Duration) error
}

TTLWriter is an optional interface for databases that support per-key TTL outside of a transaction. Callers detect support via type assertion or UnwrapTo[TTLWriter].

A ttl <= 0 is equivalent to Put (no expiration).

Transactional

type Transactional interface {
	Update(fn func(txn Txn) error) error
	View(fn func(txn Txn) error) error
}

Transactional is an optional interface implemented by databases that support callback-style atomic transactions. Callers detect support via type assertion or UnwrapTo[Transactional].

Update runs fn in a writable transaction. If fn returns nil, the transaction is committed; if fn returns an error, the transaction is rolled back and the error is returned. Implementations may retry fn on transient conflicts, so fn MUST be idempotent.

View runs fn in a read-only transaction. Writes inside fn return ErrReadOnlyTxn.

Txn

type Txn interface {
	// Has reports whether key is present in the transaction's view.
	Has(key []byte) (bool, error)

	// Get returns the value for key in the transaction's view.
	// Returns ErrNotFound if the key is not present.
	Get(key []byte) ([]byte, error)

	// Put writes (key, value) within the transaction. Visible only after
	// the enclosing Update commits.
	Put(key, value []byte) error

	// PutWithTTL writes (key, value) with an expiration. A ttl <= 0 means
	// no TTL (equivalent to Put). The exact eviction semantics depend on
	// the backend; readers may see the key briefly after expiry.
	PutWithTTL(key, value []byte, ttl time.Duration) error

	// Delete removes key from the transaction's view.
	Delete(key []byte) error

	// NewIterator returns an iterator over the transaction's view.
	NewIterator() Iterator

	// NewIteratorWithPrefix returns an iterator over keys with the given prefix.
	NewIteratorWithPrefix(prefix []byte) Iterator

	// NewIteratorWithStart returns an iterator starting at start.
	NewIteratorWithStart(start []byte) Iterator
}

Txn is a single read/write transaction over a Transactional database. Operations within a Txn are atomic: either all are committed on nil return from the callback, or all are rolled back if the callback returns an error.

A Txn is not safe for concurrent use across goroutines.

Unwrapper

type Unwrapper interface {
	Unwrap() Database
}

Unwrapper is implemented by wrapper databases (meterdb, versiondb) to expose the underlying database for interface assertions like Replicatable.

Dependency graph