edb

package module
v0.4.13 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2026 License: MIT Imports: 35 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 database for Go, with shared data models, Go scripting, and HTML templates.

Go reference

EDB stores Go structs in bbolt. KVO reads their fields without decoding the whole row; EVM runs Go scripts; GoX renders Go-and-HTML templates. Use each on its own or together.

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.

That also makes EDB a darn good target for AI-written code. An agent can read the Go types, write an ordinary loop, and test the result. Less time translating business rules into a query language; fewer layers to misunderstand. The same small, explicit pieces that help a person move fast help an agent too.

EVM takes this further: let an AI write a plugin, compile and check it, then load it into the running application. Change a reward rule, add a report, or customize a workflow without rebuilding the host. KVO supplies typed access to data; GoX supplies templates. The host chooses the APIs the plugin can call and the execution limits it gets. Review, activation and permissions remain application policy—generated code does not get unrestricted access to the process.

With EVM, Go doubles as EDB's query language. The host can offer a call that runs a one-off script with access to the entire database. Query, join, aggregate, or update rows with ordinary Go. Use the same models and helpers as the application, without turning every new question into a new host endpoint.

How the pieces fit

Component What it does A typical use
edb Transactions, tables, primary keys, secondary indexes, and schema migrations Find a customer by email; update a balance atomically
kvo Logical models and typed property access over encoded rows or native Go structs Sum two fields across a large scan without decoding every customer
evm + evm/evmcompiler Compile a supported subset of Go to an embedded register VM Run an application-defined reward rule against a customer
gox Compile Go functions containing HTML into EVM programs Render a customer card with contextual escaping
values + nativebind Shared runtime values, type information, and native field operations Pass records between KVO and EVM; share generated Go field access
evm/evmbind Expose Go APIs to scripts and generate direct call/field bindings Let scripts call selected application services or registered model helpers

A KVO model defines a record type: its properties, their types, and stable numeric codes. EDB can store rows of that type; EVM can expose it as a script type, including for values that never enter a database.

A record is one value of that type. Its data can be a native Go struct, decoded memory, or bytes encoded as MessagePack, Fast2, or Compact2. The same property accesses work across these representations.

flowchart LR
    Go[Native Go code] --> DB[EDB transactions and indexes]
    DB -->|record views| KVO[KVO models and records]
    Go -->|typed properties| KVO
    Scripts[Go scripts] --> EVM[EVM]
    Templates[GoX templates] --> EVM
    EVM -->|model fields| KVO

Getting started

Go 1.27+. Install the API described here from the kvo branch:

go get github.com/andreyvit/edb@kvo

For a complete example, run this from a checkout:

go run ./examples/loyalty

The loyalty example creates a temporary database, inserts three customers, compares struct and KVO reads, runs a reward rule, renders HTML, and redeems points. It removes the database when finished. Its output includes:

Alice & Bob: 1000 points
VIP balance (Go structs): 1500
VIP balance (KVO): 1500
VIP bonus (EVM): 100

The examples below build up that application. The complete model declarations, Go script, and GoX template are executable sources, covered together by an example test.

Database

Define rows and indexes in Go

The first field of a row is its primary key. A key can be a scalar or a struct containing a composite key. msgpack:"-" keeps the key out of the value payload; EDB restores it when decoding a Go row. The kvo tags below map fields to the model introduced later.

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"`
}

An indexed table declares a KVO model and callbacks that yield index keys. The model below supplies the typed properties; the same callback reads native rows and encoded records:

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

    CustomersTable = edb.DefineTable(DBSchema, "customers", CustomerModel, func(b *edb.TableBuilder[uint64]) {
        customersByEmailIndex = b.AddIndex("by_email", edbindexing.ByFieldIfNonZero(Customer_Email), edb.IndexOptDeprecatedUnique)
        customersByTagIndex = b.AddIndex("by_tag", edbindexing.ByScalarList(Customer_Tags))
    })

    CustomerRows = CustomersTable.Rows[Customer]()
)

