db

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

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

Go to latest
Published: Oct 13, 2026 License: MIT Imports: 24 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.2. 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 7; opening formats 3–6 upgrades them permanently, so keep a backup before upgrading.

go get github.com/apteva/db@v0.2.0-alpha.2
go install github.com/apteva/db/cmd/aptevadbctl@v0.2.0-alpha.2
go install github.com/apteva/db/cmd/aptevadb-server@v0.2.0-alpha.2
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.

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.

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-6 database upgrades both metadata slots durably to format 7 before returning. Older binaries then refuse to open it; keep a backup if you need to use one. Page, log and document layouts are unchanged; computed catalogs, group counters and unique constraints require the version bump. 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) and $count: {}; $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 is mapped read-only (the mapping doubles as the file grows). A clean page is a view into the OS page cache: loading it costs a small struct and a page fault, no copy and no syscall, and the cache is shared across threads and processes. The writer copies a page into a private buffer before modifying it; a checkpoint writes the buffer and hands the page back to the mapping. With Options.CacheBytes set, clean leaf pages are evicted by a CLOCK sweep (internal pages stay resident so checkpoints can always reach dirty leaves) and a checkpoint runs once dirty pages reach three quarters of the limit.

  • Writable-buffer lifetime (page_buffers.go, wal_buffer.go). In the default unlimited-cache mode, private leaf and overflow pages use anonymous mapped arenas; small internal pages use Go storage. WAL buffers up to 16 MiB remain on the Go heap to avoid increasing GC work on small databases; larger buffers use owned anonymous mappings. Checkpoint captures and snapshot overlays retain explicit references; unused arenas and superseded WAL buffers are returned to the OS when those references are released. Compaction and backup write completed pages in bounded batches instead of retaining an entire replacement tree. Bounded-cache mode retains Go writable buffers and its original compaction builder to preserve parallel read CPU efficiency. Backup always uses the streaming builder. Sibling balancing reuses its cell-length scratch slice. These mappings are outside Go's heap, so measure total process RSS and memory footprint as well as runtime.MemStats. CacheBytes controls the logical page cache, not a hard limit on all process memory, memtables or snapshot versions.

  • 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 map 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: 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 $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 only when the active memtable reaches four times its budget.

  • 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. 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.

Documentation

Overview

Package db provides the embedded AptevaDB document/key-value database. Open owns one local directory exclusively. Use DurableOptions for full-sync acknowledged-write durability; Options{} selects asynchronous writes.

Collections support create-only Insert, replacement Upsert, existing-only Replace, point reads, consistent snapshot scans/queries, unique secondary indexes and stored computed fields/collections. Begin/Update provide optimistic serializable read/write transactions; NewBatch commits writes across collections. Writing transactions return ErrConflict after any concurrent committed write.

Close snapshots, transactions, cursors and Reader handles promptly. DB and Collection are concurrency-safe; transactions, batches and cursors are owned by one goroutine. Callback/cursor buffers are borrowed; copy retained bytes. Format upgrades are one-way; back up before upgrading. Only Linux and macOS are supported. See github.com/apteva/db/client for the remote Go driver.

Package engine is a from-scratch embedded key-value engine: a B+tree over fixed-size slotted pages, a write-ahead log with group commit, and copy-on-write checkpoints so the data file is never torn.

Index

Constants

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 bounds key+value so a page always holds at least three cells,
	// which the split logic relies on.
	MaxCellSize = PageSize / 4
	// MaxKeySize bounds keys; lengths are stored as uint16.
	MaxKeySize = MaxCellSize - 64
)
View Source
const DefaultQueryMemoryBytes int64 = 64 << 20
View Source
const FormatVersion = 7

FormatVersion is the on-disk format this build writes. Open also reads formats 3 through 6 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.2"

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 (
	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 must be 1..1024 bytes")
	ErrCellSize      = errors.New("aptevadb: key+value too large")
	ErrClosed        = errors.New("aptevadb: closed")
	ErrIndexBuilding = errors.New("aptevadb: an index is being built")
	ErrOptions       = errors.New("aptevadb: invalid options")
	ErrFormat        = errors.New("aptevadb: unsupported file format version")
)
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 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 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 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 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 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) AggregateParallel

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

AggregateParallel runs a JSON pipeline over up to shards key ranges (or shards of an index's primary keys) at once; 1 runs it on the calling goroutine.

func (*Collection) ComputedCollection

func (c *Collection) ComputedCollection() (*ComputedCollectionInfo, error)

ComputedCollection returns a detached definition, or nil for an ordinary collection. Snapshot handles read the catalog as it stood at that snapshot.

func (*Collection) ComputedFields

func (c *Collection) ComputedFields() (map[string]json.RawMessage, error)

ComputedFields reads definitions through this collection's live/snapshot view. Changing the returned map or its bytes cannot change stored rules.

func (*Collection) 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) RunParallel

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

RunParallel executes a compiled pipeline over the collection in shards.

func (*Collection) Scan

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

Scan calls fn for every key in [start, end) of the collection in key order; nil bounds are open. fn returns false to stop.

