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
- Variables
- func ComputedGroupKey(v any) ([]byte, error)
- func Decode(document []byte, out any) error
- func DecodeDocument(doc []byte) (map[string]any, error)
- func Encode(document any) ([]byte, error)
- func EncodeJSON(dst []byte, src []byte) ([]byte, error)
- func FormatVersionOf(dir string) (uint32, error)
- func Import(ctx context.Context, r io.Reader, destination string) error
- func Restore(ctx context.Context, backupDir, destination string) error
- type ArrayBuilder
- func (a *ArrayBuilder) Array(arr []byte)
- func (a *ArrayBuilder) Bool(v bool)
- func (a *ArrayBuilder) Bytes() []byte
- func (a *ArrayBuilder) Doc(sub []byte)
- func (a *ArrayBuilder) Err() error
- func (a *ArrayBuilder) Float(v float64)
- func (a *ArrayBuilder) Int(v int64)
- func (a *ArrayBuilder) Null()
- func (a *ArrayBuilder) Reset()
- func (a *ArrayBuilder) String(v string)
- type Batch
- func (b *Batch) Commit() error
- func (b *Batch) CommitContext(ctx context.Context) error
- func (b *Batch) Delete(key []byte) error
- func (b *Batch) Insert(key, val []byte) error
- func (b *Batch) InsertJSON(key, doc []byte) error
- func (b *Batch) Len() int
- func (b *Batch) Replace(key, val []byte) error
- func (b *Batch) ReplaceJSON(key, doc []byte) error
- func (b *Batch) Upsert(key, val []byte) error
- func (b *Batch) UpsertJSON(key, doc []byte) error
- func (b *Batch) With(c *Collection) *Batch
- type Change
- type ChangeCursor
- type ChangeFeedOptions
- type ChangeFeedStats
- type ChangeOp
- type Collection
- func (c *Collection) Aggregate(ctx context.Context, pipeline []byte) ([]map[string]any, error)
- func (c *Collection) AggregateParallel(ctx context.Context, pipeline []byte, shards int) ([]map[string]any, error)
- func (c *Collection) ComputedCollection() (*ComputedCollectionInfo, error)
- func (c *Collection) ComputedFields() (map[string]json.RawMessage, error)
- func (c *Collection) CountDocuments(ctx context.Context, filter []byte, opts CountOptions) (int64, error)
- func (c *Collection) CreateCompoundIndex(ctx context.Context, name string, fields []IndexField, options ...IndexOptions) error
- func (c *Collection) CreateIndex(ctx context.Context, name, field string, opts ...IndexOptions) error
- func (c *Collection) CreateUniqueIndex(ctx context.Context, name, field string) error
- func (c *Collection) DB() *DB
- func (c *Collection) DefineComputedFields(ctx context.Context, definitions []byte) error
- func (c *Collection) Delete(key []byte) error
- func (c *Collection) DropIndex(ctx context.Context, name string) error
- func (c *Collection) ExplainQuery(ctx context.Context, filter []byte, opts QueryOptions) (QueryPlan, error)
- func (c *Collection) Find(key, dst []byte) ([]byte, bool, error)
- func (c *Collection) FindDocument(key []byte, out any) (bool, error)
- func (c *Collection) FindJSON(key []byte) ([]byte, bool, error)
- func (c *Collection) FindOne(ctx context.Context, filter []byte, out any) (bool, error)
- func (c *Collection) Indexes() map[string]string
- func (c *Collection) Insert(key, val []byte) error
- func (c *Collection) InsertDocument(key []byte, document any) error
- func (c *Collection) InsertJSON(key, doc []byte) error
- func (c *Collection) ListIndexes() []IndexInfo
- func (c *Collection) Name() string
- func (c *Collection) NewBatch() *Batch
- func (c *Collection) NewCursor() *Cursor
- func (c *Collection) NewIndexCursor(ctx context.Context, name string, opts IndexCursorOptions) (*IndexCursor, error)
- func (c *Collection) NewReader() (*Reader, error)
- func (c *Collection) Query(ctx context.Context, filter []byte, opts QueryOptions, ...) error
- func (c *Collection) Replace(key, val []byte) error
- func (c *Collection) ReplaceDocument(key []byte, document any) error
- func (c *Collection) ReplaceJSON(key, doc []byte) error
- func (c *Collection) Run(ctx context.Context, p *Pipeline) ([]map[string]any, error)
- func (c *Collection) RunParallel(ctx context.Context, p *Pipeline, shards int) ([]map[string]any, error)
- func (c *Collection) Scan(start, end []byte, fn func(key, val []byte) bool) error
- func (c *Collection) ShardBounds(n int) ([][]byte, error)
- func (c *Collection) Shards(n int) ([]Source, error)
- func (c *Collection) Source(start, end []byte) Source
- func (c *Collection) String() string
- func (c *Collection) UpdateDocument(ctx context.Context, key []byte, fn func(map[string]any) error) error
- func (c *Collection) Upsert(key, val []byte) error
- func (c *Collection) UpsertDocument(key []byte, document any) error
- func (c *Collection) UpsertJSON(key, doc []byte) error
- func (c *Collection) Watch(ctx context.Context, o WatchOptions) (*ChangeCursor, error)
- type ComputedCollectionInfo
- type CountOptions
- type Cursor
- func (c *Cursor) Close() error
- func (c *Cursor) Err() error
- func (c *Cursor) First() bool
- func (c *Cursor) Key() []byte
- func (c *Cursor) Last() bool
- func (c *Cursor) Next() bool
- func (c *Cursor) Prev() bool
- func (c *Cursor) Seek(key []byte) bool
- func (c *Cursor) Valid() bool
- func (c *Cursor) Value() []byte
- type DB
- func (db *DB) Aggregate(ctx context.Context, pipeline []byte) ([]map[string]any, error)
- func (db *DB) AggregateParallel(ctx context.Context, pipeline []byte, shards int) ([]map[string]any, error)
- func (db *DB) Backup(ctx context.Context, dir string) error
- func (db *DB) Begin(ctx context.Context) (*Tx, error)
- func (db *DB) ChangeFeedStats() ChangeFeedStats
- func (db *DB) Checkpoint() error
- func (db *DB) Close() error
- func (db *DB) Collection(name string) (*Collection, error)
- func (db *DB) Collections() []string
- func (db *DB) Compact(ctx context.Context) error
- func (db *DB) ComputedFields() (map[string]json.RawMessage, error)
- func (db *DB) CountDocuments(ctx context.Context, filter []byte, opts CountOptions) (int64, error)
- func (db *DB) CreateCompoundIndex(ctx context.Context, name string, fields []IndexField, options ...IndexOptions) error
- func (db *DB) CreateComputedCollection(ctx context.Context, name, source string, pipeline []byte) (*Collection, error)
- func (db *DB) CreateIndex(ctx context.Context, name, field string, opts ...IndexOptions) error
- func (db *DB) CreateUniqueIndex(ctx context.Context, name, field string) error
- func (db *DB) DefineComputedFields(ctx context.Context, definitions []byte) error
- func (db *DB) Delete(key []byte) error
- func (db *DB) DropCollection(ctx context.Context, name string) error
- func (db *DB) DropIndex(ctx context.Context, name string) error
- func (db *DB) Export(ctx context.Context, w io.Writer) error
- func (db *DB) Find(key, dst []byte) ([]byte, bool, error)
- func (db *DB) FindJSON(key []byte) ([]byte, bool, error)
- func (db *DB) FlushLog() error
- func (db *DB) Health() error
- func (db *DB) Indexes() map[string]string
- func (db *DB) Insert(key, val []byte) error
- func (db *DB) InsertJSON(key, doc []byte) error
- func (db *DB) ListIndexes() []IndexInfo
- func (db *DB) NewBatch() *Batch
- func (db *DB) NewCursor() *Cursor
- func (db *DB) NewReader() (*Reader, error)
- func (db *DB) OpenCollection(name string) (*Collection, error)
- func (db *DB) Replace(key, val []byte) error
- func (db *DB) ReplaceJSON(key, doc []byte) error
- func (db *DB) Scan(start, end []byte, fn func(key, val []byte) bool) error
- func (db *DB) ShardBounds(n int) ([][]byte, error)
- func (db *DB) Shards(n int) ([]Source, error)
- func (db *DB) Snapshot() (*Snapshot, error)
- func (db *DB) SnapshotAndWatch(ctx context.Context, o WatchOptions) (*Snapshot, *ChangeCursor, error)
- func (db *DB) Source(start, end []byte) Source
- func (db *DB) Stats() Stats
- func (db *DB) Update(ctx context.Context, fn func(*Tx) error) error
- func (db *DB) Upsert(key, val []byte) error
- func (db *DB) UpsertJSON(key, doc []byte) error
- func (db *DB) Verify(ctx context.Context) error
- func (db *DB) VerifyIndexes(ctx context.Context) error
- func (db *DB) Watch(ctx context.Context, o WatchOptions) (*ChangeCursor, error)
- type DocBuilder
- func (b *DocBuilder) Array(name string, arr []byte)
- func (b *DocBuilder) Bool(name string, v bool)
- func (b *DocBuilder) Bytes() []byte
- func (b *DocBuilder) Doc(name string, sub []byte)
- func (b *DocBuilder) Err() error
- func (b *DocBuilder) Float(name string, v float64)
- func (b *DocBuilder) Int(name string, v int64)
- func (b *DocBuilder) Null(name string)
- func (b *DocBuilder) Reset()
- func (b *DocBuilder) String(name string, v string)
- type IndexCursor
- func (c *IndexCursor) Close() error
- func (c *IndexCursor) Err() error
- func (c *IndexCursor) First() bool
- func (c *IndexCursor) Key() []byte
- func (c *IndexCursor) Last() bool
- func (c *IndexCursor) Next() bool
- func (c *IndexCursor) Position() []byte
- func (c *IndexCursor) Prev() bool
- func (c *IndexCursor) Seek(values []any) bool
- func (c *IndexCursor) SeekAfter(position []byte) bool
- func (c *IndexCursor) SeekBefore(position []byte) bool
- func (c *IndexCursor) Valid() bool
- func (c *IndexCursor) Value() []byte
- type IndexCursorOptions
- type IndexField
- type IndexInfo
- type IndexOptions
- type Limits
- type Options
- type Pipeline
- type QueryOptions
- type QueryPlan
- type QueryStats
- type Reader
- type Snapshot
- func (s *Snapshot) Aggregate(ctx context.Context, pipeline []byte) ([]map[string]any, error)
- func (s *Snapshot) AggregateParallel(ctx context.Context, pipeline []byte, shards int) ([]map[string]any, error)
- func (s *Snapshot) Close()
- func (s *Snapshot) Collection(name string) (*Collection, error)
- func (s *Snapshot) ComputedFields() (map[string]json.RawMessage, error)
- func (s *Snapshot) CountDocuments(ctx context.Context, filter []byte, opts CountOptions) (int64, error)
- func (s *Snapshot) Find(key, dst []byte) ([]byte, bool, error)
- func (s *Snapshot) NewCursor() *Cursor
- func (s *Snapshot) NewReader() (*Reader, error)
- func (s *Snapshot) Scan(start, end []byte, fn func(key, val []byte) bool) error
- func (s *Snapshot) Source(start, end []byte) Source
- type Source
- type Stats
- type SyncMode
- type Tx
- func (tx *Tx) Collection(name string) (*TxCollection, error)
- func (tx *Tx) Commit() error
- func (tx *Tx) CommitContext(ctx context.Context) error
- func (tx *Tx) Delete(key []byte) error
- func (tx *Tx) Find(key, dst []byte) ([]byte, bool, error)
- func (tx *Tx) FindJSON(key []byte) ([]byte, bool, error)
- func (tx *Tx) Insert(key, val []byte) error
- func (tx *Tx) InsertJSON(key, val []byte) error
- func (tx *Tx) Replace(key, val []byte) error
- func (tx *Tx) ReplaceJSON(key, val []byte) error
- func (tx *Tx) Rollback()
- func (tx *Tx) Scan(start, end []byte, fn func([]byte, []byte) bool) error
- func (tx *Tx) Upsert(key, val []byte) error
- func (tx *Tx) UpsertJSON(key, val []byte) error
- type TxCollection
- func (c *TxCollection) Delete(key []byte) error
- func (c *TxCollection) Find(key, dst []byte) ([]byte, bool, error)
- func (c *TxCollection) FindDocument(key []byte, out any) (bool, error)
- func (c *TxCollection) FindJSON(key []byte) ([]byte, bool, error)
- func (c *TxCollection) Insert(key, val []byte) error
- func (c *TxCollection) InsertDocument(key []byte, document any) error
- func (c *TxCollection) InsertJSON(key, doc []byte) error
- func (c *TxCollection) Replace(key, val []byte) error
- func (c *TxCollection) ReplaceDocument(key []byte, document any) error
- func (c *TxCollection) ReplaceJSON(key, doc []byte) error
- func (c *TxCollection) Scan(start, end []byte, fn func([]byte, []byte) bool) error
- func (c *TxCollection) Upsert(key, val []byte) error
- func (c *TxCollection) UpsertDocument(key []byte, document any) error
- func (c *TxCollection) UpsertJSON(key, doc []byte) error
- type WatchOptions
Constants ¶
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.
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 )
const DefaultQueryMemoryBytes int64 = 64 << 20
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.
const MaxTransactionBytes = 256 << 20
MaxTransactionBytes bounds staged atomic maintenance and transaction writes.
const MaxValueSize = 1 << 30
MaxValueSize bounds a value; larger ones are refused.
const Version = "0.2.0-alpha.6"
Version is the library version.
Variables ¶
var ( ErrPipeline = errors.New("aptevadb: bad pipeline") ErrLimit = errors.New("aptevadb: aggregation exceeded its memory limit") )
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") )
var ( ErrNoSuchCollection = errors.New("aptevadb: no such collection") ErrCollectionName = errors.New("aptevadb: bad collection name") ErrTooManyCollections = errors.New("aptevadb: too many collections") ErrReadOnly = errors.New("aptevadb: a snapshot is read-only") )
var ( ErrComputedCollection = errors.New("aptevadb: invalid computed collection definition or value") ErrComputedCollectionReadOnly = errors.New("aptevadb: computed collection is maintained by its source") ErrComputedCollectionExists = errors.New("aptevadb: computed collection destination already exists") ErrComputedCollectionDependency = errors.New("aptevadb: collection has computed dependents") ErrComputedCollectionLimit = errors.New("aptevadb: computed collection staging exceeds 256 MiB") )
var ( ErrComputedField = errors.New("aptevadb: invalid computed field definition or value") ErrComputedNonEmpty = errors.New("aptevadb: computed definitions require an empty collection") )
var ( ErrKeyExists = errors.New("aptevadb: key already exists") ErrNotFound = errors.New("aptevadb: key not found") ErrTransactionTooLarge = errors.New("aptevadb: transaction exceeds 256 MiB staging limit") )
var ( ErrKeySize = errors.New("aptevadb: key 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") )
var ( ErrIndexExists = errors.New("aptevadb: index already exists") ErrNoSuchIndex = errors.New("aptevadb: no such index") )
var DefaultLimits = Limits{MaxGroups: 1 << 20, MaxRows: 1 << 20, MaxBytes: DefaultQueryMemoryBytes}
DefaultLimits apply to every parsed pipeline until SetLimits is called.
var ErrConflict = errors.New("aptevadb: transaction conflicted with a concurrent write")
var ErrCorrupt = errors.New("aptevadb: corrupt page")
ErrCorrupt reports a page whose checksum does not match its contents.
var ErrDestinationExists = errors.New("aptevadb: restore destination already exists")
var ErrDocument = errors.New("aptevadb: malformed document")
var ErrDuplicateKey = errors.New("aptevadb: duplicate unique index value")
var ErrIndexOrder = errors.New("aptevadb: ordered access requires an exact index; rebuild the legacy index")
var ErrIndexValue = errors.New("aptevadb: compound indexes require finite scalar fields")
var ErrLocked = errors.New("aptevadb: database is locked by another process")
ErrLocked reports that another process holds the database.
var ErrRestoreIncomplete = errors.New("aptevadb: incomplete restore; remove the incomplete destination and restore again")
var ErrSnapshotsOpen = errors.New("aptevadb: operation not allowed while snapshots are open")
var ErrUniqueValue = errors.New("aptevadb: unique indexes require finite scalar numbers")
var ErrValueSize = errors.New("aptevadb: value too large")
Functions ¶
func ComputedGroupKey ¶
ComputedGroupKey returns the primary key used by a grouped computed collection. Keys encode scalar types exactly (unlike index float keys). Missing and null share a key; integral float keys normalize to int64.
func Decode ¶
Decode decodes a binary document. Maps preserve int64/float64 values; typed fields use encoding/json rules, with json.Number in interface fields.
func DecodeDocument ¶
DecodeDocument converts a binary document into a map.
func EncodeJSON ¶
EncodeJSON converts a JSON object (nested objects and arrays allowed, up to 16 levels) into the binary document format.
func FormatVersionOf ¶
FormatVersionOf reports the on-disk format version of the database in dir, read from its meta pages without opening it, so a file this build refuses can still be identified. It does not take the database lock.
Types ¶
type ArrayBuilder ¶
type ArrayBuilder struct {
// contains filtered or unexported fields
}
ArrayBuilder encodes array elements: [count u16] then type+payload each.
func (*ArrayBuilder) Array ¶
func (a *ArrayBuilder) Array(arr []byte)
func (*ArrayBuilder) Bool ¶
func (a *ArrayBuilder) Bool(v bool)
func (*ArrayBuilder) Bytes ¶
func (a *ArrayBuilder) Bytes() []byte
func (*ArrayBuilder) Doc ¶
func (a *ArrayBuilder) Doc(sub []byte)
func (*ArrayBuilder) 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) CommitContext ¶
CommitContext checks cancellation before logging; once logging starts the atomic write and required flush are completed.
func (*Batch) InsertJSON ¶
InsertJSON queues a new JSON document.
func (*Batch) ReplaceJSON ¶
ReplaceJSON queues a replacement JSON document.
func (*Batch) UpsertJSON ¶
UpsertJSON queues a create or replacement from JSON.
func (*Batch) With ¶
func (b *Batch) With(c *Collection) *Batch
With returns the same batch bound to collection c: writes queued through either handle commit together.
type 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.
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 Collection ¶
type Collection struct {
// contains filtered or unexported fields
}
Collection is a named key space of a DB. The zero-cost default collection is what the DB's own Insert/Find/Scan/Aggregate methods use. A Collection obtained from a Snapshot reads through that snapshot.
func (*Collection) Aggregate ¶
Aggregate runs a JSON pipeline over the collection, through a secondary index when the leading $match allows it, and on every core when the pipeline's streaming part is a $match/$group (or $count) without a window: AggregateParallel with GOMAXPROCS shards.
func (*Collection) AggregateParallel ¶
func (c *Collection) AggregateParallel(ctx context.Context, pipeline []byte, shards int) ([]map[string]any, error)
AggregateParallel runs a JSON pipeline over up to shards key ranges (or shards of an index's primary keys) at once; 1 runs it on the calling goroutine.
func (*Collection) ComputedCollection ¶
func (c *Collection) ComputedCollection() (*ComputedCollectionInfo, error)
ComputedCollection returns a detached definition, or nil for an ordinary collection. Snapshot handles read the catalog as it stood at that snapshot.
func (*Collection) ComputedFields ¶
func (c *Collection) ComputedFields() (map[string]json.RawMessage, error)
ComputedFields reads definitions through this collection's live/snapshot view. Changing the returned map or its bytes cannot change stored rules.
func (*Collection) 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 ¶
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 ¶
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. 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 ¶
func (c *Collection) Watch(ctx context.Context, o WatchOptions) (*ChangeCursor, error)
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 ¶
Close releases the cursor's read view. Close is idempotent. A cursor is owned by one goroutine; Key and Value are valid until its next operation.
type DB ¶
type DB struct {
// contains filtered or unexported fields
}
DB is a single-writer, multi-reader key-value store.
func (*DB) Aggregate ¶
Aggregate runs a JSON pipeline over the default collection on one goroutine, through a secondary index when the leading $match allows it.
func (*DB) AggregateParallel ¶
func (db *DB) AggregateParallel(ctx context.Context, pipeline []byte, shards int) ([]map[string]any, error)
AggregateParallel runs a JSON pipeline over the default collection in up to shards key ranges at once.
func (*DB) Backup ¶
Backup writes a compact copy of the database into dir, which must not exist or must be empty. It works from a snapshot, so writers continue.
ctx cancels the copy, which is then removed.
func (*DB) ChangeFeedStats ¶
func (db *DB) ChangeFeedStats() ChangeFeedStats
func (*DB) Checkpoint ¶
Checkpoint runs a full checkpoint and waits for it.
func (*DB) Collection ¶
func (db *DB) Collection(name string) (*Collection, error)
Collection returns the named collection, creating it when absent. The empty name is the default collection.
func (*DB) Collections ¶
Collections lists the named collections, sorted.
func (*DB) Compact ¶
Compact rewrites the database into a fresh, densely packed file and swaps it in. The copy is made from a snapshot while writers continue. Writes made during the copy are replayed from the log into the new file in rounds without the lock; the lock is held only to apply the last few records in memory and swap the files. The new file's meta points back into the existing log, so no flush happens under the lock.
ctx cancels it between its rounds; the copy is discarded and the database untouched.
func (*DB) ComputedFields ¶
func (db *DB) ComputedFields() (map[string]json.RawMessage, error)
ComputedFields returns a detached copy of the default collection's expression definitions.
func (*DB) CountDocuments ¶
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 ¶
CreateIndex builds an index on a document field of the default collection.
func (*DB) CreateUniqueIndex ¶
func (*DB) DefineComputedFields ¶
DefineComputedFields installs or replaces the default collection's stored generated fields. See Collection.DefineComputedFields.
func (*DB) Delete ¶
Delete removes key from the default collection. Deleting an absent key is not an error.
func (*DB) DropCollection ¶
DropCollection atomically removes a named collection, its indexes and catalog. Cancellation and staging-limit errors leave it intact. Existing snapshots continue to see their original collection. The default collection cannot drop.
func (*DB) Export ¶
Export writes a versioned, lossless JSON-lines logical backup. Binary keys and values are base64; computed outputs are rebuilt from source rows on import. Schemas, stored-field rules, computed collections and unique indexes are kept.
func (*DB) Find ¶
Find appends the value for key in the default collection to dst and reports whether it exists.
func (*DB) FlushLog ¶
FlushLog hands buffered log records to the OS without waiting for an fsync; see DURABILITY.md.
func (*DB) Insert ¶
Insert creates a key in the default collection; duplicates return ErrKeyExists. Values that do not fit a cell are stored in overflow pages, up to MaxValueSize.
func (*DB) InsertJSON ¶
InsertJSON encodes a flat JSON object and stores it under key.
func (*DB) ListIndexes ¶
func (*DB) NewCursor ¶
NewCursor returns a cursor over the default collection positioned nowhere; call Seek, First or Last.
func (*DB) OpenCollection ¶
func (db *DB) OpenCollection(name string) (*Collection, error)
OpenCollection returns an existing collection without creating one.
func (*DB) ReplaceJSON ¶
ReplaceJSON replaces an existing JSON document in the default collection.
func (*DB) Scan ¶
Scan calls fn for every key in [start, end) of the default collection in key order at one snapshot; nil bounds are open. fn returns false to stop. The snapshot is released before returning. Writers may run between leaves and callbacks without changing the scan's view. Callback keys and values are read-only and valid only during fn.
func (*DB) ShardBounds ¶
ShardBounds returns up to n-1 keys that split the default collection into ranges of roughly equal page count.
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 ¶
Source adapts a key range of the default collection to the aggregation executor.
func (*DB) UpsertJSON ¶
UpsertJSON creates or replaces a JSON document in the default collection.
func (*DB) Verify ¶
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 ¶
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 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 ¶
IndexCursorOptions bounds tuples in the index's physical order, including its mixed directions. Prefix restricts leading components. Zero bounds are open.
type IndexField ¶
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 ¶
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
// 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" or an object of "$field" refs; $sum $avg $min $max $count $countNonNull $first $last), $sort (one or more keys, in order), $skip, $limit, $project (inclusion or exclusion), $count, $unwind, $lookup (from/localField/foreignField/as). Field references may be dotted paths into nested documents.
Leading $match/$skip/$limit stages, a $lookup immediately unwound on its own field, further $match stages and a following $group run as one streaming pass over the source without decoding documents into maps; the join is a hash join over the foreign collection, or index probes when the pipeline is selective and the foreign field is indexed.
func ParsePipeline ¶
ParsePipeline compiles a JSON array of stages.
func (*Pipeline) Run ¶
Run executes the pipeline over src on the calling goroutine. A $lookup stage needs a collection to resolve "from" against: use Collection.Run.
ctx cancels a long run: the pass checks it every few thousand records and returns ctx.Err().
func (*Pipeline) RunSharded ¶
RunSharded executes the pipeline over key-ordered shards concurrently when the streaming prefix is a $match/$group (no $skip/$limit), merging the per-shard groups. Other pipelines run serially over the shards in order.
type QueryOptions ¶
type QueryOptions struct {
Skip, Limit int
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 Reader ¶
type Reader struct {
// contains filtered or unexported fields
}
Reader is a reusable live or snapshot point-read handle. Give each worker its own Reader to avoid modifying a shared per-read counter. A Reader is safe for concurrent use, including Close, but separate worker handles provide better scaling. Close it when finished to restore the fast writer path when no handles remain. No lock is held between calls.
type Snapshot ¶
type Snapshot struct {
// contains filtered or unexported fields
}
Snapshot is a consistent read view: the tree and memtable as they were when it was taken. Pages modified afterwards are copied first and their old version kept in the snapshot's overlay, so readers never see a later write. While a snapshot is open, page ids it may reference are quarantined instead of reused.
func (*Snapshot) Aggregate ¶
Aggregate runs a pipeline over the snapshot's default collection, through an index when the leading $match allows it.
func (*Snapshot) AggregateParallel ¶
func (s *Snapshot) AggregateParallel(ctx context.Context, pipeline []byte, shards int) ([]map[string]any, error)
AggregateParallel runs a pipeline over the snapshot's default collection in key-range shards.
func (*Snapshot) Close ¶
func (s *Snapshot) Close()
Close releases the snapshot and any page ids it kept from reuse.
func (*Snapshot) Collection ¶
func (s *Snapshot) Collection(name string) (*Collection, error)
Collection returns the named collection as it stands in the snapshot; "" is the default collection. Later catalog changes are invisible.
func (*Snapshot) ComputedFields ¶
func (s *Snapshot) ComputedFields() (map[string]json.RawMessage, error)
ComputedFields returns the default collection's definitions at the snapshot.
func (*Snapshot) CountDocuments ¶
type Stats ¶
type Stats struct {
ResidentPages, HighWaterPages, FreePages, DirtyPages int
Loads, Writes, Evictions, Balances, Merges, Relocations uint64
Height int
MemtableEntries, MemtableBytes int
Snapshots, QuarantinedPages int
Collections, Indexes int
LockHolds map[string]time.Duration
WriteStalls, IndexScans uint64
}
Stats reports resident and file-level counters.
type SyncMode ¶
type SyncMode uint8
SyncMode selects the flush primitive used when Options.Sync is on.
const ( // SyncFull survives power loss: F_FULLFSYNC on macOS, fsync elsewhere. SyncFull SyncMode = iota // SyncBarrier is F_BARRIERFSYNC on macOS: ordered and handed to the drive, // but the drive cache is not forced to stable media. fsync elsewhere. SyncBarrier // SyncOS is plain fsync(2). On macOS this survives an OS crash, not a // power loss; it is SQLite's default behaviour there. SyncOS )
type Tx ¶
type Tx struct {
// contains filtered or unexported fields
}
Tx is an optimistic serializable read/write transaction. Reads use one snapshot plus its staged writes (including computed outputs). A writing transaction fails with ErrConflict if any database write committed since Begin. The caller may retry the whole transaction. Tx is not goroutine-safe. Collections must be created before Begin; DDL is outside transactions.
func (*Tx) Collection ¶
func (tx *Tx) Collection(name string) (*TxCollection, error)
func (*Tx) CommitContext ¶
Commit closes the transaction whether it succeeds or fails. Validation, constraints, computed outputs and all writes share one writer lock/WAL group. CommitContext also observes cancellation of the original Begin context.
func (*Tx) InsertJSON ¶
func (*Tx) ReplaceJSON ¶
func (*Tx) Rollback ¶
func (tx *Tx) Rollback()
Rollback discards writes and releases the read snapshot; repeated calls are safe.
func (*Tx) UpsertJSON ¶
type TxCollection ¶
type TxCollection struct {
// contains filtered or unexported fields
}
func (*TxCollection) Delete ¶
func (c *TxCollection) Delete(key []byte) error
func (*TxCollection) FindDocument ¶
func (c *TxCollection) FindDocument(key []byte, out any) (bool, error)
func (*TxCollection) Insert ¶
func (c *TxCollection) Insert(key, val []byte) error
func (*TxCollection) InsertDocument ¶
func (c *TxCollection) InsertDocument(key []byte, document any) error
func (*TxCollection) InsertJSON ¶
func (c *TxCollection) InsertJSON(key, doc []byte) error
func (*TxCollection) Replace ¶
func (c *TxCollection) Replace(key, val []byte) error
func (*TxCollection) ReplaceDocument ¶
func (c *TxCollection) ReplaceDocument(key []byte, document any) error
func (*TxCollection) ReplaceJSON ¶
func (c *TxCollection) ReplaceJSON(key, doc []byte) error
func (*TxCollection) Upsert ¶
func (c *TxCollection) Upsert(key, val []byte) error
func (*TxCollection) UpsertDocument ¶
func (c *TxCollection) UpsertDocument(key []byte, document any) error
func (*TxCollection) UpsertJSON ¶
func (c *TxCollection) UpsertJSON(key, doc []byte) error
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.
Source Files
¶
- aggregate.go
- aggregate_numeric.go
- aggregate_sort.go
- change_cursor.go
- change_feed.go
- change_wal.go
- checkpoint.go
- collection.go
- compound_index.go
- computed.go
- computed_collection.go
- computed_collection_delta.go
- computed_collection_plan.go
- computed_doc.go
- computed_expr.go
- contracts.go
- copy_builder.go
- count.go
- cursor.go
- db.go
- directory_lock.go
- doc.go
- documents.go
- export.go
- file.go
- index.go
- index_cursor.go
- lookup.go
- memtable.go
- overflow.go
- package_doc.go
- page.go
- page_buffers.go
- pager.go
- query_memory.go
- query_plan.go
- reader.go
- restore.go
- scan.go
- snapshot.go
- sync_other.go
- transaction.go
- tree.go
- tree_mutex.go
- tree_split.go
- unique.go
- wal.go
- wal_buffer.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package client is the Go driver for an AptevaDB HTTP v1 server.
|
Package client is the Go driver for an AptevaDB HTTP v1 server. |
|
cmd
|
|
|
aptevadb-server
command
|
|
|
aptevadbctl
command
Command aptevadbctl inspects and maintains a database directory.
|
Command aptevadbctl inspects and maintains a database directory. |
|
demo
command
|
|
|
examples
|
|
|
embedded
command
|
|
|
internal
|
|
|
protocol
Package protocol defines the version-one AptevaDB HTTP envelopes.
|
Package protocol defines the version-one AptevaDB HTTP envelopes. |
|
Package server exposes an embedded AptevaDB through the version-one HTTP API.
|
Package server exposes an embedded AptevaDB through the version-one HTTP API. |