edbindexing supplies ByField (including zero), ByFieldIfNonZero, ByTimeFieldIfNonZero (using IsZero), and ByScalarList. Pass a callback directly for compound keys or domain-specific conditions.

One row can contribute several entries to an index, or none. This gives you tag indexes, filtered indexes, and compound keys without a query language. EDB maintains the entries when you update or delete the row.

Open, write, read

Open a persistent file during application startup, and close it at shutdown:

db, err := edb.Open("customers.db", DBSchema, edb.Options{})
if err != nil {
    return err
}
defer db.Close()

Use edb.InMemory as the path for the in-memory backend, useful in tests. The runnable example uses a temporary file to exercise bbolt.

Every operation runs inside a transaction. true opens a write transaction; false opens a read transaction. Put inserts or replaces the row at its primary key:

err = db.Tx(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
})
if err != nil {
    return err
}

Read by primary key or by an index:

err = db.Tx(false, func(tx *edb.Tx) error {
    customer := CustomerRows.Get(tx, 101)
    if customer == nil {
        return fmt.Errorf("customer not found")
    }
    fmt.Println(customer.FirstName) // Alice & Bob

    id, byEmail := CustomerRows.Lookup(tx, customersByEmailIndex, "alice@example.com")
    if byEmail == nil {
        return fmt.Errorf("email not found")
    }
    fmt.Println(id) // 101
    return nil
})
if err != nil {
    return err
}

Both reads return owned Go structs, or nil when absent. To delete by key, call CustomerRows.Delete(tx, 101) inside a write transaction; it returns whether a row was deleted.

Returning an error from a write callback rolls back its changes. Check the error from db.Tx, including commit failures. Write callbacks use bbolt batching and can be retried: keep external effects such as sending email outside the callback, after a successful commit. db.Read and db.Write are convenience forms that panic on errors.

Query with an index and a loop

Calculate the total available points for customers tagged vip:

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
}

Use CustomerRows.Scan(tx).Rows() to visit every customer. Table and index handles provide Exact, inclusive Range, From/After, and Through/Before; append .Reversed() to reverse the order. For example:

for id, customer := range CustomerRows.ExactIndexScan(tx, customersByTagIndex, "vip").Reversed().Entries() {
    // Export, aggregate, or join to another table using id.
    fmt.Println(id, customer.Email)
}

slices.Collect(scan.Rows()) collects decoded rows when you need them all in memory. For aggregation or streaming, range over the iterator directly. Scans are reusable descriptions: each iteration opens a new cursor in the same transaction, including after an early break. Keys() reads primary keys without fetching row payloads.

For bounded reads, use edb.ReadChunks(db, 500, query) with a factory returning a RecordScan or RowScan. Each chunk has its own read transaction and can be passed directly to other table operations for joins. For application-controlled transactions, use scan.Resume(bookmark).Chunk(500). Bookmarks own the complete index-and-primary-key position, including for reverse scans. Reopening between chunks changes the snapshot. See resumable scans, key-set composition, and keys-first updates for examples and ownership rules.

Lookup returns the primary key and the first matching row in storage order, even for a nonunique index. Use Exact(...).Entries() for every match. LookupKey returns (key, found) without reading the row. Keys can be strings, named scalar types, or structs containing composite keys; each handle validates its declared types at construction.

KVO

KVO separates the model, the stored format, and how you access a value. You can read a few fields directly from a stored row, decode once for repeated access, or wrap an existing Go struct. The application-facing property API stays the same.

Declare properties once

Register properties with stable codes and types, then include them in a model. These declarations belong at package scope or in application initialization, not inside a request or scan:

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

customer:first_name is the globally qualified property name; first_name is its local name within the customer model. A field can use either spelling in its kvo tag. Reuse a property across models when it has the same meaning and type. Registration panics on code/name collisions, including ambiguous local names within a model. Treat persistent codes as schema identifiers: do not renumber them or reuse retired codes for a different meaning.

kvo here is github.com/andreyvit/edb/kvo; values is its sibling package. The complete model file includes all imports.

Attach the model to a table

