db

package module
v0.2.0-alpha.11 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 2, 2026 License: MIT Imports: 32 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

AptevaDB

A Go document and key-value database with named collections, atomic transactions, scalar and compound indexes with mixed directions, snapshots, aggregation, stored computed fields and computed collections. Use it embedded, or run the HTTP server and connect with the Go driver.

Public alpha: v0.2.0-alpha.11. Go 1.25+, Linux and macOS, amd64 and arm64. Windows, replication and SQL are not supported. The module has no external runtime dependencies. The file format is 10; opening formats 3–9 upgrades them permanently, so keep a backup before upgrading.

go get github.com/apteva/db@v0.2.0-alpha.11
go install github.com/apteva/db/cmd/aptevadbctl@v0.2.0-alpha.11
go install github.com/apteva/db/cmd/aptevadb-server@v0.2.0-alpha.11
import (
    "context"
    db "github.com/apteva/db"
)

database, err := db.Open("./data", db.DurableOptions())
if err != nil { return err }
defer database.Close()
users, err := database.Collection("users")
if err != nil { return err }
err = users.InsertJSON([]byte("u1"), []byte(`{"name":"Ada","age":30}`))
if err != nil { return err }
err = users.CreateUniqueIndex(context.Background(), "name", "name")
if err != nil { return err }
var user struct { Name string; Age int }
found, err := users.FindOne(context.Background(), []byte(`{"age":{"$gte":18}}`), &user)

Run go run ./examples/embedded for a complete example with error handling. The root package is the embedded Go API; client is the remote Go driver. See USAGE.md for transactions, streaming queries and operation contracts, OPERATIONS.md for backup/import/recovery and limits, SERVER.md for the server/driver and HTTP protocol, DURABILITY.md, FORMAT.md, and CHANGELOG.md.

Durability: DurableOptions() enables full synchronous flushing. Options{} deliberately uses asynchronous writes for compatibility and benchmark comparisons; recent acknowledged writes can be lost after a crash. The server and maintenance CLI use the durable profile.

One process owns a database directory. Within it, DB and collection handles support concurrent use; writes serialize. Transactions, batches and cursors belong to one goroutine. Close snapshots/cursors/transactions promptly: they retain older pages and prevent compaction while held.

Alpha.5 adds native change feeds: opt-in capture, filtered/projected subscriptions, replay and snapshot handoff for embedded apps and the HTTP Go client. Opening older databases performs a one-way format-10 migration; back up with the original binary first. The change-feed validation report includes all trials, CPU/RSS results and measured capture/fan-out costs.

The alpha.4 aggregation and release report records exact integer accumulation/parallel merges, non-null field counting, format-8 migration, public Go/client/CLI checks and all 24 benchmark processes. Serial integer SUM/AVG remained essentially flat; background activity affected parallel timings. All archive hashes and the downloaded daemon were verified.

The scan optimization report records roughly 22% lower cursor-scan time on main, 128 retained benchmark processes and Linux/macOS validation. Some other medians were slower on the busy workstation; the report includes all samples and does not claim universal improvement.

The alpha.3 cursor and index validation report includes the two reported regressions, 8,160-byte encoded entries, matched-harness alpha.2 comparisons and large-entry results against Pebble and both SQLite bindings. Raw scans and some short write samples were slower; all measurements are retained.

