This document describes the public Go API for github.com/AfshinJalili/bitgask.
The main database handle. Safe for concurrent use. Writes are serialized internally.
Transaction handle created by db.Transaction(). Transactions are single-goroutine, provide snapshot isolation and read-your-writes, and commit as a batch. Conflicts use last-commit-wins semantics.
type RecordMeta struct {
ExpiresAt time.Time
Deleted bool
Timestamp time.Time
FileID uint32
Offset int64
Size uint32
}ExpiresAtis zero for non-expiring keys.Deletedis true for tombstones.FileID,Offset, andSizereference the record in the data file.
type Stats struct {
TotalBytes int64
DeadBytes int64
Keys int
DataFiles int
LastMerge time.Time
}Snapshot iterator returned by NewIterator. It reads values lazily when you call Next.
type MergeOptions struct {
Force bool
}type CompressionType uint8
const (
CompressionSnappy CompressionType = 0
CompressionNone CompressionType = 1
)type Logger interface {
Printf(format string, args ...interface{})
}func Open(path string, opts ...Option) (*DB, error)Creates or opens a database at path. Acquires a lock and loads the keydir.
func Repair(path string, opts ...Option) (*DB, error)Rebuilds from data files and truncates corrupt tails when possible. Rewrites hint files if enabled.
func Validate(path string, opts ...Option) (Report, error)Scans data and hint files for corruption without mutating the database.
func (db *DB) Close() errorCloses the database and releases the lock. Subsequent calls return ErrClosed.
func (db *DB) Reopen() errorRebuilds the keydir and reopens files. Blocks other operations while running.
func (db *DB) Transaction() *TxnReturns a new transaction snapshot. Transactions are not safe for concurrent use.
func (db *DB) Put(key, value []byte) errorWrites a value. Returns ErrInvalidKey for empty keys, ErrOversized for large keys/values.
func (db *DB) PutWithTTL(key, value []byte, ttl time.Duration) errorWrites a value that expires after ttl.
func (db *DB) Get(key []byte) ([]byte, error)Returns ErrKeyNotFound if missing, or ErrExpired if the key is expired.
func (db *DB) Meta(key []byte) (RecordMeta, error)Returns metadata for a key. Returns ErrExpired if expired.
func (db *DB) Delete(key []byte) errorWrites a tombstone. Returns ErrKeyNotFound if the key does not exist.
func (db *DB) Expire(key []byte, ttl time.Duration) (bool, error)Atomically updates key expiry. Returns false, nil when the key does not exist. A non-positive ttl deletes the key.
func (db *DB) Has(key []byte) (bool, error)Returns true if the key exists and is not expired.
func (t *Txn) Commit() error
func (t *Txn) Discard()Commit writes the batch and makes changes visible atomically to in-process readers. Discard releases the transaction without committing.
func (t *Txn) Put(key, value []byte) error
func (t *Txn) PutWithTTL(key, value []byte, ttl time.Duration) errorQueue writes in the transaction. Reads within the transaction see these writes immediately.
func (t *Txn) Get(key []byte) ([]byte, error)
func (t *Txn) Has(key []byte) (bool, error)
func (t *Txn) Delete(key []byte) errorReads are served from the transaction cache first, then the snapshot.
func (t *Txn) IterKeys(ctx context.Context, fn func(key []byte) bool) error
func (t *Txn) Iter(ctx context.Context, prefix []byte, fn func(key, value []byte, meta RecordMeta) bool) error
func (t *Txn) Scan(prefix []byte, fn func(key, value []byte, meta RecordMeta) bool) error
func (t *Txn) Range(start, end []byte, fn func(key, value []byte, meta RecordMeta) bool) errorIterates over the transaction view (snapshot + pending writes). Range uses byte-wise ordering.
func (db *DB) Keys() <-chan []byteStreams keys on a channel. The channel is closed when iteration completes.
func (db *DB) KeysContext(ctx context.Context) <-chan []byteLike Keys but stops early on context cancellation.
func (db *DB) IterKeys(ctx context.Context, fn func(key []byte) bool) errorStreaming key iteration. The callback runs under a read lock. Avoid calling back into the DB.
func (db *DB) Iter(ctx context.Context, prefix []byte, fn func(key, value []byte, meta RecordMeta) bool) errorStreaming key-value iteration with an optional prefix. The callback runs under a read lock.
func (db *DB) Scan(prefix []byte, fn func(key, value []byte, meta RecordMeta) bool) errorSnapshots the keydir and iterates live keys with the given prefix.
func (db *DB) Range(start, end []byte, fn func(key, value []byte, meta RecordMeta) bool) errorIterates keys with start <= key < end using byte-wise ordering.
func (db *DB) Sift(pred func(key []byte, meta RecordMeta) bool, fn func(key, value []byte, meta RecordMeta) bool) errorFilters keys with a predicate, then iterates values.
func (db *DB) Fold(init any, fn func(any, []byte, []byte, RecordMeta) any) (any, error)Reduces over live records and returns the final accumulator.
func (db *DB) NewIterator(prefix []byte) (*Iterator, error)Creates a snapshot iterator. Call Close when done.
func (db *DB) Sync() errorForces an fsync of the active data file.
func (db *DB) RunGC() (int, error)Removes expired keys from the keydir. Returns the number of keys removed.
func (db *DB) Merge(opts ...MergeOptions) errorCompacts the database. Use MergeOptions{Force: true} to bypass thresholds.
func (db *DB) CompactIfNeeded() (bool, error)Checks thresholds and runs a merge when needed. Returns whether a merge ran.
func (db *DB) Reclaimable() (deadBytes int64, totalBytes int64, ratio float64)Reports the amount of dead data that can be reclaimed by merge.
func (db *DB) Backup(dst string) errorCopies the database directory to dst.
func (db *DB) DeleteAll() errorDeletes all data and resets the database in place.
func (db *DB) Stats() StatsReturns current size and activity statistics.
ErrInvalidKeyfor empty keysErrKeyNotFoundfor missing keysErrExpiredfor expired keysErrOversizedfor keys or values larger than configured limitsErrClosedfor closed databasesErrLockedif the lock file is held by another processErrCorruptfor data corruption
- Reads are concurrent; writes are serialized.
ReopenandCloseblock other operations while running.- Streaming iterators (
IterKeys,Iter) hold a read lock and should not call back into the DB.
db, _ := bitgask.Open("./data")
defer db.Close()
_ = db.Put([]byte("k"), []byte("v"))
val, _ := db.Get([]byte("k"))
_ = val
_ = db.PutWithTTL([]byte("temp"), []byte("value"), 5*time.Second)_ = db.IterKeys(context.Background(), func(key []byte) bool {
fmt.Println(string(key))
return true
})