Pass the model after the table name. Its first registered native type supplies the storage binding; the builder specifies only the key type. MessagePack is the default storage format:

table := edb.DefineTable(DBSchema, "customers", CustomerModel, func(b *edb.TableBuilder[uint64]) {
    // Indexes, indexer, migrations, and other table settings.
})

To store new rows in Fast2, add this inside the definition callback:

b.SetRecordStorage(edb.RecordStorage{
    Format: edb.Fast2,
})

The example uses Fast2. Index callbacks read MessagePack, Fast2, Compact2, or an already-available native row. Indexing never requires decoding an encoded row into its Go struct.

b.AddIndex creates and registers each index, returning its handle. A nil callback leaves population to a shared b.SetIndexer. IndexOptDeprecatedUnique preserves the old one-row-per-key layout and last-write-wins behavior; it does not enforce uniqueness. The table model can expose a subset of an existing row; RecordStorage requires a complete storage binding. Supply optional field mappings through model.RegisterNativeType when adding tags is impractical. See the binding guide.

Read fields without decoding the row

DefineTable returns *Table[Key]; AddIndex returns *Index[IndexKey]. Tables provide record access directly. Index queries take the table, which supplies the primary-key type:

id, customer := CustomersTable.Lookup(tx, customersByEmailIndex, "alice@example.com")

The native handles use .Rows() and return *Customer; record handles use .Records() and return kvo.Record. Both provide .Entries() and .Keys(). Shared calculations need only a record:

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 CustomersTable.ExactIndexScan(tx, customersByTagIndex, tag).Records() {
        total += PointBalance(customer)
    }
    return total
}

Get(Customer_PointsEarned) returns int64. String properties return strings; typed list properties return kvo.List[T]. No AsInt conversion is needed:

r := CustomersTable.Get(tx, 101)
if r.Missing() {
    return fmt.Errorf("customer not found")
}
name := r.Get(Customer_FirstName) // string
list := r.Get(Customer_Tags)     // kvo.List[string]
fmt.Println(name, list.Len())
for tag := range list.Iter() {
    fmt.Println(tag)
}
tags := list.Slice() // allocate a Go slice when you actually need one
fmt.Println(strings.Join(tags, ", "))

Iter() is a single-pass, range-over-function iterator; call it again for another traversal. Child objects and lists of objects can also be borrowed as records, so you can keep using their own typed properties. Low-level GetValue(code) / SetValue(code, value) use the shared values.Value carrier. GetPathValue(path) and FastSetPathValue(path, value) handle nested paths; the fast setter accepts precomputed write options for callers such as EVM.

A kvo.Record is a 16-byte handle on 64-bit platforms. It carries data and shared representation metadata, not a decoded copy of every field. Ordinary scalar reads and borrowed list traversal can allocate nothing after setup. MessagePack access scans encoded fields; Fast2 and Compact2 use their own field layouts.

Edit inside a write transaction

A record edit remembers the table, primary key, and revision it was opened with. Validate the business operation, set typed properties, and save:

func redeem(db *edb.DB, id uint64, points int64) error {
    return db.Tx(true, func(tx *edb.Tx) error {
        edit := CustomersTable.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)
        CustomersTable.Save(tx, edit)
        return nil
    })
}

Saving maintains indexes and checks the edit's revision. Edits use copy-on-write or native editing according to the representation; editing and saving can allocate. Use CustomersTable.New(tx, key) and CustomersTable.Save(tx, edit) to prepare and save an insert with an explicit primary key. CustomersTable.Put(tx, key, r) replaces a whole record; CustomersTable.Delete(tx, key) removes one. These operations use the same write and index maintenance paths as native rows.

Record operations panic on errors by default. Use Try... forms where you want to handle errors explicitly. Advanced database reads also return metadata:

r, meta, err := CustomersTable.TryGet(tx, 101)
if err != nil {
    return err
}
// r.Missing() distinguishes absence; meta has SchemaVer and ModCount.
if !r.Missing() {
    fmt.Println("stored schema:", meta.SchemaVer, "revision:", meta.ModCount)
}
Keep keys and lifetimes explicit