The alpha.2 compatibility/speed report includes three repeats against Pebble/SQLite and paired alpha.1 comparisons. The alpha.1 validation report retains 30 resource and 24 feature trials against Pebble and both SQLite bindings. Other historical results under bench/results/ describe their original builds. The separate bench module compares SQLite and Pebble without adding engine dependencies. KV comparisons use Upsert (matching the other engines' replacement behavior); Insert now performs a duplicate-key check. See BENCHMARKS.md.

Alpha.10 returns aggregation errors unchanged; its publication verification records Linux/macOS CI and soak, public Go installation and all four archive checksums.

Alpha.9 adds the typed group visitor and faster in-memory and spill aggregation; the comparison with alpha.8 retains 48 interleaved trials and the remaining tradeoffs. The publication verification confirms Linux/macOS CI and soak, public Go installation, all four archive checksums, the downloaded server/driver and alpha.8 directory compatibility.

Alpha.8 adds bounded native aggregation and resident-memory controls. The comparison with alpha.7 records 110 final trials, correctness checks and remaining performance tradeoffs. The publication verification confirms Linux/macOS CI, public Go installation, all four archive checksums, the downloaded server/driver and alpha.7 directory compatibility.

Stored computed fields

Define deterministic scalar fields on an empty collection, then write source fields normally. The database stores the derived values with each document:

err := orders.DefineComputedFields(ctx, []byte(`{
  "total": {"$multiply": ["$qty", "$price"]},
  "email_key": {"$lower": "$email"},
  "net": {"$subtract": ["$total", {"$ifNull": ["$discount", 0]}]}
}`))
if err != nil { return err }
err = orders.InsertJSON([]byte("o1"), []byte(`{
  "qty": 3, "price": 700, "discount": 100, "email": "A@EXAMPLE.COM"
}`)) // stores total=2100, net=2000, email_key="a@example.com"
if err != nil { return err }
err = orders.CreateIndex(ctx, "by_email_key", "email_key")

DB.DefineComputedFields addresses the default collection. Collection.ComputedFields, DB.ComputedFields and Snapshot.ComputedFields return detached definition maps; snapshot collection handles return the rules at that snapshot. Reads, cursors, aggregation and persistent readers use the stored values. Supplied values for computed output names are overwritten. Binary Insert, JSON writes and batches across collections all enforce the same rules. An evaluation error aborts the entire batch before any log records or index entries are written. Recovery replays stored bytes without evaluating expressions again. Ordinary indexes work on computed outputs.

Definitions map top-level output names to expressions. A string "$a.b" reads a source path; an exact computed output name may reference another definition. Dependencies are sorted automatically and cycles are rejected. Use $literal to store a string beginning with $. Supported version-one operators:

Operator Arguments / result
$add, $multiply 2–16 numeric expressions
$subtract Two numeric expressions
$divide Two numeric expressions; floating result, zero divisor rejected
$lower, $upper One string expression; ASCII casing, other bytes preserved
$concat 1–16 string expressions
$ifNull [input, fallback]; evaluates fallback only for missing/null input
$literal A null, boolean, string or finite numeric scalar

Missing and null inputs propagate null. Other type mismatches fail with ErrComputedField; integer-only arithmetic preserves int64 precision and rejects overflow, and floating arithmetic rejects non-finite results. Integer literals outside int64 are rejected. Explicit floating literals use float64. Configured collections accept validated binary documents up to 16 MiB, with unique field names, at most 4,096 total fields and nesting up to 16 levels. Definitions allow at most 64 outputs, 64 KiB of input/canonical JSON, 1,024 expression nodes and expression depth 32. Outputs are scalars, not nested document/array fields.

Installing, replacing or removing definitions requires an empty collection (ErrComputedNonEmpty otherwise); {} removes them. There is no automatic backfill yet. Deleted documents do not prevent a schema change, even before a checkpoint. Dropping a collection drops its rules too.

Format migration: opening a format-3 through format-9 database upgrades both metadata slots durably to format 10 before returning. Older binaries then refuse to open it; keep a backup if you need to use one. Format 10 adds optional WAL commit markers for change capture; page/document layouts and logical export version 2 remain unchanged. Other format versions are refused.

Benchmark the feature with cd bench and GOTOOLCHAIN=local GOWORK=off go run . -computed -n 100000 -reps 3. The harness retains every trial and checks every derived result. It compares native fields, application materialization and read-time computation with Pebble and SQLite stored generated columns, using non-durable 1,000-row batches/transactions. SQL uses typed columns; the other stores use binary documents. Index build and query phases are reported separately. This workload measures feature costs and query benefits, not a universal database ranking.

Stored computed collections

Create a collection derived from an existing source. Creation atomically backfills current documents; future source upserts, deletes and cross-collection batches maintain the stored results and their indexes in the same transaction. Computed fields on the source are evaluated first.

totals, err := database.CreateComputedCollection(ctx, "paid_totals", "orders", []byte(`[
  {"$match": {"paid": true}},
  {"$group": {"_id": "$customer", "total": {"$sum": "$amount"}, "n": {"$count": {}}}}
]`))
if err != nil { return err }
key, err := db.ComputedGroupKey(int64(42))
if err != nil { return err }
doc, found, err := totals.Find(key, nil) // current total for customer 42

The first version supports up to 16 stages: leading $match stages followed by an optional final $project or $group. An empty pipeline copies the source. Filtered/projected collections retain the source primary keys. Projection uses top-level 0/1 or boolean flags with the same semantics as ordinary aggregation. Filters support scalar comparisons and $in, including nested source paths.

Groups use _id: null or one "$field.path" reference to a scalar. Outputs support exact int64 $sum (a field or integer constant), $count: {}, and $countNonNull: "$field.path"; $sum: 1 also counts rows. Missing/null sum inputs contribute zero; other non-integer inputs fail. Checked 128-bit intermediate arithmetic permits a batch to exceed int64 temporarily if its final totals fit. Zero-sum groups remain present until their last matching member is deleted. Missing and null IDs share a key; integral floats normalize to int64. ComputedGroupKey accepts nil, bool, int, int64, finite float64, string and valid scalar json.Number. Integer IDs remain distinct above 2^53. Encoded IDs are limited to 4,026 bytes.

Computed collections are read-only: direct inserts, deletes and computed-field definitions return ErrComputedCollectionReadOnly. Their ordinary indexes, cursors, aggregation, snapshots and persistent readers work normally. Collection.ComputedCollection() returns a detached definition, or nil for an ordinary collection; a snapshot handle reads the definition at that snapshot.

The destination must be a new named collection; the source must already exist (use "" for the default collection). There are at most 64 dependents per source. Chaining, joins, array expansion, window stages, composite IDs, averages, extrema and floating-point sums are outside this version. Definitions are immutable; drop and recreate to change them. Dropping a source with dependents returns ErrComputedCollectionDependency; drop dependents first. Dropping a computed collection removes its rows, membership counters, indexes and definition atomically.

Creation and drop block readers and writers while staging a single transaction, bounded at 256 MiB (ErrComputedCollectionLimit). Context cancellation and validation failures before logging leave the database unchanged. Sources must contain validated binary documents, including documents that do not match a filter. A source-write validation or aggregate overflow error aborts the entire batch before logging. WAL recovery replays stored results without recomputing; backup and compaction preserve definitions, results and hidden membership counters.

Benchmark with cd bench and GOTOOLCHAIN=local GOWORK=off go run . -computedcollections -n 250000 -reps 3. It retains all trials and checks every summary against an independent integer model, including group moves, filter changes and deletion. Comparisons include on-demand queries, Pebble application-maintained summaries and SQLite triggers, with 1,000-row batches/transactions, WAL on and sync off. On-demand point queries use a source index where supported; stored point queries use primary keys. Benchmarks report write costs, all-group queries and 10/32-reader throughput.

Design

  • B+tree over fixed-size 16KB slotted pages (page.go). Each slot carries the cell offset, the key length and an 8-byte big-endian key prefix, so binary search runs over the compact slot array and touches the cell only on a prefix tie.

  • Mapped reads, private writes (pager.go). The data file uses stable read-only 64 MiB segments. Growing it adds segments without duplicating old mappings. Verified clean reads use mapped bytes directly, even after a page descriptor is evicted. Dirty pages stay resident; with Options.CacheBytes set, partial checkpoints begin at one quarter of the page target.

  • Buffer ownership (page_buffers.go, node_buffers.go, memtable_buffers.go, wal_buffer.go). Writable pages, page descriptors and memtable records/metadata use owned native buffers. Snapshots, cursors and checkpoint I/O retain explicit references. Retired buffers return to the OS without waiting for Go GC. Small internal pages have separate buffers so they cannot pin mostly empty leaf arenas. Normal WAL flush buffers stay on the Go heap; bursts above 2 MiB use reclaimable mappings. Both cache modes stream compaction/backup output and reuse checkpoint vectors/scratch storage. Unneeded old file-page mappings are reclaimed after copies or checkpoint/snapshot retirement, preserving file contents and all live views. These allocations sit outside Go's heap; measure process RSS and physical footprint as well as runtime.MemStats. CacheBytes is a logical page target, not a hard total-memory limit.

  • Sibling balancing (tree.go, balanceLeaf). A leaf that overflows first sheds cells to a neighbour with room and rewrites the separator; it splits only when both neighbours are full. Leaves end up ~87% full after random inserts instead of ~69%.

  • Memtable (memtable.go). With a cache limit, inserts are buffered in memory (they are already in the log) and applied to the tree in key order once Options.MemtableBytes is reached, so each leaf write carries many records. The memtable is a small in-memory B+tree (wide nodes, contiguous arrays) with a keyed hash table for point reads: a scan copies out only the entries of its range, so probes stay cheap while writers run. Applying a sorted batch reuses the leaf reached for the previous key and splits an overflowing leaf at the insertion point, keeping the left part full. If dirty pages fill the cache mid-apply, a partial checkpoint writes them out but leaves the log alone, so replay after a crash rebuilds the memtable. Default budget: one half of CacheBytes with a cache limit; without one, inserts go straight to the tree, which is faster on this design (a random insert costs about 1µs, a skip-list insert with its allocations about as much).

  • Checkpoint vacuum. Page ids are handed out lowest-first, and every full checkpoint moves the highest-numbered live pages into low free slots and truncates the free tail, so copy-on-write holes never accumulate in the file.

  • Compact (DB.Compact) rewrites the tree in key order into a fresh file and swaps it in, reclaiming the remaining split slack. It copies a snapshot while writes continue, briefly locking to swap the file.

  • Write-ahead log with group commit (wal.go). Logical records [len][crc32c][klen][key][value]. With Options.Sync every Insert waits for an fsync that concurrent inserts share: while one fsync runs, arriving writers wait on a condition; when it finishes, every writer it covered returns at once and one of the others leads the next, which covers everything appended meanwhile. Once concurrency has shown itself, a leader pauses 150µs before its fsync so the writers just released can join the group instead of each starting the next fsync alone. Without Sync, records reach the OS every 10ms or every 1MB. A log generation made entirely dead by a full checkpoint is dropped at close and after compaction.

  • Copy-on-write checkpoints (db.go, tree.go). Dirty pages are written to fresh page ids, parents are patched bottom-up, then one of two meta pages is flipped. The data file is therefore never torn; the log is truncated under a generation number so a crash between the two steps replays correctly. Freed ids are reused one checkpoint later; the free list is rebuilt at open by walking internal pages only.

  • Append optimization: inserting past the last key of the tree starts a fresh leaf instead of splitting in the middle, so sequential loads pack pages tightly.

  • Concurrency: one writer, many readers. Ordinary Find uses a sync.RWMutex and appends into a caller-provided buffer. For sustained parallel point reads, create one Reader per worker with DB.NewReader, Collection.NewReader, or Snapshot.NewReader, reuse it for Find calls, then Close it. Persistent handles distribute read counters across padded lanes. Writers exclude both ordinary and handle reads; no lock is held between handle calls. A live handle sees current values, while a snapshot handle retains its snapshot's view. Close all handles when finished so writes can skip lane coordination. Short keys and reused value buffers avoid allocations on successful point reads.

  • Cursors step within the leaf reached last, validated by a tree generation counter, and descend from the root only at leaf boundaries or after a change, so ordered iteration costs tens of nanoseconds per key.

  • Batches (db.go, Batch): many inserts, one log write, one flush. Log records carry a continuation flag, so a batch replays all-or-nothing.

  • Documents and aggregation (doc.go, scan.go, aggregate.go). JSON objects are stored in a typed binary encoding and read back with InsertJSON/FindJSON. Scan walks the tree in key order through one consistent snapshot, holding the reader lock one leaf at a time. Aggregate runs a MongoDB-style pipeline: $match ($eq $ne $gt $gte $lt $lte $in), $group (_id null, "$field" or composite; $sum $avg $min $max $count $countNonNull $first $last), $sort, $skip, $limit, $project, $count. Leading $match/$skip/$limit stages and a following $group run as one streaming pass that extracts every referenced field from each document in a single walk. AggregateParallel splits the tree into key ranges at internal separators (ShardBounds), runs a $match/$group prefix on one goroutine per range and merges the accumulators. Nested documents and arrays are supported, with dotted paths and $unwind for array expansion.

  • Delete removes a key through the same log, memtable and tree paths; emptied leaves are unlinked, leaves under a quarter full merge into a neighbour, and a root with one child collapses.

  • Large values beyond a quarter page live in overflow page chains; the leaf cell keeps an 8-byte pointer. Values up to 1GB.

  • Persisted free list so opening a large file reads only the list and the root path; a corrupt list falls back to a full walk.

  • Page checksums (crc32c) on every page, verified on first read; Verify walks the whole file checking checksums, key order, separators, overflow chains and free-list consistency.

  • Safety: one process per database (flock), a format version in the meta page, closed handles refuse calls, and an I/O error during a checkpoint puts the handle into a failed state that refuses further writes.

  • Cursor with Seek, First, Last, Next, Prev, merging the memtable.

  • Backup writes a compact copy into another directory.

  • Documents may nest objects and arrays (16 levels); field references in pipelines may be dotted paths; $unwind expands arrays; an array field matches a predicate when any element does; $sort takes several keys in order; Limits cap groups and rows so a query cannot exhaust memory.

  • Crash testing: TestCrashRecoveryWithFaultInjection runs hundreds of rounds through a file layer that trips at a random write, then loses a random suffix of unsynced writes and may tear the first lost one, per inode. After each recovery every acknowledged write must be present, an in-flight batch must be all-or-nothing, and Verify must pass. CRASH_ROUNDS=300 go test -run Crash . runs a longer soak. Fuzz targets cover documents, the pipeline parser and page operations (go test -run '^$' -fuzz '^FuzzDocument$' -fuzztime 30s .).

  • Tooling: cmd/aptevadbctl with stats, verify, get, dump, agg, compact, backup, restore, export, import, collections, version and format.

  • Background checkpoints (checkpoint.go). A checkpoint folds the frozen memtable into the tree in small locked chunks, then captures the dirty set under the lock in memory only (final page ids, patched parents, free list, meta page), and does every write and fsync outside the lock. A writer touching a captured page copies it first. Log rotation, file truncation, old-log deletion and the directory sync all happen off the lock; the log's bulk writes run on the flusher goroutine with a second buffer. Flow control: a writer waits when the active memtable reaches twice its budget while the previous table is applying. The budget includes native record/metadata storage and replaced values.

  • Non-blocking compaction and backup copy a snapshot while writers continue, replay the log delta into the copy in rounds, and hold the lock only for the last few records and two renames; the copy's meta points back into the shared log so nothing is flushed under the lock. The new mappings are warmed only after the old file has closed, preserving read performance without retaining two trees. With 64MB cache and 16MB memtable, the longest single write wait during checkpoints and compactions measured 4 to 6 ms in historical runs; see BENCHMARKS.md for current validation.

  • Snapshots (snapshot.go). Snapshot() pins the root and memtable; a page modified afterwards is copied first and its old version kept in the snapshot's overlay; page ids it may reference are quarantined, not reused. Zero cost while no snapshot is open. Snapshots offer Find, Scan, cursors and aggregation.

  • Secondary indexes (index.go). Entries live under a reserved prefix in the same tree, maintained in the same batch as the document, multikey for arrays, dotted paths. Indexes belong to a collection. Building one reads the documents from a snapshot, sorts the entries and inserts them in order without log records (leaves fill completely, one descent per leaf), then checkpoints before the catalog entry is logged; keys written meanwhile are left to the normal maintenance, a crash before the catalog entry leaves entries the next open sweeps, and compaction is refused during the build. The planner collects the primary keys an index names for the predicates of a leading $match (equality, $in, ranges) in one pass over the entries, takes the most selective candidate, and reads through it only while it names at most an eighth of the collection, then re-checks every predicate on the fetched document. Unique index creation instead stages and validates the whole index before publishing it atomically. VerifyIndexes cross-checks entries, documents and unique constraints.

  • Execution. Aggregate runs on every core by default: a $match/$group (or $count) pipeline without a window is split into key-range shards of the tree, or into shards of an index's primary keys, and the per-shard groups are merged pairwise in parallel rounds; AggregateParallel(ctx, p, 1) is the single-core run and Options.Parallelism sets the default. A collection range with nothing buffered is read leaf by leaf in place under the reader lock, without copying, when no step of the pass uses the database itself.

  • Collections (collection.go). A collection is a key range of the one tree: every user key carries a one-byte collection tag (three bytes past 253 collections), so a named collection's keys are exactly as long as the default collection's and the slot prefix keeps its seven key bytes. The catalog is a reserved key per collection, written to the log before the collection is visible. Collection offers the whole API (Insert, Find, Scan, cursors, batches, indexes, aggregation, snapshots); the DB methods address the default collection. A batch spans collections through Batch.With, and commits as one log record group. DropCollection removes indexes, keys and catalog entry in one atomic WAL group. Staging is capped at 256 MiB; cancellation or a staging-limit error leaves the collection intact.

  • $lookup joins (lookup.go). The equality form (from/localField/foreignField/as), read through the same snapshot as the source. A $lookup unwound on its own field joins in the streaming pass, with following $match stages and a $group or $count: one output record per match, or one with the foreign fields missing under preserveNullAndEmptyArrays (left join, anti-join through {"as": null}). Otherwise the join runs on materialised rows and as holds the matched documents. The join is a hash join over the foreign collection (numbers keyed by their bits, count-only when nothing but existence is needed, filtered to the outer keys after a bounded pre-pass when the outer side is small), or index probes when the foreign field is indexed and the expected number of probes costs less than hashing the collection (its size is estimated from the tree shape); a run that exceeds its probe budget switches to the table. Null and a missing field match each other; an array on either side matches by any element, each document once. Parallel runs build one table and share it across shards. Consecutive probes reuse the index leaf reached last time (a sorted outer side walks the index in order), validated by a tree generation counter. An inner join followed by a $group is turned around when the foreign side is the selective one (its $match stages can use an index) and this side's join field is indexed: the pipeline then starts from the foreign collection and probes back, with identical results.

Run

go test -race .
(cd bench && go build -o ../aptevadb-bench .) && ./aptevadb-bench -n 1000000 -workloads random,seq

Aggregation benchmark (ours, Pebble driven by our executor, SQLite SQL):

./aptevadb-bench -agg -n 1000000 -engines ours,ours-par,pebble,pebble-par,sqlite-c

Join benchmark: 100k users and 1M orders in two collections, seven $lookup pipelines against the equivalent SQL joins, results cross-checked:

./aptevadb-bench -join -n 1000000 -engines ours,ours-par,sqlite-c

Several collections in one file (keys spread over four collections, four tables for SQLite, a one-byte key prefix for Pebble):

./aptevadb-bench -n 1000000 -engines ours,ours-coll4,pebble,pebble-coll4,sqlite-c,sqlite-c-tables4

Durable-insert benchmark with 1, 10 and 50 writers:

./aptevadb-bench -durable -n 3000 -engines ours-sync,ours-sync-batch1000,pebble-sync,sqlite-c-sync

Memory-constrained run (64MB cache for every engine) and compaction:

./aptevadb-bench -n 1000000 -cachemb 64 -ourscachemb 64 -engines ours,pebble,sqlite-c-bulk -workloads random
./aptevadb-bench -n 1000000 -nopar -engines ours,ours-compact -workloads random

Engines: ours, ours-compact, ours-sync, ours-sync-batch1000, ours-sync-barrier, ours-sync-fsync, pebble, pebble-sync, pebble-batch1000, sqlite-c (C SQLite via crawshaw.io/sqlite, one autocommit per insert), sqlite-c-txn1000, sqlite-c-bulk (one transaction), sqlite-c-sync, and the pure-Go sqlite-go* equivalents via zombiezen.com/go/sqlite (modernc).

SQLite runs a WITHOUT ROWID table in WAL mode with a 512MB page cache. Pebble runs with a 512MB block cache, 64MB memtable and bloom filters. The settle phase is a full compaction for Pebble, a checkpoint followed by Compact for the engine, and a checkpoint for SQLite, so find numbers and the disk column reflect each engine's packed layout. -reps N runs each engine N times on fresh directories and keeps the best of every phase.

Not built yet

Composite indexes, index-only scans, join reordering beyond the one shape described above, the let and pipeline forms of $lookup, per-collection statistics, buffered (Bε) internal nodes, a runtime page-size option, Windows support, and any SQL layer.

The alpha.6 count validation report records all fresh-fixture count comparisons and paired read/write/scan guards. Filtered counts use collection.CountDocuments(ctx, filter, db.CountOptions{}). Scalar equality prefixes of exact compound indexes count without loading matching documents when all predicates are covered; other filters retain snapshot-consistent document evaluation. See USAGE.md for limits, null/sparse/multikey semantics, execution statistics and driver use.

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. Scan callback buffers are read-only. 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

View Source
const (
	MaxDocumentSize   = 16 << 20
	MaxDocumentFields = 4096
)

Flat document encoding, built for field access without parsing:

entries: per field [nameLen u8][name][type u8][payload]
trailer: [offset u16 of entry 0] ... [offset u16 of entry n-1][nfields u8]
null: nothing   bool: u8   int: int64 LE   float: float64 bits LE
string: [len u16][bytes]   document: [len u16][nested document]
array: [len u16][count u16][elements: type u8 + payload]

The trailer lets a reader jump to the i-th entry without walking earlier ones. Fields are stored in the order given; EncodeJSON sorts them by name.

View Source
const (
	// PageSize is the fixed on-disk and in-memory page size.
	PageSize = 16384
	// MaxCellSize is the inline-value threshold for ordinary keys.
	MaxCellSize = PageSize / 4
	// MaxKeySize bounds keys; lengths are stored as uint16.
	MaxKeySize = MaxCellSize - 64
	// MaxIndexKeySize bounds the complete encoded index entry, including its
	// primary-key suffix. Each cell plus slot fits in half a usable page,
	// so splitting with the incoming cell always fits in two pages.
	MaxIndexKeySize = (PageSize-hdrSize)/2 - slotSize - leafCellHdr - overflowPtr
)
View Source
const DefaultQueryMemoryBytes int64 = 64 << 20
View Source
const FormatVersion = 10

FormatVersion is the on-disk format this build writes. Open also reads formats 3 through 9 and upgrades them before returning; see FORMAT.md for the policy.

View Source
const MaxTransactionBytes = 256 << 20

MaxTransactionBytes bounds staged atomic maintenance and transaction writes.

View Source
const MaxValueSize = 1 << 30

MaxValueSize bounds a value; larger ones are refused.

View Source
const Version = "0.2.0-alpha.11"

Version is the library version.

Variables

View Source
var (
	ErrPipeline = errors.New("aptevadb: bad pipeline")
	ErrLimit    = errors.New("aptevadb: aggregation exceeded its memory limit")
)
View Source
var (
	ErrChangeFeedDisabled = errors.New("aptevadb: change feed is disabled")
	ErrHistoryExpired     = errors.New("aptevadb: change history expired; take a new snapshot")
	ErrResumeInvalid      = errors.New("aptevadb: invalid change resume token")
	ErrWatchLimit         = errors.New("aptevadb: change cursor limit reached")
)
View Source
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")
)
View Source
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")
)
View Source
var (
	ErrComputedField    = errors.New("aptevadb: invalid computed field definition or value")
	ErrComputedNonEmpty = errors.New("aptevadb: computed definitions require an empty collection")
)
View Source
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")
)
View Source
var (
	ErrKeySize       = errors.New("aptevadb: key or encoded index entry exceeds its size limit")
	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")
)
View Source
var (
	ErrIndexExists = errors.New("aptevadb: index already exists")
	ErrNoSuchIndex = errors.New("aptevadb: no such index")
)
View Source
var DefaultLimits = Limits{MaxGroups: 1 << 20, MaxRows: 1 << 20, MaxBytes: DefaultQueryMemoryBytes}