func (*Collection) ShardBounds

func (c *Collection) ShardBounds(n int) ([][]byte, error)

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

func (*Collection) Shards

func (c *Collection) Shards(n int) ([]Source, error)

Shards returns key-ordered sources covering the collection.

func (*Collection) Source

func (c *Collection) Source(start, end []byte) Source

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

func (*Collection) String

func (c *Collection) String() string

func (*Collection) UpdateDocument

func (c *Collection) UpdateDocument(ctx context.Context, key []byte, fn func(map[string]any) error) error

UpdateDocument runs a safe read/modify/replace transaction once. ErrConflict means the caller should retry; fn must not retain or mutate database handles.

func (*Collection) Upsert

func (c *Collection) Upsert(key, val []byte) error

Upsert creates or replaces key. It retains the pre-alpha Insert behavior.

func (*Collection) UpsertDocument

func (c *Collection) UpsertDocument(key []byte, document any) error

func (*Collection) UpsertJSON

func (c *Collection) UpsertJSON(key, doc []byte) error

UpsertJSON creates or replaces a document from a JSON object.

type ComputedCollectionInfo

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

ComputedCollectionInfo describes an immutable, stored collection definition.

type Cursor

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

Cursor iterates keys in order, forwards or backwards, merging the tree with the memtable at one snapshot taken when the cursor was created. Close the cursor to release its view. Each step re-descends the tree, so it costs a lookup rather than a pointer chase; no lock is held between calls.

func (*Cursor) Close

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

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

AggregateParallel runs a JSON pipeline over the default collection in up to shards key ranges at once.

func (*DB) Backup

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) 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) 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; sums reject overflow and floats. Inserts, overwrites, deletes and batches maintain stored results and indexes in the same WAL transaction. Creation/drop pause writers while staging at most 256 MiB. On failure before logging, neither catalog nor rows are added.

func (*DB) CreateIndex

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

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

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 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 Options

type Options struct {
	// Sync flushes the log before a write returns. Default false (async).
	// Use DurableOptions for power-loss-safe writes. Concurrent writes share flushes.
	Sync bool
	// SyncMode picks the flush primitive; default SyncFull.
	SyncMode SyncMode
	// CheckpointLogBytes is the log size that triggers a checkpoint. Default 256MB.
	CheckpointLogBytes uint64
	// LogFlushInterval is how often buffered log records are handed to the OS
	// when Sync is off. Default 10ms.
	LogFlushInterval time.Duration
	// CacheBytes targets the logical page cache, not total process memory; clean pages are evicted past it and a
	// checkpoint runs when dirty pages reach three quarters of it. 0 keeps
	// everything resident, which is fastest when the data fits in RAM.
	CacheBytes int64
	// VerifyChecksums checks every page checksum when a page is first read
	// from the file. Default true; set NoVerifyChecksums to turn it off.
	NoVerifyChecksums bool
	// Parallelism is how many goroutines Aggregate uses for a pipeline that
	// can run in shards. 0 means runtime.GOMAXPROCS(0) at Open; 1 runs on
	// the calling goroutine. AggregateParallel overrides it per call.
	Parallelism int
	// MemtableBytes buffers inserts in memory and applies them to the tree
	// in key order once the budget is reached, cutting write amplification
	// when the file is larger than the cache. Default: CacheBytes/2 with a
	// cache limit; 0 (inserts go straight to the tree) without one. Set to
	// -1 to disable with a cache limit.
	MemtableBytes int64
}

Options tunes durability and checkpointing.

func DurableOptions

func DurableOptions() Options

DurableOptions selects acknowledged writes that survive power loss on supported local filesystems and drives honoring flushes. Options{} is async.

type Pipeline

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

Pipeline is a compiled MongoDB-style aggregation pipeline.

Stages: $match (equality, $eq $ne $gt $gte $lt $lte $in; an array field matches when any element does), $group (_id as null, "$field" or an object of "$field" refs; $sum $avg $min $max $count $first $last), $sort (one or more keys, in order), $skip, $limit, $project (inclusion or exclusion), $count, $unwind, $lookup (from/localField/foreignField/as). Field references may be dotted paths into nested documents.

Leading $match/$skip/$limit stages, a $lookup immediately unwound on its own field, further $match stages and a following $group run as one streaming pass over the source without decoding documents into maps; the join is a hash join over the foreign collection, or index probes when the pipeline is selective and the foreign field is indexed.

func ParsePipeline

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) 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) 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 {
	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 {
	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) AggregateParallel

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

AggregateParallel runs a pipeline over the snapshot's default collection in key-range shards.

func (*Snapshot) Close

func (s *Snapshot) Close()

Close releases the snapshot and any page ids it kept from reuse.

func (*Snapshot) Collection

func (s *Snapshot) Collection(name string) (*Collection, error)

Collection returns the named collection as it stands in the snapshot; "" is the default collection. Later catalog changes are invisible.

func (*Snapshot) ComputedFields

func (s *Snapshot) ComputedFields() (map[string]json.RawMessage, error)

ComputedFields returns the default collection's definitions at the snapshot.

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.

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 {
	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

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