A record does not implicitly contain its database primary key. Our Customer model omits ID, because it is not stored in the payload. Keep the lookup ID, take the key returned by Lookup, or iterate over entries:

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

For example, daily statistics can use a composite primary key:

type StatsKey struct {
    CustomerID uint64
    Day        string
}

// statsTable is defined with TableBuilder[StatsKey] and a model.
stats := statsTable
for id, customer := range CustomersTable.ExactIndexScan(tx, customersByTagIndex, "vip").Entries() {
    day := stats.Get(tx, StatsKey{id, "2026-11-10"})
    if !day.Missing() {
        fmt.Println(customer.Get(Customer_FirstName), day.Get(orders))
    }
}

The complete, tested join example includes the statistics model and table. stats.Prefix(tx, StatsKey{CustomerID: id}, 1).Entries() visits that customer's days. Prefix takes a count of tuple components; it does not perform string-prefix matching. Use GetRaw only when you already have an encoded primary key.

Typed handles return the declared primary-key type, including strings and composite structs. For low-level cursor access, UintKey() supports unsigned scalar keys. Key() returns a decoded any for general keys; RawKey() returns borrowed encoded key bytes. Index cursors expose the row's primary key through these methods too. For a join with the same key encoding, tx.GetRecordByKeyRaw(otherTable, c.RawKey()) avoids boxing a Go key.

Encoded records, strings, and list elements borrow storage from their transaction. Copy a record before retaining it beyond that transaction:

var saved kvo.Record
err = db.Tx(false, func(tx *edb.Tx) error {
    saved = CustomersTable.Get(tx, 101).Own()
    return nil
})
if err != nil {
    return err
}
fmt.Println(saved.Get(Customer_FirstName)) // safe after the transaction closes

Own() retains encoded data without decoding; it can return an already native object unchanged. Use Clone() for an independent snapshot, including native structs, before hypothetical edits. Keep a key or edb.Ref and reload when you want current state from a new transaction.

list.Slice() copies the slice but its elements can still borrow storage. Use list.OwnedSlice() for retained strings/bytes or owned record elements, and recordList.CloneSlice() for independent records. See the ownership contracts. These operations run at explicit boundaries; ordinary reads have no per-read expiry check.

Read sparse fields directly. For repeated access, Fastest() returns a decoded Go struct when bound, or indexed memory otherwise. Fast() keeps Fast2 and materializes other formats. Neither promises an independent snapshot; use Clone() for that.

See KVO access for native bindings, typed collections, ownership and decode costs.

EVM

EVM runs Go source inside your application. It type-checks scripts against the packages you expose, compiles them to bytecode, and executes them with reusable VM storage. Use it for reward rules, administrative scripts, or other logic that needs to change independently of the host binary.

Write a rule against the KVO model

This is bonus.go, an EVM .go file:

package rules

import "m"

func BonusPoints(customer *m.Customer) int64 {
    if customer == nil {
        return 0
    }
    balance := customer.points_earned - customer.points_redeemed
    if balance <= 0 {
        return 0
    }
    for _, tag := range customer.tags {
        if tag == "vip" {
            return balance / 10
        }
    }
    return 0
}

m.Customer is derived from the KVO model. Its selectors resolve to property codes at compile time; customer.tags can use borrowed list traversal. The rule works with the same supported representations as native record access. No Go Customer needs to be allocated just to call it.

Compile once, then pass records

Register the model package, compile the source, and link it during setup. Here bonusSource is the file's contents, embedded by the example host:

models, err := evm.ModelPackage("m", Models)
if err != nil {
    return err
}
module, err := evmcompiler.Compile("bonus.go", bonusSource, models)
if err != nil {
    return err
}
program, err := evm.Link(module, models)
if err != nil {
    return err
}
vm := evm.New(program)

Inside a read transaction, pass the record's value directly and read the scalar result:

r := CustomersTable.Get(tx, 101)
args := []values.Value{r.Value()}
var result [1]values.Value
err := vm.RunWithBudget(ctx, "BonusPoints", args, result[:], evm.Budget{Steps: 10_000})
if err != nil {
    return err
}
bonus := result[0].AsInt() // 100

values.Value is the common runtime carrier. The entry signature supplies its type; a record fits in the carrier without an extra box. Keep the transaction open for this invocation. Reuse a VM and argument/result storage for repeated calls; a VM is neither concurrent nor reentrant. An immutable linked program can be shared by separate VMs.

ModelPackage supplies types, not database access. Your application chooses whether scripts can look up customers, scan tables, write rows, or call services. Expose those operations through host packages. evmbind builds packages from Go API declarations and generates direct wrappers. It also supports explicitly registered record methods, letting a shared Go helper such as PointBalance(kvo.Record) appear as customer.PointBalance() in scripts.

EVM supports sequential Go, including functions, closures, interfaces, collections, and a selected standard library. It does not expose arbitrary native imports, goroutines, channels, or unsafe. Execution has instruction, allocation, depth, and cancellation limits; host functions must honor cancellation themselves. Bytecode and native bindings are trusted implementation inputs, not a portable bytecode format or an isolation boundary for arbitrary native code. Host APIs also declare borrowing effects so the compiler can copy escaping records when needed. See the compiler/runtime guide and Inside EVM.

GoX

GoX adds HTML to Go functions and compiles them through EVM. Templates use the same model types and host packages as scripts. Ordinary Go expressions and control flow do the work; markup determines where values render and how they are escaped.

Here is card.gox:

func CustomerCard(b *gox.Builder, customer *m.Customer) {
    <section class="loyalty-card">
        <h2>{customer.first_name}</h2>
        <p>
            customer.points_earned - customer.points_redeemed
            " points available"
        </p>
        for _, tag := range customer.tags {
            <span class="tag">{tag}</span>
        }
    </section>
}

A renderer takes a *gox.Builder followed by its typed inputs. Expressions in element bodies produce output; literal text is quoted. GoX files autoimport supplied packages by name, so m comes from the same models package used above. .go and .gox files can share a package, call one another, and define reusable components and slots.

Compile and link once:

template, err := gox.Compile("card.gox", cardSource, models)
if err != nil {
    return err
}
card, err := template.Link(models)
if err != nil {
    return err
}

Render inside the transaction that supplies the customer, omitting the builder argument:

r := CustomersTable.Get(tx, 101)
html, err := card.Render(ctx, []values.Value{r.Value()}, gox.RenderOptions{Strict: true})
if err != nil {
    return err
}
// Write html to an HTTP response, email body, or another output.

The result contains <h2>Alice &amp; Bob</h2> and 1000 points available. GoX performs contextual escaping for HTML, attributes, URLs, JavaScript, and CSS using Go's html/template escaping rules. Template authors and host packages are trusted; data is escaped unless explicitly marked as trusted content. Strict: true turns nil-field rendering failures into errors. Renders support execution and output budgets, and a linked GoX program supports concurrent renders.

See the GoX guide for components, slots, helper functions, CSS/text output, and diagnostics.

Storage and migrations

Storage format is separate from access strategy. Full struct reads, borrowed KVO reads, and decode-once access can coexist on a table.

Format Status Where it lives
Fast2 Current indexed KVO format, aimed at direct access kvo/codec/row2
Compact2 Current compact KVO format kvo/codec/row2
MessagePack Supported legacy format; transition intended; default for ordinary struct tables kvo/codec/msgpack
Fast1 Supported legacy format; transition intended; used by the separate KVTable API kvo/codec/fast1

Fast2 and Compact2 share value semantics and can coexist within a row, so they share a codec package. kvo.Record provides common access over MessagePack, Fast2, Compact2, native structs, and decoded memory. Fast1 retains its separate legacy access API. Historical code under research/ is not the current implementation.

Change the logical schema

Rows store a schema version, starting at 1. Set the new version and migrate older rows when they are loaded. For example, a version that normalizes surrounding whitespace in customer names:

// Inside the existing 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)))
})

Migrators run in registration order when the stored version is below their target. Targets cannot exceed the table schema version. Each callback edits decoded Go structs in place or batches changes to encoded records. Reads keep migrations in memory; saves and reindexing persist them. Read metadata retains the stored version for conflict checks. Keep old properties available while migrations need them; do not reuse stored property codes for incompatible types.

Change the stored format deliberately

Passing a model to DefineTable adds KVO access without changing MessagePack storage. RecordStorage selects Fast2 or Compact2 for new keys; existing MessagePack rows keep their encoding on ordinary updates.

For a staged rollout, first deploy readers with the model and RecordStorage{Format: edb.Fast2, MessagePackInserts: true}. After every reader supports the new format, disable MessagePackInserts. Convert existing keys explicitly in write transactions:

err := db.Tx(true, func(tx *edb.Tx) error {
    tx.UpgradeRecord(CustomersTable, uint64(101)) // no-op if already converted
    return nil
})

Conversion checks that the legacy data round-trips and the indexes agree. It preserves the revision and emits no logical change; migrate an outdated logical schema first. Plan batches appropriate for your database rather than holding one large write transaction. See KVO storage and migration for format and API details.

Performance

The useful question is how much work a complete operation does: which rows it visits, which fields it reads, whether it decodes them, and what survives the transaction.

For a selective read, start with borrowed records and typed properties. For repeated broad access, benchmark Fastest() with the intended native binding. Keep model construction, compilation, linking, and reusable VM setup outside the hot loop. Generated bindings remove reflective native field/call access; they do not remove the cost of decoding a row.

Ordinary encoded scalar reads, positioned cursor records, and immediate borrowed-list traversal can have zero per-row allocations after setup. Opening transactions/cursors, first-use metadata, schema migrations, custom decoders, ownership copies, edits, and materialized collections can still allocate. Measure the whole operation with -benchmem; a zero-allocation field getter is not a zero-allocation database request.

The repository includes reproducible benchmarks and reports:

Measurement Report
Typed properties, list views, and representation choices Typed KVO access
Typed table scans and joins, including transaction overhead Database record API measurements
Direct encoded reads versus generated/reflected native fields and decoded memory Access strategies
Shared Go/EVM list cells List traversal
VM workloads and other execution engines EVM benchmarks
Realistic GoX rendering versus cached html/template GoX benchmarks

For example:

go test ./kvo -run '^$' -bench 'Benchmark(AccessStrategy|DecodedAccess|TypedList)$' -benchmem
go test ./gox -run '^$' -bench BenchmarkApplication -benchmem

Documentation

For lower-level integration, db.Bolt() and tx.BoltTx() expose the bbolt database and transaction. They return nil for the in-memory backend.

Development

go test ./...             # full suite, including bbolt-backed database tests
go test -short ./...      # database tests using the in-memory backend
go test ./examples/loyalty

Tests live beside their implementation. Run gofmt on Go changes; use both full and short test runs when changing storage or scan behavior. AGENTS.md describes repository conventions. Contributions, focused bug reports, and reproducible benchmarks are welcome.

License

Copyright (c) 2023 Andrey Tarantsov. Published under the MIT license.

Documentation

Overview

Package edb implements a document database on top of a key-value store (in this case, on top of Bolt).

We implement:

1. Tables, collection of arbitrary documents marshaled from the given struct.

2. Indices, allowing quick lookup of table data 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).

Technical Details

**Buckets.** We rely on scoped namespaces for keys called buckets. Bolt supports them natively. A flat database like Redis could simulate buckets via key prefixes. We use nested buckets in Bolt, but only for conveninece; flat buckets are fine.

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

**TableDef 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 a (an ordinal) to each one. Ordinals are never reused as indexes are removed and added.

## Binary encoding

**Key encoding**. Keys are encoded using a _tuple encoding_.

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

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

**Value data**: msgpack of the row struct.