DefaultLimits apply to every parsed pipeline until SetLimits is called.

View Source
var ErrConflict = errors.New("aptevadb: transaction conflicted with a concurrent write")
View Source
var ErrCorrupt = errors.New("aptevadb: corrupt page")

ErrCorrupt reports a page whose checksum does not match its contents.

View Source
var ErrDestinationExists = errors.New("aptevadb: restore destination already exists")
View Source
var ErrDiskLimit = errors.New("aptevadb: aggregation temporary disk quota exceeded")
View Source
var ErrDocument = errors.New("aptevadb: malformed document")
View Source
var ErrDuplicateKey = errors.New("aptevadb: duplicate unique index value")
View Source
var ErrIndexOrder = errors.New("aptevadb: ordered access requires an exact index; rebuild the legacy index")
View Source
var ErrIndexValue = errors.New("aptevadb: compound indexes require finite scalar fields")
View Source
var ErrLocked = errors.New("aptevadb: database is locked by another process")

ErrLocked reports that another process holds the database.

View Source
var ErrMemoryPressure = errors.New("aptevadb: retained storage exceeds managed memory target")

ErrMemoryPressure is returned before logging a write when retained engine storage cannot be reclaimed to the configured target. Contextual batches may wait for views to close; ordinary writes fail rather than deadlocking a caller that owns the snapshot preventing progress.

