edb

package module
v0.4.20 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: 0BSD Imports: 39 Imported by: 2 modules, 2 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

EDB

An embedded document database for Go, stored in bbolt.

Go reference

EDB stores Go structs in a bbolt file inside your process. You define rows, keys and indexes in Go, and query them with loops. Readers run concurrently; writes run one at a time.

Why?

A single server in the 2020s can handle an awful lot of a small-to-mid-sized company's workload. You can save on development time, costs and complexity by going back from the cloud to a dedicated unicorn server.

This won't be the right choice every time; there's availability and security boundaries to consider, too. But faster time-to-market and smaller development teams are worth a lot, especially for startups.

To realize those benefits, you need an efficient database:

  • Fast data access means that, instead of optimizing tricky SQL, you can loop over your data with code. Imagine the savings.
  • Serialized writes simplify statistics and read-modify-write logic, eliminating a whole class of concurrency errors.

Keep the data in your process. Avoid a network round trip for every lookup. EDB uses a memory-mapped bbolt file, concurrent readers and one writer. Replication, failover and service boundaries remain application decisions.

The same holds for AI-written code. An agent reads the Go types, writes an ordinary loop, and tests the result.

Install

Requires Go 1.27 or later.

go get github.com/andreyvit/edb

Run the example from a checkout:

go run ./examples/loyalty

Most snippets below come from that example. They use two helpers defined in its source: must returns a value or panics on an error, and ensure panics on an error.

Usage

Define rows and indexes

A row is a struct. Its first field is the primary key: a scalar, or a struct for a composite key. Mark the key msgpack:"-" to keep it out of the stored value; EDB restores it when it decodes a row.

type Customer struct {
    ID             uint64   `msgpack:"-" kvo:"-"`
    FirstName      string   `msgpack:"first_name" kvo:"first_name"`
    Email          string   `msgpack:"email" kvo:"email"`
    Tags           []string `msgpack:"tags" kvo:"tags"`
    PointsEarned   int64    `msgpack:"points_earned" kvo:"points_earned"`
    PointsRedeemed int64    `msgpack:"points_redeemed" kvo:"points_redeemed"`
}

A table also needs a model: the list of the row's properties, each with a type and a stable numeric code. EDB uses the model to read single fields of a stored row without decoding the row, including in index callbacks. Models, properties and records come from KVO, a package of the evm module; see the KVO documentation for that API.

var (
    Models       = kvo.NewSchema()
    CustomerType = kvo.NewEntityType(Models, "customer", reflect.TypeFor[Customer]())

    Customer_FirstName = kvo.NewStringProp[string](Models, 1, "customer:first_name", kvo.TMachineString)
    Customer_Email     = kvo.NewStringProp[string](Models, 2, "customer:email", kvo.TMachineString)
    Customer_Tags      = kvo.NewListProp(Models, 3, "customer:tags",
        kvo.ListOf(kvo.TMachineString), values.StringCodec[string]())
    Customer_PointsEarned   = kvo.NewSignedProp[int64](Models, 4, "customer:points_earned", kvo.TInt64)
    Customer_PointsRedeemed = kvo.NewSignedProp[int64](Models, 5, "customer:points_redeemed", kvo.TInt64)

    CustomerModel = kvo.NewModel(Models, CustomerType, func(b *kvo.ModelBuilder) {
        b.Prop(Customer_FirstName)
        b.Prop(Customer_Email)
        b.Prop(Customer_Tags)
        b.Prop(Customer_PointsEarned)
        b.Prop(Customer_PointsRedeemed)
    })
)

Property codes are written to disk by the Fast2 and Compact2 formats. Do not renumber them, and do not reuse a retired code.

DefineTable registers a table in a schema. The type parameter of TableBuilder is the primary key type; it must match the first field of the row struct.

var (
    DBSchema              = &edb.Schema{}
    customersByEmailIndex *edb.Index[string]
    customersByTagIndex   *edb.Index[string]

    Customers = edb.DefineTable(DBSchema, "customers", CustomerModel, func(b *edb.TableBuilder[uint64]) {
        b.SetRecordStorage(edb.RecordStorage{Format: edb.Fast2})
        customersByEmailIndex = b.AddIndex("by_email", edbindexing.ByFieldIfNonZero(Customer_Email))
        customersByTagIndex = b.AddIndex("by_tag", func(_ *edb.Tx, _ values.Value, r kvo.Record, yield func(string)) {
            for tag := range r.Get(Customer_Tags).Iter() {
                yield(tag)
            }
        })
    })
    CustomerRows = Customers.Rows[Customer]()
)

Customers is a *edb.Table[uint64]: it reads and writes rows as records. CustomerRows reads and writes the same rows as *Customer structs. Both accept the same keys and indexes.

An index callback receives the row as a record and yields index keys. One row can yield several keys, or none. That covers tag indexes, filtered indexes and compound keys (yield a struct). EDB updates index entries when a row is saved or deleted.

  • edbindexing has callbacks for common cases: ByField, ByFieldIfNonZero, ByTimeFieldIfNonZero, ByScalarList.
  • The callback must not keep the record or the primary key after it returns.
  • A nil callback leaves the index to one table-wide callback set with b.SetIndexer.
  • A new index on a table that already has rows is not filled from those rows. Pass edb.IndexInitialFillModeBlocking to AddIndex to fill it when the database opens, or call tx.Reindex(table, index).
  • An index that is no longer declared is deleted when the database opens.
Open a database
db := must(edb.Open("customers.db", DBSchema, edb.Options{}))
defer db.Close()

Open the database once at startup. Pass edb.InMemory as the path for an in-memory database, for example in tests. Options.IsTesting turns off fsync and turns on extra consistency checks.

Transactions

Every operation needs a transaction. db.Tx runs a callback in a write transaction (true) or a read transaction (false):

ensure(db.Tx(edb.TxMetadata{Kind: "example:seed"}, true, func(tx *edb.Tx) error {
    CustomerRows.Put(tx, &Customer{
        ID: 101, FirstName: "Alice & Bob", Email: "alice@example.com",
        Tags: []string{"vip", "newsletter"}, PointsEarned: 1250, PointsRedeemed: 250,
    })
    return nil
}))
  • An error returned from a write callback rolls back its writes. db.Tx returns that error, or the commit error.
  • A panic in a write callback rolls back too; db.Tx returns it as an error.
  • EDB can run a write callback more than once, because bbolt batches concurrent writers. Send email and make other outside calls after db.Tx returns.
  • TxMetadata labels the transaction with a Kind and a Tenant. Options.ObserveTransaction receives the labels and the duration of every write transaction. The zero value is valid.

db.Read(func(tx *edb.Tx)) and db.Write(metadata, func(tx *edb.Tx)) are the forms without an error result. db.Write panics if the commit fails.

Table methods accept a *edb.Tx or any value with a DBTx() *edb.Tx method, so a request context that carries the transaction works as well.

Write and read rows
CustomerRows.Put(tx, &Customer{ID: 102, FirstName: "Maria", Email: "maria@example.com"})

customer := CustomerRows.Get(tx, 101) // *Customer, or nil
id, byEmail := CustomerRows.Lookup(tx, customersByEmailIndex, "alice@example.com")
found := CustomerRows.Exists(tx, 103)
deleted := CustomerRows.Delete(tx, 103)
  • Put inserts the row or replaces the row with the same key. It reports whether stored data changed.
  • Get and Lookup return a struct that you own, or nil.
  • Lookup returns the primary key and the first row for an index key. Indexes are not unique; use a scan to visit every match. LookupKey returns the primary key without reading the row.
  • These methods panic on storage errors. TryGet and TryLookup return the error, and the row's ValueMeta (schema version and modification count).
Scan

A scan is a loop over a table or an index. This one sums the points of every customer with a tag:

func balanceFromStructs(tx *edb.Tx, tag string) int64 {
    var total int64
    for customer := range CustomerRows.ExactIndexScan(tx, customersByTagIndex, tag).Rows() {
        total += customer.PointsEarned - customer.PointsRedeemed
    }
    return total
}
Scan By primary key By index
Everything Scan(tx) IndexScan(tx, idx)
One key Exact(tx, key) ExactIndexScan(tx, idx, key)
lower through upper, inclusive Range(tx, lower, upper) RangeIndexScan(tx, idx, lower, upper)
>= key, > key From, After IndexScanFrom, IndexScanAfter
<= key, < key Through, Before IndexScanThrough, IndexScanBefore
First components of a composite key Prefix(tx, key, n) PrefixIndexScan(tx, idx, key, n)

Add .Reversed() for descending order. Then choose what to iterate:

for id, customer := range CustomerRows.ExactIndexScan(tx, customersByTagIndex, "vip").Reversed().Entries() {
    fmt.Println(id, customer.Email)
}
ids := slices.Collect(CustomerRows.Scan(tx).Keys())
  • Rows() yields rows, Entries() yields primary keys with rows, Keys() yields primary keys without reading rows.
  • A scan value describes a query. Each range opens a new cursor in the same transaction.
  • Prefix counts key components. It does not match string prefixes.
  • Do not save or delete rows while you scan an index that those writes change. Collect the keys first, then write.

scan.Raw() returns a cursor with Next(), for loops that need the encoded key (RawKey()) or the row's metadata (Meta()).

When the index is known only at run time, use Table.ScanIndexDef, TryLookupIndexDef and LookupKeyIndexDef with an *edb.IndexDef. The lookups take the key as a reflect.Value of type IndexDef.KeyType().

For a join, call Get on another table inside the loop. For reads too large for one transaction, edb.ReadChunks opens a new read transaction per chunk, and scan.Resume(bookmark).Chunk(n) continues a scan in a later transaction. scan.KeyCursor() supports Union and Intersect over primary keys before any row is read. See scans.

Read fields without decoding a row

CustomerRows decodes every field of every row it returns. Customers returns a record instead: a handle to the stored bytes that reads only the properties you ask for.

func PointBalance(r kvo.Record) int64 {
    return r.Get(Customer_PointsEarned) - r.Get(Customer_PointsRedeemed)
}

func balanceFromRecords(tx *edb.Tx, tag string) int64 {
    var total int64
    for customer := range Customers.ExactIndexScan(tx, customersByTagIndex, tag).Records() {
        total += PointBalance(customer)
    }
    return total
}

Customers has the same reads and scans as CustomerRows. Get and Lookup return a kvo.Record; check r.Missing() instead of nil. Scans yield Records(), Entries() and Keys(). A record read works on every storage format.

Edit a row in a write transaction
func redeem(db *edb.DB, id uint64, points int64) error {
    return db.Tx(edb.TxMetadata{}, true, func(tx *edb.Tx) error {
        edit := Customers.Edit(tx, id)
        if edit == nil {
            return fmt.Errorf("customer %d not found", id)
        }
        balance := edit.Get(Customer_PointsEarned) - edit.Get(Customer_PointsRedeemed)
        if points <= 0 || points > balance {
            return fmt.Errorf("cannot redeem %d points from a balance of %d", points, balance)
        }
        edit.Set(Customer_PointsRedeemed, edit.Get(Customer_PointsRedeemed)+points)
        Customers.Save(tx, edit)
        return nil
    })
}
  • Edit opens a private copy of the row, or returns nil. New prepares an insert under a key. EditOrCreate does one or the other.
  • Save writes the edit and updates the indexes. It reports whether stored data changed. It panics if the row was written again after the edit was opened; TrySave returns that error.
  • An edit changes only the properties you set. Fields of a MessagePack row that the model does not list stay as they are.
  • Customers.Put(tx, key, record) replaces a whole row. PutChecked replaces it only if its ValueMeta still matches the one from TryGet.
  • Customers.Delete(tx, key) deletes a row.
Keys and lifetimes of records

A record does not hold its primary key, unless the model declares a primary key property. Keep the key you passed to Get, take it from Lookup, or iterate Entries():

for id, customer := range Customers.Scan(tx).Entries() {
    fmt.Println(id, PointBalance(customer))
}

A record borrows memory from its transaction. So do the strings and lists you read from it. Do not use them after the transaction ends. To keep a record longer, copy it first:

var saved kvo.Record
db.Read(func(tx *edb.Tx) {
    saved = Customers.Get(tx, 101).Own()
})
fmt.Println(saved.Get(Customer_FirstName))
  • Own() copies the stored bytes without decoding them. Clone() makes a deep copy that shares nothing with the original.
  • Rows from CustomerRows and keys from Keys() and Entries() are ordinary Go values. You own them.
  • To see the current state in a later transaction, keep the key and read the row again.

The KVO access guide covers lists, maps, nested records and the cost of each way to read a record.

Composite keys

A struct key is stored as a tuple of its fields, in order:

type StatsKey struct {
    CustomerID uint64
    Day        string // YYYY-MM-DD sorts by date
}

for key := range stats.Prefix(tx, StatsKey{CustomerID: 101}, 1).Keys() {
    fmt.Println(key.Day)
}

stats is a table declared with edb.TableBuilder[StatsKey]. The join example declares it and joins it with customers.

Single values

A map holds named values that are not rows, such as settings or a job's position:

var (
    globals       = edb.AddKVMap(DBSchema, "globals")
    lastImportKey = edb.AddSingletonKey[ImportState](globals, "last_import")
)

var state ImportState
found := edb.SGet(tx, lastImportKey, &state)
state.Count++
edb.SPut(tx, lastImportKey, &state)

Values are encoded as MessagePack. Table and map names share one namespace.

Change notifications

tx.OnChange calls a handler after each insert, update and delete in that transaction, with the old and new row as records or structs. Use it to keep caches and derived data current. See change notifications.

Storage formats and migrations

Storage formats
Format Use
MessagePack Default for tables.
Fast2 Selected with SetRecordStorage. Fields are indexed for direct reads.
Compact2 Selected with SetRecordStorage. Smaller rows.
Fast1 Only for tables declared with edb.DefineKVTable, a separate older API.

The format of a row does not limit how you read it. Struct reads, record reads and index callbacks work on MessagePack, Fast2 and Compact2 rows, and one table can hold rows in more than one format. The KVO documentation describes the encodings.

SetRecordStorage applies to new keys. A row that is already stored keeps its format when it is updated. To move a table to Fast2:

  1. Deploy edb.RecordStorage{Format: edb.Fast2, MessagePackInserts: true}. Every running binary can now read Fast2, and none writes it yet.
  2. Remove MessagePackInserts. New keys are stored as Fast2.
  3. Convert the existing rows in write transactions:
db.Write(edb.TxMetadata{Kind: "maintenance:upgrade_customers"}, func(tx *edb.Tx) {
    for _, id := range ids {
        tx.UpgradeRecord(Customers, id)
    }
})

