Documentation
¶
Overview ¶
Package bolttable provides typed tables over a bbolt file: namespaces of tables with declared indexes, counters and cascades, a revision counter with a change feed, a per-namespace format digest with reset, and verification, statistics, online backup and compaction at open.
A Schema is declared once, usually through Must, and sealed by Open. Keys go through a KeyCodec, so their byte layout, and with it the scan order, is the caller's; values through a Codec, JSON by default. Every declaration that shapes stored bytes enters its namespace's digest, and Open refuses a file whose stored digests differ with a *FormatError unless its ResetPolicy allows the reset.
Open takes the exclusive lock on <path>.lock, a file it never removes, and under it removes stranded temporary files, inspects the file without writing, moves an invalid file aside or resets a changed namespace when Options allow it, compacts, and opens the file for writing; OpenReport tells what it did. OpenReadOnly holds the same lock shared when <path>.lock exists, leaves an absent lock file absent, and writes nothing. LockPath takes the lock for a caller's own file operations, and Options.Lock runs Open under it.
A transaction that writes a non-silent table, Touches a subject or sets a Mark reserves the next revision and records one Change, which Since returns and OnCommit receives in revision order. Every slice the package returns or keeps is a copy.
Example ¶
package main
import (
"bytes"
"context"
"fmt"
"log"
"os"
"path/filepath"
"slices"
"time"
"github.com/cplieger/bolttable"
)
type user struct {
Email string `json:"email"`
Admin bool `json:"admin"`
}
var (
schema = bolttable.NewSchema("app")
accounts = bolttable.Must(schema.Namespace("accounts"))
users = bolttable.Must(bolttable.Define(accounts, 0x01, "users",
bolttable.Uint64Key{}, bolttable.JSON[user](1), bolttable.TableOptions{}))
byEmail = bolttable.Must(bolttable.DefineIndex(users, "by_email",
bolttable.IndexOptions{Unique: true, Version: 1},
func(_ uint64, u *user) []bolttable.Entry { return []bolttable.Entry{{Key: []byte(u.Email)}} }))
admins = bolttable.Must(bolttable.DefineCounter(users, "admins", 1,
func(_ uint64, u *user) int64 {
if u.Admin {
return 1
}
return 0
}))
)
func main() {
dir, err := os.MkdirTemp("", "bolttable-example")
if err != nil {
log.Fatal(err)
}
defer func() { _ = os.RemoveAll(dir) }()
db, err := bolttable.Open(filepath.Join(dir, "app.bolt"), schema, bolttable.Options{
Retention: 1000,
LockWait: 5 * time.Second,
// A format change in a namespace the app can rebuild resets it,
// keeping two copies of the file; any other one fails Open.
Reset: bolttable.ResetPolicy{
Allow: func(n bolttable.NamespaceDigest) bool { return n.Name == "cache" },
Keep: 2,
},
OnCommit: func(c bolttable.Change) { fmt.Println("revision", c.Rev, "subjects", len(c.Subjects)) },
})
if err != nil {
log.Fatal(err)
}
defer func() { _ = db.Close() }()
ctx := context.Background()
err = db.Update(ctx, func(tx *bolttable.Tx) error {
id, err := users.NextID(tx)
if err != nil {
return err
}
tx.Touch(bolttable.Synthetic([]byte("signups")))
return users.Put(tx, id, &user{Email: "ada@example.com", Admin: true})
})
if err != nil {
log.Fatal(err)
}
err = db.View(ctx, func(r *bolttable.ReadTx) error {
id, _, found, err := byEmail.Lookup(r, []byte("ada@example.com"))
if err != nil || !found {
return err
}
n, err := admins.Value(r)
if err != nil {
return err
}
fmt.Println("user", id, "admins", n)
page, err := r.Since(0, 100)
for _, c := range page.Changes {
fmt.Printf("change %d: %d subjects, signups touched %v\n", c.Rev, len(c.Subjects), slices.ContainsFunc(c.Subjects, isSignups))
}
return err
})
if err != nil {
log.Fatal(err)
}
}
func isSignups(s bolttable.Subject) bool {
return bytes.Equal(s, bolttable.Synthetic([]byte("signups")))
}
Output: revision 1 subjects 2 user 1 admins 1 change 1: 2 subjects, signups touched true
Index ¶
- Constants
- Variables
- func CascadeIndex[PK, PV, CK, CV any](parent *Table[PK, PV], via *Index[CK, CV], version uint32, ...) error
- func CascadePrefix[PK, PV, CK, CV any](parent *Table[PK, PV], child *Table[CK, CV], version uint32, ...) error
- func Must[T any](v T, err error) T
- type BytesKey
- type Change
- type ChangePage
- type Codec
- type CompactPolicy
- type ConflictError
- type Counter
- type DB
- func (db *DB) Backup(ctx context.Context, path string) error
- func (db *DB) Batch(ctx context.Context, fn func(*Tx) error) error
- func (db *DB) Close() error
- func (db *DB) Epoch() [16]byte
- func (db *DB) OpenReport() OpenReport
- func (db *DB) Space() (Space, error)
- func (db *DB) Stats(ctx context.Context) (Stats, error)
- func (db *DB) Update(ctx context.Context, fn func(*Tx) error) error
- func (db *DB) Verify(ctx context.Context, repair bool) (VerifyReport, error)
- func (db *DB) View(ctx context.Context, fn func(*ReadTx) error) error
- type Entry
- type FormatError
- type Index
- type IndexOptions
- type InvalidFilePolicy
- type KeyCodec
- type Lock
- type Mismatch
- type Namespace
- type NamespaceDigest
- type NamespaceStats
- type OpenReport
- type Options
- type Pending
- type Range
- type ReadDB
- func (db *ReadDB) Backup(ctx context.Context, path string) error
- func (db *ReadDB) Close() error
- func (db *ReadDB) Epoch() [16]byte
- func (db *ReadDB) Space() (Space, error)
- func (db *ReadDB) Stats(ctx context.Context) (Stats, error)
- func (db *ReadDB) Verify(ctx context.Context) (VerifyReport, error)
- func (db *ReadDB) View(ctx context.Context, fn func(*ReadTx) error) error
- type ReadOptions
- type ReadTx
- type ResetPolicy
- type Schema
- type Space
- type Stats
- type Subject
- type Table
- func (t *Table[K, V]) Delete(tx *Tx, k K) (bool, error)
- func (t *Table[K, V]) Get(r *ReadTx, k K) (v V, found bool, err error)
- func (t *Table[K, V]) NextID(tx *Tx) (uint64, error)
- func (t *Table[K, V]) Put(tx *Tx, k K, v *V) error
- func (t *Table[K, V]) Scan(r *ReadTx, rg Range, fn func(K, *V) (bool, error)) error
- func (t *Table[K, V]) Subject(k K) Subject
- type TableOptions
- type TableStats
- type Tx
- type Uint64Key
- type VerifyReport
- type WriteHealth
- type WriteRecord
Examples ¶
Constants ¶
const SyntheticPrefix byte = 0xFF
SyntheticPrefix starts every subject that names no row. Define refuses it.
Variables ¶
var ( // ErrFormat matches a *FormatError: the file's stored format differs from // the schema. ErrFormat = errors.New("bolttable: stored format differs from the schema") // ErrConflict matches a *ConflictError: a Put would give a unique index // key a second row. ErrConflict = errors.New("bolttable: unique index conflict") // ErrCorrupt reports stored bytes that do not decode. Its message names // the table or index and a fingerprint of the stored key, never key or // row bytes, and it drops the codec's own error, whose text may hold // them. ErrCorrupt = errors.New("bolttable: row does not decode") // ErrCommit wraps a failure of bbolt itself to begin or commit a // transaction, so a caller tells a storage fault from its own refusal. A // failed page write keeps its *os.PathError and a failed fdatasync its // syscall.Errno, but bbolt flattens a failure to grow the file to text // (https://github.com/etcd-io/bbolt/blob/v1.5.0/db.go#L1245), so a caller // classing causes by errno falls back to "other" when none matches. ErrCommit = errors.New("bolttable: commit failed") // ErrPublished reports that Backup linked a complete copy at its path, // then failed to remove its temporary name or to fsync the directory. ErrPublished = errors.New("bolttable: backup published, not made durable") // ErrLocked reports that another process, or another handle in this one, // holds the file. ErrLocked = errors.New("bolttable: database file is locked") // ErrInvalidFile reports a file bbolt cannot read as a database: both // meta pages rejected, a page size too small to hold a meta page, fewer // bytes than its meta records, a freelist page bbolt cannot load or that // lists a page it must never reuse, or a page read that faulted or // panicked; bbolt's "file size too small" stays unclassified. A panic // inside bbolt's open, or a rollback that panics twice, leaves the file // mapped but not locked, and bbolt walks a NoFreelistSync file on an // unguarded goroutine. ErrInvalidFile = errors.New("bolttable: invalid database file") )
Functions ¶
func CascadeIndex ¶
func CascadeIndex[PK, PV, CK, CV any](parent *Table[PK, PV], via *Index[CK, CV], version uint32, prefix func(PK) []byte) error
CascadeIndex makes deleting a parent row delete, in the same transaction, every row of via's table holding an entry of via whose index key starts with prefix(parent key), and recursively their own cascades. Parent and index share one namespace.
func CascadePrefix ¶
func CascadePrefix[PK, PV, CK, CV any](parent *Table[PK, PV], child *Table[CK, CV], version uint32, prefix func(PK) []byte) error
CascadePrefix makes deleting a parent row delete, in the same transaction, every child row whose encoded key starts with prefix(parent key), and recursively their own cascades. Parent and child share one namespace.
Types ¶
type BytesKey ¶
type BytesKey struct{}
BytesKey stores a []byte key as is; Put refuses an empty one.
type Change ¶
Change is one committed revision: the subjects BeforeCommit returned (or the touched ones) and every mark.
type ChangePage ¶
type ChangePage struct {
// Changes are in revision order; empty, never nil, unless Full.
Changes []Change
// Full reports that the log cannot answer from after: a change after it
// has been trimmed (after+1 is below the oldest retained revision), or
// after is above the head. Changes is then nil and More false.
Full bool
// More reports that retained changes follow the last one returned.
More bool
}
ChangePage is one page of the change log.
type Codec ¶
type Codec[V any] interface { Version() uint32 Append(dst []byte, v *V) ([]byte, error) Decode(b []byte, v *V) error }
Codec encodes a table's values. Version enters the namespace's format digest, so an encoding change bumps it. Append must be deterministic: a Put whose encoding equals the stored bytes writes nothing. Decode receives a copy it may keep.
type CompactPolicy ¶
CompactPolicy is when Open rewrites the file without its free pages: when its free bytes, free and pending pages times the page size, reach both MinFreeRatio of the file size and MinFreeBytes. The zero value never compacts. MinFreeRatio must lie in [0, 1] and MinFreeBytes must not be negative. A compaction that fails leaves the file whole and does not fail Open: OpenReport.CompactErr holds it.
type ConflictError ¶
type ConflictError struct {
Index string
}
ConflictError names the unique index a Put collided on; errors.Is(err, ErrConflict) matches it. The transaction stays usable: the refused Put wrote nothing.
func (*ConflictError) Error ¶
func (e *ConflictError) Error() string
func (*ConflictError) Is ¶
func (*ConflictError) Is(target error) bool
Is reports whether target is ErrConflict.
type Counter ¶
type Counter[K, V any] struct { // contains filtered or unexported fields }
Counter keeps the sum of a weight over every row of its table, updated in the same transaction as the row.
func DefineCounter ¶
func DefineCounter[K, V any](t *Table[K, V], name string, version uint32, weight func(k K, v *V) int64) (*Counter[K, V], error)
DefineCounter declares a counter summing weight over the table's rows. It fails for a nil table or function, a zero version, a name already used in the namespace, and after Open.
type DB ¶
type DB struct {
// contains filtered or unexported fields
}
DB is an open bolttable file.
func Open ¶
Open opens or creates the file at path, mode 0600, under s, sealing s. Under the exclusive lock on path, taken or adopted from o.Lock and held until Close, it removes stranded temporary files, inspects a stored file without writing, applies o.InvalidFile, o.Reset and o.Compact, and creates the namespaces the file lacks; OpenReport tells what it did. A format change o.Reset refuses fails with the *FormatError, the file unchanged, and another holder of the lock with ErrLocked. The lock has LockPath's filesystem and platform limits.
func (*DB) Backup ¶
Backup writes a compacted copy of the file to path, mode 0600, from one read transaction while the database stays open. It walks into an exclusively created .<base>.bolttable-tmp beside path and publishes it with a hard link, which fails for any existing path, one created during the walk included. A failure before the link leaves no path and removes the temporary file, never one Backup did not create. After the link path is complete, and a failed removal of the temporary name or directory fsync wraps ErrPublished.
func (*DB) Batch ¶
Batch is Update through bbolt's grouped commit: concurrent calls share one transaction and fsync, in groups bounded by Options.MaxBatchSize and MaxBatchDelay. fn may run more than once (bbolt reruns a group after one call fails, and the failed call alone: https://github.com/etcd-io/bbolt/blob/v1.5.0/db.go#L1024); only its last run's writes, change and AfterCommit functions survive. Each call keeps its own subjects, marks and revision; a group's callbacks run in the order its calls ran. Batch returns as Update does.
func (*DB) Close ¶
Close closes the file, waiting for open transactions, then releases the lock Open took or frees an adopted one, which stays held. A second Close returns nil.
func (*DB) Epoch ¶
Epoch returns the random identity of this open: a reader holding a revision from another epoch must resync.
func (*DB) OpenReport ¶
func (db *DB) OpenReport() OpenReport
OpenReport returns what Open did to the file before it opened it.
func (*DB) Space ¶
Space reads the file's size, in-use and free bytes without a transaction or a page walk: the high-water mark comes from the file's meta pages, read without mapping. After Close it returns an error matching bbolt's ErrDatabaseNotOpen.
func (*DB) Stats ¶
Stats reads the file's statistics in one read transaction, walking every table's pages.
func (*DB) Update ¶
Update runs fn in one bbolt read-write transaction. fn's error, or one from BeforeCommit, rolls it back and is returned as is; a failure of bbolt itself wraps ErrCommit. A context already done runs nothing and returns ctx.Err() at once. Update returns after its own commit's callbacks ran; a call that fails returns after the callbacks of the commits before it.
func (*DB) Verify ¶
Verify rescans every table in one transaction and recomputes every index entry and counter. With repair it rewrites index entries and counters, and only those: it never rewrites or deletes a row, so an undecodable row stays reported with Repaired false, and its remedy is a restore. A repair writes no revision.
type Entry ¶
type Entry struct {
Key, Value []byte
}
Entry is one index entry a row produces. Key is the index key; Value is the projection a lookup or scan returns without reading the row.
type FormatError ¶
type FormatError struct {
Namespaces []NamespaceDigest
// Missing, sorted, is what OpenReadOnly found absent and Open would
// create: each declared namespace the file has no bucket for, and
// "bolttable" when it lacks the library bucket or its change log. Open
// never fills it.
Missing []string
}
FormatError names every namespace whose stored format differs from the schema; errors.Is(err, ErrFormat) matches it. Every name in Namespaces is one Reset.Allow is asked about and Reset.Force accepts.
func (*FormatError) Error ¶
func (e *FormatError) Error() string
func (*FormatError) Is ¶
func (*FormatError) Is(target error) bool
Is reports whether target is ErrFormat.
type Index ¶
type Index[K, V any] struct { // contains filtered or unexported fields }
Index is a declared index over a table. Each row maps to any number of entries: none makes the index sparse, several make it per-element.
func DefineIndex ¶
func DefineIndex[K, V any](t *Table[K, V], name string, o IndexOptions, entries func(k K, v *V) []Entry) (*Index[K, V], error)
DefineIndex declares an index whose entries entries computes from a row. It fails for a nil table or function, a zero version, a name already used in the namespace, and after Open.
type IndexOptions ¶
IndexOptions configures an index. A Unique index gives each key at most one row. Version enters the namespace's format digest and must not be zero.
type InvalidFilePolicy ¶
type InvalidFilePolicy uint8
InvalidFilePolicy is what Open does with a file wrapping ErrInvalidFile.
const ( // InvalidFileFail returns the error and leaves the file untouched. InvalidFileFail InvalidFilePolicy = iota // InvalidFileMoveAside renames the file to <path>.<stamp>.invalid, stamp // the UTC time as 20060102T150405.000000000Z, and opens a new empty file. // Open moves at most one file aside: a new file that is invalid fails. InvalidFileMoveAside )
type KeyCodec ¶
type KeyCodec[K any] interface { Version() uint32 AppendKey(dst []byte, k K) []byte ParseKey(b []byte) (K, error) }
KeyCodec lays a table's keys out as bytes; the byte order is the order Scan visits. Version enters the namespace's format digest, so a layout change bumps it. ParseKey receives a copy it may keep.
type Lock ¶
type Lock struct {
// contains filtered or unexported fields
}
Lock is the exclusive process lock on a database path, the file <path>.lock. The lock assumes a local filesystem (see LockPath).
func LockPath ¶
LockPath takes the exclusive lock on path, waiting up to wait: zero tries once, negative is an error, and another holder fails it with ErrLocked. It creates <path>.lock, mode 0600, and never removes or renames it. Pass the Lock as Options.Lock to Open path under it. The lock, flock(2) on Linux, the BSDs and Darwin, excludes other processes and other handles in this one only on a local filesystem: NFS and, since Linux 5.5, CIFS emulate flock with per-process byte-range locks. Other platforms, Windows included, get an error wrapping errors.ErrUnsupported.
type Mismatch ¶
Mismatch is one table, index or counter, named namespace.name, whose stored state differs from a rescan of its rows. For a table, Undecodable counts rows that do not decode; their index entries count as neither missing nor extra. For an index, Missing and Extra count entries. For a counter, a stored total differing from the exact sum of its rows' weights, or a sum outside int64, is one Missing and one Extra, and Undecodable counts rows its sum could not include, which leaves it unchecked.
type Namespace ¶
type Namespace struct {
// contains filtered or unexported fields
}
Namespace is one top-level bucket holding its tables, with its own format digest, so one namespace's format change never resets another's rows. Prefixes are unique across the schema, so a Subject stays prefix plus key.
type NamespaceDigest ¶
NamespaceDigest is one mismatched top-level bucket. A zero Want is a stored bucket the schema does not declare, or the library's own bucket; a zero Stored is a bucket holding no digest, or any bucket of a file whose layout is not this library's. A declared namespace the file lacks is a FormatError.Missing name, never a NamespaceDigest.
type NamespaceStats ¶
type NamespaceStats struct {
Name string
Tables []TableStats
Format [32]byte
}
NamespaceStats is one namespace's stored format digest and its tables.
type OpenReport ¶
type OpenReport struct {
// Invalid is why the file was moved aside; it wraps ErrInvalidFile.
Invalid error
// CompactErr is a compaction that failed and left the file as it was,
// or a directory fsync that failed after it, with Compacted set.
CompactErr error
// MovedAside is the invalid file's new path; "" when none.
MovedAside string
// Kept is the .old copy taken before the reset; "" when none.
Kept string
// Reset is every name reset, sorted, with the digest stored and the one
// recreated; Want is zero for a name the schema does not declare.
Reset []NamespaceDigest
Compacted bool
}
OpenReport is what Open did to the file before it opened it.
type Options ¶
type Options struct {
// BeforeCommit runs once per revision-reserving transaction, before bbolt
// commits, and returns the subjects to record. It may write silent tables
// and add marks; a non-silent write or Touch fails the transaction, and
// its error rolls everything back. It may return subjects naming no row,
// built with Synthetic, which reach Since and OnCommit unchanged; a
// subject starting with neither a declared prefix nor SyntheticPrefix
// fails the transaction.
BeforeCommit func(*Tx, *Pending) ([]Subject, error)
// OnCommit receives each committed change. OnCommit and every AfterCommit
// function run in commit order across the DB, silent-only and empty
// commits included: each commit's callbacks return before the next
// commit's start. They run one at a time, outside every bbolt lock, and
// must not block or start a write on the same DB, which deadlocks; a View
// is allowed.
OnCommit func(Change)
// CommitFault, for tests of a caller's write-fault handling, is asked
// once per run of every Update and Batch call, after fn, BeforeCommit
// and the change record, with the call's context; Verify's repair never
// asks it. A non-nil error fails the run as a failed bbolt commit would:
// it rolls back, runs no callback, and the call returns an error
// wrapping ErrCommit and the hook's error. In a Batch group it fails
// only the calls it selects, on every rerun, where a real commit failure
// fails the whole group. Production leaves it nil.
CommitFault func(ctx context.Context) error
// Lock is a lock the caller took with LockPath(path, …) and still holds.
// Open runs under it instead of taking its own, and Close leaves it
// held. nil has Open take the lock and Close release it. Setting it with
// a non-zero LockWait is an error.
Lock *Lock
// Reset decides what Open resets.
Reset ResetPolicy
// Compact decides when Open compacts the file.
Compact CompactPolicy
// Retention is how many of the newest changes Since can return; it must
// not be negative.
Retention int
// MaxBatchSize and MaxBatchDelay bound a Batch group: it runs when it
// holds MaxBatchSize calls or MaxBatchDelay after its first call,
// whichever comes first. Zero means 1000 calls and 10 ms; negative is an
// error.
MaxBatchSize int
MaxBatchDelay time.Duration
// LockWait is how long Open waits for another holder of <path>.lock,
// polling every 50 ms. Zero tries once; negative is an error.
LockWait time.Duration
// InvalidFile is what Open does with a file wrapping ErrInvalidFile.
InvalidFile InvalidFilePolicy
}
Options configures an open DB. The zero value records Touched as each change's subjects, delivers nothing and retains no change, so every Since below the head answers full.
type Pending ¶
Pending is the revision a transaction is about to commit, handed to BeforeCommit. Its slices are copies.
type Range ¶
Range selects keys k with Prefix as a prefix, From <= k (when From is not nil) and k < To (when To is not nil), visited in byte order or, when Reverse, in reverse. A table compares its encoded keys; an index compares index keys, and a non-unique index visits a key's rows in primary-key order. From >= To selects nothing. A page resumes exactly (forward: From set to the last key plus 0x00; reverse: To set to the last key) only when each key names one row: a table, a unique index, or a non-unique index whose key carries something unique per row, such as a sequence.
type ReadDB ¶
type ReadDB struct {
// contains filtered or unexported fields
}
ReadDB is a file opened by OpenReadOnly. It has no write method.
func OpenReadOnly ¶
func OpenReadOnly(path string, s *Schema, o ReadOptions) (rdb *ReadDB, err error)
OpenReadOnly opens the file at path for reading only under s, sealing s: it creates, resets, compacts and writes nothing. It holds the shared lock on an existing <path>.lock until Close, so a writer's Open fails with ErrLocked meanwhile, and fails with ErrLocked when a writer keeps it past o.LockWait. An absent or empty file wraps fs.ErrNotExist, an unreadable one ErrInvalidFile; a file Open would reset or complete fails with a *FormatError whose Missing names what Open would create. The lock has LockPath's filesystem and platform limits.
func (*ReadDB) Close ¶
Close closes the file, waiting for open transactions, and releases the shared lock. A second Close returns nil.
type ReadOptions ¶
type ReadOptions struct {
// Retention is how many of the newest changes Since can return, as
// Options.Retention.
Retention int
// LockWait is how long OpenReadOnly waits for a writer holding
// <path>.lock, as Options.LockWait.
LockWait time.Duration
}
ReadOptions configures OpenReadOnly.
type ReadTx ¶
type ReadTx struct {
// contains filtered or unexported fields
}
ReadTx reads one consistent snapshot. It is valid only inside the function View passed it to, or while its Tx is.
func (*ReadTx) Rev ¶
Rev returns the head revision: the newest committed one, 0 before any. It fails after the transaction ended, and with ErrCorrupt when the library bucket, the change log or the head is damaged.
func (*ReadTx) Since ¶
func (r *ReadTx) Since(after uint64, limit int) (ChangePage, error)
Since returns at most limit retained changes with Rev above after, in order. limit below 1 is an error. To continue, call again with after set to the last returned Rev; pages read in one transaction agree, and a later transaction may find the log trimmed past after, which it reports as Full.
type ResetPolicy ¶
type ResetPolicy struct {
// Allow reports whether a namespace a *FormatError lists may be reset.
// Open asks it once per listed name, in order, and resets only when it
// accepts every one; nil accepts none. Its panic reaches the caller.
Allow func(NamespaceDigest) bool
// Force names namespaces Open resets even when their format matches.
// Each must be stored in the file, declared by the schema, or
// "bolttable"; a new file stores nothing, so there it resets nothing.
Force []string
// Keep is how many .old copies of the file to keep, the new one
// included: before a reset Open copies the file to
// <path>.<8 hex>.<stamp>.old, the hex from the first reset name's stored
// digest, and removes the older copies. Zero takes no copy and removes
// none; negative is an error.
Keep int
}
ResetPolicy decides what Open resets. The zero value resets nothing.
type Schema ¶
type Schema struct {
// contains filtered or unexported fields
}
Schema is the set of namespaces a file holds. Declarations build it before the first Open, which seals it; a declaration after that fails.
type Space ¶
type Space struct {
// FileBytes is the data file's size, including the tail bbolt grows the
// file by ahead of use, which holds no page yet.
FileBytes int64
// InUseBytes is the pages below bbolt's high-water mark, as the newest
// valid meta page records it, less FreeBytes.
InUseBytes int64
// FreeBytes is free and pending pages times the page size, as of the
// last write commit or the open. Pending pages count: they become
// reusable once the readers pinning them finish, and compaction drops
// them.
FreeBytes int64
}
Space is the file's size, the bytes its data uses and the bytes bbolt can reuse. InUseBytes + FreeBytes is at most FileBytes; the rest is bbolt's preallocated tail.
type Stats ¶
type Stats struct {
Namespaces []NamespaceStats
Rev uint64
Oldest uint64
Commits uint64
Space Space
}
Stats describes an open file. Rev and Oldest bound what Since returns. Commits counts every bbolt commit since Open whose meta page reached the file: one per Batch group, and silent-only, byte-equal and empty writes too. A rolled-back transaction does not count; one whose fdatasync failed after the meta write does, though its call returned ErrCommit, since bbolt's next transaction id moves past it (https://github.com/etcd-io/bbolt/blob/v1.5.0/tx.go#L607).
type Subject ¶
type Subject []byte
Subject names one row in the change feed: a table's prefix byte plus the encoded key, or SyntheticPrefix plus caller-owned bytes for a subject naming no row.
type Table ¶
type Table[K, V any] struct { // contains filtered or unexported fields }
Table is a typed table declared in a namespace.
func Define ¶
func Define[K, V any](ns *Namespace, prefix byte, name string, k KeyCodec[K], v Codec[V], o TableOptions) (*Table[K, V], error)
Define declares a table under a prefix byte unique across the schema and a name unique in its namespace. It fails for a nil namespace or codec, a zero codec version, a duplicate prefix or name, SyntheticPrefix, and after Open.
func (*Table[K, V]) Delete ¶
Delete removes the row under k, its index entries and counter weights, and runs the table's cascades; it reports whether a row was there.
func (*Table[K, V]) Get ¶
Get returns the row under k; found is false for an absent row. A stored value that does not decode is ErrCorrupt.
func (*Table[K, V]) NextID ¶
NextID returns the table's next sequence number, starting at 1. It records no subject; on a non-silent table it fails the transaction inside BeforeCommit, as a write does. After Open resets the namespace it stays above every id the namespace issued before.
func (*Table[K, V]) Put ¶
Put stores v under k, updating every index and counter of the table in the same transaction. A value whose encoding equals the stored bytes writes nothing and records no subject. It fails with a *ConflictError when a unique index key belongs to another row, writing nothing; a counter leaving int64 fails it and the whole transaction.
type TableOptions ¶
type TableOptions struct {
Silent bool
}
TableOptions configures a table. A Silent table's writes reserve no revision, record no subject and never reach Since; a non-silent write inside BeforeCommit fails the transaction.
type TableStats ¶
TableStats is one table's row count and the bytes its pages use.
type Tx ¶
type Tx struct {
// contains filtered or unexported fields
}
Tx is a read-write transaction. It is valid only inside the function Update or Batch passed it to.
func (*Tx) AfterCommit ¶
func (tx *Tx) AfterCommit(fn func())
AfterCommit registers fn to run once after this transaction commits, never after a rollback or a discarded Batch run; for signals about silent writes. It runs after OnCommit and earlier AfterCommit functions, in commit order across the DB (see Options.OnCommit).
func (*Tx) Mark ¶
Mark records a mark in this transaction's change; a transaction with a mark reserves a revision even when it wrote nothing.
type Uint64Key ¶
type Uint64Key struct{}
Uint64Key encodes a uint64 big-endian, so byte order is numeric order.
type VerifyReport ¶
type VerifyReport struct {
Mismatches []Mismatch
}
VerifyReport lists every mismatch Verify found.
type WriteHealth ¶
type WriteHealth struct {
// contains filtered or unexported fields
}
WriteHealth keeps the outcome of writes per caller-named class. The zero value is ready; it is safe for concurrent use and must not be copied after first use.
func (*WriteHealth) Class ¶
func (h *WriteHealth) Class(class string) (WriteRecord, bool)
Class returns the record of class; false when Record never changed it.
func (*WriteHealth) Record ¶
func (h *WriteHealth) Record(class string, err error) WriteRecord
Record notes the result of one Update or Batch call of class and returns the class's record after it. nil records a commit, which clears a failing run of that class only; an error wrapping ErrCommit records a failure; every other error (the function's own, *ConflictError, ErrCorrupt, a context error) changes nothing.
type WriteRecord ¶
type WriteRecord struct {
// LastErr is the latest ErrCommit, kept after a recovery.
LastErr error
// FirstFailed starts the current failing run; zero when not failing.
FirstFailed time.Time
LastFailed time.Time
LastOK time.Time
// Failures counts every ErrCommit recorded and is never reset.
Failures uint64
// Failing reports that the latest commit or failure recorded failed.
Failing bool
}
WriteRecord is one class's write outcomes since its WriteHealth was made.