View Source
var ErrRestoreIncomplete = errors.New("aptevadb: incomplete restore; remove the incomplete destination and restore again")
View Source
var ErrSnapshotsOpen = errors.New("aptevadb: operation not allowed while snapshots are open")
View Source
var ErrUniqueValue = errors.New("aptevadb: unique indexes require finite scalar numbers")
View Source
var ErrValueSize = errors.New("aptevadb: value too large")

Functions

func CleanupAggregationTemp

func CleanupAggregationTemp(ctx context.Context, root string) (int, error)

CleanupAggregationTemp removes only abandoned, published execution leases. Active executions hold an exclusive OS lock and are never removed. Default per-database scratch is cleaned on successful Open; custom roots can use this function after a process crash. It does not inspect arbitrary temporary files.

func ComputedGroupKey

func ComputedGroupKey(v any) ([]byte, error)

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 Decode

func Decode(document []byte, out any) error

Decode decodes a binary document. Maps preserve int64/float64 values; typed fields use encoding/json rules, with json.Number in interface fields.

func DecodeDocument

func DecodeDocument(doc []byte) (map[string]any, error)

DecodeDocument converts a binary document into a map.

func Encode

func Encode(document any) ([]byte, error)

Encode marshals a Go struct/map into the engine's binary document format.

func EncodeJSON

func EncodeJSON(dst []byte, src []byte) ([]byte, error)

EncodeJSON converts a JSON object (nested objects and arrays allowed, up to 16 levels) into the binary document format.

func FormatVersionOf

func FormatVersionOf(dir string) (uint32, error)

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.

func Import

func Import(ctx context.Context, r io.Reader, destination string) error

Import creates a new directory from Export. It never replaces an existing directory. Failed/interrupted imports remain marked and cannot be opened. The export is trusted local input, not an unbounded network endpoint.

func Restore

func Restore(ctx context.Context, backupDir, destination string) error

Restore verifies a backup and creates a new database directory. The destination must not exist. A marker prevents Open from accepting an interrupted restore. Existing directories are never overwritten.

Types

type AggregateOptions

type AggregateOptions struct {
	MaxMemoryBytes int64
	AllowDiskUse   bool
	TempDir        string
	MaxDiskBytes   int64
	Hint           string
	Stats          *AggregateStats
}