UpgradeRecord returns false if the row is missing or already converted. It keeps the row's modification count and sends no change notification. It panics if the row does not survive the conversion unchanged, if the index entries would differ, or if the row is not at the table's schema version; TryUpgradeRecord returns the error. Convert in batches; do not hold one long write transaction.

Schema versions

Every row stores the schema version it was written with. A table starts at version 1. To change the meaning of stored data, raise the version and add a migrator:

// Inside the DefineTable callback:
b.SetSchemaVersion(2)
b.AddMigrator(2, func(tx *edb.Tx, key uint64, customer *kvo.Editor) {
    customer.Set(Customer_FirstName, strings.TrimSpace(customer.Get(Customer_FirstName)))
})
  • A migrator runs when a row with a version below its target is loaded. Migrators run in the order they were added.
  • A read migrates the row in memory only. A save or a reindex stores the migrated row with the new version.
  • A migrator must not change the primary key or keep the editor.
  • Keep old properties declared while a migrator reads them.

Adding a field needs no migration: an absent field reads as its zero value.

Storage compatibility lists what must stay stable when you move or rename Go types.

Go as a query language

A query, a report or a business rule over EDB tables is a Go function. EVM compiles Go source at run time and runs it inside your process. With it, an application can accept such functions as scripts, for example from an admin console or a plugin, without a new build.

The application decides what a script can reach. EDB supplies three pieces:

  • Rows. A record from Get or from a scan is the value EVM passes to a script. A script reads customer.points_earned on the stored row, inside the transaction that produced it. evm.ModelPackage turns the models of your tables into the package that scripts import.
  • Transactions and scans. edb.TransactionBindingSource holds the Go declarations of Tx, TxMetadata, ValueMeta, RawRange and the table and index definitions; edb.BindingSource holds ValueMeta alone. Pass one to evmbind.New and select the types, methods and functions that scripts get. In a script, tx.KVGetRaw lends the stored bytes for reads. A write or escape copies the backing once for all aliases. Go callers borrow read-only bytes until the next write or transaction end. Use bytes.Clone to modify or retain them.
  • Struct rows. TableBuilder.SetNativeSchema takes the application's evmbind schema. Struct rows of that table then use the same field access and type identity as the application's other bindings.

The loyalty example compiles a bonus rule and an HTML template and runs both on a stored customer. The evm documentation covers the language subset, host bindings and execution limits.

Technical details

Buckets

Each table has a bbolt bucket with nested buckets: tablename/data for rows and tablename/i_<indexname> for each index. A map has one bucket.

db.Bolt() and tx.BoltTx() return the bbolt database and transaction. Both return nil for the in-memory database.

Key encoding

A key is a tuple of components. Integers take 8 bytes, big-endian; strings are stored as their bytes. The encoded key is all components joined, then the length of every component except the last, then the number of components. The lengths and the count are variable-length integers written in reverse, so they are read from the end. A single-component key has one byte of overhead.

An index entry's key is the index key with the encoded primary key added as the last component. Its value is empty.

Value encoding

A stored row is a header, the row data and the row's index keys.

The header is five unsigned varints: flags, schema version, modification count, data size, index size. The flags tell MessagePack rows from Fast2 and Compact2 rows.

The index keys list every entry the row added to an index: the count, then for each entry the index ordinal, the key length and the key bytes. EDB uses the list to delete the old entries when the row changes, even if the index callback has changed since.

Table states

Each table has a state document under the _state key of its bucket. It assigns every index an ordinal, a positive integer that is never reused, and records which indexes are filled.

Performance

Count the work of a whole operation: the rows it visits, the fields it reads, whether it decodes rows, and what it keeps after the transaction.

  • A record read of a scalar field allocates nothing per row once the transaction and the cursor are open. A struct read allocates the struct and its fields.
  • Keys() reads no row data. String and composite keys allocate one value per key.
  • Opening a transaction or a cursor, migrating a row, Own(), Clone(), edits and saves allocate.
  • Measure the complete request with -benchmem.
Measurement Report
Table scans, joins and key types Typed rows and records
Chunked scans and key set operations Scans
Reads, inserts, edits and reindexing per format Encoded record reads and writes
Index callbacks Index callbacks
Table and index handles Typed handles

Documentation

research/ holds past experiments and audits. It does not describe the current API.

Development

go test ./...             # bbolt
go test -short ./...      # in-memory backend
go test ./examples/loyalty

Run both suites after a change to storage or scans. Run gofmt. Tests live next to the code they cover. AGENTS.md describes the layout and conventions.

Auto-testing via modd (go install github.com/cortesi/modd/cmd/modd@latest):

modd

Bug reports and benchmarks that reproduce are welcome.

License

Copyright (c) 2023 Andrey Tarantsov. Published under the Zero-Clause BSD license.

Documentation

Overview

Package edb implements a document database on top of a key-value store (bbolt, or an in-memory store for tests).

We implement:

1. Tables, collections of rows. A row is a Go struct; its first field is the primary key. A table can also read and edit a stored row as a record, one field at a time, without decoding the row.

2. Indices, allowing quick lookup of table rows by custom values.

3. Maps, exposing raw key-value buckets with string keys and untyped values.

4. Singleton Keys, allowing to store a typed value for a given key within a map (say, a “config” value in a “globals” map).

Every operation runs inside a transaction: see DB.Tx, DB.Read and DB.Write. Tables are declared with DefineTable.

Technical Details

**Buckets.** We rely on scoped namespaces for keys called buckets. Bolt supports them natively. A flat database could simulate buckets via key prefixes. We use nested buckets in Bolt (tablename/data and tablename/i_indexname), but only for convenience; flat buckets are fine.

**Index ordinals.** We assign a unique positive integer ordinal to each index. These values are never reused, even if an index is removed.

**Table states.** We store a meta document per table, called “table state”. This document holds the information about which indexes are defined for the table, and assigns an ordinal to each one.

## Binary encoding

**Key encoding**. Keys are encoded using a tuple encoding: all components, then the lengths of all components except the last, then the number of components.

**Value**: value header, then encoded data, then encoded index key records.

**Value header**: 1. Flags (uvarint). 2. Schema version (uvarint). 3. Modification count (uvarint). 4. Data size (uvarint). 5. Index size (uvarint).

**Value data**: the row encoded as MessagePack, Fast2 or Compact2; see StorageFormat. The flags tell MessagePack rows from Fast2 and Compact2 rows.

**Index key records** (inside a value) record the keys contributed by this row. If index computation changes in the future, we still need to know which index keys to delete when updating the row, so we store all index keys. Format: 1. Number of entries (uvarint). 2. For each entry: index ordinal (uvarint), key length (uvarint), key bytes.

Index

Constants

View Source
const (
	DumpTableHeaders = DumpFlags(1 << iota)
	DumpRows
	DumpStats
	DumpIndices
	DumpIndexRows

	DumpAll = DumpFlags(0xFFFFFFFFFFFFFFFF)
)
View Source
const (
	MsgPack encodingMethod = iota
	JSON
)
View Source
const (
	ScanMethodFull = ScanMethod(iota)
	ScanMethodExact
	ScanMethodRange
)
View Source
const InMemory = "memory:"

Variables

View Source
var (
	ErrReplicationOverload      = errors.New("edb: replication RAM capacity exhausted")
	ErrReplicationGroupSize     = errors.New("edb: replication group exceeds limit")
	ErrReplicationSchema        = errors.New("edb: unsupported replication schema revision")
	ErrReplicationShardChange   = errors.New("edb: shard change requires explicit delete and put")
	ErrReplicationTransactionID = errors.New("edb: replication transaction ID must advance")
	ErrReplicationPoisoned      = errors.New("edb: replication capture is poisoned")
)
View Source
var (
	ReaderCount atomic.Int64
	WriterCount atomic.Int64
)
View Source
var BindingSource embed.FS

BindingSource contains native declarations for source-based host bindings. Consumers select their public types and cache the resulting binding schema.

View Source
var Break = errors.New("break")
View Source
var ErrBucketNotFound = errors.New("bucket not found")

ErrBucketNotFound is returned by StorageTx.DeleteBucket when the bucket doesn't exist.

View Source
var ErrLocalWriteRejected = errors.New("edb: local application writes are fenced")
View Source
var ErrNoRecordBinding = errors.New("table has no record binding")
View Source
var ErrRecordSchemaVersion = errors.New("row needs a schema migration before record access")
View Source
var TransactionBindingSource embed.FS

TransactionBindingSource supplies the native transaction declarations. Consumers select types and the fields/methods needed by their host API.

Functions

func All

func All[Row any](c Cursor[Row]) []*Row

func AllKeys

func AllKeys[Key any](c RawCursor) []Key

func AllLimited added in v0.1.6

func AllLimited[Row any](c Cursor[Row], limit int) []*Row

func AllRawKeys

func AllRawKeys(c RawCursor) [][]byte

func AllTableRows

func AllTableRows[Row any](txh Txish) []*Row

func AllUntypedKeys

func AllUntypedKeys(c RawCursor) []any

func Count added in v0.1.6

func Count(c RawCursor) int

func CountAll

func CountAll(txh Txish, tblArg AnyTable) int

func DeleteAll

func DeleteAll(c RawCursor) int

func DeleteByKey

func DeleteByKey[Row any](txh Txish, key any) bool

func DeleteRow

func DeleteRow[Row any](txh Txish, row *Row) bool

func Exists

func Exists[Row any](txh Txish, key any) bool

func Filter added in v0.1.1

func Filter[Row any](c Cursor[Row], f func(*Row) bool) []*Row

func First added in v0.1.1

func First[Row any](c Cursor[Row]) *Row

func FirstKey added in v0.3.25

func FirstKey[Key, Row any](c Cursor[Row]) Key

func Get

func Get[Row any](txh Txish, key any) *Row

func GetByKeyRaw added in v0.1.6

func GetByKeyRaw[Row any](txh Txish, keyRaw []byte) *Row

func IndexPrimaryKey added in v0.4.13

func IndexPrimaryKey[Key any](v values.Value) Key

IndexPrimaryKey decodes a callback's primary-key cell using the table's exact Go key type. Scalars also support AsUint, AsString, etc. Aggregate keys use native Go storage, not VM cell arrays. Returned strings and slices are borrowed; neither they nor the original cell may be retained or mutated by the callback.

func Lookup

func Lookup[Row any](txh Txish, idxArg AnyIndex, indexKey any) *Row

func LookupExists added in v0.2.0

func LookupExists(txh Txish, idxArg AnyIndex, indexKey any) bool

func LookupKey

func LookupKey[Key any](txh Txish, idxArg AnyIndex, indexKey any) (Key, bool)

func Memo

func Memo[T any](txish Txish, key string, f func() (T, error)) (T, error)

func Proto

func Proto[T any]() any

func Put

func Put(txh Txish, rows ...any) bool

func PutByKey added in v0.4.13

func PutByKey[Row any](txh Txish, key any, row *Row) bool

PutByKey is the explicitly keyed counterpart of Put for native Go rows.

func ReadChunks added in v0.4.13

func ReadChunks[S chunkScan[C], C scanChunk](db *DB, metadata TxMetadata, limit int, query func(*Tx) S) iter.Seq[C]

ReadChunks yields nonempty chunks, opening and closing a read transaction for each one. query must return the same query using the supplied transaction on each call; an initial Resume bookmark is honored. Both RecordScan and RowScan are supported, with their corresponding chunk type inferred automatically.

Use the yielded chunk as Txish for joins. Breaking the outer loop, returning, or panicking closes its transaction. Breaking an inner iteration ends that chunk early and the next starts after the last consumed entry. Leaving a chunk entirely unconsumed stops the scan rather than looping forever.

The loop body holds a read transaction; perform writes outside it. Use Chunk with explicit transaction boundaries for read-then-write batches.

Each chunk sees a NEW snapshot. This is not a consistent whole-database export: writes between chunks can add, remove, or move entries. Retain records with Own before leaving a chunk. Never mutate the scanned index while walking its cursor; collect keys first, close the reader, then write.

func ReadReplicationStatus added in v0.4.17

func ReadReplicationStatus(path string) (uint64, error)

func Reload

func Reload[Row any](txh Txish, row *Row) *Row

func SGet

func SGet[T any](txh Txish, sk *SKey[T], v *T) bool

func SGetRaw

func SGetRaw[T any](txh Txish, sk *SKey[T]) []byte

SGetRaw returns the encoded value, bypassing the key's declared value type.

func SPut

func SPut[T any](txh Txish, sk *SKey[T], v *T)

func SPutRaw

func SPutRaw[T any](txh Txish, sk *SKey[T], raw []byte)

SPutRaw stores encoded bytes without validating their value type.

func Select added in v0.1.1

func Select[Row any](c Cursor[Row], f func(*Row) bool) *Row

Types

type AnyIndex added in v0.4.13

type AnyIndex interface{ IndexDef() *IndexDef }

AnyIndex accepts a typed index or its shared definition.

type AnyTable added in v0.4.13

type AnyTable interface {
	TableDef() *TableDef
}

AnyTable accepts a typed table or its shared definition. Database operations resolve the definition once; cursors and caches retain the concrete pointer.

type BatchCommitStats added in v0.4.19

type BatchCommitStats struct {
	PageAllocBytes int64
	WriteDuration  time.Duration
}

type BatchObservation added in v0.4.19

type BatchObservation struct {
	Outcome      BatchOutcome
	CallbacksRun int
	CommitStats  *BatchCommitStats
}

type BatchOutcome added in v0.4.19

type BatchOutcome uint8
const (
	BatchCommitted BatchOutcome = iota + 1
	BatchCallbackAborted
)

type Change added in v0.2.0

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

func (*Change) HasKey added in v0.2.0

func (chg *Change) HasKey() bool

func (*Change) HasNewGoStruct added in v0.4.13

func (chg *Change) HasNewGoStruct() bool

func (*Change) HasNewRecord added in v0.4.13

func (chg *Change) HasNewRecord() bool

func (*Change) HasOldGoStruct added in v0.4.13

func (chg *Change) HasOldGoStruct() bool

func (*Change) HasOldRecord added in v0.4.13

func (chg *Change) HasOldRecord() bool

func (*Change) Key added in v0.2.0

func (chg *Change) Key() any

func (*Change) KeyVal added in v0.2.0

func (chg *Change) KeyVal() reflect.Value

func (*Change) NewGoStruct added in v0.4.13

func (chg *Change) NewGoStruct() any

NewGoStruct returns an independently decoded *T, or nil when absent or not requested. It contains all persisted fields, including fields outside a KVO projection, and the database primary key. Mutating it does not save changes.