**IndexDef 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 (
	ReaderCount atomic.Int64
	WriterCount atomic.Int64
)
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 ErrNoRecordBinding = errors.New("table has no record binding")
View Source
var ErrRecordSchemaVersion = errors.New("row needs a schema migration before record access")

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, 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 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 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) BeginRead

func (db *DB) BeginRead() *Tx

func (*DB) BeginUpdate

func (db *DB) BeginUpdate() *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(f func(tx *Tx))

func (*DB) ReadErr

func (db *DB) ReadErr(f func(tx *Tx) error) error

func (*DB) Size added in v0.1.6

func (db *DB) Size() int64

func (*DB) Tx

func (db *DB) Tx(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(f func(tx *Tx))

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

func (*KVCursor) RawKey added in v0.3.1

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

func (*KVCursor) RawValue added in v0.3.1

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

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

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) 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 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 {
	Logf      func(format string, args ...any)
	Verbose   bool
	IsTesting bool
	MmapSize  int

	NoPersistentFreeList bool
	CaptureTxStack       bool
	ReuseTxBuffers       bool
}

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
	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 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 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 process-local, 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

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) 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) 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) 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]) Scan added in v0.4.13

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

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

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

func (*Tx) KVGetRaw added in v0.3.0

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

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) 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) 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 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.
evm
Package evm implements a register VM for compiled Go programs.
Package evm implements a register VM for compiled Go programs.
bench/internal/mathwork
Package mathwork holds the independent numeric workloads.
Package mathwork holds the independent numeric workloads.
bench/internal/optwork
Package optwork holds workloads compiled by both Go and EVM.
Package optwork holds workloads compiled by both Go and EVM.
bench/internal/workload
Package workload contains shared fixtures for the EVM and Lua benchmarks.
Package workload contains shared fixtures for the EVM and Lua benchmarks.
evmasm
Package evmasm assembles textual EVM code without a Go compiler.
Package evmasm assembles textual EVM code without a Go compiler.
evmbind
Package evmbind builds a reusable EVM host schema from Go declarations.
Package evmbind builds a reusable EVM host schema from Go declarations.
evmbind/cmd/evmbind command
Command evmbind generates a package of native wrappers for an EVM API.
Command evmbind generates a package of native wrappers for an EVM API.
evmbind/internal/methodfixture
Code generated by kvo.
Code generated by kvo.
evmcompiler
Package evmcompiler compiles sequential Go 1.23 to EVM bytecode.
Package evmcompiler compiles sequential Go 1.23 to EVM bytecode.
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.
gox
Package gox compiles GoX templates into typed EVM functions.
Package gox compiles GoX templates into typed EVM functions.
internal
inlinerow
Code generated by kvo.
Code generated by kvo.
inlinerow/gen command
naming
Package naming defines identifier spelling rules for EDB frontends.
Package naming defines identifier spelling rules for EDB frontends.
statrow
Code generated by kvo.
Code generated by kvo.
statrow/gen command
valuebench
Code generated by kvo.
Code generated by kvo.
valuebench/gen command
kvo
Package kvo defines logical models, typed properties, and record access and editing over MessagePack, Fast2, Compact2, native Go structs, and decoded memory.
Package kvo defines logical models, typed properties, and record access and editing over MessagePack, Fast2, Compact2, native Go structs, and decoded memory.
codec/fast1
Package fast1 implements the original KVO word-map storage format.
Package fast1 implements the original KVO word-map storage format.
codec/msgpack
Package msgpack implements EDB's MessagePack struct encoding.
Package msgpack implements EDB's MessagePack struct encoding.
codec/row2
Package row2 reads and writes the Fast2 and Compact2 KVO row formats.
Package row2 reads and writes the Fast2 and Compact2 KVO row formats.
Package nativebind selects native bindings once, when a schema is built.
Package nativebind selects native bindings once, when a schema is built.
internal/fixture
Code generated by nativebind.
Code generated by nativebind.
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.
Package values defines two-word values shared by KVO adapters and EVM.
Package values defines two-word values shared by KVO adapters and EVM.

Jump to

Keyboard shortcuts

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