AggregateOptions controls bounded execution. Disk use is opt-in. TempDir must be on a filesystem with adequate space; MaxDiskBytes includes merge output while its inputs still exist. Zero selects a 1-GiB quota per execution. Results without an explicit sort have unspecified group order.

type AggregateStats

type AggregateStats struct {
	Strategy, Index                              string
	InputRows, Groups, Returned                  int64
	PeakMemoryBytes, SpilledBytes, PeakDiskBytes int64
	SpillRuns, MergePasses                       int
	SpillPartitions, MaxPartitionDepth           int
}

AggregateStats describes this execution, excluding caller-retained results, snapshots and the engine page cache. It is updated before the call returns.

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) Err

func (a *ArrayBuilder) Err() error

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) Commit

func (b *Batch) Commit() error

Commit applies the batch atomically and, in sync mode, waits for one flush.

func (*Batch) CommitContext

func (b *Batch) CommitContext(ctx context.Context) error

CommitContext checks cancellation before logging; once logging starts the atomic write and required flush are completed.

func (*Batch) Delete

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

Delete queues a tombstone in the batch.

func (*Batch) Insert

func (b *Batch) Insert(key, val []byte) error

Insert queues a create. Conditions are checked in operation order at Commit.

func (*Batch) InsertJSON

func (b *Batch) InsertJSON(key, doc []byte) error

InsertJSON queues a new JSON document.

func (*Batch) Len

func (b *Batch) Len() int

Len reports the number of queued inserts.

func (*Batch) Replace

func (b *Batch) Replace(key, val []byte) error

Replace queues a replacement; an absent key fails the entire batch.

func (*Batch) ReplaceJSON

func (b *Batch) ReplaceJSON(key, doc []byte) error

ReplaceJSON queues a replacement JSON document.

func (*Batch) Upsert

func (b *Batch) Upsert(key, val []byte) error

Upsert queues a create or replacement in the batch.

func (*Batch) UpsertJSON

func (b *Batch) UpsertJSON(key, doc []byte) error

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 Change

type Change struct {
	Operation   ChangeOp `json:"operation"`
	Collection  string   `json:"collection,omitempty"`
	Key         []byte   `json:"key,omitempty"`
	Value       []byte   `json:"value,omitempty"`
	HasValue    bool     `json:"has_value,omitempty"`
	CommitToken string   `json:"commit_token"`
	EndOfCommit bool     `json:"end_of_commit,omitempty"`
}

Change buffers are read-only and valid until the cursor's next Next call. Clone for asynchronous processing. A CommitToken is safe to save only after EndOfCommit is processed. Put describes a final write; unchanged upserts and absent deletes can appear.

func (Change) Clone

func (c Change) Clone() Change

func (Change) Decode

func (c Change) Decode(out any) error

type ChangeCursor

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

ChangeCursor is pull based. Next/Change/Err belong to one goroutine; Close and ResumeToken are safe concurrently. Next blocks until a change, a coalesced progress heartbeat, cancellation, history expiry, or DB close.

func (*ChangeCursor) Change

func (c *ChangeCursor) Change() Change

func (*ChangeCursor) Close

func (c *ChangeCursor) Close() error

func (*ChangeCursor) Err

func (c *ChangeCursor) Err() error

func (*ChangeCursor) Next

func (c *ChangeCursor) Next() bool

func (*ChangeCursor) ResumeToken

func (c *ChangeCursor) ResumeToken() string

ResumeToken returns the last fully delivered commit (or safely skipped filtered commit). Saving it before processing the current commit is unsafe.

type ChangeFeedOptions

type ChangeFeedOptions struct {
	Disabled       bool          `json:"disabled,omitempty"`
	RetentionBytes int64         `json:"retention_bytes,omitempty"`
	RetentionAge   time.Duration `json:"retention_age,omitempty"`
	// CacheBytes bounds shared hot commit data/metadata; zero selects 8 MiB.
	CacheBytes  int64 `json:"cache_bytes,omitempty"`
	MaxWatchers int   `json:"max_watchers,omitempty"`
	// MaxWatchBytes bounds aggregate cursor working buffers, default 64 MiB.
	MaxWatchBytes int64 `json:"max_watch_bytes,omitempty"`
	// MaxCaptureBytes bounds commit metadata/coalescing work, excluding existing
	// staged values. Exhaustion rejects the write before any record is logged.
	MaxCaptureBytes int64 `json:"max_capture_bytes,omitempty"`
}

ChangeFeedOptions configures persistent capture. Nil in Options leaves a fresh database disabled and preserves an existing database's stored settings. Disabled explicitly ends the old history and invalidates its tokens. Retention is logical: WAL files are reclaimed at segment boundaries once no longer needed for database recovery. The active recovery tail is never lost.

type ChangeFeedStats

type ChangeFeedStats struct {
	Enabled         bool
	Watchers        int
	CacheBytes      int64
	ReaderBytes     int64
	PeakReaderBytes int64
	PlanBytes       int64
	FilterGroups    int
	RetentionBytes  int64
	RetentionAge    time.Duration
}

ChangeFeedStats reports shared cache usage, not total process RSS.

type ChangeOp

type ChangeOp string
const (
	ChangePut    ChangeOp = "put"
	ChangeDelete ChangeOp = "delete"
	ChangeReset  ChangeOp = "reset"
	ChangeDrop   ChangeOp = "drop"
	// ChangeProgress is a control frame, not a row mutation.
	ChangeProgress ChangeOp = "progress"
)

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

func (c *Collection) Aggregate(ctx context.Context, pipeline []byte) ([]map[string]any, error)

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) AggregateEach

func (c *Collection) AggregateEach(ctx context.Context, pipeline []byte, opts AggregateOptions, yield func(map[string]any) bool) error

AggregateEach streams completed result rows from one snapshot. A callback may keep its map; retained caller allocations are outside the execution budget. False stops execution and releases temporary files and the owned snapshot.

func (*Collection) AggregateGroups

func (c *Collection) AggregateGroups(ctx context.Context, pipeline []byte, opts AggregateOptions, yield func(GroupView) error) error

AggregateGroups parses pipeline and runs it with RunGroups.

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) AggregateWithOptions

func (c *Collection) AggregateWithOptions(ctx context.Context, pipeline []byte, opts AggregateOptions) ([]map[string]any, error)

AggregateWithOptions retains the result slice within the same execution budget. Use AggregateEach when result cardinality exceeds the memory budget.

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) CountDocuments

func (c *Collection) CountDocuments(ctx context.Context, filter []byte, opts CountOptions) (int64, error)

CountDocuments counts documents matching Query's JSON filter at one snapshot. Exact scalar compound equality prefixes use an index-only scan when every predicate is covered. Other predicates use document evaluation; multikey entries are never counted as separate documents. Counts exclude raw values that are not encoded documents. Errors return zero, not a partial count.

func (*Collection) CreateCompoundIndex

func (c *Collection) CreateCompoundIndex(ctx context.Context, name string, fields []IndexField, options ...IndexOptions) error

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) ExplainQuery

func (c *Collection) ExplainQuery(ctx context.Context, filter []byte, opts QueryOptions) (QueryPlan, error)

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

func (c *Collection) FindOne(ctx context.Context, filter []byte, out any) (bool, error)

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) NewIndexCursor

func (c *Collection) NewIndexCursor(ctx context.Context, name string, opts IndexCursorOptions) (*IndexCursor, error)

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

func (c *Collection) Run(ctx context.Context, p *Pipeline) ([]map[string]any, error)

Run executes a compiled pipeline over the collection on the calling goroutine.

func (*Collection) RunEach

func (c *Collection) RunEach(ctx context.Context, p *Pipeline, opts AggregateOptions, yield func(map[string]any) bool) error

RunEach executes a compiled pipeline with bounded blocking operators. The existing Run/Aggregate methods continue to collect all results in memory.

func (*Collection) RunGroups

func (c *Collection) RunGroups(ctx context.Context, p *Pipeline, opts AggregateOptions, yield func(GroupView) error) error