func (*Change) NewGoStructVal added in v0.4.13

func (chg *Change) NewGoStructVal() reflect.Value

func (*Change) NewRecord added in v0.4.13

func (chg *Change) NewRecord() kvo.Record

NewRecord returns the requested post-write record; it is missing for deletes. Records borrow transaction data. Call Own to retain one beyond the transaction.

func (*Change) OldGoStruct added in v0.4.13

func (chg *Change) OldGoStruct() any

OldGoStruct returns an independently decoded pre-write *T, or nil when absent, not requested, or unreadable. Old-value decode errors are logged when possible and do not prevent repairing or deleting a damaged value.

func (*Change) OldGoStructVal added in v0.4.13

func (chg *Change) OldGoStructVal() reflect.Value

func (*Change) OldRecord added in v0.4.13

func (chg *Change) OldRecord() kvo.Record

OldRecord returns the requested pre-write record; it is missing for inserts or when decoding the old value fails. Like NewRecord, it borrows transaction data.

func (*Change) Op added in v0.2.0

func (chg *Change) Op() Op

func (*Change) RawKey added in v0.2.0

func (chg *Change) RawKey() []byte

func (*Change) Table added in v0.2.0

func (chg *Change) Table() *TableDef

type ChangeFlags added in v0.2.0

type ChangeFlags uint64
const (
	ChangeFlagNotify ChangeFlags = 1 << iota
	ChangeFlagIncludeKey
	ChangeFlagIncludeNewRecord
	ChangeFlagIncludeOldRecord
	ChangeFlagIncludeNewGoStruct
	ChangeFlagIncludeOldGoStruct
)

func (ChangeFlags) Contains added in v0.2.0

func (v ChangeFlags) Contains(f ChangeFlags) bool

func (ChangeFlags) ContainsAny added in v0.2.0

func (v ChangeFlags) ContainsAny(f ChangeFlags) bool

type Cursor

type Cursor[Row any] struct {
	RawCursor
}

func ExactIndexScan

func ExactIndexScan[Row any](txh Txish, idxArg AnyIndex, indexValue any) Cursor[Row]

func ExactTableScan added in v0.1.6

func ExactTableScan[Row any](txh Txish, value any) Cursor[Row]

func FullIndexScan

func FullIndexScan[Row any](txh Txish, idxArg AnyIndex) Cursor[Row]

func FullReverseTableScan added in v0.1.4

func FullReverseTableScan[Row any](txh Txish) Cursor[Row]

func FullTableScan added in v0.1.1

func FullTableScan[Row any](txh Txish) Cursor[Row]

func IndexScan

func IndexScan[Row any](txh Txish, idxArg AnyIndex, opt ScanOptions) Cursor[Row]

func PrefixIndexScan

func PrefixIndexScan[Row any](txh Txish, idxArg AnyIndex, els int, indexValue any) Cursor[Row]

func RangeIndexScan added in v0.1.6

func RangeIndexScan[Row any](txh Txish, idxArg AnyIndex, lowerValue, upperValue any, lowerInc, upperInc bool) Cursor[Row]

func RangeTableScan added in v0.1.6

func RangeTableScan[Row any](txh Txish, lowerValue, upperValue any, lowerInc, upperInc bool) Cursor[Row]

func ReverseExactIndexScan added in v0.1.5

func ReverseExactIndexScan[Row any](txh Txish, idxArg AnyIndex, indexValue any) Cursor[Row]

func ReversePrefixIndexScan added in v0.1.5

func ReversePrefixIndexScan[Row any](txh Txish, idxArg AnyIndex, els int, indexValue any) Cursor[Row]

func ReverseRangeIndexScan added in v0.1.6

func ReverseRangeIndexScan[Row any](txh Txish, idxArg AnyIndex, lowerValue, upperValue any, lowerInc, upperInc bool) Cursor[Row]

func ReverseRangeTableScan added in v0.1.6

func ReverseRangeTableScan[Row any](txh Txish, lowerValue, upperValue any, lowerInc, upperInc bool) Cursor[Row]

func TableScan

func TableScan[Row any](txh Txish, opt ScanOptions) Cursor[Row]

func (Cursor[Row]) Key

func (c Cursor[Row]) Key() any

func (Cursor[Row]) Meta

func (c Cursor[Row]) Meta() ValueMeta

func (Cursor[Row]) Next

func (c Cursor[Row]) Next() bool

func (Cursor[Row]) Raw added in v0.1.6

func (c Cursor[Row]) Raw() RawCursor

func (Cursor[Row]) Record added in v0.4.13

func (c Cursor[Row]) Record() kvo.Record

Record panics on error. Use TryRecord to handle errors explicitly.

func (Cursor[Row]) RecordEdit added in v0.4.13

func (c Cursor[Row]) RecordEdit() *RecordEdit

RecordEdit panics on error. Use TryRecordEdit to handle errors explicitly.

func (Cursor[Row]) Row

func (c Cursor[Row]) Row() *Row

func (Cursor[Row]) RowInto added in v0.4.13

func (c Cursor[Row]) RowInto(dst *Row) (ValueMeta, error)

RowInto replaces *dst with the current row. A scan can reuse the same struct on each iteration. Use Row when handing independently owned rows to another consumer. Maps and slices from earlier rows are never reused.

func (Cursor[Row]) RowVal

func (c Cursor[Row]) RowVal() (reflect.Value, ValueMeta)

func (Cursor[Row]) Rows added in v0.3.14

func (c Cursor[Row]) Rows() func(yield func(*Row) bool)

func (Cursor[Row]) TryRecord added in v0.4.13

func (c Cursor[Row]) TryRecord() (kvo.Record, ValueMeta, error)

func (Cursor[Row]) TryRecordEdit added in v0.4.13

func (c Cursor[Row]) TryRecordEdit() (*RecordEdit, error)

TryRecordEdit opens the current cursor row for writing without full decoding when its codec supports direct access. It retains the stale-save check. Call it after a successful Next, while the cursor is positioned on the row.

type DB

type DB struct {
	ReaderCount        atomic.Int64
	WriterCount        atomic.Int64
	PendingWriterCount atomic.Int64
	ReadCount          atomic.Uint64
	WriteCount         atomic.Uint64
	// contains filtered or unexported fields
}

func Open

func Open(path string, schema *Schema, opt Options) (*DB, error)

func (*DB) AllowsLocalWrites added in v0.4.17

func (db *DB) AllowsLocalWrites() bool

func (*DB) AllowsRowMigrations added in v0.4.17

func (db *DB) AllowsRowMigrations() bool

AllowsRowMigrations exposes the policy for application migration schedulers. The application remains responsible for gating its jobs and external effects.

func (*DB) ApplyReplication added in v0.4.17

func (db *DB) ApplyReplication(g *ReplicationGroup) error

ApplyReplication consumes one complete replication log-validated source group. The consumer validates history/filter continuity and delivers groups in order. Caller-owned bytes must remain valid until return; failed groups can be retried.

func (*DB) BeginRead

func (db *DB) BeginRead(metadata TxMetadata) (tx *Tx)

func (*DB) BeginUpdate

func (db *DB) BeginUpdate(metadata TxMetadata) (tx *Tx)

func (*DB) Bolt

func (db *DB) Bolt() *bbolt.DB

func (*DB) Close

func (db *DB) Close()

Close is safe to call multiple times, but not concurrently.

func (*DB) CloseWithSafeToQuitCallback added in v0.3.23

func (db *DB) CloseWithSafeToQuitCallback(safeToQuit func())

Close is safe to call multiple times, but not concurrently.

func (*DB) DescribeOpenTxns added in v0.1.6

func (db *DB) DescribeOpenTxns() string

func (*DB) IsClosed added in v0.3.12

func (db *DB) IsClosed() bool

func (*DB) Read

func (db *DB) Read(metadata TxMetadata, f func(tx *Tx))

func (*DB) ReadErr

func (db *DB) ReadErr(metadata TxMetadata, f func(tx *Tx) error) error

func (*DB) ReplicationPoisoned added in v0.4.17

func (db *DB) ReplicationPoisoned() (bool, error)

func (*DB) ReplicationStatus added in v0.4.17

func (db *DB) ReplicationStatus() (committedID uint64, err error)

ReplicationStatus returns the database's last committed replication transaction ID from a snapshot. Capture allocates the next ID; apply preserves the incoming ID. Both update this checkpoint atomically with their data. Uncommitted/aborted attempts are invisible. Missing status is zero, even with replication disabled. This is neither a Bolt ID nor an external replication log cursor. The consumer validates history identity, detects gaps and chooses recovery policy.

func (*DB) Size added in v0.1.6

func (db *DB) Size() int64

func (*DB) Tx

func (db *DB) Tx(metadata TxMetadata, writable bool, f func(tx *Tx) error) error

Tx currently implements Check-Mutate phases for writable transactions:

Phase 1, Check: before any modifications are made. Runs inside bdb.Batch. Returning an error won't cause the entire batch to fail.

Phase 2, Mutate: from the first mutation. Runs inside bdb.Batch. The entire transaction will be retried in case of error.

TODO: split Mutate phase into Mutate and Post-Mutate phases:

Phase 1, Check (initial phase): inside bdb.Batch, error does not fail batch.

Phase 2, Mutate (initiated by any mutation call): inside bdb.Batch, error fails batch.

Phase 3, Read (initiated by explicit call like Commit): mutations committed, outside bdb.Batch, a new read-only tx is opened on demand.

Check-Mutate-Read would allow to avoid holding the batch during rendering.

A read-only transaction would be a natural extension of Check-Mutate-Read with Check and Mutate phases skipped.

func (*DB) Write

func (db *DB) Write(metadata TxMetadata, f func(tx *Tx))

func (*DB) WriteTx added in v0.4.20

func (db *DB) WriteTx(metadata TxMetadata, f func(tx *Tx) error) (committed bool, err error)

WriteTx runs a managed write transaction and reports whether its final attempt committed. The callback may be replayed. It must not commit or close tx itself. The callback error and the storage outcome are separate: a check that returns an error before writing can commit an empty attempt, and CommitDespiteError can commit writes while returning the callback error.

type DataError

type DataError struct {
	Data []byte
	Off  int
	Err  error
	Msg  string
}

func (*DataError) Error

func (e *DataError) Error() string

func (*DataError) Unwrap

func (e *DataError) Unwrap() error

type DumpFlags

type DumpFlags uint64

func (DumpFlags) Contains

func (f DumpFlags) Contains(v DumpFlags) bool

type FlatMarshaler

type FlatMarshaler interface {
	MarshalFlat(buf []byte) []byte
}

type FlatMarshallable

type FlatMarshallable interface {
	FlatMarshaler
	FlatUnmarshaler
}

type FlatUnmarshaler

type FlatUnmarshaler interface {
	UnmarshalFlat(buf []byte) error
}

type Index

type Index[IndexKey any] struct {
	// contains filtered or unexported fields
}

Index declares the index-key type. Table methods supply the primary-key type when looking up records or scanning index entries.

func (*Index[IndexKey]) IndexDef added in v0.4.13

func (i *Index[IndexKey]) IndexDef() *IndexDef

type IndexBuilder

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

func (*IndexBuilder) Add

func (b *IndexBuilder) Add(idxArg AnyIndex, value any) *IndexRow

func (*IndexBuilder) PrimaryKey added in v0.4.13

func (b *IndexBuilder) PrimaryKey() any

PrimaryKey decodes the row key for index expressions that need it. Add already associates each entry with its row.

type IndexDef added in v0.4.13

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

func (*IndexDef) DecodeIndexKeyVal added in v0.4.13

func (idx *IndexDef) DecodeIndexKeyVal(tup tuple) reflect.Value

func (*IndexDef) DecodeIndexKeyValInto added in v0.4.13

func (idx *IndexDef) DecodeIndexKeyValInto(keyVal reflect.Value, tup tuple)

func (*IndexDef) DecodeKeyVal added in v0.4.13

func (idx *IndexDef) DecodeKeyVal(rawKey []byte) reflect.Value

func (*IndexDef) DecodeKeyValInto added in v0.4.13

func (idx *IndexDef) DecodeKeyValInto(keyVal reflect.Value, rawKey []byte)

func (*IndexDef) EncodeKey added in v0.4.13

func (idx *IndexDef) EncodeKey(key any) []byte

func (*IndexDef) EncodeKeyVal added in v0.4.13

func (idx *IndexDef) EncodeKeyVal(keyVal reflect.Value) []byte

func (*IndexDef) FullName added in v0.4.13

func (idx *IndexDef) FullName() string

func (*IndexDef) IndexDef added in v0.4.13

func (i *IndexDef) IndexDef() *IndexDef

func (*IndexDef) IsUnique added in v0.4.13

func (idx *IndexDef) IsUnique() bool

func (*IndexDef) KeyString added in v0.4.13

func (idx *IndexDef) KeyString(key any) string

func (*IndexDef) KeyType added in v0.4.20

func (idx *IndexDef) KeyType() reflect.Type

KeyType is the declared native index-key type.

func (*IndexDef) ParseNakedIndexKey added in v0.4.13

func (idx *IndexDef) ParseNakedIndexKey(s string) (any, error)

func (*IndexDef) ParseNakedIndexKeyVal added in v0.4.13

func (idx *IndexDef) ParseNakedIndexKeyVal(s string) (reflect.Value, error)

func (*IndexDef) RawKeyString added in v0.4.13

func (idx *IndexDef) RawKeyString(keyRaw []byte) string

func (*IndexDef) ShortName added in v0.4.13

func (idx *IndexDef) ShortName() string

func (*IndexDef) Table added in v0.4.13

func (idx *IndexDef) Table() *TableDef

func (*IndexDef) TryDecodeKeyValInto added in v0.4.13

func (idx *IndexDef) TryDecodeKeyValInto(keyVal reflect.Value, rawKey []byte) error

type IndexInitialFillMode added in v0.4.4

type IndexInitialFillMode int
const (
	IndexInitialFillModeSkip IndexInitialFillMode = iota
	IndexInitialFillModeBlocking
)

type IndexOpt added in v0.2.0

type IndexOpt int
const (
	// Deprecated: use IndexInitialFillModeSkip.
	IndexOptSkipInitialFill IndexOpt = iota
	IndexOptDebugScans
	// IndexOptDeprecatedUnique stores one primary key per index key. Conflicting
	// writes retain the historical last-write-wins behavior, not a constraint.
	IndexOptDeprecatedUnique
)

func (IndexOpt) String added in v0.4.13

func (o IndexOpt) String() string

type IndexRow

type IndexRow struct {
	IndexOrd uint64
	Index    *IndexDef
	KeyRaw   []byte
	KeyBuf   []byte
	ValueRaw []byte
	ValueBuf []byte
}

type KVCursor added in v0.3.1

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

func (*KVCursor) IndexKeys added in v0.3.2

func (c *KVCursor) IndexKeys() func(yield func(k []byte) bool)

func (*KVCursor) Keys added in v0.3.1

func (c *KVCursor) Keys() func(yield func(k []byte) bool)

func (*KVCursor) Next added in v0.3.1

func (c *KVCursor) Next() bool

func (*KVCursor) Object added in v0.3.1

func (c *KVCursor) Object() fast1.ImmutableMap

func (*KVCursor) Objects added in v0.3.1

func (c *KVCursor) Objects() func(yield func(k []byte, o fast1.ImmutableMap) bool)

func (*KVCursor) RawIndexKey added in v0.3.2

func (c *KVCursor) RawIndexKey() []byte

RawIndexKey returns the read-only index key, or nil for a table scan.

func (*KVCursor) RawKey added in v0.3.1

func (c *KVCursor) RawKey() []byte

RawKey returns the read-only primary key.

func (*KVCursor) RawValue added in v0.3.1

func (c *KVCursor) RawValue() []byte

RawValue returns the read-only stored value.

func (*KVCursor) RawValues added in v0.3.1

func (c *KVCursor) RawValues() func(yield func(k, v []byte) bool)

type KVIndex added in v0.3.2

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

func (*KVIndex) FullName added in v0.3.2

func (idx *KVIndex) FullName() string

func (*KVIndex) ShortName added in v0.3.2

func (idx *KVIndex) ShortName() string

func (*KVIndex) Table added in v0.3.2

func (idx *KVIndex) Table() *KVTable

type KVIndexContentBuilder added in v0.3.2

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

func (*KVIndexContentBuilder) Add added in v0.3.2

func (b *KVIndexContentBuilder) Add(ik []byte)

type KVIndexKey added in v0.3.2

type KVIndexKey interface {
	Clone() KVIndexKey
	PutBytes(raw []byte) bool
	String() string
	FillPrimaryKey(pk KVKey)
}

type KVIndexKeyToPrimaryKey added in v0.3.2

type KVIndexKeyToPrimaryKey = func(ik []byte) []byte

type KVIndexer added in v0.3.2

type KVIndexer = func(b *KVIndexContentBuilder, pk []byte, v fast1.ImmutableRecord)

type KVKey added in v0.3.2

type KVKey interface {
	Clone() KVKey
	PutBytes(raw []byte) bool
	String() string
}

type KVMap

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

func AddKVMap

func AddKVMap(scm *Schema, name string) *KVMap

func (*KVMap) Name added in v0.4.17

func (mp *KVMap) Name() string

func (*KVMap) NameHash added in v0.4.17

func (mp *KVMap) NameHash() uint64

NameHash returns xxHash64 of the lowercase registered name, cached at declaration.

type KVTable added in v0.3.0

type KVTable struct {
	TaggableImpl
	// contains filtered or unexported fields
}

func DefineKVTable added in v0.3.0

func DefineKVTable(scm *Schema, name string, rootModel *kvo.Model, keySample KVKey, build func(b *KVTableBuilder)) *KVTable

func DefineRawTable added in v0.3.3

func DefineRawTable(scm *Schema, name string, build func(b *KVTableBuilder)) *KVTable

func (*KVTable) KeyBytesToString added in v0.3.2

func (tbl *KVTable) KeyBytesToString(k []byte) string

func (*KVTable) Name added in v0.3.0

func (tbl *KVTable) Name() string

func (*KVTable) NameHash added in v0.4.17

func (tbl *KVTable) NameHash() uint64

NameHash returns xxHash64 of the lowercase registered name, cached at declaration.

func (*KVTable) NewKey added in v0.3.2

func (tbl *KVTable) NewKey() KVKey

func (*KVTable) RootModel added in v0.3.2

func (tbl *KVTable) RootModel() *kvo.Model

func (*KVTable) RootType added in v0.3.4

func (tbl *KVTable) RootType() kvo.AnyType

type KVTableBuilder added in v0.3.0

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

func (*KVTableBuilder) DefineIndex added in v0.3.2

func (b *KVTableBuilder) DefineIndex(name string, keySample KVIndexKey, resolver KVIndexKeyToPrimaryKey, indexer KVIndexer) *KVIndex

func (*KVTableBuilder) Tag added in v0.3.8

func (b *KVTableBuilder) Tag(tag *Tag)

type KeyCursor added in v0.4.13

type KeyCursor[Key any] struct {
	// contains filtered or unexported fields
}

KeyCursor is a single-pass primary-key stream. It never fetches row payloads. Keys decodes owned Go keys; RawKey borrows the current transaction's storage. A cursor and any union/intersection built from it stay in that transaction.

func (*KeyCursor[Key]) Intersect added in v0.4.13

func (c *KeyCursor[Key]) Intersect(others ...*KeyCursor[Key]) *KeyCursor[Key]

Intersect consumes its inputs with the same rules as Union, emitting only keys present in every input. It does not read or decode any rows.

func (*KeyCursor[Key]) Key added in v0.4.13

func (c *KeyCursor[Key]) Key() Key

func (*KeyCursor[Key]) Keys added in v0.4.13

func (c *KeyCursor[Key]) Keys() iter.Seq[Key]

func (*KeyCursor[Key]) Next added in v0.4.13

func (c *KeyCursor[Key]) Next() bool

func (*KeyCursor[Key]) RawKey added in v0.4.13

func (c *KeyCursor[Key]) RawKey() []byte

func (*KeyCursor[Key]) Union added in v0.4.13

func (c *KeyCursor[Key]) Union(others ...*KeyCursor[Key]) *KeyCursor[Key]

Union consumes c and the other cursors, returning each primary key once. Inputs must scan the same table, transaction, and direction and be ordered by primary key. Do not reuse an input cursor after composing it. Encoded keys are compared directly, including strings and composite keys; only emitted keys are decoded. Setup costs O(inputs) space, with no per-key allocations from merging. Native key decoding may allocate for strings/custom key types.

Exact index scans with non-unsigned keys receive a key-only preflight pass: tuple-footer bytes embedded in variable-length keys can violate primary-key order. An inversion panics before any results are emitted; use materialized sets for such key domains. Built-in unsigned keys need no extra pass.

type LocalWriteMode added in v0.4.17

type LocalWriteMode uint8
const (
	AllowLocalWrites LocalWriteMode = iota
	RejectLocalWrites
)

func (LocalWriteMode) String added in v0.4.17

func (p LocalWriteMode) String() string

type LocalWritePolicy added in v0.4.17

type LocalWritePolicy struct {
	Mode    LocalWriteMode
	Include func(ReplicationObject) bool
}

LocalWritePolicy controls application mutations, not DDL, apply or index maintenance.

type Op added in v0.2.0

type Op int
const (
	OpNone   Op = 0
	OpPut    Op = 1
	OpDelete Op = 2
)

func (Op) String added in v0.2.0

func (v Op) String() string

type Options

type Options struct {
	// Policies are independent of replication capabilities; zero values preserve existing behavior.
	LocalWrites   LocalWritePolicy
	RowMigrations RowMigrationPolicy
	Replication   *ReplicationOptions
	Logf          func(format string, args ...any)
	Verbose       bool
	IsTesting     bool
	MmapSize      int

	NoPersistentFreeList    bool
	CaptureTxStack          bool
	ReuseTxBuffers          bool
	ObserveWriteTransaction func(TxObservation)
	ObserveReadTransaction  func(TxObservation)
	TxObserveBatch          func(BatchObservation)
}

type RawCursor

type RawCursor interface {
	Bookmark() ScanBookmark
	Table() *TableDef
	Tx() *Tx
	Next() bool
	Key() any
	// UintKey returns the primary key as uint64. It accepts unsigned integer
	// types, including named types, and panics for other key types. The built-in
	// unsigned encoding is read without reflection or allocation.
	UintKey() uint64
	RawKey() []byte
	RowVal() (reflect.Value, ValueMeta)
	TryRowVal() (reflect.Value, ValueMeta, error)
	Meta() ValueMeta
	Row() (any, ValueMeta)
	TryRow() (any, ValueMeta, error)
	RawRow() []byte
	Record() kvo.Record
	TryRecord() (kvo.Record, ValueMeta, error)
	ValueMemento() []byte
}

type RawIndexCursor

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

func (*RawIndexCursor) Bookmark added in v0.4.13

func (c *RawIndexCursor) Bookmark() ScanBookmark

Bookmark owns the complete index position. For nonunique indexes the primary key is part of the encoded position; unique indexes sort by index key alone.

func (*RawIndexCursor) IndexKey added in v0.1.6

func (c *RawIndexCursor) IndexKey() any

func (*RawIndexCursor) Key

func (c *RawIndexCursor) Key() any

func (*RawIndexCursor) Meta

func (c *RawIndexCursor) Meta() ValueMeta

func (*RawIndexCursor) Next

func (c *RawIndexCursor) Next() bool

func (*RawIndexCursor) RawKey

func (c *RawIndexCursor) RawKey() []byte

func (*RawIndexCursor) RawRow added in v0.2.0

func (c *RawIndexCursor) RawRow() []byte

func (*RawIndexCursor) Record added in v0.4.13

func (c *RawIndexCursor) Record() kvo.Record

Record panics on error. Use TryRecord to handle errors explicitly.

func (*RawIndexCursor) RecordEdit added in v0.4.13

func (c *RawIndexCursor) RecordEdit() *RecordEdit

RecordEdit panics on error. Use TryRecordEdit to handle errors explicitly.

func (*RawIndexCursor) Row

func (c *RawIndexCursor) Row() (any, ValueMeta)

func (*RawIndexCursor) RowVal

func (c *RawIndexCursor) RowVal() (reflect.Value, ValueMeta)

func (*RawIndexCursor) Table

func (c *RawIndexCursor) Table() *TableDef

func (*RawIndexCursor) TryRecord added in v0.4.13

func (c *RawIndexCursor) TryRecord() (kvo.Record, ValueMeta, error)

func (*RawIndexCursor) TryRecordEdit added in v0.4.13

func (c *RawIndexCursor) TryRecordEdit() (*RecordEdit, error)

func (*RawIndexCursor) TryRow added in v0.2.1

func (c *RawIndexCursor) TryRow() (any, ValueMeta, error)

func (*RawIndexCursor) TryRowVal added in v0.2.1

func (c *RawIndexCursor) TryRowVal() (reflect.Value, ValueMeta, error)

func (*RawIndexCursor) Tx

func (c *RawIndexCursor) Tx() *Tx

func (*RawIndexCursor) UintKey added in v0.4.13

func (c *RawIndexCursor) UintKey() uint64

UintKey returns the current row's unsigned primary key, not the index key.

func (*RawIndexCursor) ValueMemento added in v0.3.17

func (c *RawIndexCursor) ValueMemento() []byte

type RawRange added in v0.3.1

type RawRange struct {
	Prefix   []byte
	Lower    []byte
	Upper    []byte
	LowerInc bool
	UpperInc bool
	Reverse  bool
}

RawRange defines a range of byte strings. The constructors use mnemonics: O means open, I means inclusive, E means exclusive; the first letter is for the lower bound, the second for the upper bound.

func RawEE added in v0.3.1

func RawEE(l, u []byte) RawRange

func RawEI added in v0.3.1

func RawEI(l, u []byte) RawRange

func RawEO added in v0.3.1

func RawEO(l []byte) RawRange

func RawIE added in v0.3.1

func RawIE(l, u []byte) RawRange

func RawII added in v0.3.1

func RawII(l, u []byte) RawRange

func RawIO added in v0.3.1

func RawIO(l []byte) RawRange

func RawOE added in v0.3.1

func RawOE(u []byte) RawRange

func RawOI added in v0.3.1

func RawOI(u []byte) RawRange

func RawOO added in v0.3.1

func RawOO() RawRange

func RawPrefix added in v0.3.1

func RawPrefix(p []byte) RawRange

func (RawRange) Prefixed added in v0.3.1

func (rang RawRange) Prefixed(p []byte) RawRange

func (RawRange) Reversed added in v0.3.1

func (rang RawRange) Reversed() RawRange

type RawRangeCursor added in v0.3.1

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

func (*RawRangeCursor) Key added in v0.3.1

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

func (*RawRangeCursor) Next added in v0.3.1

func (c *RawRangeCursor) Next() bool

func (*RawRangeCursor) Value added in v0.3.1

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

type RawTableCursor

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

func (*RawTableCursor) Bookmark added in v0.4.13

func (c *RawTableCursor) Bookmark() ScanBookmark

Bookmark copies the last visited position, including after exhaustion. Call it before closing the transaction. It does not fetch or decode a row.

func (*RawTableCursor) Key

func (c *RawTableCursor) Key() any

func (*RawTableCursor) Meta

func (c *RawTableCursor) Meta() ValueMeta

func (*RawTableCursor) Next

func (c *RawTableCursor) Next() bool

func (*RawTableCursor) RawKey

func (c *RawTableCursor) RawKey() []byte

func (*RawTableCursor) RawRow added in v0.2.0

func (c *RawTableCursor) RawRow() []byte

func (*RawTableCursor) Record added in v0.4.13

func (c *RawTableCursor) Record() kvo.Record

Record panics on error. Use TryRecord to handle errors explicitly.

func (*RawTableCursor) RecordEdit added in v0.4.13

func (c *RawTableCursor) RecordEdit() *RecordEdit

RecordEdit panics on error. Use TryRecordEdit to handle errors explicitly.

func (*RawTableCursor) Row

func (c *RawTableCursor) Row() (any, ValueMeta)

func (*RawTableCursor) RowVal

func (c *RawTableCursor) RowVal() (reflect.Value, ValueMeta)

func (*RawTableCursor) Table

func (c *RawTableCursor) Table() *TableDef

func (*RawTableCursor) TryRecord added in v0.4.13

func (c *RawTableCursor) TryRecord() (kvo.Record, ValueMeta, error)

func (*RawTableCursor) TryRecordEdit added in v0.4.13

func (c *RawTableCursor) TryRecordEdit() (*RecordEdit, error)

func (*RawTableCursor) TryRow added in v0.2.1

func (c *RawTableCursor) TryRow() (any, ValueMeta, error)

func (*RawTableCursor) TryRowVal added in v0.2.1

func (c *RawTableCursor) TryRowVal() (reflect.Value, ValueMeta, error)

func (*RawTableCursor) Tx

func (c *RawTableCursor) Tx() *Tx

func (*RawTableCursor) UintKey added in v0.4.13

func (c *RawTableCursor) UintKey() uint64

UintKey returns the current unsigned primary key without boxing it.

func (*RawTableCursor) ValueMemento added in v0.3.17

func (c *RawTableCursor) ValueMemento() []byte

type RecordChunk added in v0.4.13

type RecordChunk[Key any] struct {
	// contains filtered or unexported fields
}

RecordChunk is a single-pass, bounded scan in one transaction. It implements Txish: pass the chunk to other table operations to join in the same snapshot. Records and their borrowed fields remain valid only within that transaction.

func (RecordChunk) Bookmark added in v0.4.13

func (c RecordChunk) Bookmark() ScanBookmark

Bookmark owns the last consumed position. An unconsumed chunk returns its starting bookmark. Capture it before closing the transaction.

func (RecordChunk) Count added in v0.4.13

func (c RecordChunk) Count() int

Count returns the number of entries consumed from this chunk, including entries rejected by application filters.

func (RecordChunk) DBTx added in v0.4.13

func (c RecordChunk) DBTx() *Tx

func (*RecordChunk[Key]) Entries added in v0.4.13

func (c *RecordChunk[Key]) Entries() iter.Seq2[Key, kvo.Record]

func (*RecordChunk[Key]) Keys added in v0.4.13

func (c *RecordChunk[Key]) Keys() iter.Seq[Key]

func (RecordChunk) More added in v0.4.13

func (c RecordChunk) More() bool

More finishes the chunk and checks for another matching entry without loading its row. After More, iteration is no longer allowed; Bookmark remains usable. This is a statement about this transaction's snapshot, not future writes.

func (*RecordChunk[Key]) Records added in v0.4.13

func (c *RecordChunk[Key]) Records() iter.Seq[kvo.Record]

func (RecordChunk) Tx added in v0.4.13

func (c RecordChunk) Tx() *Tx

Tx returns the current chunk's transaction. It must not be closed or replaced while iterating the chunk. DBTx also makes the chunk usable as a Txish.

type RecordEdit added in v0.4.13

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

RecordEdit holds a private edit of the row as it was opened in this write transaction. SaveRecord updates its revision so it can be saved again.

func (*RecordEdit) Delete added in v0.4.13

func (e *RecordEdit) Delete(p interface{ Code() uint64 })

func (*RecordEdit) Edit added in v0.4.13

func (e *RecordEdit) Edit(p *kvo.PropRef[kvo.Record]) *kvo.Editor

func (*RecordEdit) EditOrCreate added in v0.4.13

func (e *RecordEdit) EditOrCreate(p *kvo.PropRef[kvo.Record]) *kvo.Editor

func (*RecordEdit) Editor added in v0.4.13

func (e *RecordEdit) Editor() *kvo.Editor

func (*RecordEdit) Get added in v0.4.13

func (e *RecordEdit) Get[T any, P kvo.Property[T]](p P) T

Get and Set access an edit's typed properties directly. Editor exposes the underlying editor for advanced path and collection operations.

func (*RecordEdit) Has added in v0.4.13

func (e *RecordEdit) Has(p interface{ Code() uint64 }) bool

func (*RecordEdit) List added in v0.4.13

func (e *RecordEdit) List[E any, P kvo.ListProperty[E]](p P) E

func (*RecordEdit) Map added in v0.4.13

func (e *RecordEdit) Map[K comparable, V any](p *kvo.MapPropRef[K, V]) *kvo.MapEditor[K, V]

func (*RecordEdit) New added in v0.4.13

func (e *RecordEdit) New(p *kvo.PropRef[kvo.Record]) *kvo.Editor

func (*RecordEdit) Record added in v0.4.13

func (e *RecordEdit) Record() kvo.Record

func (*RecordEdit) Set added in v0.4.13

func (e *RecordEdit) Set[T any, P kvo.Property[T]](p P, value T)

func (*RecordEdit) Table added in v0.4.13

func (e *RecordEdit) Table() *TableDef

func (*RecordEdit) TrySet added in v0.4.13

func (e *RecordEdit) TrySet[T any, P kvo.Property[T]](p P, value T) error

type RecordScan added in v0.4.13

type RecordScan[Key any] struct {
	// contains filtered or unexported fields
}

RecordScan is a reusable scan description. Each iteration opens a fresh cursor in the same transaction. Records borrow their transaction's storage; retain them beyond it only after Record.Own. Keys are decoded values.

func (RecordScan[Key]) Chunk added in v0.4.13

func (s RecordScan[Key]) Chunk(limit int) *RecordChunk[Key]

Chunk opens a single-pass cursor yielding at most limit entries. Unlike a reusable scan, repeated iterations continue the same chunk. limit must be positive. Call Bookmark and More before closing the transaction to resume in a later transaction. Use ReadChunks to manage that loop automatically.

func (RecordScan[Key]) Entries added in v0.4.13

func (s RecordScan[Key]) Entries() iter.Seq2[Key, kvo.Record]

func (RecordScan) KeyCursor added in v0.4.13

func (s RecordScan) KeyCursor() *KeyCursor[Key]

KeyCursor opens an independent key-only cursor. Table scans and exact index scans can be merged with Union or Intersect (subject to the key ordering check described on Union). A general index scan is ordered by index key first, so it cannot be merged directly even when its primary keys happen to look sorted in a small sample.

func (RecordScan) Keys added in v0.4.13

func (s RecordScan) Keys() iter.Seq[Key]

Keys decodes primary keys without loading or decoding row payloads.

func (RecordScan) Raw added in v0.4.13

func (s RecordScan) Raw() RawCursor

Raw opens a cursor for low-level operations. It does not consume an earlier iteration; all scans and iterators must stay inside their transaction.

func (RecordScan[Key]) Records added in v0.4.13

func (s RecordScan[Key]) Records() iter.Seq[kvo.Record]

func (RecordScan[Key]) Resume added in v0.4.13

func (s RecordScan[Key]) Resume(b ScanBookmark) RecordScan[Key]

func (RecordScan[Key]) Reversed added in v0.4.13

func (s RecordScan[Key]) Reversed() RecordScan[Key]

type RecordStorage added in v0.4.13

type RecordStorage struct {
	// MessagePackInserts deploys the dual reader before enabling KVO on new keys.
	MessagePackInserts bool
	Format             StorageFormat
	Mode               nativebind.Mode
	Generated          *kvo.Generated
}

RecordStorage selects Fast2 or Compact2 for new keys. Format must be explicit. Existing keys keep their envelope version until UpgradeRecord converts them in a write transaction.

type ReplicationApplyOptions added in v0.4.17

type ReplicationApplyOptions struct {
	SchemaRev        uint64
	SupportsRevision func(uint64) bool
}

ReplicationApplyOptions accepts complete groups from a consumer-validated history. Apply never invokes row migrators or captures a new local change group.

type ReplicationCaptureOptions added in v0.4.17

type ReplicationCaptureOptions struct {
	BestEffort        bool
	NextTransactionID func(lastCommittedID uint64) (uint64, error)
	SchemaRev         uint64
	Include           func(ReplicationObject) bool
	// Shard resolves one stable shard per object/key. Empty success means global;
	// unknown attribution must return an error. Missing raw deletes pass Present=false.
	Shard func(ReplicationObject, []byte, ReplicationValue) ([]byte, error)
	Sink  ReplicationSink
}

type ReplicationChange added in v0.4.17

type ReplicationChange struct {
	Object  ReplicationObject
	Op      ReplicationOp
	Ordinal uint64
	Key     []byte
	Value   ReplicationValue
	Shard   []byte
}

type ReplicationGroup added in v0.4.17

type ReplicationGroup struct {
	TransactionID uint64
	SchemaRev     uint64
	Changes       []ReplicationChange
}

type ReplicationObject added in v0.4.17

type ReplicationObject struct {
	Table   *TableDef
	KVTable *KVTable
	Map     *KVMap
}

ReplicationObject carries local table/map descriptors for stable wire IDs. A replication log decoder must resolve wire IDs to destination descriptors before ApplyReplication.

func (ReplicationObject) Kind added in v0.4.17

func (ReplicationObject) NameHash added in v0.4.17

func (o ReplicationObject) NameHash() uint64

NameHash returns the registered object's cached schema hash. Invalid or ambiguous descriptors panic, rather than silently selecting an object kind.

type ReplicationObjectKind added in v0.4.17

type ReplicationObjectKind uint8
const (
	ReplicationInvalidObject ReplicationObjectKind = iota
	ReplicationRowTable
	ReplicationKVTable
	ReplicationSingletonMap
)

type ReplicationOp added in v0.4.17

type ReplicationOp uint8
const (
	ReplicationPut ReplicationOp = iota + 1
	ReplicationDelete
)

type ReplicationOptions added in v0.4.17

type ReplicationOptions struct {
	Capture *ReplicationCaptureOptions
	Apply   *ReplicationApplyOptions
}

ReplicationOptions enables independent capture and apply capabilities. Neither capability changes local-write or row-migration policy. Nil disables both. Open copies these options; callbacks and descriptors must remain immutable.

type ReplicationPoisoner added in v0.4.17

type ReplicationPoisoner interface {
	Poison(error)
}

type ReplicationReservation added in v0.4.17

type ReplicationReservation interface {
	Stage(ReplicationChange) (ReplicationChange, error)
	Publish(transactionID, schemaRev uint64)
	Cancel()
}

type ReplicationSink added in v0.4.17

type ReplicationSink interface {
	// Reserve must enqueue a pending slot before returning. Fail admission instead
	// of waiting for the current transaction's commit/drain. No I/O or DB reentry.
	Reserve() (ReplicationReservation, error)
	// Drain runs after write admission stops. Wait for all accepted slots to resolve,
	// consume them in order, and durably sync. Final Publish/Cancel calls may overlap.
	Drain() error
}

ReplicationSink admits physical capture attempts into one database's ordered queue. EDB calls Reserve synchronously under Bolt's serialized writer, so successful reservation order is physical-attempt order, before commit. Publications/cancellations may arrive later and out of order. Consume slots strictly in reservation order, waiting for pending heads and skipping cancelled ones; sorting only groups already published does not establish a safe prefix. Exactly one Publish or Cancel follows each successful reservation in normal process execution. See _docs/REPLICATION-CONSUMER-CONTRACT.md for the full contract.

type ReplicationValue added in v0.4.17

type ReplicationValue struct {
	Present   bool
	Flags     uint64
	SchemaVer uint64
	ModCount  uint64
	Data      []byte
}

ReplicationValue excludes the stored row's local index tail. Present distinguishes a missing value from a singleton's empty/nil PUT. Flags identifies the row codec.

type RowChunk added in v0.4.13

type RowChunk[Row, Key any] struct {
	// contains filtered or unexported fields
}

RowChunk is the native-row counterpart of RecordChunk. Rows are decoded owned values; the chunk itself still belongs to its transaction.

func (RowChunk) Bookmark added in v0.4.13

func (c RowChunk) Bookmark() ScanBookmark

Bookmark owns the last consumed position. An unconsumed chunk returns its starting bookmark. Capture it before closing the transaction.

func (RowChunk) Count added in v0.4.13

func (c RowChunk) Count() int

Count returns the number of entries consumed from this chunk, including entries rejected by application filters.

func (RowChunk) DBTx added in v0.4.13

func (c RowChunk) DBTx() *Tx

func (*RowChunk[Row, Key]) Entries added in v0.4.13

func (c *RowChunk[Row, Key]) Entries() iter.Seq2[Key, *Row]

func (*RowChunk[Row, Key]) Keys added in v0.4.13

func (c *RowChunk[Row, Key]) Keys() iter.Seq[Key]

func (RowChunk) More added in v0.4.13

func (c RowChunk) More() bool

More finishes the chunk and checks for another matching entry without loading its row. After More, iteration is no longer allowed; Bookmark remains usable. This is a statement about this transaction's snapshot, not future writes.

func (*RowChunk[Row, Key]) Rows added in v0.4.13

func (c *RowChunk[Row, Key]) Rows() iter.Seq[*Row]

func (RowChunk) Tx added in v0.4.13

func (c RowChunk) Tx() *Tx

Tx returns the current chunk's transaction. It must not be closed or replaced while iterating the chunk. DBTx also makes the chunk usable as a Txish.

type RowMigrationPolicy added in v0.4.17

type RowMigrationPolicy uint8

RowMigrationPolicy controls row transforms during startup, decode and reindex. Skipping row migrations still permits local DDL and index-only backfills.

const (
	AllowRowMigrations RowMigrationPolicy = iota
	SkipRowMigrations
)

func (RowMigrationPolicy) String added in v0.4.17

func (p RowMigrationPolicy) String() string

type RowScan added in v0.4.13

type RowScan[Row, Key any] struct {
	// contains filtered or unexported fields
}

RowScan uses the same scan rules but materializes owned native Go rows.

func (RowScan[Row, Key]) Chunk added in v0.4.13

func (s RowScan[Row, Key]) Chunk(limit int) *RowChunk[Row, Key]

func (RowScan[Row, Key]) Entries added in v0.4.13

func (s RowScan[Row, Key]) Entries() iter.Seq2[Key, *Row]

func (RowScan) KeyCursor added in v0.4.13

func (s RowScan) KeyCursor() *KeyCursor[Key]

KeyCursor opens an independent key-only cursor. Table scans and exact index scans can be merged with Union or Intersect (subject to the key ordering check described on Union). A general index scan is ordered by index key first, so it cannot be merged directly even when its primary keys happen to look sorted in a small sample.

func (RowScan) Keys added in v0.4.13

func (s RowScan) Keys() iter.Seq[Key]

Keys decodes primary keys without loading or decoding row payloads.

func (RowScan) Raw added in v0.4.13

func (s RowScan) Raw() RawCursor

Raw opens a cursor for low-level operations. It does not consume an earlier iteration; all scans and iterators must stay inside their transaction.

func (RowScan[Row, Key]) Resume added in v0.4.13

func (s RowScan[Row, Key]) Resume(b ScanBookmark) RowScan[Row, Key]

func (RowScan[Row, Key]) Reversed added in v0.4.13

func (s RowScan[Row, Key]) Reversed() RowScan[Row, Key]

func (RowScan[Row, Key]) Rows added in v0.4.13

func (s RowScan[Row, Key]) Rows() iter.Seq[*Row]

type RowTable added in v0.4.13

type RowTable[Row, Key any] struct {
	// contains filtered or unexported fields
}

RowTable is the native Go row counterpart of Table.

func (RowTable[Row, Key]) After added in v0.4.13

func (t RowTable[Row, Key]) After(txh Txish, key Key) RowScan[Row, Key]

func (RowTable[Row, Key]) Before added in v0.4.13

func (t RowTable[Row, Key]) Before(txh Txish, key Key) RowScan[Row, Key]

func (RowTable) Delete added in v0.4.13

func (t RowTable) Delete(txh Txish, key Key) bool

func (RowTable[Row, Key]) Exact added in v0.4.13

func (t RowTable[Row, Key]) Exact(txh Txish, key Key) RowScan[Row, Key]

func (RowTable[Row, Key]) ExactIndexScan added in v0.4.13

func (t RowTable[Row, Key]) ExactIndexScan[IndexKey any](txh Txish, idx *Index[IndexKey], key IndexKey) RowScan[Row, Key]

func (RowTable) Exists added in v0.4.13

func (t RowTable) Exists(txh Txish, key Key) bool

func (RowTable[Row, Key]) From added in v0.4.13

func (t RowTable[Row, Key]) From(txh Txish, key Key) RowScan[Row, Key]

func (RowTable[Row, Key]) Get added in v0.4.13

func (t RowTable[Row, Key]) Get(txh Txish, key Key) *Row

Get returns an owned native row, or nil when the key is absent.

func (RowTable[Row, Key]) GetRaw added in v0.4.13

func (t RowTable[Row, Key]) GetRaw(txh Txish, key []byte) *Row

func (RowTable[Row, Key]) IndexScan added in v0.4.13

func (t RowTable[Row, Key]) IndexScan[IndexKey any](txh Txish, idx *Index[IndexKey]) RowScan[Row, Key]

func (RowTable[Row, Key]) IndexScanAfter added in v0.4.13

func (t RowTable[Row, Key]) IndexScanAfter[IndexKey any](txh Txish, idx *Index[IndexKey], key IndexKey) RowScan[Row, Key]

func (RowTable[Row, Key]) IndexScanBefore added in v0.4.13

func (t RowTable[Row, Key]) IndexScanBefore[IndexKey any](txh Txish, idx *Index[IndexKey], key IndexKey) RowScan[Row, Key]

func (RowTable[Row, Key]) IndexScanFrom added in v0.4.13

func (t RowTable[Row, Key]) IndexScanFrom[IndexKey any](txh Txish, idx *Index[IndexKey], key IndexKey) RowScan[Row, Key]

func (RowTable[Row, Key]) IndexScanThrough added in v0.4.13

func (t RowTable[Row, Key]) IndexScanThrough[IndexKey any](txh Txish, idx *Index[IndexKey], key IndexKey) RowScan[Row, Key]

func (RowTable[Row, Key]) Lookup added in v0.4.13

func (t RowTable[Row, Key]) Lookup[IndexKey any](txh Txish, idx *Index[IndexKey], key IndexKey) (Key, *Row)

func (RowTable[Row, Key]) LookupKey added in v0.4.13

func (t RowTable[Row, Key]) LookupKey[IndexKey any](txh Txish, idx *Index[IndexKey], key IndexKey) (Key, bool)

func (RowTable) Model added in v0.4.13

func (t RowTable) Model() *kvo.Model

func (RowTable[Row, Key]) Prefix added in v0.4.13

func (t RowTable[Row, Key]) Prefix(txh Txish, key Key, components int) RowScan[Row, Key]

func (RowTable[Row, Key]) PrefixIndexScan added in v0.4.13

func (t RowTable[Row, Key]) PrefixIndexScan[IndexKey any](txh Txish, idx *Index[IndexKey], key IndexKey, components int) RowScan[Row, Key]

func (RowTable[Row, Key]) Put added in v0.4.13

func (t RowTable[Row, Key]) Put(txh Txish, row *Row) bool

func (RowTable[Row, Key]) PutByKey added in v0.4.13

func (t RowTable[Row, Key]) PutByKey(txh Txish, key Key, row *Row) bool

func (RowTable[Row, Key]) Range added in v0.4.13

func (t RowTable[Row, Key]) Range(txh Txish, lower, upper Key) RowScan[Row, Key]

func (RowTable[Row, Key]) RangeIndexScan added in v0.4.13

func (t RowTable[Row, Key]) RangeIndexScan[IndexKey any](txh Txish, idx *Index[IndexKey], lower, upper IndexKey) RowScan[Row, Key]

func (RowTable[Row, Key]) Records added in v0.4.13

func (t RowTable[Row, Key]) Records() Table[Key]

func (RowTable[Row, Key]) Scan added in v0.4.13

func (t RowTable[Row, Key]) Scan(txh Txish) RowScan[Row, Key]

func (RowTable) Table added in v0.4.13

func (t RowTable) Table() *TableDef

func (RowTable[Row, Key]) Through added in v0.4.13

func (t RowTable[Row, Key]) Through(txh Txish, key Key) RowScan[Row, Key]

func (RowTable[Row, Key]) TryGet added in v0.4.13

func (t RowTable[Row, Key]) TryGet(txh Txish, key Key) (*Row, ValueMeta, error)

func (RowTable[Row, Key]) TryGetRaw added in v0.4.13

func (t RowTable[Row, Key]) TryGetRaw(txh Txish, key []byte) (*Row, ValueMeta, error)

func (RowTable[Row, Key]) TryLookup added in v0.4.13

func (t RowTable[Row, Key]) TryLookup[IndexKey any](txh Txish, idx *Index[IndexKey], key IndexKey) (Key, *Row, ValueMeta, error)

type SKey

type SKey[T any] struct {
	// contains filtered or unexported fields
}

SKey identifies a singleton storing a value of type T. SGet and SPut carry this type through to their destination and source arguments.

func AddSingletonKey

func AddSingletonKey[T any](mp *KVMap, key string) *SKey[T]

AddSingletonKey declares a singleton's value type. A key can be declared only once within a map, even if a second declaration uses the same value type.

func (*SKey[T]) Raw

func (sk *SKey[T]) Raw() []byte

func (*SKey[T]) String

func (sk *SKey[T]) String() string

func (*SKey[T]) ValueType added in v0.4.13

func (sk *SKey[T]) ValueType() reflect.Type

type ScanBookmark added in v0.4.13

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

ScanBookmark is an owned, immutable position in a table or index scan. Its zero value starts at the beginning. It can outlive the cursor and transaction. Nonunique index positions include both the index key and primary key; a primary key alone cannot resume a general index scan.

A bookmark belongs to its table/index and traversal direction. Resume keeps the new scan's bounds, so it can also narrow the original query. Bookmarks are tied to in-process table/index definitions and have no serialization format; their position bytes are owned and can outlive transactions. They are not durable pagination tokens or snapshots. Between read transactions, inserts behind the position are missed and entries moved ahead of it can be visited again. Collect keys first when changing a scanned index.

func (ScanBookmark) IsZero added in v0.4.13

func (b ScanBookmark) IsZero() bool

type ScanMethod

type ScanMethod int

type ScanOptions

type ScanOptions struct {
	Reverse         bool
	Method          ScanMethod
	PrefixValue     reflect.Value
	PrefixEls       int
	Lower           reflect.Value
	Upper           reflect.Value
	LowerInc        bool
	UpperInc        bool
	LowerPrimaryKey reflect.Value
	UpperPrimaryKey reflect.Value
	// contains filtered or unexported fields
}

func ExactIDRangeScan added in v0.3.1

func ExactIDRangeScan(exact, lower, upper any, lowerInc, upperInc bool) ScanOptions

func ExactIDRangeScanVal added in v0.3.1

func ExactIDRangeScanVal(exact, lower, upper reflect.Value, lowerInc, upperInc bool) ScanOptions

func ExactScan

func ExactScan(v any) ScanOptions

func ExactScanVal

func ExactScanVal(val reflect.Value) ScanOptions

func FullScan

func FullScan() ScanOptions

func LowerBoundScan added in v0.2.0

func LowerBoundScan(lower any, includeEqual bool) ScanOptions

func RangeScan added in v0.1.6

func RangeScan(lower, upper any, lowerInc, upperInc bool) ScanOptions

func RangeScanVal added in v0.1.6

func RangeScanVal(lower, upper reflect.Value, lowerInc, upperInc bool) ScanOptions

func UpperBoundScan added in v0.2.0

func UpperBoundScan(upper any, includeEqual bool) ScanOptions

func (ScanOptions) LogString added in v0.1.2

func (so ScanOptions) LogString() string

func (ScanOptions) Prefix

func (so ScanOptions) Prefix(els int) ScanOptions

func (ScanOptions) PrimaryKeyRange added in v0.4.8

func (so ScanOptions) PrimaryKeyRange(lower, upper any, lowerInc, upperInc bool) ScanOptions

PrimaryKeyRange restricts the primary keys at the index range's endpoints. It does not specify a physical continuation position. Use Resume for paging: variable-width index keys can interleave, so logical endpoint restrictions may need to visit entries before a complete index-key/primary-key seek.

func (ScanOptions) PrimaryKeyRangeVal added in v0.4.8

func (so ScanOptions) PrimaryKeyRangeVal(lower, upper reflect.Value, lowerInc, upperInc bool) ScanOptions

func (ScanOptions) Resume added in v0.4.13

func (so ScanOptions) Resume(b ScanBookmark) ScanOptions

Resume continues exclusively after the bookmark in traversal order, retaining all query bounds. A zero bookmark leaves the scan unchanged.

func (ScanOptions) Reversed

func (so ScanOptions) Reversed() ScanOptions

type Schema

type Schema struct {
	Name string
	// contains filtered or unexported fields
}

func (*Schema) Include added in v0.1.3

func (scm *Schema) Include(peer *Schema)

Include composes all table families and singleton maps without modifying peer. A conflicting declaration panics and leaves the receiving schema unchanged.

func (*Schema) KVMapByNameHash added in v0.4.17

func (scm *Schema) KVMapByNameHash(hash uint64) *KVMap

KVMapByNameHash returns nil for an unknown hash or another object kind.

func (*Schema) KVTableByNameHash added in v0.4.17

func (scm *Schema) KVTableByNameHash(hash uint64) *KVTable

KVTableByNameHash returns nil for an unknown hash or another object kind.

func (*Schema) KVTableNamed added in v0.3.2

func (scm *Schema) KVTableNamed(name string) *KVTable

func (*Schema) KVTables added in v0.3.7

func (scm *Schema) KVTables() []*KVTable

func (*Schema) NameHash added in v0.4.17

func (scm *Schema) NameHash(name string) uint64

NameHash returns the cached hash of a registered table, KV table or singleton map. Lookup is case-insensitive, like TableNamed; an unknown name panics.

func (*Schema) TableByNameHash added in v0.4.17

func (scm *Schema) TableByNameHash(hash uint64) *TableDef

TableByNameHash returns nil for an unknown hash or another object kind.

func (*Schema) TableByRow added in v0.1.2

func (scm *Schema) TableByRow(row any) *TableDef

func (*Schema) TableByRowType added in v0.1.2

func (scm *Schema) TableByRowType(rt reflect.Type) *TableDef

func (*Schema) TableNamed

func (scm *Schema) TableNamed(name string) *TableDef

func (*Schema) Tables

func (scm *Schema) Tables() []*TableDef

type StorageFormat added in v0.4.13

type StorageFormat uint8

StorageFormat names payload encodings, not row-envelope versions. Fast1 and MessagePack remain supported; new storage should use Fast2 or Compact2.

const (
	MessagePack StorageFormat = iota
	Fast1
	Fast2
	Compact2
)

func (StorageFormat) String added in v0.4.13

func (f StorageFormat) String() string

type Table

type Table[Key any] struct {
	// contains filtered or unexported fields
}

Table is a table's encoding-independent access API with a declared key type. DefineTable constructs it together with its shared definition.

func DefineTable added in v0.2.0

func DefineTable[Key any](scm *Schema, name string, model *kvo.Model, f func(b *TableBuilder[Key])) *Table[Key]

DefineTable registers a model-backed table. The model's first registered Go struct supplies native storage and its first field supplies the primary key. Key must exactly match that field's type. The schema version defaults to 1. SetRecordStorage selects Fast2 or Compact2 instead of MessagePack for new keys.

func (Table[Key]) After added in v0.4.13

func (t Table[Key]) After(txh Txish, key Key) RecordScan[Key]

func (Table[Key]) Before added in v0.4.13

func (t Table[Key]) Before(txh Txish, key Key) RecordScan[Key]

func (Table) Delete added in v0.4.13

func (t Table) Delete(txh Txish, key Key) bool

func (Table[Key]) Edit added in v0.4.13

func (t Table[Key]) Edit(txh Txish, key Key) *RecordEdit

Edit opens a private edit in the current write transaction, or returns nil.

func (Table[Key]) EditOrCreate added in v0.4.13

func (t Table[Key]) EditOrCreate(txh Txish, key Key) *RecordEdit

EditOrCreate opens the existing row or prepares an insert under this key.

func (Table[Key]) Exact added in v0.4.13

func (t Table[Key]) Exact(txh Txish, key Key) RecordScan[Key]

func (Table[Key]) ExactIndexScan added in v0.4.13

func (t Table[Key]) ExactIndexScan[IndexKey any](txh Txish, idx *Index[IndexKey], key IndexKey) RecordScan[Key]

func (Table) Exists added in v0.4.13

func (t Table) Exists(txh Txish, key Key) bool

func (Table[Key]) From added in v0.4.13

func (t Table[Key]) From(txh Txish, key Key) RecordScan[Key]

func (Table[Key]) Get added in v0.4.13

func (t Table[Key]) Get(txh Txish, key Key) kvo.Record

Get returns a borrowed record, or a missing record when the key is absent.

func (Table[Key]) GetRaw added in v0.4.13

func (t Table[Key]) GetRaw(txh Txish, key []byte) kvo.Record

GetRaw accepts an encoded primary key. The returned record does not retain it.

func (Table[Key]) IndexScan added in v0.4.13

func (t Table[Key]) IndexScan[IndexKey any](txh Txish, idx *Index[IndexKey]) RecordScan[Key]

func (Table[Key]) IndexScanAfter added in v0.4.13

func (t Table[Key]) IndexScanAfter[IndexKey any](txh Txish, idx *Index[IndexKey], key IndexKey) RecordScan[Key]

func (Table[Key]) IndexScanBefore added in v0.4.13

func (t Table[Key]) IndexScanBefore[IndexKey any](txh Txish, idx *Index[IndexKey], key IndexKey) RecordScan[Key]

func (Table[Key]) IndexScanFrom added in v0.4.13

func (t Table[Key]) IndexScanFrom[IndexKey any](txh Txish, idx *Index[IndexKey], key IndexKey) RecordScan[Key]

func (Table[Key]) IndexScanThrough added in v0.4.13

func (t Table[Key]) IndexScanThrough[IndexKey any](txh Txish, idx *Index[IndexKey], key IndexKey) RecordScan[Key]

func (Table[Key]) Key added in v0.4.13

func (t Table[Key]) Key(edit *RecordEdit) Key

Key returns this edit's primary key, including when the model omits it.

func (Table[Key]) Lookup added in v0.4.13

func (t Table[Key]) Lookup[IndexKey any](txh Txish, idx *Index[IndexKey], key IndexKey) (Key, kvo.Record)

func (Table[Key]) LookupKey added in v0.4.13

func (t Table[Key]) LookupKey[IndexKey any](txh Txish, idx *Index[IndexKey], key IndexKey) (Key, bool)

func (Table[Key]) LookupKeyIndexDef added in v0.4.20

func (t Table[Key]) LookupKeyIndexDef(txh Txish, idx *IndexDef, key reflect.Value) (Key, bool)

LookupKeyIndexDef finds a primary key without loading its record.

func (Table) Model added in v0.4.13

func (t Table) Model() *kvo.Model

func (Table[Key]) New added in v0.4.13

func (t Table[Key]) New(txh Txish, key Key) *RecordEdit

New prepares an insert; Save checks that the primary key is still free.

func (Table[Key]) Prefix added in v0.4.13

func (t Table[Key]) Prefix(txh Txish, key Key, components int) RecordScan[Key]

Prefix matches the first components of a composite key, using the declared key type. It is a tuple prefix, not a string prefix.

func (Table[Key]) PrefixIndexScan added in v0.4.13

func (t Table[Key]) PrefixIndexScan[IndexKey any](txh Txish, idx *Index[IndexKey], key IndexKey, components int) RecordScan[Key]

func (Table[Key]) Put added in v0.4.13

func (t Table[Key]) Put(txh Txish, key Key, r kvo.Record) bool

Put inserts or replaces a record under an explicit key and reports a change. Use PutChecked when replacing a previously read revision conditionally.

func (Table[Key]) PutChecked added in v0.4.13

func (t Table[Key]) PutChecked(txh Txish, key Key, r kvo.Record, expected ValueMeta) bool

PutChecked replaces only the expected revision (zero metadata means insert).

func (Table[Key]) Range added in v0.4.13

func (t Table[Key]) Range(txh Txish, lower, upper Key) RecordScan[Key]

Range includes both endpoints. From/After and Through/Before provide inclusive/exclusive one-sided bounds; Reversed changes traversal order.

func (Table[Key]) RangeIndexScan added in v0.4.13

func (t Table[Key]) RangeIndexScan[IndexKey any](txh Txish, idx *Index[IndexKey], lower, upper IndexKey) RecordScan[Key]

func (Table[Key]) Rows added in v0.4.13

func (t Table[Key]) Rows[Row any]() RowTable[Row, Key]

func (Table[Key]) Save added in v0.4.13

func (t Table[Key]) Save(txh Txish, edit *RecordEdit) bool

func (Table[Key]) SaveWith added in v0.4.20

func (t Table[Key]) SaveWith(txh Txish, edit *RecordEdit, prepare func(*kvo.Editor) error) bool

SaveWith prepares pending editor changes after native save validation.

func (Table[Key]) Scan added in v0.4.13

func (t Table[Key]) Scan(txh Txish) RecordScan[Key]

func (Table[Key]) ScanIndexDef added in v0.4.20

func (t Table[Key]) ScanIndexDef(txh Txish, idx *IndexDef, opt ScanOptions) RecordScan[Key]

ScanIndexDef constructs the native scan when the index-key type is known only at runtime. Generic index methods use the same scan representation.

func (Table) Table added in v0.4.13

func (t Table) Table() *TableDef

func (Table[Key]) Through added in v0.4.13

func (t Table[Key]) Through(txh Txish, key Key) RecordScan[Key]

func (Table[Key]) TryEdit added in v0.4.13

func (t Table[Key]) TryEdit(txh Txish, key Key) (*RecordEdit, error)

func (Table[Key]) TryEditOrCreate added in v0.4.13

func (t Table[Key]) TryEditOrCreate(txh Txish, key Key) (*RecordEdit, error)

func (Table[Key]) TryGet added in v0.4.13

func (t Table[Key]) TryGet(txh Txish, key Key) (kvo.Record, ValueMeta, error)

func (Table[Key]) TryGetRaw added in v0.4.13

func (t Table[Key]) TryGetRaw(txh Txish, key []byte) (kvo.Record, ValueMeta, error)

func (Table[Key]) TryLookup added in v0.4.13

func (t Table[Key]) TryLookup[IndexKey any](txh Txish, idx *Index[IndexKey], key IndexKey) (Key, kvo.Record, ValueMeta, error)

func (Table[Key]) TryLookupIndexDef added in v0.4.20

func (t Table[Key]) TryLookupIndexDef(txh Txish, idx *IndexDef, key reflect.Value) (Key, kvo.Record, ValueMeta, error)

TryLookupIndexDef is TryLookup for a dynamically obtained index and key. It preserves the native key type, missing result and strict-index behavior.

func (Table[Key]) TryNew added in v0.4.13

func (t Table[Key]) TryNew(txh Txish, key Key) (*RecordEdit, error)

func (Table[Key]) TryPutChecked added in v0.4.13

func (t Table[Key]) TryPutChecked(txh Txish, key Key, r kvo.Record, expected ValueMeta) (ValueMeta, error)

func (Table[Key]) TrySave added in v0.4.13

func (t Table[Key]) TrySave(txh Txish, edit *RecordEdit) (ValueMeta, error)

func (Table[Key]) TrySaveWith added in v0.4.20

func (t Table[Key]) TrySaveWith(txh Txish, edit *RecordEdit, prepare func(*kvo.Editor) error) (ValueMeta, error)

TrySaveWith prepares pending editor changes after native save validation.

type TableBuilder added in v0.2.0

type TableBuilder[Key any] struct {
	// contains filtered or unexported fields
}

func (*TableBuilder[Key]) AddIndex added in v0.2.0

func (b *TableBuilder[Key]) AddIndex[T any](name string, indexer func(tx *Tx, pk values.Value, row kvo.Record, yield func(T)), opts ...any) *Index[T]

AddIndex registers an index on this table and returns it. The optional callback yields keys of T. A nil callback leaves population to TableBuilder.SetIndexer. Both forms may coexist. Callbacks share the write transaction; records, primary-key cells, and yield are borrowed and must not be mutated or retained. The primary key uses the shared native-value ABI; use AsUint/AsString or IndexPrimaryKey[T].

func (*TableBuilder[Key]) AddMigrator added in v0.4.13

func (b *TableBuilder[Key]) AddMigrator(toVer uint64, f func(tx *Tx, key Key, edit *kvo.Editor))

AddMigrator runs f when the stored version is below toVer. Eligible callbacks run in registration order, each comparing against the original stored version. toVer must be positive and no greater than the final table schema version. Native editors update structs in place; encoded editors preserve untouched fields. Reads do not persist migrations; saves and reindexing do. The callback must not change the primary key or retain the editor.

func (*TableBuilder[Key]) SetIndexer added in v0.4.13

func (b *TableBuilder[Key]) SetIndexer(f func(Key, kvo.Record, *IndexBuilder))

SetIndexer builds secondary indexes from logical properties on any row format. The primary key is supplied separately; records need no stored key property. The record and its bytes are borrowed, read-only, and valid only during f. Use a presence-significant property when absent and zero index differently.

func (*TableBuilder[Key]) SetNativeSchema added in v0.4.13

func (b *TableBuilder[Key]) SetNativeSchema(schema kvo.NativeSchema)

SetNativeSchema shares native field operations and value types with the host VM.

func (*TableBuilder[Key]) SetRecordStorage added in v0.4.13

func (b *TableBuilder[Key]) SetRecordStorage(storage RecordStorage)

func (*TableBuilder[Key]) SetSchemaVersion added in v0.2.0

func (b *TableBuilder[Key]) SetSchemaVersion(ver uint64)

func (*TableBuilder[Key]) SuppressContentWhenLogging added in v0.2.0

func (b *TableBuilder[Key]) SuppressContentWhenLogging()

func (*TableBuilder[Key]) Tag added in v0.3.8

func (b *TableBuilder[Key]) Tag(tag *Tag)

type TableDef added in v0.4.13

type TableDef struct {
	TaggableImpl
	// contains filtered or unexported fields
}

func (*TableDef) DecodeKeyVal added in v0.4.13

func (tbl *TableDef) DecodeKeyVal(rawKey []byte) reflect.Value

func (*TableDef) DecodeKeyValInto added in v0.4.13

func (tbl *TableDef) DecodeKeyValInto(keyVal reflect.Value, rawKey []byte)

func (*TableDef) EncodeKey added in v0.4.13

func (tbl *TableDef) EncodeKey(key any) []byte

func (*TableDef) EncodeKeyVal added in v0.4.13

func (tbl *TableDef) EncodeKeyVal(keyVal reflect.Value) []byte

func (*TableDef) IndexNamed added in v0.4.13

func (tbl *TableDef) IndexNamed(name string) *IndexDef

func (*TableDef) Indices added in v0.4.13

func (tbl *TableDef) Indices() []*IndexDef

func (*TableDef) KeyString added in v0.4.13

func (tbl *TableDef) KeyString(key any) string

func (*TableDef) KeyType added in v0.4.13

func (tbl *TableDef) KeyType() reflect.Type

func (*TableDef) Model added in v0.4.13

func (t *TableDef) Model() *kvo.Model

Model returns the table's logical model.

func (*TableDef) Name added in v0.4.13

func (tbl *TableDef) Name() string

func (*TableDef) NameHash added in v0.4.17

func (tbl *TableDef) NameHash() uint64

NameHash returns xxHash64 of the lowercase registered name, cached at declaration.

func (*TableDef) NewRow added in v0.4.13

func (tbl *TableDef) NewRow() any

func (*TableDef) NewRowVal added in v0.4.13

func (tbl *TableDef) NewRowVal() reflect.Value

func (*TableDef) ParseKey added in v0.4.13

func (tbl *TableDef) ParseKey(s string) (any, error)

func (*TableDef) ParseKeyVal added in v0.4.13

func (tbl *TableDef) ParseKeyVal(s string) (reflect.Value, error)

func (*TableDef) RawKeyString added in v0.4.13

func (tbl *TableDef) RawKeyString(keyRaw []byte) string

func (*TableDef) RowHasZeroKey added in v0.4.13

func (tbl *TableDef) RowHasZeroKey(row any) bool

func (*TableDef) RowKey added in v0.4.13

func (tbl *TableDef) RowKey(row any) any

func (*TableDef) RowKeyVal added in v0.4.13

func (tbl *TableDef) RowKeyVal(rowVal reflect.Value) reflect.Value

func (*TableDef) RowType added in v0.4.13

func (tbl *TableDef) RowType() reflect.Type

func (*TableDef) RowValHasZeroKey added in v0.4.13

func (tbl *TableDef) RowValHasZeroKey(rowVal reflect.Value) bool

func (*TableDef) Rows added in v0.4.13

func (t *TableDef) Rows[Row, Key any]() RowTable[Row, Key]

Rows validates both the native row type and the primary key type.

func (*TableDef) SchemaVersion added in v0.4.13

func (tbl *TableDef) SchemaVersion() uint64

SchemaVersion is the version written by current saves. Stored rows may have older versions until they are loaded, migrated, and saved.

func (*TableDef) SetRowKey added in v0.4.13

func (tbl *TableDef) SetRowKey(row, key any)

func (*TableDef) SetRowKeyVal added in v0.4.13

func (tbl *TableDef) SetRowKeyVal(rowVal, keyVal reflect.Value)

func (*TableDef) TableDef added in v0.4.13

func (t *TableDef) TableDef() *TableDef

func (*TableDef) TryDecodeKeyValInto added in v0.4.13

func (tbl *TableDef) TryDecodeKeyValInto(keyVal reflect.Value, rawKey []byte) error

func (*TableDef) TryRawKeyString added in v0.4.13

func (tbl *TableDef) TryRawKeyString(keyRaw []byte) (string, error)

func (*TableDef) Typed added in v0.4.13

func (t *TableDef) Typed[Key any]() Table[Key]

Typed binds a dynamically obtained definition, validating its primary-key type and record model. Statically declared tables need no separate binding.

type TableError

type TableError struct {
	Table string
	Index string
	Key   []byte
	Msg   string
	Err   error
}

func (*TableError) Error

func (e *TableError) Error() string

func (*TableError) Unwrap

func (e *TableError) Unwrap() error

type TableStats

type TableStats struct {
	Rows      int64
	IndexRows int64

	DataSize   int64
	DataAlloc  int64
	IndexSize  int64
	IndexAlloc int64
}

func (*TableStats) TotalAlloc

func (ts *TableStats) TotalAlloc() int64

func (*TableStats) TotalSize

func (ts *TableStats) TotalSize() int64

type Tablish added in v0.3.17

type Tablish interface {
	TableName() string
	HasTag(tag *Tag) bool
}

type Tag added in v0.3.8

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

func NewTag added in v0.3.8

func NewTag(name string) *Tag

func (*Tag) Name added in v0.3.8

func (tag *Tag) Name() string

func (*Tag) String added in v0.3.8

func (tag *Tag) String() string

type TagFamily added in v0.3.8

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

func NewTagFamily added in v0.3.8

func NewTagFamily(name string, tags []*Tag, defaultTag *Tag, card TagFamilyCardinality) *TagFamily

func (*TagFamily) Name added in v0.3.8

func (fam *TagFamily) Name() string

func (*TagFamily) String added in v0.3.8

func (fam *TagFamily) String() string

type TagFamilyCardinality added in v0.3.8

type TagFamilyCardinality int
const (
	TagFamilyCardinalityOptionalOne TagFamilyCardinality = iota
	TagFamilyCardinalityRequiredOne
	TagFamilyCardinalityOptionalMany
	TagFamilyCardinalityRequiredMany
)

type TaggableImpl added in v0.3.8

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

func (*TaggableImpl) HasTag added in v0.3.8

func (i *TaggableImpl) HasTag(tag *Tag) bool

func (*TaggableImpl) TagInFamily added in v0.3.8

func (i *TaggableImpl) TagInFamily(fam *TagFamily) *Tag

type Tx

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

