Documentation
¶
Overview ¶
Package gdbx is a pure Go implementation of MDBX, a high-performance embedded transactional key-value database.
gdbx is file-format compatible with libmdbx, allowing existing MDBX databases to be opened and manipulated by this Go implementation.
Key features:
- B+ tree data structure for efficient key-value storage
- MVCC (Multi-Version Concurrency Control) for concurrent reads
- Single writer, multiple readers concurrency model
- Memory-mapped I/O for high performance
- ACID transactions with crash recovery
- Nested transaction infrastructure (parent page delegation)
Basic usage:
env, err := gdbx.Create()
if err != nil {
log.Fatal(err)
}
defer env.Close()
err = env.Open("/path/to/db", gdbx.NoSubdir, 0644)
if err != nil {
log.Fatal(err)
}
// Begin a write transaction
txn, err := env.BeginTxn(nil, 0)
if err != nil {
log.Fatal(err)
}
// Open the default database
dbi, err := txn.OpenDBI("", gdbx.Create)
if err != nil {
txn.Abort()
log.Fatal(err)
}
// Put a key-value pair
err = txn.Put(dbi, []byte("key"), []byte("value"), 0)
if err != nil {
txn.Abort()
log.Fatal(err)
}
_, _, err = txn.Commit()
if err != nil {
log.Fatal(err)
}
Index ¶
- Constants
- Variables
- func CursorToPool(c *Cursor)
- func FromHex(s string) []byte
- func GetSysRamInfo() (pageSize, totalPages, availablePages int, err error)
- func IsCorrupted(err error) bool
- func IsErrno(err error, errno Errno) bool
- func IsErrnoFn(err error, fn func(error) bool) bool
- func IsKeyExist(err error) bool
- func IsKeyExists(err error) bool
- func IsMapFull(err error) bool
- func IsNotExist(err error) bool
- func IsNotFound(err error) bool
- func SetDebug(flags uint) uint
- func SetDebugLog(enabled bool)
- func Version() string
- type BuildInfo
- type CmpFunc
- type CommitLatency
- type Cursor
- func (c *Cursor) Bind(txn *Txn, dbi DBI) error
- func (c *Cursor) Close()
- func (c *Cursor) Count() (uint64, error)
- func (c *Cursor) DBI() DBI
- func (c *Cursor) Del(flags uint) error
- func (c *Cursor) EOF() bool
- func (c *Cursor) Get(key, value []byte, op CursorOp) ([]byte, []byte, error)
- func (c *Cursor) OnFirst() bool
- func (c *Cursor) OnLast() bool
- func (c *Cursor) Put(key, value []byte, flags uint) error
- func (c *Cursor) PutMulti(key []byte, page []byte, stride int, flags uint) error
- func (c *Cursor) PutReserve(key []byte, n int, flags uint) ([]byte, error)
- func (c *Cursor) PutTree(key, treeData []byte, flags uint) error
- func (c *Cursor) Renew(txn *Txn) error
- func (c *Cursor) SetUserCtx(ctx any)
- func (c *Cursor) Txn() *Txn
- func (c *Cursor) Unbind() error
- func (c *Cursor) UserCtx() any
- type CursorOp
- type DBI
- type Duration16dot16
- type Env
- func (e *Env) BeginTxn(parent *Txn, flags uint) (*Txn, error)
- func (e *Env) Close()
- func (e *Env) CloseDBI(db DBI)
- func (e *Env) CloseEx(dontSync bool)
- func (e *Env) Copy(path string, flags uint) error
- func (e *Env) CopyFD(fd uintptr, flags uint) error
- func (e *Env) EnableSpillBuffer(initialCap uint32) error
- func (e *Env) FD() (uintptr, error)
- func (e *Env) Flags() (uint, error)
- func (e *Env) GetOption(option uint) (uint64, error)
- func (e *Env) GetSyncBytes() (uint, error)
- func (e *Env) GetSyncPeriod() (time.Duration, error)
- func (e *Env) Info(txn *Txn) (*EnvInfo, error)
- func (e *Env) Label() Label
- func (e *Env) LeafNodeMax() int
- func (e *Env) MaxDBs() uint32
- func (e *Env) MaxKeySize() int
- func (e *Env) MaxReaders() uint32
- func (e *Env) MaxValSize() int
- func (e *Env) Open(path string, flags uint, mode os.FileMode) error
- func (e *Env) Path() string
- func (e *Env) PreExtendMmap(size int64) error
- func (e *Env) ReaderCheck() (int, error)
- func (e *Env) ReaderList(fn func(info ReaderInfo) error) error
- func (e *Env) RunTxn(flags uint, fn TxnOp) error
- func (e *Env) SetCompare(dbi DBI, cmp func(a, b []byte) int) error
- func (e *Env) SetDebug(flags uint) error
- func (e *Env) SetDupCompare(dbi DBI, cmp func(a, b []byte) int) error
- func (e *Env) SetEnvFlags(flags uint, enable bool) error
- func (e *Env) SetFlags(flags uint) error
- func (e *Env) SetGeometry(sizeLower, sizeNow, sizeUpper, growthStep, shrinkThreshold int64, pageSize int) error
- func (e *Env) SetGeometryGeo(geo Geometry) error
- func (e *Env) SetGeometrySize(sizeLower, sizeNow, sizeUpper, growthStep, shrinkThreshold Size, pageSize int) error
- func (e *Env) SetMaxDBs(dbs uint32) error
- func (e *Env) SetMaxReaders(readers uint32) error
- func (e *Env) SetOption(option uint, value uint64) error
- func (e *Env) SetPageSize(size uint32) error
- func (e *Env) SetStrictThreadMode(mode bool)
- func (e *Env) SetSyncBytes(threshold uint) error
- func (e *Env) SetSyncPeriod(period time.Duration) error
- func (e *Env) SetUserCtx(ctx any)
- func (e *Env) SpillBuffer() *spill.Buffer
- func (e *Env) Stat() (*Stat, error)
- func (e *Env) SubPageLimit() int
- func (e *Env) Sync(force bool, nonblock bool) error
- func (e *Env) UnsetFlags(flags uint) error
- func (e *Env) Update(fn TxnOp) error
- func (e *Env) UpdateLocked(fn TxnOp) error
- func (e *Env) UserCtx() any
- func (e *Env) View(fn TxnOp) error
- type EnvInfo
- type EnvInfoGeo
- type EnvInfoPageOps
- type Errno
- type Error
- type ErrorCode
- type Geometry
- type HandleSlowReadersFunc
- type Label
- type LogLvl
- type LoggerFunc
- type Multi
- type NodeFlags
- type OpError
- type PageFlags
- type ReaderInfo
- type Size
- type Stat
- type TxInfo
- type Txn
- func (txn *Txn) Abort()
- func (txn *Txn) CloseDBI(dbi DBI) error
- func (txn *Txn) Cmp(dbi DBI, a, b []byte) int
- func (txn *Txn) Commit() (CommitLatency, error)
- func (txn *Txn) CreateDBI(name string) (DBI, error)
- func (txn *Txn) DBIFlags(dbi DBI) (uint, error)
- func (txn *Txn) DBIStat(dbi DBI) (*Stat, error)
- func (txn *Txn) DCmp(dbi DBI, a, b []byte) int
- func (txn *Txn) DebugGetPage(pageNum uint32) ([]byte, error)
- func (txn *Txn) Del(dbi DBI, key, value []byte) error
- func (txn *Txn) Drop(dbi DBI, del bool) error
- func (txn *Txn) Env() *Env
- func (txn *Txn) EnvWarmup(flags uint, timeout time.Duration) error
- func (txn *Txn) Flags(dbi DBI) (uint, error)
- func (txn *Txn) Get(dbi DBI, key []byte) ([]byte, error)
- func (txn *Txn) GetTree(dbi DBI) *tree
- func (txn *Txn) ID() uint64
- func (txn *Txn) Info(scanRlt bool) (*TxInfo, error)
- func (txn *Txn) IsReadOnly() bool
- func (txn *Txn) ListDBI() ([]string, error)
- func (txn *Txn) OpenCursor(dbi DBI) (*Cursor, error)
- func (txn *Txn) OpenDBI(name string, flags uint, cmp, dcmp CmpFunc) (DBI, error)
- func (txn *Txn) OpenDBISimple(name string, flags uint) (DBI, error)
- func (txn *Txn) OpenRoot(flags uint) (DBI, error)
- func (txn *Txn) Park(autounpark bool) error
- func (txn *Txn) Put(dbi DBI, key, value []byte, flags uint) error
- func (txn *Txn) PutReserve(dbi DBI, key []byte, n int, flags uint) ([]byte, error)
- func (txn *Txn) ReleaseAllCursors(unbind bool) error
- func (txn *Txn) Renew() error
- func (txn *Txn) Reset()
- func (txn *Txn) RunOp(fn TxnOp, terminate bool) error
- func (txn *Txn) Sequence(dbi DBI, increment uint64) (uint64, error)
- func (txn *Txn) SetUserCtx(ctx any)
- func (txn *Txn) Stat(dbi DBI) (*Stat, error)
- func (txn *Txn) StatDBI(dbi DBI) (*Stat, error)
- func (txn *Txn) Sub(fn TxnOp) error
- func (txn *Txn) Unpark(restartIfOusted bool) error
- func (txn *Txn) UserCtx() any
- type TxnOp
- type VersionInfo
Constants ¶
const ( // Magic is a 56-bit prime that identifies MDBX files Magic uint64 = 0x59659DBDEF4C11 // DataVersion is the database file format version DataVersion = 3 // LockVersion is the lock file format version LockVersion = 6 // DataMagic combines magic and version for validation DataMagic = (Magic << 8) + DataVersion // LockMagic combines magic and lock version LockMagic = (Magic << 8) + LockVersion )
Database format constants - must match libmdbx for file compatibility
const ( // MinPageSize is the minimum allowed page size (256 bytes) MinPageSize = 256 // MaxPageSize is the maximum allowed page size (64KB) MaxPageSize = 65536 // DefaultPageSize is the default page size (4KB) DefaultPageSize = 4096 )
Page size constraints
const ( // PageHeaderSize is the fixed page header size (20 bytes) PageHeaderSize = 20 // NodeHeaderSize is the fixed node header size (8 bytes) NodeHeaderSize = 8 )
Page header and node sizes
const ( // MaxDBI is the maximum number of named databases MaxDBI = 32765 // MaxDataSize is the maximum size of a data item MaxDataSize = 0x7fff0000 // MaxPageNo is the maximum page number MaxPageNo uint32 = 0x7FFFffff // NumMetas is the number of meta pages (rotating) NumMetas = 3 // MinPageNo is the first non-meta page number MinPageNo = NumMetas // CoreDBs is the number of core databases (GC and Main) CoreDBs = 2 // FreeDBI is the handle for the GC/free page database FreeDBI = 0 // MainDBI is the handle for the main database MainDBI = 1 )
Database limits
const ( // MinTxnID is the minimum valid transaction ID MinTxnID uint64 = 1 // InitialTxnID is the initial transaction ID for new databases InitialTxnID uint64 = MinTxnID + NumMetas - 1 // InvalidTxnID represents an invalid transaction ID InvalidTxnID uint64 = 0xFFFFFFFFFFFFFFFF )
Transaction ID constants
const ( // EnvDefaults is the default (durable) mode EnvDefaults uint = 0 // Validation enables extra validation of DB structure Validation uint = 0x00002000 // NoSubdir means the path is a filename, not a directory NoSubdir uint = 0x00004000 // ReadOnly opens the environment in read-only mode ReadOnly uint = 0x00020000 // Exclusive opens in exclusive/monopolistic mode Exclusive uint = 0x00400000 // Accede uses existing mode if opened by other processes Accede uint = 0x40000000 // WriteMap maps data with write permission (faster, riskier) WriteMap uint = 0x00080000 // NoStickyThreads allows transactions to move between threads NoStickyThreads uint = 0x00200000 // NoReadAhead disables OS readahead NoReadAhead uint = 0x00800000 // NoMemInit skips zeroing malloc'd memory NoMemInit uint = 0x01000000 // LifoReclaim uses LIFO policy for GC reclamation LifoReclaim uint = 0x04000000 // PagePerturb fills released pages with garbage (debug) PagePerturb uint = 0x08000000 // NoMetaSync skips meta page sync after commit NoMetaSync uint = 0x00040000 // SafeNoSync skips sync but keeps steady commits SafeNoSync uint = 0x00010000 // UtterlyNoSync skips all syncs (dangerous) UtterlyNoSync = SafeNoSync | NoMetaSync // Durable is an alias for EnvDefaults (mdbx-go compatibility) Durable = EnvDefaults // Readonly is an alias for ReadOnly (mdbx-go compatibility) Readonly = ReadOnly // NoTLS is an alias for NoStickyThreads (mdbx-go compatibility) NoTLS = NoStickyThreads // NoReadahead is an alias for NoReadAhead (mdbx-go compatibility) NoReadahead = NoReadAhead )
Environment flags (untyped uint constants for mdbx-go compatibility)
const ( // TxnReadWrite is the default read-write transaction TxnReadWrite uint = 0 // TxnReadOnly creates a read-only transaction TxnReadOnly uint = 0x20000 // TxnReadOnlyPrepare prepares a read-only transaction TxnReadOnlyPrepare = TxnReadOnly | 0x01000000 // TxnTry attempts a non-blocking write transaction TxnTry uint = 0x10000000 // TxnNoMetaSync skips meta sync for this transaction TxnNoMetaSync uint = 0x00040000 // TxnNoSync skips sync for this transaction TxnNoSync uint = 0x00010000 )
Transaction flags (untyped uint constants for mdbx-go compatibility)
const ( TxRW = TxnReadWrite TxRO = TxnReadOnly TxNoSync = TxnNoSync TxNoMetaSync = TxnNoMetaSync )
Transaction flag aliases (mdbx-go short naming convention)
const ( // DBDefaults uses default comparison and features DBDefaults uint = 0 // ReverseKey uses reverse string comparison for keys ReverseKey uint = 0x02 // DupSort allows multiple values per key (sorted) DupSort uint = 0x04 // IntegerKey uses uint32/uint64 keys in native byte order IntegerKey uint = 0x08 // DupFixed uses fixed-size values in DUPSORT tables DupFixed uint = 0x10 // IntegerDup uses fixed-size integer values in DUPSORT IntegerDup uint = 0x20 // ReverseDup uses reverse comparison for values ReverseDup uint = 0x40 // Create creates the database if it doesn't exist Create uint = 0x40000 // DBAccede opens with unknown flags DBAccede uint = 0x40000000 )
Database flags (untyped uint constants for mdbx-go compatibility)
const ( // Upsert is the default insert-or-update mode Upsert uint = 0 // NoOverwrite returns error if key exists NoOverwrite uint = 0x10 // NoDupData returns error if key-value pair exists (DUPSORT) NoDupData uint = 0x20 // Current overwrites current item (cursor put) Current uint = 0x40 // AllDups replaces all duplicates for key AllDups uint = 0x80 // Reserve reserves space without copying data Reserve uint = 0x10000 // Append assumes data is being appended Append uint = 0x20000 // AppendDup assumes duplicate data is being appended AppendDup uint = 0x40000 // Multiple stores multiple data items (DUPFIXED) Multiple uint = 0x80000 )
Put flags (untyped uint constants for mdbx-go compatibility)
const ( // CopyDefaults performs a standard copy CopyDefaults uint = 0 // CopyCompact compacts the database during copy CopyCompact uint = 0x01 )
Copy flags
const ( // WarmupDefault is the default warmup behavior WarmupDefault uint = 0 // WarmupForce forces warmup even if already done WarmupForce uint = 0x01 // WarmupOomSafe uses OOM-safe warmup (slower but safer) WarmupOomSafe uint = 0x02 // WarmupLock holds lock during warmup WarmupLock uint = 0x04 // WarmupTouchLimit limits pages touched during warmup WarmupTouchLimit uint = 0x08 // WarmupRelease releases pages after warmup WarmupRelease uint = 0x10 )
Warmup flags (mdbx-go compatibility)
const ( // DataFileName is the data file name in an environment directory DataFileName = "mdbx.dat" // LockFileName is the lock file name in an environment directory LockFileName = "mdbx.lck" // LockSuffix is appended when NoSubdir is used LockSuffix = "-lck" )
File names
const ( DbgAssert uint = 1 DbgAudit uint = 2 DbgJitter uint = 4 DbgDump uint = 8 DbgLegacyMultiOpen uint = 16 DbgLegacyTxOverlap uint = 32 DbgDoNotChange uint = 0xFFFFFFFF )
Debug constants (mdbx-go compatibility)
const ( // First positions at the first key First uint = iota // FirstDup positions at the first duplicate of current key FirstDup // GetBoth positions at exact key-value pair GetBoth // GetBothRange positions at key with value >= specified GetBothRange // GetCurrent returns current key-value GetCurrent // GetMultiple returns multiple values (DUPFIXED) GetMultiple // Last positions at the last key Last // LastDup positions at the last duplicate of current key LastDup // Next moves to the next key-value Next // NextDup moves to the next duplicate of current key NextDup // NextMultiple returns next multiple values (DUPFIXED) NextMultiple // NextNoDup moves to the first value of next key NextNoDup // Prev moves to the previous key-value Prev // PrevDup moves to the previous duplicate of current key PrevDup // PrevNoDup moves to the last value of previous key PrevNoDup // Set positions at specified key Set // SetKey positions at key, returns key and value SetKey // SetRange positions at first key >= specified SetRange // PrevMultiple returns previous multiple values (DUPFIXED) PrevMultiple // SetLowerbound positions at first key-value >= specified SetLowerbound // SetUpperbound positions at first key-value > specified SetUpperbound // LesserThan positions at the key less than specified LesserThan )
Cursor operation constants (untyped uint for mdbx-go compatibility)
const ( OptMaxDB uint = 0 OptMaxReaders uint = 1 OptSyncBytes uint = 2 OptSyncPeriod uint = 3 OptRpAugmentLimit uint = 4 OptLooseLimit uint = 5 OptDpReserveLimit uint = 6 OptDpReverseLimit uint = 6 // Alias for OptDpReserveLimit (mdbx-go typo compatibility) OptTxnDpLimit uint = 7 OptTxnDpInitial uint = 8 OptSpillMinDenominator uint = 9 OptSpillMaxDenominator uint = 10 OptSpillParent4ChildDenominator uint = 11 OptMergeThreshold16dot16Percent uint = 12 OptWriteThroughThreshold uint = 13 OptPreFaultWriteEnable uint = 14 OptPreferWafInsteadofBalance uint = 15 OptGCTimeLimit uint = 16 )
Option constants for GetOption/SetOption (mdbx-go compatibility)
const ( // Major is the major version number Major = 0 // Minor is the minor version number Minor = 1 // Patch is the patch version number Patch = 0 )
Version constants
const AllowTxOverlap = DbgLegacyTxOverlap
AllowTxOverlap allows overlapping transactions (mdbx-go compatibility)
const CursorStackSize = 32
CursorStackSize is the maximum tree depth supported
const InvalidPageNo uint32 = 0xFFFFFFFF
InvalidPageNo represents an invalid page number (empty tree marker)
const LoggerDoNotChange = LogLvlDoNotChange
LoggerDoNotChange is an alias for LogLvlDoNotChange (mdbx-go compatibility)
const MapFull = ErrMapFull
MapFull is an alias for ErrMapFull (mdbx-go compatibility)
const MaxDbi = MaxDBI
MaxDbi is the maximum number of named databases (mdbx-go compatibility alias)
Variables ¶
var ( ErrKeyExistError = NewError(ErrKeyExist) ErrNotFoundError = NewError(ErrNotFound) ErrPageNotFoundError = NewError(ErrPageNotFound) ErrCorruptedError = NewError(ErrCorrupted) ErrPanicError = NewError(ErrPanic) ErrVersionMismatchError = NewError(ErrVersionMismatch) ErrInvalidError = NewError(ErrInvalid) ErrMapFullError = NewError(ErrMapFull) ErrDBsFullError = NewError(ErrDBsFull) ErrReadersFullError = NewError(ErrReadersFull) ErrTxnFullError = NewError(ErrTxnFull) ErrCursorFullError = NewError(ErrCursorFull) ErrPageFullError = NewError(ErrPageFull) ErrUnableExtendMapsizeError = NewError(ErrUnableExtendMapsize) ErrIncompatibleError = NewError(ErrIncompatible) ErrBadRSlotError = NewError(ErrBadRSlot) ErrBadTxnError = NewError(ErrBadTxn) ErrBadValSizeError = NewError(ErrBadValSize) ErrBadDBIError = NewError(ErrBadDBI) ErrProblemError = NewError(ErrProblem) ErrBusyError = NewError(ErrBusy) )
Common error variables for convenience
var CorruptErrorBacktraceRecommendations = "Otherwise - please create issue in Application repo."
CorruptErrorBacktraceRecommendations is the backtrace recommendation for corruption errors (mdbx-go compatibility)
var CorruptErrorHardwareRecommendations = "" /* 403-byte string literal not displayed */
CorruptErrorHardwareRecommendations is the hardware recommendation for corruption errors (mdbx-go compatibility)
var CorruptErrorMessage = CorruptErrorHardwareRecommendations + " " + CorruptErrorBacktraceRecommendations + " " + CorruptErrorRecoveryRecommendations
CorruptErrorMessage is the combined error message for corruption errors (mdbx-go compatibility)
var CorruptErrorRecoveryRecommendations = "" /* 191-byte string literal not displayed */
CorruptErrorRecoveryRecommendations is the recovery recommendation for corruption errors (mdbx-go compatibility)
var DebugCursor = false
var DebugPrune = false
DebugPrune enables verbose debug output for cursor refresh operations
var ErrBadCursorError = NewError(ErrBadTxn)
ErrBadCursorError indicates an invalid cursor
var MapFullErrorMessage = "The allocated database storage size limit has been reached."
MapFullErrorMessage is the error message for MapFull (mdbx-go compatibility)
var NotFound = errors.New("key not found")
NotFound is a sentinel error for "key not found" (mdbx-go compatibility). Use IsNotFound() to check for this error.
Functions ¶
func CursorToPool ¶
func CursorToPool(c *Cursor)
CursorToPool returns a cursor to the pool. The cursor should be unbound (Close() called) before returning.
func GetSysRamInfo ¶
GetSysRamInfo returns system RAM information.
func IsCorrupted ¶
IsCorrupted returns true if the error indicates database corruption
func IsKeyExist ¶
IsKeyExist returns true if the error is ErrKeyExist
func IsKeyExists ¶
IsKeyExists is an alias for IsKeyExist (mdbx-go compatibility)
func IsNotExist ¶
IsNotExist returns true if the error indicates a file doesn't exist.
func IsNotFound ¶
IsNotFound returns true if the error is ErrNotFound
func SetDebug ¶
SetDebug sets debug flags (mdbx-go compatibility). Returns the previous debug flags.
func SetDebugLog ¶
func SetDebugLog(enabled bool)
SetDebugLog enables or disables debug logging (for debugging only).
Types ¶
type BuildInfo ¶
BuildInfo contains build information (mdbx-go compatibility).
func GetBuildInfo ¶
func GetBuildInfo() BuildInfo
GetBuildInfo returns build information (mdbx-go compatibility).
type CommitLatency ¶
type CommitLatency struct {
Preparation time.Duration
GCWallClock time.Duration
GCCpuTime time.Duration
Audit time.Duration
Write time.Duration
Sync time.Duration
Ending time.Duration
Whole time.Duration
}
CommitLatency contains timing information about a commit operation. For mdbx-go API compatibility.
type Cursor ¶
type Cursor struct {
// contains filtered or unexported fields
}
Cursor provides navigation through a database.
func CursorFromPool ¶
func CursorFromPool() *Cursor
CursorFromPool gets a cursor from the pool. The cursor must be bound to a transaction using Bind before use.
func (*Cursor) Bind ¶
Bind binds a cursor to a transaction and database. This is useful for cursor pooling - get a cursor from CursorFromPool(), then bind it to reuse it across transactions.
func (*Cursor) PutReserve ¶
Cursor.PutReserve reserves space for a value.
func (*Cursor) PutTree ¶
PutTree inserts or updates a sub-database entry in the main database. This sets the N_TREE flag on the node, which is required for libmdbx compatibility. The value should be a 48-byte serialized Tree structure.
func (*Cursor) Renew ¶
Renew renews a cursor for a new read-only transaction. This is used with cursor pooling to reuse a cursor.
func (*Cursor) SetUserCtx ¶
SetUserCtx sets user context data on the cursor.
type CursorOp ¶
type CursorOp = uint
CursorOp is for backward compatibility (deprecated, use uint constants directly)
type Duration16dot16 ¶
type Duration16dot16 uint32
Duration16dot16 is a 16.16 fixed-point duration (mdbx-go compatibility).
func NewDuration16dot16 ¶
func NewDuration16dot16(d time.Duration) Duration16dot16
NewDuration16dot16 converts a time.Duration to 16.16 fixed-point.
func (Duration16dot16) ToDuration ¶
func (d Duration16dot16) ToDuration() time.Duration
ToDuration converts 16.16 fixed-point to time.Duration.
type Env ¶
type Env struct {
// contains filtered or unexported fields
}
Env represents a database environment.
func NewEnv ¶
NewEnv creates a new environment handle. The environment must be opened with Open before use. The label parameter is for identification purposes (mdbx-go compatibility).
func (*Env) Close ¶
func (e *Env) Close()
Close closes the environment and releases resources. Waits for all active read transactions to finish before unmapping.
func (*Env) CloseDBI ¶
CloseDBI closes a database handle. This is normally unnecessary as handles are closed when the environment closes.
func (*Env) EnableSpillBuffer ¶
EnableSpillBuffer creates a spill buffer for dirty pages. This reduces heap pressure by storing dirty pages in a memory-mapped file instead of Go-allocated memory. Call this after Open() but before starting write transactions. The initialCap parameter specifies the initial capacity in pages. If initialCap is 0, a default value is used.
func (*Env) GetSyncBytes ¶
GetSyncBytes returns the threshold for auto-sync.
func (*Env) GetSyncPeriod ¶
GetSyncPeriod returns the period for auto-sync.
func (*Env) Info ¶
Info returns information about the environment. The txn parameter is optional and can be nil.
func (*Env) LeafNodeMax ¶
LeafNodeMax returns the maximum size of a leaf node. This matches libmdbx's leaf_nodemax calculation.
func (*Env) MaxKeySize ¶
MaxKeySize returns the maximum key size for the environment. This matches libmdbx's branch page constraint: BRANCH_NODE_MAX = EVEN_FLOOR((PAGEROOM - indx - node) / 2 - indx) MaxKeySize = BRANCH_NODE_MAX - NODESIZE
func (*Env) MaxReaders ¶
MaxReaders returns the maximum number of readers.
func (*Env) MaxValSize ¶
MaxValSize returns the maximum inline value size. Values larger than this are stored on overflow pages automatically.
func (*Env) PreExtendMmap ¶
PreExtendMmap extends the mmap to the specified size. Call this after Open() when using WriteMap mode to avoid heap allocations during write transactions. The size should be large enough to accommodate all pages that will be written during the transaction. NOTE: This should be called before any transactions start, as remapping while transactions are active can cause issues. Returns nil on success, error on failure.
func (*Env) ReaderCheck ¶
ReaderCheck clears stale entries from the reader lock table. Returns the number of stale readers cleared.
func (*Env) ReaderList ¶
func (e *Env) ReaderList(fn func(info ReaderInfo) error) error
ReaderList returns information about all active readers.
func (*Env) RunTxn ¶
RunTxn runs a transaction with the given flags. The transaction is automatically committed when fn returns nil, or aborted when fn returns an error.
func (*Env) SetCompare ¶
SetCompare sets a custom key comparison function for a database. Must be called before any data operations on the database.
func (*Env) SetDupCompare ¶
SetDupCompare sets a custom data comparison function for DUPSORT databases. Must be called before any data operations on the database.
func (*Env) SetEnvFlags ¶
SetEnvFlags sets or clears environment flags.
func (*Env) SetGeometry ¶
func (e *Env) SetGeometry(sizeLower, sizeNow, sizeUpper, growthStep, shrinkThreshold int64, pageSize int) error
SetGeometry sets the database size parameters.
func (*Env) SetGeometryGeo ¶
SetGeometryGeo sets database geometry using Geometry struct (mdbx-go compatibility).
func (*Env) SetGeometrySize ¶
func (e *Env) SetGeometrySize(sizeLower, sizeNow, sizeUpper, growthStep, shrinkThreshold Size, pageSize int) error
SetGeometrySize sets database geometry using Size types (mdbx-go compatibility).
func (*Env) SetMaxDBs ¶
SetMaxDBs sets the maximum number of named databases. Must be called before Open.
func (*Env) SetMaxReaders ¶
SetMaxReaders sets the maximum number of reader slots. Must be called before Open.
func (*Env) SetPageSize ¶
SetPageSize sets the page size for a new database. Must be called before Open. Must be a power of 2 between 256 and 65536.
func (*Env) SetStrictThreadMode ¶
SetStrictThreadMode sets strict thread mode. In gdbx (pure Go), this is a no-op since Go handles threading differently.
func (*Env) SetSyncBytes ¶
SetSyncBytes sets the threshold for auto-sync.
func (*Env) SetSyncPeriod ¶
SetSyncPeriod sets the period for auto-sync.
func (*Env) SetUserCtx ¶
SetUserCtx sets user context on the environment.
func (*Env) SpillBuffer ¶
SpillBuffer returns the spill buffer, or nil if not enabled.
func (*Env) SubPageLimit ¶
SubPageLimit returns the maximum inline sub-page size. When a sub-page exceeds this, it's converted to a sub-tree. This matches libmdbx's subpage_limit calculation.
func (*Env) Sync ¶
Sync flushes the environment to disk. If force is true, a synchronous flush is performed. If nonblock is true, the function returns immediately if a sync is already in progress.
func (*Env) UnsetFlags ¶
UnsetFlags clears flags in the environment.
func (*Env) Update ¶
Update executes a read-write transaction. The transaction is automatically committed when fn returns nil, or aborted when fn returns an error.
func (*Env) UpdateLocked ¶
UpdateLocked behaves like Update but does not lock the calling goroutine. Use this if the calling goroutine is already locked to its thread.
type EnvInfo ¶
type EnvInfo struct {
Geo EnvInfoGeo
PageOps EnvInfoPageOps
MapSize int64
LastPNO int64 // Alias for LastPgNo (mdbx-go compatibility)
LastPgNo int64
LastTxnID uint64
RecentTxnID uint64
LatterReaderTxnID uint64
MaxReaders uint32
NumReaders uint32
PageSize uint32
SystemPageSize uint32
MiLastPgNo uint64
AutoSyncThreshold uint64
UnsyncedBytes uint64
SinceSync Duration16dot16
AutosyncPeriod Duration16dot16
SinceReaderCheck Duration16dot16
Flags uint32
// Legacy fields for backward compatibility
GeoLower uint64
GeoUpper uint64
GeoCurrent uint64
GeoShrink uint64
GeoGrow uint64
}
EnvInfo holds environment information.
type EnvInfoGeo ¶
type EnvInfoGeo struct {
Lower uint64 // Lower limit for datafile size
Upper uint64 // Upper limit for datafile size
Current uint64 // Current datafile size
Shrink uint64 // Shrink threshold in bytes
Grow uint64 // Growth step in bytes
}
EnvInfoGeo contains geometry information for an environment.
type EnvInfoPageOps ¶
type EnvInfoPageOps struct {
Newly uint64 // Newly allocated pages
Cow uint64 // Copy-on-write pages
Clone uint64 // Cloned pages
Split uint64 // Page splits
Merge uint64 // Page merges
Spill uint64 // Spilled dirty pages
Unspill uint64 // Unspilled pages
Wops uint64 // Write operations
Minicore uint64 // Minicore pages
Prefault uint64 // Prefaulted pages
Msync uint64 // Memory sync operations
Fsync uint64 // File sync operations
}
EnvInfoPageOps contains page operation statistics.
type Error ¶
Error represents a gdbx error with an error code
type ErrorCode ¶
type ErrorCode int
ErrorCode represents MDBX-compatible error codes
const ( // Success indicates the operation completed successfully Success ErrorCode = 0 // ErrSuccess is an alias for Success (mdbx-go compatibility) ErrSuccess = Success // ResultFalse is an alias for Success ResultFalse = Success // ResultTrue indicates success with special meaning ResultTrue ErrorCode = -1 // ErrKeyExist indicates the key/data pair already exists ErrKeyExist ErrorCode = -30799 // ErrNotFound indicates the key/data pair was not found (EOF) ErrNotFound ErrorCode = -30798 // ErrPageNotFound indicates a requested page was not found (corruption) ErrPageNotFound ErrorCode = -30797 // ErrCorrupted indicates the database is corrupted ErrCorrupted ErrorCode = -30796 // ErrPanic indicates a fatal environment error ErrPanic ErrorCode = -30795 // ErrVersionMismatch indicates DB version doesn't match library ErrVersionMismatch ErrorCode = -30794 // ErrInvalid indicates the file is not a valid MDBX file ErrInvalid ErrorCode = -30793 // ErrMapFull indicates the environment mapsize was reached ErrMapFull ErrorCode = -30792 // ErrDBsFull indicates the environment maxdbs was reached ErrDBsFull ErrorCode = -30791 // ErrReadersFull indicates the environment maxreaders was reached ErrReadersFull ErrorCode = -30790 // ErrTxnFull indicates the transaction has too many dirty pages ErrTxnFull ErrorCode = -30788 // ErrCursorFull indicates cursor stack overflow (corruption) ErrCursorFull ErrorCode = -30787 // ErrPageFull indicates a page has no space (internal error) ErrPageFull ErrorCode = -30786 // ErrUnableExtendMapsize indicates mapping couldn't be extended ErrUnableExtendMapsize ErrorCode = -30785 // ErrIncompatible indicates incompatible operation or flags ErrIncompatible ErrorCode = -30784 // ErrBadRSlot indicates reader slot was corrupted or reused ErrBadRSlot ErrorCode = -30783 // ErrBadTxn indicates the transaction is invalid ErrBadTxn ErrorCode = -30782 // ErrBadValSize indicates invalid key or data size ErrBadValSize ErrorCode = -30781 // ErrBadDBI indicates the DBI handle is invalid ErrBadDBI ErrorCode = -30780 // ErrProblem indicates an unexpected internal error ErrProblem ErrorCode = -30779 // ErrBusy indicates another write transaction is running ErrBusy ErrorCode = -30778 // ErrMultiVal indicates the key has multiple associated values ErrMultiVal ErrorCode = -30421 // ErrMultival is an alias for ErrMultiVal (mdbx-go compatibility) ErrMultival = ErrMultiVal // ErrBadSign indicates bad signature (memory corruption or ABI mismatch) ErrBadSign ErrorCode = -30420 // ErrWannaRecovery indicates recovery is needed but DB is read-only ErrWannaRecovery ErrorCode = -30419 // ErrKeyMismatch indicates key mismatch with cursor position ErrKeyMismatch ErrorCode = -30418 // ErrTooLarge indicates database is too large for system ErrTooLarge ErrorCode = -30417 // ErrThreadMismatch indicates thread attempted to use unowned object ErrThreadMismatch ErrorCode = -30416 // ErrTxnOverlapping indicates overlapping read/write transactions ErrTxnOverlapping ErrorCode = -30415 // ErrBacklogDepleted indicates GC ran out of free pages ErrBacklogDepleted ErrorCode = -30414 // ErrDuplicatedCLK indicates duplicate lock file exists ErrDuplicatedCLK ErrorCode = -30413 // ErrDanglingDBI indicates resources need closing before DBI can be reused ErrDanglingDBI ErrorCode = -30412 // ErrOusted indicates parked transaction was evicted for GC ErrOusted ErrorCode = -30411 // ErrMVCCRetarded indicates parked transaction's snapshot is too old ErrMVCCRetarded ErrorCode = -30410 )
Error codes - matching MDBX for compatibility
const ErrPermissionDenied ErrorCode = -1 // Will use syscall.EACCES
ErrPermissionDenied indicates a write operation on read-only transaction
type Geometry ¶
type Geometry struct {
SizeLower Size // Lower limit for datafile size
SizeNow Size // Current datafile size (use -1 for default)
SizeUpper Size // Upper limit for datafile size
GrowthStep Size // Growth step in bytes
ShrinkThreshold Size // Shrink threshold in bytes
PageSize int // Page size in bytes (use -1 for default)
}
Geometry holds database geometry parameters (mdbx-go compatibility).
type HandleSlowReadersFunc ¶
type HandleSlowReadersFunc func(env *Env, txn *Txn, pid int, tid uint64, laggard uint64, gap uint64, space uint64, retry int) int
HandleSlowReadersFunc is called when slow readers are detected (mdbx-go compatibility).
func SetHandleSlowReaders ¶
func SetHandleSlowReaders(fn HandleSlowReadersFunc) HandleSlowReadersFunc
SetHandleSlowReaders sets the slow readers handler (mdbx-go compatibility). Returns the previous handler.
type Label ¶
type Label string
Label is a label for an environment (mdbx-go compatibility)
const Default Label = "default"
Default is the default environment label (mdbx-go compatibility)
type LogLvl ¶
type LogLvl int
Log level constants (mdbx-go compatibility)
func SetLogger ¶
func SetLogger(logger LoggerFunc, level LogLvl) LogLvl
SetLogger sets the logger function and level (mdbx-go compatibility). Returns the previous log level.
type LoggerFunc ¶
LoggerFunc is a callback function for logging (mdbx-go compatibility).
type Multi ¶
type Multi struct {
// contains filtered or unexported fields
}
Multi wraps multi-value pages for DUPFIXED databases.
type PageFlags ¶
type PageFlags uint16
PageFlags define page types
const ( // PageBranch indicates a branch (internal) page PageBranch PageFlags = 0x01 // PageLeaf indicates a leaf page PageLeaf PageFlags = 0x02 // PageLarge indicates a large/overflow page PageLarge PageFlags = 0x04 // PageMeta indicates a meta page PageMeta PageFlags = 0x08 // PageLegacyDirty is a legacy dirty flag (pre v0.10) PageLegacyDirty PageFlags = 0x10 // PageBad is an explicit flag for invalid pages PageBad = PageLegacyDirty // PageDupfix indicates a DUPFIXED page PageDupfix PageFlags = 0x20 // PageSubP indicates a sub-page for DUPSORT PageSubP PageFlags = 0x40 // PageSpilled indicates a page spilled in parent txn PageSpilled PageFlags = 0x2000 // PageLoose indicates a freed page available for reuse PageLoose PageFlags = 0x4000 // PageFrozen indicates a retired page with known status PageFrozen PageFlags = 0x8000 )
type ReaderInfo ¶
ReaderInfo contains information about a reader slot (mdbx-go compatibility).
type Stat ¶
type Stat struct {
PageSize uint32 // Page size in bytes
Depth uint32 // Tree depth
BranchPages uint64 // Number of branch pages
LeafPages uint64 // Number of leaf pages
LargePages uint64 // Number of overflow pages
OverflowPages uint64 // Alias for LargePages (mdbx-go compat)
Entries uint64 // Number of entries
Root uint32 // Root page number (for debugging)
ModTxnID uint64 // Last modification transaction ID
}
Stat holds database statistics.
type TxInfo ¶
type TxInfo struct {
ID uint64
ReaderLag uint64
SpaceUsed uint64
SpaceLimitSoft uint64
SpaceLimitHard uint64
SpaceRetired uint64
SpaceLeftover uint64
SpaceDirty uint64
Spill uint64 // Pages spilled to disk
Unspill uint64 // Pages unspilled from disk
}
TxInfo contains transaction information.
type Txn ¶
type Txn struct {
// contains filtered or unexported fields
}
Txn represents a database transaction.
func (*Txn) Commit ¶
func (txn *Txn) Commit() (CommitLatency, error)
Commit commits the transaction and returns latency information. Returns (CommitLatency, error) for mdbx-go API compatibility.
func (*Txn) CreateDBI ¶
CreateDBI creates a new named database. This is a convenience wrapper around OpenDBI with Create flag.
func (*Txn) DebugGetPage ¶
DebugGetPage returns a page by number (for debugging).
func (*Txn) Drop ¶
Drop deletes all data in a database, or deletes the database entirely. If del is true, the database is deleted; otherwise it is emptied.
func (*Txn) Flags ¶
Flags returns the flags for a database. This is an alias for DBIFlags (mdbx-go compatibility).
func (*Txn) Get ¶
Get retrieves a value by key. This is optimized to avoid cursor allocation for simple lookups.
func (*Txn) IsReadOnly ¶
IsReadOnly returns true if this is a read-only transaction.
func (*Txn) OpenCursor ¶
OpenCursor opens a cursor on a database.
func (*Txn) OpenDBI ¶
OpenDBI opens a database/table within the transaction. The cmp parameter is the key comparison function (nil for default). The dcmp parameter is the data/value comparison function for DUPSORT (nil for default).
func (*Txn) OpenDBISimple ¶
OpenDBISimple opens a database/table within the transaction using default comparators. This is the simple form without custom comparators (mdbx-go compatibility).
func (*Txn) PutReserve ¶
PutReserve reserves space for a value and returns a slice to write into.
func (*Txn) ReleaseAllCursors ¶
ReleaseAllCursors closes all cursors in the transaction.
func (*Txn) RunOp ¶
RunOp runs a function in the transaction. If terminate is true, the transaction is committed/aborted based on error.
func (*Txn) Sequence ¶
Sequence gets or updates the sequence number for a database. If increment > 0, adds to the sequence and returns the new value. If increment == 0, returns the current value without changing it.
func (*Txn) SetUserCtx ¶
SetUserCtx sets user context on the transaction.
func (*Txn) StatDBI ¶
StatDBI returns statistics for a database. This is an alias for Stat (mdbx-go compatibility).
type TxnOp ¶
TxnOp is a function that operates on a transaction. This is the callback type for View, Update, and RunTxn.
type VersionInfo ¶
type VersionInfo struct {
Major uint8
Minor uint8
Release uint8
Revision uint16
Git string
Describe string
Datetime string
Tree string
Commit string
Sourcery string
}
VersionInfo contains version information (mdbx-go compatibility).
func GetVersionInfo ¶
func GetVersionInfo() VersionInfo
GetVersionInfo returns version information (mdbx-go compatibility).
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package fastmap provides a fast hash map for integer keys.
|
Package fastmap provides a fast hash map for integer keys. |
|
Package mmap provides cross-platform memory mapping functionality.
|
Package mmap provides cross-platform memory mapping functionality. |
|
Package spill provides a memory-mapped spill buffer for dirty pages.
|
Package spill provides a memory-mapped spill buffer for dirty pages. |