RunGroups visits every completed group without allocating owned result maps. The pipeline must end in $group and have a grouping streaming prefix. Return an error to reject a group/stop execution; results must be staged by callers requiring atomic output. One snapshot and all execution budgets still apply. RunGroups runs a compiled pipeline ending in one $group and calls yield with each completed group as a borrowed GroupView, without building row maps. No earlier stage may be a $group or $count. A non-nil error from yield stops execution and is returned unchanged; opts apply as for RunEach.

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. Callback keys and values are read-only and valid only during fn.

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.

func (*Collection) Watch

Collection.Watch is a convenience scoped to the collection's name. A drop is explicit; a later recreation with that name emits a new Reset.

type ComputedCollectionInfo

type ComputedCollectionInfo struct {
	Source   string          `json:"source"`
	Pipeline json.RawMessage `json:"pipeline"`
}

ComputedCollectionInfo describes an immutable, stored collection definition.

type CountOptions

type CountOptions struct {
	Skip, Limit    int
	Hint           string
	MaxMemoryBytes int64
	Stats          *QueryStats
}

CountOptions controls CountDocuments. Zero Limit is unlimited. Hint chooses a candidate covering index; $natural forces document evaluation. An existing hinted index that cannot prove coverage falls back to document evaluation. MaxMemoryBytes has the same exclusions and default as QueryOptions.

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. Sequential steps reuse the current leaf while its generation is unchanged; other movements descend the tree. No lock is held between calls.

func (*Cursor) Close

func (c *Cursor) Close() error

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.

func (*Cursor) Err

func (c *Cursor) Err() error

func (*Cursor) First

func (c *Cursor) First() bool

First positions the cursor at the smallest key.

func (*Cursor) Key

func (c *Cursor) Key() []byte

func (*Cursor) Last

func (c *Cursor) Last() bool

Last positions the cursor at the largest key.

func (*Cursor) Next

func (c *Cursor) Next() bool

Next advances to the following key.

func (*Cursor) Prev

func (c *Cursor) Prev() bool

Prev moves to the preceding key.

func (*Cursor) Seek

func (c *Cursor) Seek(key []byte) bool

Seek positions the cursor at the first key >= key.

func (*Cursor) Valid

func (c *Cursor) Valid() bool

func (*Cursor) Value

func (c *Cursor) Value() []byte

type DB

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

DB is a single-writer, multi-reader key-value store.

func Open

func Open(dir string, opts Options) (*DB, error)

Open opens or creates the database in dir.

func (*DB) Aggregate

func (db *DB) Aggregate(ctx context.Context, pipeline []byte) ([]map[string]any, error)

Aggregate runs a JSON pipeline over the default collection on one goroutine, through a secondary index when the leading $match allows it.

func (*DB) AggregateEach

func (db *DB) AggregateEach(ctx context.Context, pipeline []byte, opts AggregateOptions, yield func(map[string]any) bool) error

func (*DB) AggregateGroups

func (d *DB) AggregateGroups(ctx context.Context, p []byte, o AggregateOptions, y func(GroupView) error) error

AggregateGroups runs AggregateGroups on the default collection.

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) AggregateWithOptions

func (db *DB) AggregateWithOptions(ctx context.Context, pipeline []byte, opts AggregateOptions) ([]map[string]any, error)

func (*DB) Backup

func (db *DB) Backup(ctx context.Context, dir string) error

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) Begin

func (db *DB) Begin(ctx context.Context) (*Tx, error)

func (*DB) ChangeFeedStats

func (db *DB) ChangeFeedStats() ChangeFeedStats

func (*DB) Checkpoint

func (db *DB) Checkpoint() error

Checkpoint runs a full checkpoint and waits for it.

func (*DB) Close

func (db *DB) Close() error

Close checkpoints and releases the files.

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

func (db *DB) Collections() []string

Collections lists the named collections, sorted.

func (*DB) Compact

func (db *DB) Compact(ctx context.Context) error

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) CountDocuments

func (db *DB) CountDocuments(ctx context.Context, filter []byte, opts CountOptions) (int64, error)

func (*DB) CreateCompoundIndex

func (db *DB) CreateCompoundIndex(ctx context.Context, name string, fields []IndexField, options ...IndexOptions) error

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 / $countNonNull; stored sums reject final int64 overflow and floating inputs. 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

func (db *DB) CreateIndex(ctx context.Context, name, field string, opts ...IndexOptions) error

CreateIndex builds an index on a document field of the default collection.

func (*DB) CreateUniqueIndex

func (db *DB) CreateUniqueIndex(ctx context.Context, name, field string) error

func (*DB) DefineComputedFields

func (db *DB) DefineComputedFields(ctx context.Context, definitions []byte) error

DefineComputedFields installs or replaces the default collection's stored generated fields. See Collection.DefineComputedFields.

func (*DB) Delete

func (db *DB) Delete(key []byte) error

Delete removes key from the default collection. Deleting an absent key is not an error.

func (*DB) DropCollection

func (db *DB) DropCollection(ctx context.Context, name string) error

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) DropIndex

func (db *DB) DropIndex(ctx context.Context, name string) error

DropIndex removes an index of the default collection.

func (*DB) Export

func (db *DB) Export(ctx context.Context, w io.Writer) error

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

func (db *DB) Find(key, dst []byte) ([]byte, bool, error)

Find appends the value for key in the default collection to dst and reports whether it exists.

func (*DB) FindJSON

func (db *DB) FindJSON(key []byte) ([]byte, bool, error)

FindJSON returns the document under key as JSON.

func (*DB) FlushLog

func (db *DB) FlushLog() error

FlushLog hands buffered log records to the OS without waiting for an fsync; see DURABILITY.md.

func (*DB) Health

func (db *DB) Health() error

Health reports whether the database can safely continue accepting requests.

func (*DB) Indexes

func (db *DB) Indexes() map[string]string

Indexes lists the default collection's index names and fields.

func (*DB) Insert

func (db *DB) Insert(key, val []byte) error

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

func (db *DB) InsertJSON(key, doc []byte) error

InsertJSON encodes a flat JSON object and stores it under key.

func (*DB) ListIndexes

func (db *DB) ListIndexes() []IndexInfo

func (*DB) MemoryStats

func (db *DB) MemoryStats(ctx context.Context) (MemoryStats, error)

MemoryStats measures file page-cache residency using mincore on supported target platforms. This is distinct from process RSS and the conservative tracked mapped working-set estimate; private allocations are separate again. This is an explicit diagnostic syscall, never performed per point lookup.

func (*DB) NewBatch

func (db *DB) NewBatch() *Batch

NewBatch returns an empty batch bound to the default collection.

func (*DB) NewCursor

func (db *DB) NewCursor() *Cursor

NewCursor returns a cursor over the default collection positioned nowhere; call Seek, First or Last.

func (*DB) NewReader

func (db *DB) NewReader() (*Reader, error)

NewReader returns a reusable point-read handle for the default collection.

func (*DB) OpenCollection

func (db *DB) OpenCollection(name string) (*Collection, error)

OpenCollection returns an existing collection without creating one.

func (*DB) Replace

func (db *DB) Replace(key, val []byte) error

Replace replaces an existing key in the default collection.

func (*DB) ReplaceJSON

func (db *DB) ReplaceJSON(key, doc []byte) error

ReplaceJSON replaces an existing JSON document in the default collection.

func (*DB) Scan

func (db *DB) Scan(start, end []byte, fn func(key, val []byte) bool) error

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. Callback keys and values are read-only and valid only during fn.

func (*DB) ShardBounds

func (db *DB) ShardBounds(n int) ([][]byte, error)

ShardBounds returns up to n-1 keys that split the default collection into ranges of roughly equal page count.

func (*DB) Shards

func (db *DB) Shards(n int) ([]Source, error)

Shards returns key-ordered sources covering the default collection.

func (*DB) Snapshot

func (db *DB) Snapshot() (*Snapshot, error)

Snapshot takes a consistent view. Close it when done.