func (*Tx) BeginVerbose added in v0.2.0

func (tx *Tx) BeginVerbose()

func (*Tx) BoltTx added in v0.4.0

func (tx *Tx) BoltTx() *bbolt.Tx

BoltTx returns the underlying Bolt transaction if this DB uses Bolt, otherwise nil.

func (*Tx) Close

func (tx *Tx) Close()

func (*Tx) Commit

func (tx *Tx) Commit() error

func (*Tx) CommitDespiteError

func (tx *Tx) CommitDespiteError()

func (*Tx) DB added in v0.1.2

func (tx *Tx) DB() *DB

func (*Tx) DBTx

func (tx *Tx) DBTx() *Tx

DBTx implements Txish

func (*Tx) DecodeMementoVal added in v0.3.17

func (tx *Tx) DecodeMementoVal(tblArg AnyTable, keyRaw []byte, memento []byte) (rowVal reflect.Value, meta ValueMeta, err error)

func (*Tx) DeleteByKey

func (tx *Tx) DeleteByKey(tblArg AnyTable, key any) bool

func (*Tx) DeleteByKeyRaw

func (tx *Tx) DeleteByKeyRaw(tblArg AnyTable, keyRaw []byte) bool

func (*Tx) DeleteByKeyVal

func (tx *Tx) DeleteByKeyVal(tblArg AnyTable, keyVal reflect.Value) bool

func (*Tx) DeleteRecord added in v0.4.13

func (tx *Tx) DeleteRecord(tblArg AnyTable, row kvo.Record) bool

DeleteRecord derives the key from an explicitly declared model property. Use DeleteByKey when the record does not store its primary key.

func (*Tx) Dump

func (tx *Tx) Dump(f DumpFlags) string

func (*Tx) EditRecord added in v0.4.13

func (tx *Tx) EditRecord(tArg AnyTable, key any, edit func(*kvo.Editor))

EditRecord opens, edits, and saves one record using the table's storage codec. A missing key is a no-op. Use NewRecordEdit to prepare an insert.

func (*Tx) EndVerbose added in v0.2.0

func (tx *Tx) EndVerbose()

func (*Tx) Exists

func (tx *Tx) Exists(tblArg AnyTable, key any) bool

func (*Tx) ExistsByKeyRaw added in v0.1.6

func (tx *Tx) ExistsByKeyRaw(tblArg AnyTable, keyRaw []byte) bool

func (*Tx) Get

func (tx *Tx) Get(tblArg AnyTable, key any) (any, ValueMeta)

func (*Tx) GetByKeyRaw added in v0.1.6

func (tx *Tx) GetByKeyRaw(tblArg AnyTable, keyRaw []byte) (any, ValueMeta)

func (*Tx) GetByKeyVal

func (tx *Tx) GetByKeyVal(tblArg AnyTable, keyVal reflect.Value) (any, ValueMeta)

func (*Tx) GetMemo

func (tx *Tx) GetMemo(key string) (any, bool)

func (*Tx) GetMeta

func (tx *Tx) GetMeta(tblArg AnyTable, key any) ValueMeta

func (*Tx) GetMetaByKeyVal

func (tx *Tx) GetMetaByKeyVal(tblArg AnyTable, keyVal reflect.Value) ValueMeta

func (*Tx) GetRecord added in v0.4.13

func (tx *Tx) GetRecord(tArg AnyTable, key any) kvo.Record

GetRecord panics on error. Use TryGetRecord to handle errors explicitly.

func (*Tx) GetRecordByKeyRaw added in v0.4.13

func (tx *Tx) GetRecordByKeyRaw(t AnyTable, key []byte) kvo.Record

GetRecordByKeyRaw panics on error. Use TryGetRecordByKeyRaw to handle errors explicitly.

func (*Tx) GetRecordByKeyVal added in v0.4.13

func (tx *Tx) GetRecordByKeyVal(tArg AnyTable, key reflect.Value) kvo.Record

GetRecordByKeyVal accepts an existing reflected key without boxing it into an interface. It panics on error; TryGetRecordByKeyVal also returns metadata.

func (*Tx) IndexScan

func (tx *Tx) IndexScan(idxArg AnyIndex, opt ScanOptions) *RawIndexCursor

func (*Tx) IsWritable

func (tx *Tx) IsWritable() bool

func (*Tx) KVGet added in v0.3.0

func (tx *Tx) KVGet(tbl *KVTable, key []byte) fast1.ImmutableMap

KVGet returns a read-only snapshot valid until the next write or transaction end.

func (*Tx) KVGetRaw added in v0.3.0

func (tx *Tx) KVGetRaw(tbl *KVTable, key []byte) []byte

KVGetRaw returns read-only storage valid until the next write or transaction end. Clone the bytes before modifying them or keeping them longer.

func (*Tx) KVGetRawView added in v0.4.20

func (tx *Tx) KVGetRawView(tbl *KVTable, key []byte) []byte

KVGetRawView returns read-only storage valid within the current transaction, until the next write. Copy the bytes before changing or retaining them.

func (*Tx) KVIndexScan added in v0.3.2

func (tx *Tx) KVIndexScan(idx *KVIndex, rang RawRange) *KVCursor

func (*Tx) KVPut added in v0.3.0

func (tx *Tx) KVPut(tbl *KVTable, key []byte, value fast1.Packable)

func (*Tx) KVPutRaw added in v0.3.0

func (tx *Tx) KVPutRaw(tbl *KVTable, key, value []byte)

func (*Tx) KVTableScan added in v0.3.1

func (tx *Tx) KVTableScan(tbl *KVTable, rang RawRange) *KVCursor

func (*Tx) KVTableStats added in v0.3.7

func (tx *Tx) KVTableStats(tbl *KVTable) TableStats

func (*Tx) Lookup

func (tx *Tx) Lookup(idxArg AnyIndex, indexKey any) any

func (*Tx) LookupExists added in v0.2.0

func (tx *Tx) LookupExists(idxArg AnyIndex, indexKeyVal reflect.Value) bool

func (*Tx) LookupKey

func (tx *Tx) LookupKey(idxArg AnyIndex, indexKey any) any

func (*Tx) LookupKeyVal

func (tx *Tx) LookupKeyVal(idxArg AnyIndex, indexKeyVal reflect.Value) reflect.Value

func (*Tx) LookupVal

func (tx *Tx) LookupVal(idxArg AnyIndex, indexKeyVal reflect.Value) (reflect.Value, ValueMeta)

func (*Tx) Memo

func (tx *Tx) Memo(key string, f func() (any, error)) (any, error)

func (*Tx) Metadata added in v0.4.15

func (tx *Tx) Metadata() TxMetadata

func (*Tx) NewRecordEdit added in v0.4.13

func (tx *Tx) NewRecordEdit(tArg AnyTable, key any) *RecordEdit

NewRecordEdit panics on error. Use TryNewRecordEdit to handle errors explicitly.

func (*Tx) OnChange added in v0.1.4

func (tx *Tx) OnChange(opts map[*TableDef]ChangeFlags, f func(tx *Tx, chg *Change))

OnChange installs a transaction-local handler. Notifications run after each mutation, before commit (which may still roll back). No-op writes do not notify. Request old/new records or independently decoded Go structs explicitly; deletes have only an old value. Record notifications require a KVO model. The options map must not be modified while installed.

func (*Tx) OpenRecordEdit added in v0.4.13

func (tx *Tx) OpenRecordEdit(tArg AnyTable, key any) *RecordEdit

OpenRecordEdit panics on error. Use TryOpenRecordEdit to handle errors explicitly.

func (*Tx) Put

func (tx *Tx) Put(tblArg AnyTable, row any) (oldMeta, newMeta ValueMeta)

func (*Tx) PutByKey added in v0.4.13

func (tx *Tx) PutByKey(tblArg AnyTable, key, row any) (oldMeta, newMeta ValueMeta)

PutByKey inserts or replaces a row using an explicit database key. KVO records need no key property. A native Go row is shallow-copied before its key field is set, so the caller's struct is not changed.

func (*Tx) PutRecordChecked added in v0.4.13

func (tx *Tx) PutRecordChecked(tArg AnyTable, key any, row kvo.Record, expected ValueMeta)

PutRecordChecked panics on error. Use TryPutRecordChecked to handle errors explicitly.

func (*Tx) PutVal

func (tx *Tx) PutVal(tblArg AnyTable, rowVal reflect.Value) (oldMeta, newMeta ValueMeta)

func (*Tx) Reindex

func (tx *Tx) Reindex(tblArg AnyTable, idxArg AnyIndex)

func (*Tx) SaveRecord added in v0.4.13

func (tx *Tx) SaveRecord(e *RecordEdit)

SaveRecord panics on error. Use TrySaveRecord to handle errors explicitly.

func (*Tx) Schema added in v0.1.2

func (tx *Tx) Schema() *Schema

func (*Tx) SetLogger added in v0.3.1

func (tx *Tx) SetLogger(logger *slog.Logger)

func (*Tx) StartTime added in v0.3.18

func (tx *Tx) StartTime() time.Time

func (*Tx) TableScan

func (tx *Tx) TableScan(tblArg AnyTable, opt ScanOptions) *RawTableCursor

func (*Tx) TableStats

func (tx *Tx) TableStats(tblArg AnyTable) TableStats

func (*Tx) TryEditRecord added in v0.4.13

func (tx *Tx) TryEditRecord(tArg AnyTable, key any, edit func(*kvo.Editor) error) (ValueMeta, error)

TryEditRecord discards the edit if the callback returns an error. It checks for intervening writes before saving, just like an explicitly opened edit.

func (*Tx) TryGet added in v0.2.1

func (tx *Tx) TryGet(tblArg AnyTable, key any) (any, ValueMeta, error)

func (*Tx) TryGetByKeyVal added in v0.2.1

func (tx *Tx) TryGetByKeyVal(tblArg AnyTable, keyVal reflect.Value) (any, ValueMeta, error)

func (*Tx) TryGetRecord added in v0.4.13

func (tx *Tx) TryGetRecord(tArg AnyTable, key any) (kvo.Record, ValueMeta, error)

TryGetRecord borrows the row payload and selects its codec. Fastest can decode once for repeated access. Migrations and custom object codecs may decode eagerly.

func (*Tx) TryGetRecordByKeyRaw added in v0.4.13

func (tx *Tx) TryGetRecordByKeyRaw(t AnyTable, key []byte) (kvo.Record, ValueMeta, error)

TryGetRecordByKeyRaw accepts an already encoded key. The result borrows only the stored payload, not this key. A transaction reuses one lookup cursor per table.

func (*Tx) TryGetRecordByKeyVal added in v0.4.13

func (tx *Tx) TryGetRecordByKeyVal(tArg AnyTable, key reflect.Value) (kvo.Record, ValueMeta, error)

func (*Tx) TryNewRecordEdit added in v0.4.13

func (tx *Tx) TryNewRecordEdit(tArg AnyTable, key any) (*RecordEdit, error)

TryNewRecordEdit prepares an insert. The table's insert policy selects the backing representation. SaveRecord rechecks that the key is still free.

func (*Tx) TryOpenRecordEdit added in v0.4.13

func (tx *Tx) TryOpenRecordEdit(tArg AnyTable, key any) (*RecordEdit, error)

TryOpenRecordEdit returns nil without error when the key is missing.

func (*Tx) TryPutRecordChecked added in v0.4.13

func (tx *Tx) TryPutRecordChecked(tArg AnyTable, key any, row kvo.Record, expected ValueMeta) (ValueMeta, error)

TryPutRecordChecked inserts or replaces a record using an explicit primary key. expected is the revision from GetRecord, or zero metadata for an insert. The existing row's storage codec is preserved; new keys follow table policy.

func (*Tx) TrySaveRecord added in v0.4.13

func (tx *Tx) TrySaveRecord(e *RecordEdit) (ValueMeta, error)

func (*Tx) TrySaveRecordWith added in v0.4.20

func (tx *Tx) TrySaveRecordWith(e *RecordEdit, prepare func(*kvo.Editor) error) (ValueMeta, error)

TrySaveRecordWith prepares pending editor changes after native save validation.

func (*Tx) TryUpgradeRecord added in v0.4.13

func (tx *Tx) TryUpgradeRecord(tArg AnyTable, key any) (bool, error)

TryUpgradeRecord changes only the envelope version and payload. Index bytes, revision and schema version remain intact. Repeating it is a no-op.

func (*Tx) UnsafeDeleteByKeyRawSkippingIndex added in v0.1.4

func (tx *Tx) UnsafeDeleteByKeyRawSkippingIndex(tblArg AnyTable, keyRaw []byte) bool

func (*Tx) UpgradeRecord added in v0.4.13

func (tx *Tx) UpgradeRecord(tArg AnyTable, key any) bool

UpgradeRecord panics on error. Use TryUpgradeRecord to handle errors explicitly.

type TxMetadata added in v0.4.15

type TxMetadata struct {
	Kind   string
	Tenant string
}

type TxObservation added in v0.4.15

type TxObservation struct {
	Metadata TxMetadata
	Writable bool
	Duration time.Duration
}

type Txish

type Txish interface {
	DBTx() *Tx
}

type ValueMeta

type ValueMeta struct {
	SchemaVer uint64
	ModCount  uint64
}

func GetMeta added in v0.4.7

func GetMeta[Row any](txh Txish, key any) ValueMeta

func (ValueMeta) Exists

func (vm ValueMeta) Exists() bool

func (ValueMeta) IsMissing

func (vm ValueMeta) IsMissing() bool

func (ValueMeta) IsModified added in v0.2.3

func (vm ValueMeta) IsModified(oldMeta ValueMeta) bool

Directories

Path Synopsis
Package edbindexing supplies typed index callbacks for common property reads.
Package edbindexing supplies typed index callbacks for common property reads.
examples
loyalty command
This example uses a temporary database; it leaves no files behind.
This example uses a temporary database; it leaves no files behind.
internal
statrow
Code generated by kvo.
Code generated by kvo.
statrow/gen command
research
kvo/cmd/census command
Census inventories table registration sites and reachable Go payload shapes.
Census inventories table registration sites and reachable Go payload shapes.
kvo/draft
Package kvodraft is an executable draft of KVO's schema-independent framing.
Package kvodraft is an executable draft of KVO's schema-independent framing.
kvo/experiments
Package kvolab contains disposable representation experiments, not a storage API.
Package kvolab contains disposable representation experiments, not a storage API.
storage-compat command
Command storage-compat rehearses old/new/old persistence using a disposable DB.
Command storage-compat rehearses old/new/old persistence using a disposable DB.

Jump to

Keyboard shortcuts

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