Documentation
¶
Overview ¶
Package db provides the embedded AptevaDB document/key-value database. Open owns one local directory exclusively. Use DurableOptions for full-sync acknowledged-write durability; Options{} selects asynchronous writes.
Collections support create-only Insert, replacement Upsert, existing-only Replace, point reads, consistent snapshot scans/queries, unique secondary indexes and stored computed fields/collections. Begin/Update provide optimistic serializable read/write transactions; NewBatch commits writes across collections. Writing transactions return ErrConflict after any concurrent committed write.
Close snapshots, transactions, cursors and Reader handles promptly. DB and Collection are concurrency-safe; transactions, batches and cursors are owned by one goroutine. Callback/cursor buffers are borrowed; copy retained bytes. Format upgrades are one-way; back up before upgrading. Only Linux and macOS are supported. See github.com/apteva/db/client for the remote Go driver.
Package engine is a from-scratch embedded key-value engine: a B+tree over fixed-size slotted pages, a write-ahead log with group commit, and copy-on-write checkpoints so the data file is never torn.
Index ¶
- Constants
- Variables
- func ComputedGroupKey(v any) ([]byte, error)
- func Decode(document []byte, out any) error
- func DecodeDocument(doc []byte) (map[string]any, error)
- func Encode(document any) ([]byte, error)
- func EncodeJSON(dst []byte, src []byte) ([]byte, error)
- func FormatVersionOf(dir string) (uint32, error)
- func Import(ctx context.Context, r io.Reader, destination string) error
- func Restore(ctx context.Context, backupDir, destination string) error
- type ArrayBuilder
- func (a *ArrayBuilder) Array(arr []byte)
- func (a *ArrayBuilder) Bool(v bool)
- func (a *ArrayBuilder) Bytes() []byte
- func (a *ArrayBuilder) Doc(sub []byte)
- func (a *ArrayBuilder) Float(v float64)
- func (a *ArrayBuilder) Int(v int64)
- func (a *ArrayBuilder) Null()
- func (a *ArrayBuilder) Reset()
- func (a *ArrayBuilder) String(v string)
- type Batch
- func (b *Batch) Commit() error
- func (b *Batch) CommitContext(ctx context.Context) error
- func (b *Batch) Delete(key []byte) error
- func (b *Batch) Insert(key, val []byte) error
- func (b *Batch) InsertJSON(key, doc []byte) error
- func (b *Batch) Len() int
- func (b *Batch) Replace(key, val []byte) error
- func (b *Batch) ReplaceJSON(key, doc []byte) error
- func (b *Batch) Upsert(key, val []byte) error
- func (b *Batch) UpsertJSON(key, doc []byte) error
- func (b *Batch) With(c *Collection) *Batch
- type Collection
- func (c *Collection) Aggregate(ctx context.Context, pipeline []byte) ([]map[string]any, error)
- func (c *Collection) AggregateParallel(ctx context.Context, pipeline []byte, shards int) ([]map[string]any, error)
- func (c *Collection) ComputedCollection() (*ComputedCollectionInfo, error)
- func (c *Collection) ComputedFields() (map[string]json.RawMessage, error)
- func (c *Collection) CreateIndex(ctx context.Context, name, field string, opts ...IndexOptions) error
- func (c *Collection) CreateUniqueIndex(ctx context.Context, name, field string) error
- func (c *Collection) DB() *DB
- func (c *Collection) DefineComputedFields(ctx context.Context, definitions []byte) error
- func (c *Collection) Delete(key []byte) error
- func (c *Collection) DropIndex(ctx context.Context, name string) error
- func (c *Collection) Find(key, dst []byte) ([]byte, bool, error)
- func (c *Collection) FindDocument(key []byte, out any) (bool, error)
- func (c *Collection) FindJSON(key []byte) ([]byte, bool, error)
- func (c *Collection) FindOne(ctx context.Context, filter []byte, out any) (bool, error)
- func (c *Collection) Indexes() map[string]string
- func (c *Collection) Insert(key, val []byte) error
- func (c *Collection) InsertDocument(key []byte, document any) error
- func (c *Collection) InsertJSON(key, doc []byte) error
- func (c *Collection) ListIndexes() []IndexInfo
- func (c *Collection) Name() string
- func (c *Collection) NewBatch() *Batch
- func (c *Collection) NewCursor() *Cursor
- func (c *Collection) NewReader() (*Reader, error)
- func (c *Collection) Query(ctx context.Context, filter []byte, opts QueryOptions, ...) error
- func (c *Collection) Replace(key, val []byte) error
- func (c *Collection) ReplaceDocument(key []byte, document any) error
- func (c *Collection) ReplaceJSON(key, doc []byte) error
- func (c *Collection) Run(ctx context.Context, p *Pipeline) ([]map[string]any, error)
- func (c *Collection) RunParallel(ctx context.Context, p *Pipeline, shards int) ([]map[string]any, error)
- func (c *Collection) Scan(start, end []byte, fn func(key, val []byte) bool) error
- func (c *Collection) ShardBounds(n int) ([][]byte, error)
- func (c *Collection) Shards(n int) ([]Source, error)
- func (c *Collection) Source(start, end []byte) Source
- func (c *Collection) String() string
- func (c *Collection) UpdateDocument(ctx context.Context, key []byte, fn func(map[string]any) error) error
- func (c *Collection) Upsert(key, val []byte) error
- func (c *Collection) UpsertDocument(key []byte, document any) error
- func (c *Collection) UpsertJSON(key, doc []byte) error
- type ComputedCollectionInfo
- type Cursor
- func (c *Cursor) Close() error
- func (c *Cursor) Err() error
- func (c *Cursor) First() bool
- func (c *Cursor) Key() []byte
- func (c *Cursor) Last() bool
- func (c *Cursor) Next() bool
- func (c *Cursor) Prev() bool
- func (c *Cursor) Seek(key []byte) bool
- func (c *Cursor) Valid() bool
- func (c *Cursor) Value() []byte
- type DB
- func (db *DB) Aggregate(ctx context.Context, pipeline []byte) ([]map[string]any, error)
- func (db *DB) AggregateParallel(ctx context.Context, pipeline []byte, shards int) ([]map[string]any, error)
- func (db *DB) Backup(ctx context.Context, dir string) error
- func (db *DB) Begin(ctx context.Context) (*Tx, error)
- func (db *DB) Checkpoint() error
- func (db *DB) Close() error
- func (db *DB) Collection(name string) (*Collection, error)
- func (db *DB) Collections() []string
- func (db *DB) Compact(ctx context.Context) error
- func (db *DB) ComputedFields() (map[string]json.RawMessage, error)
- func (db *DB) CreateComputedCollection(ctx context.Context, name, source string, pipeline []byte) (*Collection, error)
- func (db *DB) CreateIndex(ctx context.Context, name, field string, opts ...IndexOptions) error
- func (db *DB) CreateUniqueIndex(ctx context.Context, name, field string) error
- func (db *DB) DefineComputedFields(ctx context.Context, definitions []byte) error
- func (db *DB) Delete(key []byte) error
- func (db *DB) DropCollection(ctx context.Context, name string) error
- func (db *DB) DropIndex(ctx context.Context, name string) error
- func (db *DB) Export(ctx context.Context, w io.Writer) error
- func (db *DB) Find(key, dst []byte) ([]byte, bool, error)
- func (db *DB) FindJSON(key []byte) ([]byte, bool, error)
- func (db *DB) FlushLog() error
- func (db *DB) Health() error
- func (db *DB) Indexes() map[string]string
- func (db *DB) Insert(key, val []byte) error
- func (db *DB) InsertJSON(key, doc []byte) error
- func (db *DB) ListIndexes() []IndexInfo
- func (db *DB) NewBatch() *Batch
- func (db *DB) NewCursor() *Cursor
- func (db *DB) NewReader() (*Reader, error)
- func (db *DB) OpenCollection(name string) (*Collection, error)
- func (db *DB) Replace(key, val []byte) error
- func (db *DB) ReplaceJSON(key, doc []byte) error
- func (db *DB) Scan(start, end []byte, fn func(key, val []byte) bool) error
- func (db *DB) ShardBounds(n int) ([][]byte, error)
- func (db *DB) Shards(n int) ([]Source, error)
- func (db *DB) Snapshot() (*Snapshot, error)
- func (db *DB) Source(start, end []byte) Source
- func (db *DB) Stats() Stats
- func (db *DB) Update(ctx context.Context, fn func(*Tx) error) error
- func (db *DB) Upsert(key, val []byte) error
- func (db *DB) UpsertJSON(key, doc []byte) error
- func (db *DB) Verify(ctx context.Context) error
- func (db *DB) VerifyIndexes(ctx context.Context) error
- type DocBuilder
- func (b *DocBuilder) Array(name string, arr []byte)
- func (b *DocBuilder) Bool(name string, v bool)
- func (b *DocBuilder) Bytes() []byte
- func (b *DocBuilder) Doc(name string, sub []byte)
- func (b *DocBuilder) Float(name string, v float64)
- func (b *DocBuilder) Int(name string, v int64)
- func (b *DocBuilder) Null(name string)
- func (b *DocBuilder) Reset()
- func (b *DocBuilder) String(name string, v string)
- type IndexInfo
- type IndexOptions
- type Limits
- type Options
- type Pipeline
- type QueryOptions
- type Reader
- type Snapshot
- func (s *Snapshot) Aggregate(ctx context.Context, pipeline []byte) ([]map[string]any, error)
- func (s *Snapshot) AggregateParallel(ctx context.Context, pipeline []byte, shards int) ([]map[string]any, error)
- func (s *Snapshot) Close()
- func (s *Snapshot) Collection(name string) (*Collection, error)
- func (s *Snapshot) ComputedFields() (map[string]json.RawMessage, error)
- func (s *Snapshot) Find(key, dst []byte) ([]byte, bool, error)
- func (s *Snapshot) NewCursor() *Cursor
- func (s *Snapshot) NewReader() (*Reader, error)
- func (s *Snapshot) Scan(start, end []byte, fn func(key, val []byte) bool) error
- func (s *Snapshot) Source(start, end []byte) Source
- type Source
- type Stats
- type SyncMode
- type Tx
- func (tx *Tx) Collection(name string) (*TxCollection, error)
- func (tx *Tx) Commit() error
- func (tx *Tx) CommitContext(ctx context.Context) error
- func (tx *Tx) Delete(key []byte) error
- func (tx *Tx) Find(key, dst []byte) ([]byte, bool, error)
- func (tx *Tx) FindJSON(key []byte) ([]byte, bool, error)
- func (tx *Tx) Insert(key, val []byte) error
- func (tx *Tx) InsertJSON(key, val []byte) error
- func (tx *Tx) Replace(key, val []byte) error
- func (tx *Tx) ReplaceJSON(key, val []byte) error
- func (tx *Tx) Rollback()
- func (tx *Tx) Scan(start, end []byte, fn func([]byte, []byte) bool) error
- func (tx *Tx) Upsert(key, val []byte) error
- func (tx *Tx) UpsertJSON(key, val []byte) error
- type TxCollection
- func (c *TxCollection) Delete(key []byte) error
- func (c *TxCollection) Find(key, dst []byte) ([]byte, bool, error)
- func (c *TxCollection) FindDocument(key []byte, out any) (bool, error)
- func (c *TxCollection) FindJSON(key []byte) ([]byte, bool, error)
- func (c *TxCollection) Insert(key, val []byte) error
- func (c *TxCollection) InsertDocument(key []byte, document any) error
- func (c *TxCollection) InsertJSON(key, doc []byte) error
- func (c *TxCollection) Replace(key, val []byte) error
- func (c *TxCollection) ReplaceDocument(key []byte, document any) error
- func (c *TxCollection) ReplaceJSON(key, doc []byte) error
- func (c *TxCollection) Scan(start, end []byte, fn func([]byte, []byte) bool) error
- func (c *TxCollection) Upsert(key, val []byte) error
- func (c *TxCollection) UpsertDocument(key []byte, document any) error
- func (c *TxCollection) UpsertJSON(key, doc []byte) error
Constants ¶
const ( // PageSize is the fixed on-disk and in-memory page size. PageSize = 16384 // MaxCellSize bounds key+value so a page always holds at least three cells, // which the split logic relies on. MaxCellSize = PageSize / 4 // MaxKeySize bounds keys; lengths are stored as uint16. MaxKeySize = 1024 )
const FormatVersion = 6
FormatVersion is the on-disk format this build writes. Open also reads formats 3, 4 and 5 and upgrades them before returning; see FORMAT.md for the policy.
const MaxTransactionBytes = 256 << 20
MaxTransactionBytes bounds staged atomic maintenance and transaction writes.
const MaxValueSize = 1 << 30
MaxValueSize bounds a value; larger ones are refused.
const Version = "0.2.0-alpha.1"
Version is the library version.
Variables ¶
var ( ErrPipeline = errors.New("aptevadb: bad pipeline") ErrLimit = errors.New("aptevadb: aggregation exceeded its memory limit") )
var ( ErrNoSuchCollection = errors.New("aptevadb: no such collection") ErrCollectionName = errors.New("aptevadb: bad collection name") ErrTooManyCollections = errors.New("aptevadb: too many collections") ErrReadOnly = errors.New("aptevadb: a snapshot is read-only") )
var ( ErrComputedCollection = errors.New("aptevadb: invalid computed collection definition or value") ErrComputedCollectionReadOnly = errors.New("aptevadb: computed collection is maintained by its source") ErrComputedCollectionExists = errors.New("aptevadb: computed collection destination already exists") ErrComputedCollectionDependency = errors.New("aptevadb: collection has computed dependents") ErrComputedCollectionLimit = errors.New("aptevadb: computed collection staging exceeds 256 MiB") )
var ( ErrComputedField = errors.New("aptevadb: invalid computed field definition or value") ErrComputedNonEmpty = errors.New("aptevadb: computed definitions require an empty collection") )
var ( ErrKeyExists = errors.New("aptevadb: key already exists") ErrNotFound = errors.New("aptevadb: key not found") ErrTransactionTooLarge = errors.New("aptevadb: transaction exceeds 256 MiB staging limit") )
var ( ErrKeySize = errors.New("aptevadb: key must be 1..1024 bytes") ErrCellSize = errors.New("aptevadb: key+value too large") ErrClosed = errors.New("aptevadb: closed") ErrIndexBuilding = errors.New("aptevadb: an index is being built") ErrOptions = errors.New("aptevadb: invalid options") ErrFormat = errors.New("aptevadb: unsupported file format version") )
var ( ErrIndexExists = errors.New("aptevadb: index already exists") ErrNoSuchIndex = errors.New("aptevadb: no such index") )
var DefaultLimits = Limits{MaxGroups: 1 << 20, MaxRows: 1 << 20}
DefaultLimits apply to every parsed pipeline until SetLimits is called.
var ErrConflict = errors.New("aptevadb: transaction conflicted with a concurrent write")
var ErrCorrupt = errors.New("aptevadb: corrupt page")
ErrCorrupt reports a page whose checksum does not match its contents.
var ErrDestinationExists = errors.New("aptevadb: restore destination already exists")
var ErrDocument = errors.New("aptevadb: malformed document")
var ErrDuplicateKey = errors.New("aptevadb: duplicate unique index value")
var ErrLocked = errors.New("aptevadb: database is locked by another process")
ErrLocked reports that another process holds the database.
var ErrRestoreIncomplete = errors.New("aptevadb: incomplete restore; remove the incomplete destination and restore again")
var ErrSnapshotsOpen = errors.New("aptevadb: operation not allowed while snapshots are open")
var ErrUniqueValue = errors.New("aptevadb: unique indexes require finite scalar numbers")
var ErrValueSize = errors.New("aptevadb: value too large")
Functions ¶
func ComputedGroupKey ¶
ComputedGroupKey returns the primary key used by a grouped computed collection. Keys encode scalar types exactly (unlike index float keys). Missing and null share a key; integral float keys normalize to int64.
func DecodeDocument ¶
DecodeDocument converts a binary document into a map.
func EncodeJSON ¶
EncodeJSON converts a JSON object (nested objects and arrays allowed, up to 16 levels) into the binary document format.
func FormatVersionOf ¶
FormatVersionOf reports the on-disk format version of the database in dir, read from its meta pages without opening it, so a file this build refuses can still be identified. It does not take the database lock.
Types ¶
type ArrayBuilder ¶
type ArrayBuilder struct {
// contains filtered or unexported fields
}
ArrayBuilder encodes array elements: [count u16] then type+payload each.
func (*ArrayBuilder) Array ¶
func (a *ArrayBuilder) Array(arr []byte)
func (*ArrayBuilder) Bool ¶
func (a *ArrayBuilder) Bool(v bool)
func (*ArrayBuilder) Bytes ¶
func (a *ArrayBuilder) Bytes() []byte
func (*ArrayBuilder) Doc ¶
func (a *ArrayBuilder) Doc(sub []byte)
func (*ArrayBuilder) Float ¶
func (a *ArrayBuilder) Float(v float64)
func (*ArrayBuilder) Int ¶
func (a *ArrayBuilder) Int(v int64)
func (*ArrayBuilder) Null ¶
func (a *ArrayBuilder) Null()
func (*ArrayBuilder) Reset ¶
func (a *ArrayBuilder) Reset()
func (*ArrayBuilder) String ¶
func (a *ArrayBuilder) String(v string)
type Batch ¶
type Batch struct {
// contains filtered or unexported fields
}
Batch aggregates writes into one log write and one flush, applied atomically: readers see nothing until Commit returns, and a crash replays all of it or none. It is not safe for concurrent use. Writes go to the batch's collection; With returns a view of the same batch bound to another collection, so one batch can span collections.
func (*Batch) CommitContext ¶
CommitContext checks cancellation before logging; once logging starts the atomic write and required flush are completed.
func (*Batch) InsertJSON ¶
InsertJSON queues a new JSON document.
func (*Batch) ReplaceJSON ¶
ReplaceJSON queues a replacement JSON document.
func (*Batch) UpsertJSON ¶
UpsertJSON queues a create or replacement from JSON.
func (*Batch) With ¶
func (b *Batch) With(c *Collection) *Batch
With returns the same batch bound to collection c: writes queued through either handle commit together.
type Collection ¶
type Collection struct {
// contains filtered or unexported fields
}
Collection is a named key space of a DB. The zero-cost default collection is what the DB's own Insert/Find/Scan/Aggregate methods use. A Collection obtained from a Snapshot reads through that snapshot.
func (*Collection) Aggregate ¶
Aggregate runs a JSON pipeline over the collection, through a secondary index when the leading $match allows it, and on every core when the pipeline's streaming part is a $match/$group (or $count) without a window: AggregateParallel with GOMAXPROCS shards.
func (*Collection) AggregateParallel ¶
func (c *Collection) AggregateParallel(ctx context.Context, pipeline []byte, shards int) ([]map[string]any, error)
AggregateParallel runs a JSON pipeline over up to shards key ranges (or shards of an index's primary keys) at once; 1 runs it on the calling goroutine.
func (*Collection) ComputedCollection ¶
func (c *Collection) ComputedCollection() (*ComputedCollectionInfo, error)
ComputedCollection returns a detached definition, or nil for an ordinary collection. Snapshot handles read the catalog as it stood at that snapshot.
func (*Collection) ComputedFields ¶
func (c *Collection) ComputedFields() (map[string]json.RawMessage, error)
ComputedFields reads definitions through this collection's live/snapshot view. Changing the returned map or its bytes cannot change stored rules.
func (*Collection) CreateIndex ¶
func (c *Collection) CreateIndex(ctx context.Context, name, field string, opts ...IndexOptions) error
CreateIndex builds an index on a document field (a dotted path is allowed). The definition is registered first, so writes made during the build maintain it and their keys are left to that maintenance; the existing documents are read from a snapshot, their entries sorted and inserted in order (leaves fill completely and each costs one descent), without log records: a checkpoint makes them durable before the catalog entry is logged. A crash before that leaves entries with no catalog entry, which the next open removes. Compaction waits for the build.
ctx cancels the build between its steps; a cancelled build leaves no trace but entries the next open sweeps.
func (*Collection) CreateUniqueIndex ¶
func (c *Collection) CreateUniqueIndex(ctx context.Context, name, field string) error
func (*Collection) DB ¶
func (c *Collection) DB() *DB
DB returns the database the collection belongs to.
func (*Collection) DefineComputedFields ¶
func (c *Collection) DefineComputedFields(ctx context.Context, definitions []byte) error
DefineComputedFields installs a JSON object mapping output names to deterministic expressions, for example:
{"total":{"$multiply":["$qty","$price"]},"email_key":{"$lower":"$email"}}
The collection must be empty. Pass {} to remove its definitions. Outputs are top-level scalars, may depend on other computed fields, and overwrite any supplied values. Missing/null inputs propagate null (use $ifNull for defaults). Integer arithmetic checks overflow; $divide produces a float. $lower/$upper use ASCII casing. Definitions are versioned and persisted. All upserts, including binary Insert and cross-collection batches, compute their outputs before logging; reads do no additional work.
func (*Collection) Delete ¶
func (c *Collection) Delete(key []byte) error
Delete removes key. Deleting an absent key is not an error.
func (*Collection) DropIndex ¶
func (c *Collection) DropIndex(ctx context.Context, name string) error
DropIndex removes an index and all its entries.
func (*Collection) Find ¶
func (c *Collection) Find(key, dst []byte) ([]byte, bool, error)
Find appends the value for key to dst and reports whether it exists.
func (*Collection) FindDocument ¶
func (c *Collection) FindDocument(key []byte, out any) (bool, error)
func (*Collection) FindJSON ¶
func (c *Collection) FindJSON(key []byte) ([]byte, bool, error)
FindJSON returns the document under key rendered as JSON.
func (*Collection) FindOne ¶
FindOne decodes the first matching document into out; absence is (false,nil).
func (*Collection) Indexes ¶
func (c *Collection) Indexes() map[string]string
Indexes lists the collection's index names and the fields they cover.
func (*Collection) Insert ¶
func (c *Collection) Insert(key, val []byte) error
Insert creates key. An existing key returns ErrKeyExists without changing it.
func (*Collection) InsertDocument ¶
func (c *Collection) InsertDocument(key []byte, document any) error
func (*Collection) InsertJSON ¶
func (c *Collection) InsertJSON(key, doc []byte) error
InsertJSON creates a document from a JSON object; duplicates fail.
func (*Collection) ListIndexes ¶
func (c *Collection) ListIndexes() []IndexInfo
func (*Collection) Name ¶
func (c *Collection) Name() string
Name returns the collection's name; the default collection is "".
func (*Collection) NewBatch ¶
func (c *Collection) NewBatch() *Batch
NewBatch returns an empty batch whose writes go to this collection; see Batch.With for writing several collections atomically.
func (*Collection) NewCursor ¶
func (c *Collection) NewCursor() *Cursor
NewCursor returns a cursor over the collection positioned nowhere.
func (*Collection) NewReader ¶
func (c *Collection) NewReader() (*Reader, error)
NewReader returns a reusable point-read handle for this collection's view.
func (*Collection) Query ¶
func (c *Collection) Query(ctx context.Context, filter []byte, opts QueryOptions, yield func(key, document []byte) bool) error
Query streams documents matching a JSON filter (the $match syntax) in key order. It uses an applicable index and one snapshot for the whole operation. No result array is retained; yield returns false to stop. Callback bytes are valid only during the callback. Aggregation still materializes its results.
func (*Collection) Replace ¶
func (c *Collection) Replace(key, val []byte) error
Replace replaces an existing key; an absent key returns ErrNotFound.
func (*Collection) ReplaceDocument ¶
func (c *Collection) ReplaceDocument(key []byte, document any) error
func (*Collection) ReplaceJSON ¶
func (c *Collection) ReplaceJSON(key, doc []byte) error
ReplaceJSON replaces an existing document from a JSON object.
func (*Collection) Run ¶
Run executes a compiled pipeline over the collection on the calling goroutine.
func (*Collection) RunParallel ¶
func (c *Collection) RunParallel(ctx context.Context, p *Pipeline, shards int) ([]map[string]any, error)
RunParallel executes a compiled pipeline over the collection in shards.
func (*Collection) Scan ¶
func (c *Collection) Scan(start, end []byte, fn func(key, val []byte) bool) error
Scan calls fn for every key in [start, end) of the collection in key order; nil bounds are open. fn returns false to stop.
func (*Collection) ShardBounds ¶
func (c *Collection) ShardBounds(n int) ([][]byte, error)
ShardBounds returns up to n-1 keys splitting the collection into ranges of roughly equal page count.
func (*Collection) Shards ¶
func (c *Collection) Shards(n int) ([]Source, error)
Shards returns key-ordered sources covering the collection.
func (*Collection) Source ¶
func (c *Collection) Source(start, end []byte) Source
Source adapts a key range of the collection to the aggregation executor.
func (*Collection) String ¶
func (c *Collection) String() string
func (*Collection) UpdateDocument ¶
func (c *Collection) UpdateDocument(ctx context.Context, key []byte, fn func(map[string]any) error) error
UpdateDocument runs a safe read/modify/replace transaction once. ErrConflict means the caller should retry; fn must not retain or mutate database handles.
func (*Collection) Upsert ¶
func (c *Collection) Upsert(key, val []byte) error
Upsert creates or replaces key. It retains the pre-alpha Insert behavior.
func (*Collection) UpsertDocument ¶
func (c *Collection) UpsertDocument(key []byte, document any) error
func (*Collection) UpsertJSON ¶
func (c *Collection) UpsertJSON(key, doc []byte) error
UpsertJSON creates or replaces a document from a JSON object.
type ComputedCollectionInfo ¶
type ComputedCollectionInfo struct {
Source string `json:"source"`
Pipeline json.RawMessage `json:"pipeline"`
}
ComputedCollectionInfo describes an immutable, stored collection definition.
type Cursor ¶
type Cursor struct {
// contains filtered or unexported fields
}
Cursor iterates keys in order, forwards or backwards, merging the tree with the memtable at one snapshot taken when the cursor was created. Close the cursor to release its view. Each step re-descends the tree, so it costs a lookup rather than a pointer chase; no lock is held between calls.
func (*Cursor) Close ¶
Close releases the cursor's read view. Close is idempotent. A cursor is owned by one goroutine; Key and Value are valid until its next operation.
type DB ¶
type DB struct {
// contains filtered or unexported fields
}
DB is a single-writer, multi-reader key-value store.
func (*DB) Aggregate ¶
Aggregate runs a JSON pipeline over the default collection on one goroutine, through a secondary index when the leading $match allows it.
func (*DB) AggregateParallel ¶
func (db *DB) AggregateParallel(ctx context.Context, pipeline []byte, shards int) ([]map[string]any, error)
AggregateParallel runs a JSON pipeline over the default collection in up to shards key ranges at once.
func (*DB) Backup ¶
Backup writes a compact copy of the database into dir, which must not exist or must be empty. It works from a snapshot, so writers continue.
ctx cancels the copy, which is then removed.
func (*DB) Checkpoint ¶
Checkpoint runs a full checkpoint and waits for it.
func (*DB) Collection ¶
func (db *DB) Collection(name string) (*Collection, error)
Collection returns the named collection, creating it when absent. The empty name is the default collection.
func (*DB) Collections ¶
Collections lists the named collections, sorted.
func (*DB) Compact ¶
Compact rewrites the database into a fresh, densely packed file and swaps it in. The copy is made from a snapshot while writers continue. Writes made during the copy are replayed from the log into the new file in rounds without the lock; the lock is held only to apply the last few records in memory and swap the files. The new file's meta points back into the existing log, so no flush happens under the lock.
ctx cancels it between its rounds; the copy is discarded and the database untouched.
func (*DB) ComputedFields ¶
func (db *DB) ComputedFields() (map[string]json.RawMessage, error)
ComputedFields returns a detached copy of the default collection's expression definitions.
func (*DB) CreateComputedCollection ¶
func (db *DB) CreateComputedCollection(ctx context.Context, name, source string, pipeline []byte) (*Collection, error)
CreateComputedCollection creates and atomically backfills a read-only collection. The source must exist and cannot itself be computed. A pipeline may have leading $match stages and one final $project or $group. Groups allow a scalar/null _id and integer $sum / $count; sums reject overflow and floats. Inserts, overwrites, deletes and batches maintain stored results and indexes in the same WAL transaction. Creation/drop pause writers while staging at most 256 MiB. On failure before logging, neither catalog nor rows are added.
func (*DB) CreateIndex ¶
CreateIndex builds an index on a document field of the default collection.
func (*DB) CreateUniqueIndex ¶
func (*DB) DefineComputedFields ¶
DefineComputedFields installs or replaces the default collection's stored generated fields. See Collection.DefineComputedFields.
func (*DB) Delete ¶
Delete removes key from the default collection. Deleting an absent key is not an error.
func (*DB) DropCollection ¶
DropCollection atomically removes a named collection, its indexes and catalog. Cancellation and staging-limit errors leave it intact. Existing snapshots continue to see their original collection. The default collection cannot drop.
func (*DB) Export ¶
Export writes a versioned, lossless JSON-lines logical backup. Binary keys and values are base64; computed outputs are rebuilt from source rows on import. Schemas, stored-field rules, computed collections and unique indexes are kept.
func (*DB) Find ¶
Find appends the value for key in the default collection to dst and reports whether it exists.
func (*DB) FlushLog ¶
FlushLog hands buffered log records to the OS without waiting for an fsync; see DURABILITY.md.
func (*DB) Insert ¶
Insert creates a key in the default collection; duplicates return ErrKeyExists. Values that do not fit a cell are stored in overflow pages, up to MaxValueSize.
func (*DB) InsertJSON ¶
InsertJSON encodes a flat JSON object and stores it under key.
func (*DB) ListIndexes ¶
func (*DB) NewCursor ¶
NewCursor returns a cursor over the default collection positioned nowhere; call Seek, First or Last.
func (*DB) OpenCollection ¶
func (db *DB) OpenCollection(name string) (*Collection, error)
OpenCollection returns an existing collection without creating one.
func (*DB) ReplaceJSON ¶
ReplaceJSON replaces an existing JSON document in the default collection.
func (*DB) Scan ¶
Scan calls fn for every key in [start, end) of the default collection in key order at one snapshot; nil bounds are open. fn returns false to stop. The snapshot is released before returning. Writers may run between leaves and callbacks without changing the scan's view.
func (*DB) ShardBounds ¶
ShardBounds returns up to n-1 keys that split the default collection into ranges of roughly equal page count.
func (*DB) Source ¶
Source adapts a key range of the default collection to the aggregation executor.
func (*DB) UpsertJSON ¶
UpsertJSON creates or replaces a JSON document in the default collection.
type DocBuilder ¶
type DocBuilder struct {
// contains filtered or unexported fields
}
DocBuilder encodes flat documents with no per-field allocation.
func (*DocBuilder) Array ¶
func (b *DocBuilder) Array(name string, arr []byte)
Array adds an array (bytes from an ArrayBuilder).
func (*DocBuilder) Bool ¶
func (b *DocBuilder) Bool(name string, v bool)
func (*DocBuilder) Bytes ¶
func (b *DocBuilder) Bytes() []byte
Bytes seals and returns the encoded document; valid until the next Reset.
func (*DocBuilder) Doc ¶
func (b *DocBuilder) Doc(name string, sub []byte)
Doc adds a nested document (bytes from another DocBuilder).
func (*DocBuilder) Float ¶
func (b *DocBuilder) Float(name string, v float64)
func (*DocBuilder) Int ¶
func (b *DocBuilder) Int(name string, v int64)
func (*DocBuilder) Null ¶
func (b *DocBuilder) Null(name string)
func (*DocBuilder) Reset ¶
func (b *DocBuilder) Reset()
Reset starts a new document, reusing the buffer.
func (*DocBuilder) String ¶
func (b *DocBuilder) String(name string, v string)
type IndexOptions ¶
type IndexOptions struct{ Unique bool }
IndexOptions controls secondary-index constraints. Missing fields are not indexed; null is a value. Multikey uniqueness is across documents, not within one array. Integers compare exactly; mixed int/float comparisons use the engine's numeric semantics. Non-finite floating-point values are refused.
type Limits ¶
type Limits struct {
MaxGroups int // distinct $group keys
MaxRows int // materialised rows at any stage
}
Limits bound the memory an aggregation may use.
type Options ¶
type Options struct {
// Sync flushes the log before a write returns. Default false (async).
// Use DurableOptions for power-loss-safe writes. Concurrent writes share flushes.
Sync bool
// SyncMode picks the flush primitive; default SyncFull.
SyncMode SyncMode
// CheckpointLogBytes is the log size that triggers a checkpoint. Default 256MB.
CheckpointLogBytes uint64
// LogFlushInterval is how often buffered log records are handed to the OS
// when Sync is off. Default 10ms.
LogFlushInterval time.Duration
// CacheBytes targets the logical page cache, not total process memory; clean pages are evicted past it and a
// checkpoint runs when dirty pages reach three quarters of it. 0 keeps
// everything resident, which is fastest when the data fits in RAM.
CacheBytes int64
// VerifyChecksums checks every page checksum when a page is first read
// from the file. Default true; set NoVerifyChecksums to turn it off.
NoVerifyChecksums bool
// Parallelism is how many goroutines Aggregate uses for a pipeline that
// can run in shards. 0 means runtime.GOMAXPROCS(0) at Open; 1 runs on
// the calling goroutine. AggregateParallel overrides it per call.
Parallelism int
// MemtableBytes buffers inserts in memory and applies them to the tree
// in key order once the budget is reached, cutting write amplification
// when the file is larger than the cache. Default: CacheBytes/2 with a
// cache limit; 0 (inserts go straight to the tree) without one. Set to
// -1 to disable with a cache limit.
MemtableBytes int64
}
Options tunes durability and checkpointing.
func DurableOptions ¶
func DurableOptions() Options
DurableOptions selects acknowledged writes that survive power loss on supported local filesystems and drives honoring flushes. Options{} is async.
type Pipeline ¶
type Pipeline struct {
// contains filtered or unexported fields
}
Pipeline is a compiled MongoDB-style aggregation pipeline.
Stages: $match (equality, $eq $ne $gt $gte $lt $lte $in; an array field matches when any element does), $group (_id as null, "$field" or an object of "$field" refs; $sum $avg $min $max $count $first $last), $sort (one or more keys, in order), $skip, $limit, $project (inclusion or exclusion), $count, $unwind, $lookup (from/localField/foreignField/as). Field references may be dotted paths into nested documents.
Leading $match/$skip/$limit stages, a $lookup immediately unwound on its own field, further $match stages and a following $group run as one streaming pass over the source without decoding documents into maps; the join is a hash join over the foreign collection, or index probes when the pipeline is selective and the foreign field is indexed.
func ParsePipeline ¶
ParsePipeline compiles a JSON array of stages.
func (*Pipeline) Run ¶
Run executes the pipeline over src on the calling goroutine. A $lookup stage needs a collection to resolve "from" against: use Collection.Run.
ctx cancels a long run: the pass checks it every few thousand records and returns ctx.Err().
func (*Pipeline) RunSharded ¶
RunSharded executes the pipeline over key-ordered shards concurrently when the streaming prefix is a $match/$group (no $skip/$limit), merging the per-shard groups. Other pipelines run serially over the shards in order.
type QueryOptions ¶
type QueryOptions struct{ Skip, Limit int }
QueryOptions controls a key-ordered streaming query. Zero Limit is unlimited.
type Reader ¶
type Reader struct {
// contains filtered or unexported fields
}
Reader is a reusable live or snapshot point-read handle. Give each worker its own Reader to avoid modifying a shared per-read counter. A Reader is safe for concurrent use, including Close, but separate worker handles provide better scaling. Close it when finished to restore the fast writer path when no handles remain. No lock is held between calls.
type Snapshot ¶
type Snapshot struct {
// contains filtered or unexported fields
}
Snapshot is a consistent read view: the tree and memtable as they were when it was taken. Pages modified afterwards are copied first and their old version kept in the snapshot's overlay, so readers never see a later write. While a snapshot is open, page ids it may reference are quarantined instead of reused.
func (*Snapshot) Aggregate ¶
Aggregate runs a pipeline over the snapshot's default collection, through an index when the leading $match allows it.
func (*Snapshot) AggregateParallel ¶
func (s *Snapshot) AggregateParallel(ctx context.Context, pipeline []byte, shards int) ([]map[string]any, error)
AggregateParallel runs a pipeline over the snapshot's default collection in key-range shards.
func (*Snapshot) Close ¶
func (s *Snapshot) Close()
Close releases the snapshot and any page ids it kept from reuse.
func (*Snapshot) Collection ¶
func (s *Snapshot) Collection(name string) (*Collection, error)
Collection returns the named collection as it stands in the snapshot; "" is the default collection. Later catalog changes are invisible.
func (*Snapshot) ComputedFields ¶
func (s *Snapshot) ComputedFields() (map[string]json.RawMessage, error)
ComputedFields returns the default collection's definitions at the snapshot.
type Stats ¶
type Stats struct {
ResidentPages, HighWaterPages, FreePages, DirtyPages int
Loads, Writes, Evictions, Balances, Merges, Relocations uint64
Height int
MemtableEntries, MemtableBytes int
Snapshots, QuarantinedPages int
Collections, Indexes int
LockHolds map[string]time.Duration
WriteStalls, IndexScans uint64
}
Stats reports resident and file-level counters.
type SyncMode ¶
type SyncMode uint8
SyncMode selects the flush primitive used when Options.Sync is on.
const ( // SyncFull survives power loss: F_FULLFSYNC on macOS, fsync elsewhere. SyncFull SyncMode = iota // SyncBarrier is F_BARRIERFSYNC on macOS: ordered and handed to the drive, // but the drive cache is not forced to stable media. fsync elsewhere. SyncBarrier // SyncOS is plain fsync(2). On macOS this survives an OS crash, not a // power loss; it is SQLite's default behaviour there. SyncOS )
type Tx ¶
type Tx struct {
// contains filtered or unexported fields
}
Tx is an optimistic serializable read/write transaction. Reads use one snapshot plus its staged writes (including computed outputs). A writing transaction fails with ErrConflict if any database write committed since Begin. The caller may retry the whole transaction. Tx is not goroutine-safe. Collections must be created before Begin; DDL is outside transactions.
func (*Tx) Collection ¶
func (tx *Tx) Collection(name string) (*TxCollection, error)
func (*Tx) CommitContext ¶
Commit closes the transaction whether it succeeds or fails. Validation, constraints, computed outputs and all writes share one writer lock/WAL group. CommitContext also observes cancellation of the original Begin context.
func (*Tx) InsertJSON ¶
func (*Tx) ReplaceJSON ¶
func (*Tx) Rollback ¶
func (tx *Tx) Rollback()
Rollback discards writes and releases the read snapshot; repeated calls are safe.
func (*Tx) UpsertJSON ¶
type TxCollection ¶
type TxCollection struct {
// contains filtered or unexported fields
}
func (*TxCollection) Delete ¶
func (c *TxCollection) Delete(key []byte) error
func (*TxCollection) FindDocument ¶
func (c *TxCollection) FindDocument(key []byte, out any) (bool, error)
func (*TxCollection) Insert ¶
func (c *TxCollection) Insert(key, val []byte) error
func (*TxCollection) InsertDocument ¶
func (c *TxCollection) InsertDocument(key []byte, document any) error
func (*TxCollection) InsertJSON ¶
func (c *TxCollection) InsertJSON(key, doc []byte) error
func (*TxCollection) Replace ¶
func (c *TxCollection) Replace(key, val []byte) error
func (*TxCollection) ReplaceDocument ¶
func (c *TxCollection) ReplaceDocument(key []byte, document any) error
func (*TxCollection) ReplaceJSON ¶
func (c *TxCollection) ReplaceJSON(key, doc []byte) error
func (*TxCollection) Upsert ¶
func (c *TxCollection) Upsert(key, val []byte) error
func (*TxCollection) UpsertDocument ¶
func (c *TxCollection) UpsertDocument(key []byte, document any) error
func (*TxCollection) UpsertJSON ¶
func (c *TxCollection) UpsertJSON(key, doc []byte) error
Source Files
¶
- aggregate.go
- aggregate_sort.go
- checkpoint.go
- collection.go
- computed.go
- computed_collection.go
- computed_collection_delta.go
- computed_collection_plan.go
- computed_doc.go
- computed_expr.go
- contracts.go
- copy_builder.go
- cursor.go
- db.go
- directory_lock.go
- doc.go
- documents.go
- export.go
- file.go
- index.go
- lookup.go
- memtable.go
- overflow.go
- package_doc.go
- page.go
- page_buffers.go
- pager.go
- reader.go
- restore.go
- scan.go
- snapshot.go
- sync_other.go
- transaction.go
- tree.go
- tree_mutex.go
- unique.go
- wal.go
- wal_buffer.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package client is the Go driver for an AptevaDB HTTP v1 server.
|
Package client is the Go driver for an AptevaDB HTTP v1 server. |
|
cmd
|
|
|
aptevadb-server
command
|
|
|
aptevadbctl
command
Command aptevadbctl inspects and maintains a database directory.
|
Command aptevadbctl inspects and maintains a database directory. |
|
demo
command
|
|
|
examples
|
|
|
embedded
command
|
|
|
internal
|
|
|
protocol
Package protocol defines the version-one AptevaDB HTTP envelopes.
|
Package protocol defines the version-one AptevaDB HTTP envelopes. |
|
Package server exposes an embedded AptevaDB through the version-one HTTP API.
|
Package server exposes an embedded AptevaDB through the version-one HTTP API. |