func (*DB) SnapshotAndWatch

func (db *DB) SnapshotAndWatch(ctx context.Context, o WatchOptions) (*Snapshot, *ChangeCursor, error)

SnapshotAndWatch captures the initial state and feed boundary under one writer lock. After must be empty. Closing the snapshot does not close the feed.

func (*DB) Source

func (db *DB) Source(start, end []byte) Source

Source adapts a key range of the default collection to the aggregation executor.

func (*DB) Stats

func (db *DB) Stats() Stats

func (*DB) TrimMemory

func (db *DB) TrimMemory(ctx context.Context, targetBytes int64) (int64, error)

TrimMemory drops cold file translations to the target while preserving mapping addresses/contents. Recently accessed chunks survive this sweep; a hot working set may exceed the soft target. Call again after an idle interval, or configure MappedCacheBytes for automatic periodic sweeps.

func (*DB) Update

func (db *DB) Update(ctx context.Context, fn func(*Tx) error) error

Update runs fn once and commits on success; it does not retry callbacks.

func (*DB) Upsert

func (db *DB) Upsert(key, val []byte) error

Upsert creates or replaces a key in the default collection.

func (*DB) UpsertJSON

func (db *DB) UpsertJSON(key, doc []byte) error

UpsertJSON creates or replaces a JSON document in the default collection.

func (*DB) Verify

func (db *DB) Verify(ctx context.Context) error

Verify checks the whole database: page checksums, key order within and across pages, overflow chains, and that no page is both reachable and free. It reads every page.

func (*DB) VerifyIndexes

func (db *DB) VerifyIndexes(ctx context.Context) error

VerifyIndexes checks every index of every collection against the documents: each entry's document exists and carries the value, and each document's indexed values have entries. It reads everything.

func (*DB) Watch

func (db *DB) Watch(ctx context.Context, o WatchOptions) (*ChangeCursor, error)

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)

func (*DocBuilder) Bool

func (b *DocBuilder) Bool(name string, v bool)

func (*DocBuilder) Bytes

func (b *DocBuilder) Bytes() []byte

func (*DocBuilder) Doc

func (b *DocBuilder) Doc(name string, sub []byte)

func (*DocBuilder) Err

func (b *DocBuilder) Err() error

Err reports invalid builder state or an encoding that exceeds document limits.

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 GroupView

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

GroupView borrows one completed group's typed state. It and any string from String are valid only during the callback. Any returns an owned Go value. Int64 never rounds an overflowing integer subtotal through float64.

func (GroupView) Any

func (g GroupView) Any(name string) any

func (GroupView) Bool

func (g GroupView) Bool(name string) (bool, bool)

func (GroupView) Float64

func (g GroupView) Float64(name string) (float64, bool)

func (GroupView) ID

func (g GroupView) ID(index int) any

func (GroupView) IDCount

func (g GroupView) IDCount() int

func (GroupView) IDName

func (g GroupView) IDName(index int) string

func (GroupView) Int64

func (g GroupView) Int64(name string) (int64, bool)

func (GroupView) IntegerSum

func (g GroupView) IntegerSum(name string) (high int64, low uint64, ok bool)

IntegerSum exposes the exact signed-128 integer subtotal for SUM/AVG when no floating inputs contributed. The low limb is unsigned; high is sign-extended.

func (GroupView) IsNull

func (g GroupView) IsNull(name string) bool

func (GroupView) Kind

func (g GroupView) Kind(name string) string

Kind distinguishes missing/null and exact integer/floating results without boxing.

func (GroupView) MetricCount

func (g GroupView) MetricCount() int

MetricCount and MetricName list the accumulators in pipeline order.

func (GroupView) MetricName

func (g GroupView) MetricName(index int) string

func (GroupView) String

func (g GroupView) String(name string) (string, bool)

type IndexCursor

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

IndexCursor streams physical index entries at one snapshot. A compound index has one entry per document; a scalar multikey index can repeat a document. Key, Value and Position are borrowed until the next movement. Close promptly.

func (*IndexCursor) Close

func (c *IndexCursor) Close() error

func (*IndexCursor) Err

func (c *IndexCursor) Err() error

func (*IndexCursor) First

func (c *IndexCursor) First() bool

func (*IndexCursor) Key

func (c *IndexCursor) Key() []byte

func (*IndexCursor) Last

func (c *IndexCursor) Last() bool

func (*IndexCursor) Next

func (c *IndexCursor) Next() bool

func (*IndexCursor) Position

func (c *IndexCursor) Position() []byte

func (*IndexCursor) Prev

func (c *IndexCursor) Prev() bool

func (*IndexCursor) Seek

func (c *IndexCursor) Seek(values []any) bool

func (*IndexCursor) SeekAfter

func (c *IndexCursor) SeekAfter(position []byte) bool

func (*IndexCursor) SeekBefore

func (c *IndexCursor) SeekBefore(position []byte) bool

func (*IndexCursor) Valid

func (c *IndexCursor) Valid() bool

func (*IndexCursor) Value

func (c *IndexCursor) Value() []byte

type IndexCursorOptions

type IndexCursorOptions struct {
	Prefix, Lower, Upper           []any
	LowerExclusive, UpperInclusive bool
}

IndexCursorOptions bounds tuples in the index's physical order, including its mixed directions. Prefix restricts leading components. Zero bounds are open.

type IndexField

type IndexField struct {
	Field string `json:"field"`
	Desc  bool   `json:"desc,omitempty"`
}

IndexField specifies one component in a lexicographic compound index.

type IndexInfo

type IndexInfo struct {
	Name, Field   string
	Unique        bool
	Fields        []IndexField
	NullsDistinct bool
	Sparse        bool
	Encoding      uint8
}

IndexInfo describes a persisted secondary index.

type IndexOptions

type IndexOptions struct {
	Unique        bool
	NullsDistinct bool
	Sparse        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
	MaxBytes  int64 // retained working memory; zero selects 64 MiB
}

Limits bound the memory an aggregation may use.

type MemoryStats

type MemoryStats struct {
	ProcessResidentBytes                                               int64
	MappedResidentEstimateBytes                                        int64
	PrivatePageBytes, DescriptorBytes, MemtableBytes, WALBytes         int64
	ActiveMemtableBytes, ImmutableMemtableBytes, RetainedMemtableBytes int64
	SnapshotPinnedBytes, CheckpointPinnedBytes, PinnedBytes            int64
	QueryWorkingBytes, ManagedBufferBytes, MetadataEstimateBytes       int64
	MappedVirtualBytes, MappedPageCacheBytes, MappedTargetBytes        int64
	PageCacheResidencyMeasured                                         bool
	ReclaimedMappedBytes                                               int64
	ManagedTargetBytes                                                 int64
}

MemoryStats separates allocated buffers, file page-cache residency, the tracked mapped working-set estimate and process RSS. These are not additive. SnapshotPinnedBytes and CheckpointPinnedBytes overlap allocated categories; PinnedBytes is their union plus retired memtable leases, never an extra total. MetadataEstimateBytes is conservative Go bookkeeping, not measured Go RSS. ManagedBufferBytes includes private page/descriptor/memtable/WAL storage, including temporary compaction/backup storage owned by the same database.

type Options

type Options struct {
	// ManagedMemoryBytes is a soft target for owned engine buffers and tracked
	// aggregate working memory. Admission happens before a write enters the WAL;
	// one atomic write or in-flight copy may temporarily exceed it. Zero disables.
	ManagedMemoryBytes int64
	// MappedCacheBytes enables cold mapped-page recency tracking and one-second
	// reclamation sweeps. It is a soft resident target; hot mappings survive.
	MappedCacheBytes int64

	// 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 one quarter 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, including record/metadata storage and overwritten records.
	// Writers can buffer up to two active budgets while a previous table applies.
	// 0 (inserts go straight to the tree) without one. Set to
	// -1 to disable with a cache limit.
	MemtableBytes int64
	// ChangeFeed enables persistent opt-in change capture; see CHANGE_FEEDS.md.
	ChangeFeed *ChangeFeedOptions
}

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", a $dateTrunc or an object of those; $sum $avg $min $max $count $countNonNull $countDistinct $first $last, each with an optional where filter), $sort (one or more keys, in order), $skip, $limit, $project (inclusion or exclusion, plus computed $dateTrunc fields), $count, $unwind, $lookup (from/localField/foreignField/as; foreignField "$key" is the record key). 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

func ParsePipeline(src []byte) (*Pipeline, error)

ParsePipeline compiles a JSON array of stages.

func (*Pipeline) Run

func (p *Pipeline) Run(ctx context.Context, src Source) ([]map[string]any, error)

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) RunEach

func (p *Pipeline) RunEach(ctx context.Context, src Source, opts AggregateOptions, yield func(map[string]any) bool) error

RunEach also supports caller-supplied sources. Collection.RunEach is required for index planning, native snapshot ownership and $lookup resolution.

func (*Pipeline) RunGroups

func (p *Pipeline) RunGroups(ctx context.Context, src Source, opts AggregateOptions, yield func(GroupView) error) error

RunGroups provides the same borrowed visitor for caller-supplied sources. Collection.RunGroups supplies native index planning, snapshots and lookups.

func (*Pipeline) RunSharded

func (p *Pipeline) RunSharded(ctx context.Context, shards []Source) ([]map[string]any, error)

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.

func (*Pipeline) RunWithOptions

func (p *Pipeline) RunWithOptions(ctx context.Context, src Source, opts AggregateOptions) ([]map[string]any, error)

RunWithOptions is the materializing counterpart of Pipeline.RunEach.

func (*Pipeline) SetLimits

func (p *Pipeline) SetLimits(l Limits)

SetLimits overrides the memory limits for this pipeline.

type QueryOptions

type QueryOptions struct {
	Skip, Limit    int
	Sort           []IndexField
	Hint           string
	KeyDescending  bool
	MaxMemoryBytes int64
	Stats          *QueryStats
}

QueryOptions controls a key-ordered streaming query. Zero Limit is unlimited.

type QueryPlan

type QueryPlan struct {
	IndexOnly      bool // True only when document evaluation is provably unnecessary.
	Access         string
	Index          string
	Fields         []IndexField
	EqualityPrefix int
	Reverse        bool
	SortInMemory   bool
	MaxMemoryBytes int64
}

QueryPlan describes access and retained query memory, excluding snapshots, page caches, caller allocations and the one current borrowed input document.

type QueryStats

type QueryStats struct {
	// DocumentFetches counts candidate documents loaded for evaluation.
	// IndexEntriesExamined counts entries visited by the index-only count path.
	DocumentFetches, IndexEntriesExamined int64
	Examined, Returned                    int64
	PeakMemoryBytes                       int64
	Plan                                  QueryPlan
}

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.

func (*Reader) Close

func (r *Reader) Close() error

Close releases this handle. Repeated calls are harmless. It waits for in-flight lookups before removing the registration used by writers.

func (*Reader) Find

func (r *Reader) Find(key, dst []byte) ([]byte, bool, error)

Find appends the value for key to dst[:0], matching Collection.Find.

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

func (s *Snapshot) Aggregate(ctx context.Context, pipeline []byte) ([]map[string]any, error)

Aggregate runs a pipeline over the snapshot's default collection, through an index when the leading $match allows it.

func (*Snapshot) AggregateEach

func (s *Snapshot) AggregateEach(ctx context.Context, pipeline []byte, opts AggregateOptions, yield func(map[string]any) bool) error

func (*Snapshot) AggregateGroups

func (s *Snapshot) AggregateGroups(ctx context.Context, p []byte, o AggregateOptions, y func(GroupView) error) error

AggregateGroups runs AggregateGroups on the snapshot's default collection.

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) AggregateWithOptions

func (s *Snapshot) AggregateWithOptions(ctx context.Context, pipeline []byte, opts AggregateOptions) ([]map[string]any, error)

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.

func (*Snapshot) CountDocuments

func (s *Snapshot) CountDocuments(ctx context.Context, filter []byte, opts CountOptions) (int64, error)

func (*Snapshot) Find

func (s *Snapshot) Find(key, dst []byte) ([]byte, bool, error)

Find reads the default collection through the snapshot.

func (*Snapshot) NewCursor

func (s *Snapshot) NewCursor() *Cursor

NewCursor iterates the snapshot's default collection.

func (*Snapshot) NewReader

func (s *Snapshot) NewReader() (*Reader, error)

NewReader returns a reusable point-read handle for this snapshot.

func (*Snapshot) Scan

func (s *Snapshot) Scan(start, end []byte, fn func(key, val []byte) bool) error

Scan iterates the default collection of the snapshot in key order. Callback keys and values are read-only and valid only during fn.

func (*Snapshot) Source

func (s *Snapshot) Source(start, end []byte) Source

Source adapts a key range of the snapshot's default collection to the aggregation executor.

type Source

type Source func(yield func(key, val []byte) bool) error

Source streams key/value pairs into a pipeline; yield returns false to stop.

type Stats

type Stats struct {
	// WALBufferBytes is allocated active, spare and in-flight log-buffer storage.
	WALBufferBytes int
	// InFlightPages counts resident checkpoint pages not already counted dirty.
	InFlightPages                                           int
	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) Commit

func (tx *Tx) Commit() error

func (*Tx) CommitContext

func (tx *Tx) CommitContext(ctx context.Context) error

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) Delete

func (tx *Tx) Delete(key []byte) error

func (*Tx) Find

func (tx *Tx) Find(key, dst []byte) ([]byte, bool, error)

func (*Tx) FindJSON

func (tx *Tx) FindJSON(key []byte) ([]byte, bool, error)

func (*Tx) Insert

func (tx *Tx) Insert(key, val []byte) error

func (*Tx) InsertJSON

func (tx *Tx) InsertJSON(key, val []byte) error

func (*Tx) Replace

func (tx *Tx) Replace(key, val []byte) error

func (*Tx) ReplaceJSON

func (tx *Tx) ReplaceJSON(key, val []byte) error

func (*Tx) Rollback

func (tx *Tx) Rollback()

Rollback discards writes and releases the read snapshot; repeated calls are safe.

func (*Tx) Scan

func (tx *Tx) Scan(start, end []byte, fn func([]byte, []byte) bool) error

func (*Tx) Upsert

func (tx *Tx) Upsert(key, val []byte) error

func (*Tx) UpsertJSON

func (tx *Tx) UpsertJSON(key, val []byte) error

type TxCollection

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

func (*TxCollection) Delete

func (c *TxCollection) Delete(key []byte) error

func (*TxCollection) Find

func (c *TxCollection) Find(key, dst []byte) ([]byte, bool, error)

func (*TxCollection) FindDocument

func (c *TxCollection) FindDocument(key []byte, out any) (bool, error)

func (*TxCollection) FindJSON

func (c *TxCollection) FindJSON(key []byte) ([]byte, 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) Scan

func (c *TxCollection) Scan(start, end []byte, fn func([]byte, []byte) bool) 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

type WatchOptions

type WatchOptions struct {
	Collections    []string        `json:"collections,omitempty"`
	Operations     []ChangeOp      `json:"operations,omitempty"`
	KeyPrefix      []byte          `json:"key_prefix,omitempty"`
	Filter         json.RawMessage `json:"filter,omitempty"`
	Fields         []string        `json:"fields,omitempty"`
	IncludeValues  bool            `json:"include_values,omitempty"`
	After          string          `json:"after,omitempty"`
	MaxMemoryBytes int64           `json:"max_memory_bytes,omitempty"`
	// HeartbeatInterval coalesces progress through filtered commits; default 15s.
	HeartbeatInterval time.Duration `json:"heartbeat_interval,omitempty"`
}

WatchOptions applies filters inside the engine before delivery. Filter uses Query's predicate language against Put's exact committed value. Delete has no post-image and cannot match a document predicate; Reset/Drop always pass for a selected collection. Use a computed collection for live query membership.

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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL