kvo

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Dec 2, 2026 License: 0BSD Imports: 24 Imported by: 3 modules, 0 packages

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

README

KVO

Go reference

KVO gives you typed data records with a single API across every storage format. You declare a model once as a list of typed properties with stable numeric codes. After that, reading and editing a record works the same way whether its data lives in a Go struct, an encoded binary row, or decoded memory—and reading a single property from a row decodes only that property, not the whole row.

KVO separates three concerns: what a record means, how it is stored, and who reads it. Go code, EVM scripts, and GoX templates all work on the same records with the same types. Because kvo never imports the VM, you can use the data model on its own.

kvo does not include a database. A database such as edb stores the rows, hands out records, and decides when edits are saved.

A model in a page

Each property has a stable numeric code, a name, and a type. Declaring it returns a typed reference so every read and write uses the property's Go type:

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

	Customer_Name   = kvo.NewStringProp[string](Schema, 1, "customer:name", kvo.TMachineString)
	Customer_Earned = kvo.NewSignedProp[int64](Schema, 3, "customer:points_earned", kvo.TInt64)

	CustomerModel = kvo.NewModel(Schema, CustomerType, func(b *kvo.ModelBuilder) {
		b.Prop(Customer_Name)
		b.Prop(Customer_Earned)
	})

	Customers = kvo.Bind(reflect.TypeFor[Customer](), CustomerModel)
)

A kvo.Record is a 16-byte handle that views data in place:

fromStruct := Customers.Record(reflect.ValueOf(&customer))
fromRow := Customers.Encoded(row2.Open(rowBytes))

earned := fromRow.Get(Customer_Earned) // int64, read directly from rowBytes

edit := fromRow.Edit()
edit.Set(Customer_Earned, earned+100)
updated := edit.Record() // builds a new row; rowBytes is unchanged

Editing a struct record writes directly to the struct; editing an encoded row builds a new row. Code that takes a kvo.Record does not need to know which representation it received.

For a complete runnable walkthrough—one model over a Go struct, a Fast2 row, and a MessagePack row, read and edited from both Go and a script—see examples/kvo-basic and the root README.

Concepts

Term Meaning
Schema Holds properties and models.
Property A stable numeric code, a qualified name such as customer:points_earned, and a type. The code is its identity in every stored row—never renumber or reuse one.
Model The list of properties that belong to one record type.
Record kvo.Record, a 16-byte handle to one value of a model. It borrows the data it views.
Editor record.Edit(): typed writes to a struct, or a batch of changes that encodes a new row.
Binding Ties a model to a Go struct type and constructs records from structs and rows.

Always declare schemas, properties, models, and bindings at package scope or during startup. Their metadata lives for the lifetime of the process, so building them per request leaks memory.

Representations

Representation Package Status
Go struct kvo Read and written in place through nativebind field access.
Fast2 row kvo/codec/row2 Current. Full-width scalar slots and a key directory; favors access speed.
Compact2 row kvo/codec/row2 Current. Short integers and a trailing catalog; favors compact size.
MessagePack row kvo/codec/msgpack Supported legacy format. Views scan the encoded map; edits rewrite the changed path and preserve unknown fields.
Fast1 row kvo/codec/fast1 Supported legacy format with its own API.
Decoded memory kvo record.Fastest() on a row whose model has no Go struct: indexed, owned values.

Fast2 and Compact2 live in the same package because they share scalar semantics and container framing. You can even mix them inside one row: b.Prop(child, kvo.Compact) stores a child record compactly inside a Fast2 row. Layout is purely storage metadata and never changes a property's type.

Rows do not migrate themselves. Any reader that knows the model can read all of these formats; which format a table writes is configured by the database.

Lifetimes

A record borrows its underlying bytes, so a row read inside a database transaction is valid only for that transaction:

  • Call record.Own() to keep the data after its source is gone.
  • Call record.Clone() to make an independent copy you can safely edit.

EVM scripts get lifetime management automatically—the compiler inserts copies whenever a script keeps a record past its scope. Native Go code must call Own() or Clone() explicitly.

Packages

Package Responsibility
kvo Models, typed properties, record and collection views, editors, Go bindings, and their generator.
kvo/codec/row2 Fast2 and Compact2 wire formats, views, writers, and editors.
kvo/codec/msgpack MessagePack views, copy-on-write edits, and struct encoder/decoder.
kvo/codec/fast1 Original word-map encoding with its own views and edits.
values Shared runtime values, types, shapes, and scalar conversions.
nativebind Reflected and generated Go struct field access.

Further reading

Documentation

Overview

Package kvo defines logical models, typed properties, and record access and editing over MessagePack, Fast2, Compact2, native Go structs, and decoded memory. Records and collection views use 16-byte handles. Storage codecs live in the codec subpackages; values supplies the shared value representation.

Fastest materializes the native binding when attached, or indexed memory otherwise, independently of the storage format. Fast keeps an existing Fast2 view and otherwise uses Fastest.

Package record binds registered Go structs to persistent KVO property codes.

Index

Examples

Constants

View Source
const RuntimePropBase uint64 = 1 << 63

RuntimePropBase reserves the upper half of the property namespace for runtime fields.

View Source
const TimeOffsetMicros = 62_135_596_800_000_000

TimeOffsetMicros is offset to Time.UnixMicro() that kvo stores, chosen such that time.Time{}.UnixMicro() = -TimeOffsetMicros. With this offset, 0 micros correspond to zero time instead of Unix epoch, and we can treat all times as unsigned integers.

Variables

View Source
var (
	TInt = NewIntType[int]("int", func(fc *FmtContext, v int) string {
		return strconv.FormatInt(int64(v), 10)
	})
	TInt8 = NewIntType[int8]("int8", func(fc *FmtContext, v int8) string {
		return strconv.FormatInt(int64(v), 10)
	})
	TInt16 = NewIntType[int16]("int16", func(fc *FmtContext, v int16) string {
		return strconv.FormatInt(int64(v), 10)
	})
	TInt32 = NewIntType[int32]("int32", func(fc *FmtContext, v int32) string {
		return strconv.FormatInt(int64(v), 10)
	})
	TInt64 = NewIntType[int64]("int64", func(fc *FmtContext, v int64) string {
		return strconv.FormatInt(v, 10)
	})
	TUint = NewIntType[uint]("uint", func(fc *FmtContext, v uint) string {
		return strconv.FormatUint(uint64(v), 10)
	})
	TUint8 = NewIntType[uint8]("uint8", func(fc *FmtContext, v uint8) string {
		return strconv.FormatUint(uint64(v), 10)
	})
	TUint16 = NewIntType[uint16]("uint16", func(fc *FmtContext, v uint16) string {
		return strconv.FormatUint(uint64(v), 10)
	})
	TUint32 = NewIntType[uint32]("uint32", func(fc *FmtContext, v uint32) string {
		return strconv.FormatUint(uint64(v), 10)
	})
	TUint64 = NewIntType[uint64]("uint64", func(fc *FmtContext, v uint64) string {
		return strconv.FormatUint(v, 10)
	})
	TUintptr = NewIntType[uintptr]("uintptr", func(fc *FmtContext, v uintptr) string {
		return strconv.FormatUint(uint64(v), 10)
	})
	TFloat32 = NewFloatType[float32]("float32", func(fc *FmtContext, v float32) string {
		return strconv.FormatFloat(float64(v), 'g', -1, 32)
	})
	TFloat64 = NewFloatType[float64]("float64", func(fc *FmtContext, v float64) string {
		return strconv.FormatFloat(v, 'g', -1, 64)
	})
	TUint64Hex = NewIntType[uint64]("uint64_hex", func(fc *FmtContext, v uint64) string {
		return "0x" + strconv.FormatUint(v, 16)
	})
	TUnknownUint64 = NewIntType[uint64]("unknown_uint64", func(fc *FmtContext, v uint64) string {
		return strconv.FormatUint(v, 10)
	})
	TUknownKey = NewIntType[uint64]("unknown_key", func(fc *FmtContext, v uint64) string {
		return "0x" + strconv.FormatUint(v, 16)
	})

	TTime = NewScalarType[time.Time]("time", func(fc *FmtContext, v uint64) string {
		return Uint64ToTime(v).Format(time.RFC3339)
	}, func(newValue, oldValue uint64) uint64 {
		return uint64(int64(newValue) - int64(oldValue))
	}, func(value, delta uint64) uint64 {
		return uint64(int64(value) + int64(delta))
	}, func(delta uint64) int {
		return sign(int64(delta))
	})

	TBool = NewScalarType[bool]("bool", func(fc *FmtContext, v uint64) string {
		switch v {
		case 0:
			return "false"
		case 1:
			return "true"
		default:
			return fmt.Sprintf("?bool(0x%x)", v)
		}
	}, nil, nil, nil)

	TMachineString = NewMachineStringType[string]("string")
)

Built-in property types for numbers, legacy timestamps, booleans, and strings.

View Source
var ErrNativeMapping = errors.New("kvo: invalid native mapping")

ErrNativeMapping identifies an invalid native declaration or an unregistered projection. Such errors are programmer errors and panic during setup.

View Source
var ErrOmittedEntry = errors.New("zero map entry requires KeepDictionaryZeroValues")

ErrOmittedEntry reports that a zero-valued dictionary entry would be lost during encoding.

View Source
var ErrPropOption = errors.New("kvo: invalid property option")

ErrPropOption identifies an invalid property option, a schema declaration error.

View Source
var TBytes = NewBytesType[[]byte]("bytes")

TBytes is the built-in byte-slice property type.

View Source
var TJSON = &JSONType{&ScalarDataType{name: "json", codeSet: allocateTypeCode(), nativeType: reflect.TypeFor[any]()}}

TJSON is the built-in type for arbitrary JSON property values.

View Source
var TTimestamp = &ScalarDataType{nativeType: reflect.TypeFor[time.Time](), name: "timestamp", codeSet: allocateTypeCode()}

TTimestamp preserves nanosecond precision over the full time.Time range. Current codecs store integers; TTime retains its legacy microsecond format.

Functions

func DecodeJSON

func DecodeJSON(v values.Value, dst any)

DecodeJSON reads the encoded value as Go JSON data.

func Encoding

func Encoding(t AnyType) row2.Encoding

Encoding describes a property's wire conversion, independently of its runtime carrier. Containers remain explicit encoded byte spans; Child navigates them.

func Hex

func Hex(v uint64) string

Hex formats a word in uppercase hexadecimal with a trailing h.

func JSONValue

func JSONValue(v any) values.Value

JSONValue and DecodeJSON implement TJSON for reflective and generated bindings. Integer JSON tokens retain all 64 bits when decoded into an interface.

func LegacyTimeCodec

func LegacyTimeCodec() values.Codec[time.Time]

LegacyTimeCodec preserves TTime's offset-microsecond word representation. New persistent timestamps should use NewTimeProp and TTimestamp instead.

func RegisterMessagePackScalar

func RegisterMessagePackScalar(t reflect.Type, decode func(msgpack.View) values.Value)

RegisterMessagePackScalar supplies direct access for a Go scalar with custom MessagePack decoding. Register during initialization, before compiling any binding/projection of this type. The function must match the Go decoder, including historical encodings and nil, and must not mutate borrowed bytes. It returns the same normalized values.Value as Get. Encoding and editing continue to use the Go type's normal MessagePack encoder.

func SameType

func SameType(a, b AnyType) bool

SameType compares logical identity, including the key and value types of separately constructed map/list declarations.

func TimeToUint64

func TimeToUint64(t time.Time) uint64

TimeToUint64 encodes microseconds relative to Go's zero time for legacy TTime fields.

func Timestamp

func Timestamp(t time.Time) values.Value

Timestamp packs a Go time as a KVO timestamp value.

func Type

func Type(model *Model) *values.Type

Type is the logical record identity, shared by all physical representations.

func Uint64ToTime

func Uint64ToTime(u uint64) time.Time

Uint64ToTime decodes a legacy TTime word. Zero yields the Go zero time.

func WriteOptions

func WriteOptions(flags PropFlag) row2.KeyAccessOptions

WriteOptions converts model property flags to the options required by FastSetPathValue. Compilers can resolve these once when linking a field access.

Types

type AnyScalarType

type AnyScalarType interface {
	AnyType
}

AnyScalarType describes a scalar accepted by schema constructors.

type AnyType

type AnyType interface {
	Name() string
	String() string
	ValueKind() ValueKind
	Model() *Model
	ItemType() AnyType
	MapKeyType() AnyType
	MapProp(key uint64) PropImpl
	MapValueType(key uint64) AnyType
	Schema() *Schema // can return nil for generic types
	FormatValue(fc *FmtContext, value uint64) string
	Sub(lhs, rhs uint64) uint64
	Add(lhs, rhs uint64) uint64
	Sign(v uint64) int
	// contains filtered or unexported methods
}

AnyType describes a logical KVO type. Use SameType to compare independently constructed collection types.

type Binding

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

Binding is immutable schema metadata, reusable across transactions and programs. Retain configured bindings: using one publishes permanent representation IDs, never per-record or per-transaction metadata.

func Bind

func Bind(t reflect.Type, model *Model) *Binding

Bind returns the shared default binding for a Go struct and logical model. Configure generated/native access once and reuse the returned binding.

Example
package main

import (
	"fmt"
	"reflect"

	"github.com/andreyvit/evm/kvo"
)

func main() {
	type Customer struct {
		Name string `kvo:"name"`
	}
	schema := kvo.NewSchema()
	typ := kvo.NewEntityType(schema, "customer", reflect.TypeFor[Customer]())
	name := kvo.NewStringProp[string](schema, 1, "customer:name", kvo.TMachineString)
	model := kvo.NewModel(schema, typ, func(b *kvo.ModelBuilder) { b.Prop(name) })
	binding := kvo.Bind(reflect.TypeFor[Customer](), model)

	customer := Customer{Name: "Ada"}
	record := binding.Record(reflect.ValueOf(&customer))
	fmt.Println(record.Get(name))
	record.Edit().Set(name, "Grace")
	fmt.Println(customer.Name)
}
Output:
Ada
Grace

func (*Binding) Decode

func (b *Binding) Decode(raw []byte, dst reflect.Value)

Decode panics on error. Use TryDecode to handle errors explicitly.

func (*Binding) DecodeProperty

func (b *Binding) DecodeProperty(dst reflect.Value, r Record, key uint64)

DecodeProperty panics on error. Use TryDecodeProperty to handle errors explicitly.

func (*Binding) DirectMessagePack

func (b *Binding) DirectMessagePack() bool

DirectMessagePack reports whether the binding can read MessagePack fields without its fallback decoder.

func (*Binding) Encode

func (b *Binding) Encode(dst []byte, row reflect.Value, layout row2.Layout) []byte

Encode appends the bound row to dst using layout and panics on an encoding error. Use Binding.TryEncode to handle errors.

func (*Binding) Encoded

func (b *Binding) Encoded(v row2.View) Record

Encoded opens a record backed by a row2 view.

func (*Binding) Generate

func (b *Binding) Generate(pkg, name string) []byte

Generate panics on error. Use TryGenerate to handle errors explicitly.

func (*Binding) MessagePack

func (b *Binding) MessagePack(raw []byte) Record

MessagePack opens the MessagePack bytes using the binding's field mapping.

func (*Binding) NativeFieldIndex

func (b *Binding) NativeFieldIndex(key uint64) int

NativeFieldIndex resolves a direct Go field at table setup. It returns -1 for a property inside an inlined struct, which cannot be the table key field.

func (*Binding) Record

func (b *Binding) Record(ptr reflect.Value) Record

Record views the supplied pointer to the bound Go struct.

func (*Binding) TryDecode

func (b *Binding) TryDecode(raw []byte, dst reflect.Value) (err error)

TryDecode materializes owned Go values. Validation follows the model into each child.

func (*Binding) TryDecodeProperty

func (b *Binding) TryDecodeProperty(dst reflect.Value, r Record, key uint64) error

TryDecodeProperty decodes one modeled property into an addressable Go value using the shared native binding. It does not decode the rest of the record.

func (*Binding) TryDecodeRecord

func (b *Binding) TryDecodeRecord(r Record, dst reflect.Value) error

TryDecodeRecord decodes a record into an addressable native struct. Encoded data is detached by the native decoder. A native record of the same Go type uses ordinary struct assignment, including its reference fields; use Clone first when an independent native data graph is required.

MessagePack retains unmodeled fields when the native source and destination types match. Conversion between different native types uses modeled fields through the row2 codec, including its representation constraints. Same-type conversion preserves Go fields, even if the source uses another property mapping. On a decode error, dst may have been cleared or partly written.

func (*Binding) TryEncode

func (b *Binding) TryEncode(dst []byte, row reflect.Value, layout row2.Layout) (out []byte, err error)

TryEncode reports data that the declared storage policies cannot represent.

func (*Binding) TryGenerate

func (b *Binding) TryGenerate(pkg, name string) ([]byte, error)

TryGenerate emits a binding in the row's own package. The caller writes the returned Go file during go generate and passes its variable to RecordStorage.

func (*Binding) TryValidate

func (b *Binding) TryValidate(raw []byte) (err error)

TryValidate checks that Decode can materialize a row without allocating the Go graph. Packed writers use this before publishing bytes supplied by a caller.

func (*Binding) Validate

func (b *Binding) Validate(raw []byte)

Validate panics on error. Use TryValidate to handle errors explicitly.

func (Binding) WithGenerated

func (b Binding) WithGenerated(g *Generated, mode nativebind.Mode) *Binding

WithGenerated returns a copy configured to select generated accessors according to mode.

func (Binding) WithNativeSchema

func (b Binding) WithNativeSchema(s NativeSchema) *Binding

WithNativeSchema returns a copy that uses the supplied native field bindings.

type BoolPropRef

type BoolPropRef[T ~bool] struct {
	// contains filtered or unexported fields
}

BoolPropRef identifies a boolean property by its stable schema code.

func BindBoolProp

func BindBoolProp[T ~bool](schema *Schema, code uint64) BoolPropRef[T]

BindBoolProp binds an existing property and checks its compatibility with the boolean codec.

func NewBoolProp

func NewBoolProp[T ~bool](schema *Schema, code uint64, name string, typ AnyType) BoolPropRef[T]

NewBoolProp registers a boolean property and returns its typed accessor.

func (BoolPropRef[T]) Code

func (p BoolPropRef[T]) Code() uint64

Code returns the stable property code.

func (BoolPropRef[T]) Get

func (p BoolPropRef[T]) Get(r Record) T

Get reads the typed value directly from the record.

func (BoolPropRef[T]) Set

func (p BoolPropRef[T]) Set(e *Editor, v T)

Set writes the typed value through the editor.

type BytesPropRef

type BytesPropRef[T ~[]byte] struct {
	// contains filtered or unexported fields
}

BytesPropRef identifies a byte-slice property by its stable schema code.

func BindBytesProp

func BindBytesProp[T ~[]byte](schema *Schema, code uint64) BytesPropRef[T]

BindBytesProp binds an existing property and checks its compatibility with the byte-slice codec.

func NewBytesProp

func NewBytesProp[T ~[]byte](schema *Schema, code uint64, name string, typ AnyType) BytesPropRef[T]

NewBytesProp registers a byte-slice property and returns its typed accessor.

func (BytesPropRef[T]) Code

func (p BytesPropRef[T]) Code() uint64

Code returns the stable property code.

func (BytesPropRef[T]) Get

func (p BytesPropRef[T]) Get(r Record) T

Get reads the typed value directly from the record.

func (BytesPropRef[T]) Set

func (p BytesPropRef[T]) Set(e *Editor, v T)

Set writes the typed value through the editor.

type Cursor

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

Cursor traverses a borrowed scalar collection once. Next does not repeat the record property lookup. Slice allocates a slice of the remaining values; strings and byte spans still borrow the source record's storage. A copied cursor has an independent traversal position.

func (Cursor[T]) Iter

func (it Cursor[T]) Iter() iter.Seq[T]

Iter returns a single-pass sequence over a copy of the current position. Breaking a range stops immediately; invoking that sequence again resumes it.

func (Cursor[T]) Len

func (it Cursor[T]) Len() int

Len reports the number of elements available for traversal.

func (*Cursor[T]) Next

func (it *Cursor[T]) Next() (T, bool)

Next advances once and returns false at the end.

func (Cursor[T]) OwnedSlice

func (it Cursor[T]) OwnedSlice() []T

OwnedSlice materializes the remaining elements and detaches their string or byte storage. Like Slice, it does not advance the original cursor.

func (Cursor[T]) Slice

func (it Cursor[T]) Slice() []T

Slice materializes the available elements. Their contents may still borrow record storage.

type Editor

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

Editor applies property edits by path. A native editor writes to its bound struct.

func EditEncoded

func EditEncoded(e *row2.Editor) *Editor

EditEncoded shares an existing codec editor and writes through immediately. Use Record.Edit for a private editor that batches encoded changes.

func (*Editor) Changes

func (e *Editor) Changes() uint64

Changes counts assignments that changed a MessagePack or native record.

func (*Editor) Delete

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

Delete removes an encoded property or resets its native field to zero. Native fields without explicit presence cannot distinguish deletion from zero.

func (*Editor) Edit

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

Edit opens an attached child editor, or returns nil for an absent/null child. Merely opening an editor does not create or mutate the child.

func (*Editor) EditOrCreate

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

EditOrCreate opens the child record or creates an empty child when missing.

func (*Editor) FastSetPathValue

func (e *Editor) FastSetPathValue(path []row2.Step, x values.Value)

FastSetPathValue writes a path using its explicitly supplied Step.Options. EVM uses this API because its linker knows the model and precomputes these options once, avoiding model-policy lookups on every guest assignment. The options could be derived from the model, but doing so here would discard that optimization. They are used as-is, not merged with model defaults: callers must supply the intended compact-child and zero-preservation policy for each step. Explicit deletion also uses this path to bypass zero preservation. Ordinary property writes should use SetValue, which derives the policy. FastSetPathValue panics on error; use TryFastSetPathValue for error handling.

func (*Editor) FastSetPathValueWithWriter

func (e *Editor) FastSetPathValueWithWriter(path []row2.Step, x values.Value, w *row2.Writer)

FastSetPathValueWithWriter is FastSetPathValue with reusable encoding scratch.

func (*Editor) Get

func (e *Editor) Get[T any, P Property[T]](p P) T

Get reads the property through its typed access descriptor.

func (*Editor) GetAs

func (e *Editor) GetAs(path []row2.Step, enc row2.Encoding) values.Value

GetAs and SetAs supply the leaf encoding for schema-free editors.

func (*Editor) GetPathValue

func (e *Editor) GetPathValue(path []row2.Step) values.Value

GetPathValue reads a nested property. Use GetValue for a direct property.

func (*Editor) GetValue

func (e *Editor) GetValue(key uint64) values.Value

GetValue reads one property, including pending edits.

func (*Editor) Has

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

Has reports the model's presence semantics, including pending changes.

func (*Editor) List

func (e *Editor) List[E any, P ListProperty[E]](p P) E

List selects the typed editor for the specified list property.

func (*Editor) Map

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

Map selects the editor for the given dictionary property.

func (*Editor) MessagePack

func (e *Editor) MessagePack() []byte

MessagePack returns the edited payload without re-encoding untouched fields. Nil means this editor has another backing representation.

func (*Editor) Model

func (e *Editor) Model() *Model

Model returns the model for the edited record.

func (*Editor) NativeModel

func (e *Editor) NativeModel() *Model

NativeModel returns the model supplied by the native binding, if present.

func (*Editor) New

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

New explicitly creates an empty child. It panics if the child already exists.

func (*Editor) OwnsData

func (e *Editor) OwnsData() bool

OwnsData reports whether the backing representation owns its data.

func (*Editor) Packed

func (e *Editor) Packed() *row2.Editor

Packed exposes the codec editor. Direct codec writes bypass attached child editors, so obtaining it invalidates those child handles. Prefer Snapshot.

func (*Editor) Record

func (e *Editor) Record() Record

Record returns the current read view. Encoded edits produce a cached immutable snapshot; native edits still refer to their native object. Clone for isolation.

func (*Editor) Set

func (e *Editor) Set[T any, P Property[T]](p P, value T)

Set assigns a typed property value through the editor.

func (*Editor) SetAs

func (e *Editor) SetAs(path []row2.Step, x values.Value, enc row2.Encoding)

SetAs panics on error. Use TrySetAs to handle errors explicitly.

func (*Editor) SetValue

func (e *Editor) SetValue(key uint64, x values.Value)

SetValue writes one property using the model's write policy, including zero preservation for presence-significant and stored-primary-key properties. It panics on error; use TrySetValue to handle errors explicitly.

func (*Editor) Snapshot

func (e *Editor) Snapshot() row2.View

Snapshot returns a row2 view of the editor's current state.

func (*Editor) TryFastSetPathValue

func (e *Editor) TryFastSetPathValue(path []row2.Step, x values.Value) error

TryFastSetPathValue is FastSetPathValue with explicit error handling.

func (*Editor) TryFastSetPathValueWithWriter

func (e *Editor) TryFastSetPathValueWithWriter(path []row2.Step, x values.Value, w *row2.Writer) (err error)

TryFastSetPathValueWithWriter is TryFastSetPathValue with reusable encoding scratch.

func (*Editor) TrySet

func (e *Editor) TrySet[T any, P Property[T]](p P, value T) (err error)

TrySet assigns the value and reports conversion or assignment failures as errors.

func (*Editor) TrySetAs

func (e *Editor) TrySetAs(path []row2.Step, x values.Value, enc row2.Encoding) (err error)

TrySetAs writes a path using an explicit leaf encoding and reports assignment errors.

func (*Editor) TrySetValue

func (e *Editor) TrySetValue(key uint64, x values.Value) (err error)

TrySetValue is SetValue with explicit error handling.

func (*Editor) WithModel

func (e *Editor) WithModel(model *Model) *Editor

WithModel attaches the logical model and returns the editor.

type EntityType

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

EntityType identifies a record type within its schema. Attach its model with NewModel.

func NewEntityType

func NewEntityType(schema *Schema, name string, nativeTypes ...reflect.Type) *EntityType

NewEntityType declares an entity in schema for use with NewModel.

func (*EntityType) Add

func (typ *EntityType) Add(lhs, rhs uint64) uint64

Add panics because EntityType does not support scalar word arithmetic.

func (*EntityType) FormatValue

func (typ *EntityType) FormatValue(fc *FmtContext, value uint64) string

FormatValue panics because EntityType does not support scalar word formatting.

func (*EntityType) ItemType

func (typ *EntityType) ItemType() AnyType

ItemType returns nil. This type has no uniform element type.

func (*EntityType) MapKeyType

func (typ *EntityType) MapKeyType() AnyType

MapKeyType returns the type of a key used to look up an entry.

func (*EntityType) MapProp

func (typ *EntityType) MapProp(key uint64) PropImpl

MapProp looks up the schema property for key, or nil if absent.

func (*EntityType) MapValueType

func (typ *EntityType) MapValueType(key uint64) AnyType

MapValueType returns the property type and panics for an unknown property code.

func (*EntityType) Model

func (typ *EntityType) Model() *Model

Model returns the attached model and panics if no model has been defined.

func (*EntityType) Name

func (typ *EntityType) Name() string

Name returns the logical type name.

func (*EntityType) NativeTypes

func (typ *EntityType) NativeTypes() []reflect.Type

NativeTypes returns the explicitly allowed struct projections for this type.

func (*EntityType) Schema

func (typ *EntityType) Schema() *Schema

Schema returns the associated schema, if any.

func (*EntityType) Sign

func (typ *EntityType) Sign(v uint64) int

Sign panics because EntityType does not support scalar word arithmetic.

func (*EntityType) String

func (typ *EntityType) String() string

String returns the logical type name for display.

func (*EntityType) Sub

func (typ *EntityType) Sub(lhs, rhs uint64) uint64

Sub panics because EntityType does not support scalar word arithmetic.

func (*EntityType) ValueKind

func (typ *EntityType) ValueKind() ValueKind

ValueKind returns the storage category for this type.

type FieldMap

type FieldMap map[reflect.Type]map[PropCode]string

FieldMap associates exposed properties with direct, exported Go fields. A type without an entry uses its registered kvo tags (or legacy edb tags). Unmapped Go fields stay on the decoded row and do not become script properties.

type Float32PropRef

type Float32PropRef[T ~float32] struct {
	// contains filtered or unexported fields
}

Float32PropRef identifies a 32-bit floating-point property by its stable schema code.

func BindFloat32Prop

func BindFloat32Prop[T ~float32](schema *Schema, code uint64) Float32PropRef[T]

BindFloat32Prop binds an existing property and checks its compatibility with the 32-bit floating-point codec.

func NewFloat32Prop

func NewFloat32Prop[T ~float32](schema *Schema, code uint64, name string, typ AnyType) Float32PropRef[T]

NewFloat32Prop registers a 32-bit floating-point property and returns its typed accessor.

func (Float32PropRef[T]) Code

func (p Float32PropRef[T]) Code() uint64

Code returns the stable property code.

func (Float32PropRef[T]) Get

func (p Float32PropRef[T]) Get(r Record) T

Get reads the typed value directly from the record.

func (Float32PropRef[T]) Set

func (p Float32PropRef[T]) Set(e *Editor, v T)

Set writes the typed value through the editor.

type Float64PropRef

type Float64PropRef[T ~float64] struct {
	// contains filtered or unexported fields
}

Float64PropRef identifies a 64-bit floating-point property by its stable schema code.

func BindFloat64Prop

func BindFloat64Prop[T ~float64](schema *Schema, code uint64) Float64PropRef[T]

BindFloat64Prop binds an existing property and checks its compatibility with the 64-bit floating-point codec.

func NewFloat64Prop

func NewFloat64Prop[T ~float64](schema *Schema, code uint64, name string, typ AnyType) Float64PropRef[T]

NewFloat64Prop registers a 64-bit floating-point property and returns its typed accessor.

func (Float64PropRef[T]) Code

func (p Float64PropRef[T]) Code() uint64

Code returns the stable property code.

func (Float64PropRef[T]) Get

func (p Float64PropRef[T]) Get(r Record) T

Get reads the typed value directly from the record.

func (Float64PropRef[T]) Set

func (p Float64PropRef[T]) Set(e *Editor, v T)

Set writes the typed value through the editor.

type FloatValue

type FloatValue interface {
	~float32 | ~float64
}

Go value constraints for word-sized numeric properties.

type FmtContext

type FmtContext struct{}

FmtContext supplies context for formatting KVO values.

type Generated

type Generated struct {
	Fields      map[reflect.Type]*nativebind.GeneratedFields
	Fingerprint string
	Encode      func([]byte, any, row2.Layout) []byte
	Decode      func([]byte, any)
}

Generated binds direct Go field operations to the exact registered model.

type IntegerStringer

type IntegerStringer interface {
	IntegerValue
	fmt.Stringer
}

Go value constraints for word-sized numeric properties.

type IntegerValue

type IntegerValue interface {
	~int | ~int8 | ~int16 | ~int32 | ~int64 | ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr
}

Go value constraints for word-sized numeric properties.

type JSONOptions

type JSONOptions struct {
	Context context.Context
	Charge  func(uint64) error
}

JSONOptions lets a host meter a detached JSON projection.

type JSONType

type JSONType struct{ *ScalarDataType }

JSONType holds a JSON value in a byte span. Missing and explicit null remain distinguishable through property presence or dictionary membership.

type LegacyTimePropRef

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

LegacyTimePropRef retains TTime's offset-microsecond word encoding.

func NewLegacyTimeProp

func NewLegacyTimeProp(schema *Schema, code uint64, name string) LegacyTimePropRef

NewLegacyTimeProp declares a property using the legacy TTime wire format.

func (LegacyTimePropRef) Code

func (p LegacyTimePropRef) Code() uint64

Code returns the stable schema code for the timestamp property.

func (LegacyTimePropRef) FromWord

func (p LegacyTimePropRef) FromWord(v uint64) time.Time

FromWord decodes the legacy offset-microsecond representation.

func (LegacyTimePropRef) Get

func (p LegacyTimePropRef) Get(r Record) time.Time

Get reads the stored timestamp as a Go time.

func (LegacyTimePropRef) ToWord

func (p LegacyTimePropRef) ToWord(v time.Time) uint64

ToWord encodes a Go time in the legacy offset-microsecond representation.

type List

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

List is a 16-byte borrowed collection view. Get resolves the property once; Cursor and Iter initialize independent, single-pass traversal positions. Keeping a List alive keeps its Go backing storage alive, but does not extend a database transaction's lifetime.

func (List[T]) Cursor

func (l List[T]) Cursor() Cursor[T]

Cursor starts an independent traversal over the list.

func (List[T]) Iter

func (l List[T]) Iter() iter.Seq[T]

Iter returns a single-pass sequence. Reusing this sequence resumes its position; call Iter again to start a separate traversal.

func (List[T]) Len

func (l List[T]) Len() int

Len reports the number of elements available for traversal.

func (List[T]) Missing

func (l List[T]) Missing() bool

Missing reports whether the list property is absent.

func (List[T]) OwnedSlice

func (l List[T]) OwnedSlice() []T

OwnedSlice copies both the slice and any borrowed string/byte elements.

func (List[T]) Slice

func (l List[T]) Slice() []T

Slice materializes the available elements. Their contents may still borrow record storage.

func (List[T]) Value

func (l List[T]) Value() values.Value

Value returns the guest value carrying the list view.

type ListAccess

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

ListAccess is shared model metadata for reading a collection when its element type is supplied dynamically, as it is in EVM bytecode. It creates the same ListCell representation used by List[T] and RecordList.

func BindListAccess

func BindListAccess(model *Model, code uint64) *ListAccess

BindListAccess returns the model's cached accessor. Recompiling a script does not create immortal representation metadata per program or per invocation.

func (*ListAccess) Get

func (a *ListAccess) Get(r Record) ListCell

Get resolves the bound list property as a collection cell.

func (*ListAccess) Records

func (a *ListAccess) Records(r Record) RecordList

Records views an object list without serialization, preserving missing elements.

func (*ListAccess) TryCell

func (a *ListAccess) TryCell(v values.Value) (ListCell, bool)

TryCell also validates the declared element type before using a dynamically transported cell. It accepts cells made by typed Go property references.

type ListCell

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

ListCell is a typed cell pointing directly at borrowed storage. Its shared representation describes the encoding and element access; no per-list box is allocated. Traversal state is separate: local in Go or reused by the VM.

func ListCellFromValue

func ListCellFromValue(v values.Value) ListCell

ListCellFromValue interprets a VM value as a collection cell.

func TryListCell

func TryListCell(v values.Value) (ListCell, bool)

TryListCell checks that v belongs to the collection representation registry. Record cells and ordinary bytes/slices are not interchangeable with list cells.

func (ListCell) At

func (l ListCell) At(index int) values.Value

At retrieves an element by zero-based index.

func (ListCell) Iter

func (l ListCell) Iter() ListValueIterator

Iter builds local traversal state; the cell itself stays 16 bytes.

func (ListCell) Len

func (l ListCell) Len() int

Len returns the element count of the borrowed collection.

func (ListCell) Value

func (l ListCell) Value() values.Value

Value transports a borrowed collection in one shared cell without boxing.

func (ListCell) View

func (l ListCell) View() ListValue

View expands a cell into stack access metadata. Retain the compact cell when passing a collection around; keep the expanded view beside a hot iterator.

type ListEditor

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

ListEditor materializes the selected list on its first mutation, then batches subsequent changes. It never decodes the enclosing record.

func (*ListEditor[T]) AddUnique

func (l *ListEditor[T]) AddUnique(v T) bool

AddUnique appends v only if absent and reports whether the list changed.

func (*ListEditor[T]) Append

func (l *ListEditor[T]) Append(items ...T)

Append adds the items at the end in argument order.

func (*ListEditor[T]) Clear

func (l *ListEditor[T]) Clear()

Clear replaces the property with an empty list.

func (*ListEditor[T]) Contains

func (l *ListEditor[T]) Contains(v T) bool

Contains reports whether the list already contains v.

func (*ListEditor[T]) Get

func (l *ListEditor[T]) Get(index int) T

Get reads the element at the zero-based index.

func (*ListEditor[T]) Iter

func (l *ListEditor[T]) Iter() iter.Seq[T]

Iter yields the current elements in list order.

func (*ListEditor[T]) Len

func (l *ListEditor[T]) Len() int

Len counts the current elements, including pending edits.

func (*ListEditor[T]) Remove

func (l *ListEditor[T]) Remove(v T) bool

Remove deletes a matching value and reports whether one was found.

func (*ListEditor[T]) RemoveAt

func (l *ListEditor[T]) RemoveAt(index int)

RemoveAt deletes the element at index.

func (*ListEditor[T]) Set

func (l *ListEditor[T]) Set(index int, v T)

Set replaces the element at index.

func (*ListEditor[T]) Slice

func (l *ListEditor[T]) Slice() []T

Slice materializes the current elements into a separate slice.

type ListPropRef

type ListPropRef[T any] struct {
	*PropRef[List[T]]
	// contains filtered or unexported fields
}

ListPropRef shares conversion and representation metadata across all values.

func BindListProp

func BindListProp[T any](schema *Schema, code uint64, codec values.Codec[T]) *ListPropRef[T]

BindListProp binds an existing list property to the supplied element codec.

func NewListProp

func NewListProp[T any](schema *Schema, code uint64, name string, typ AnyType, codec values.Codec[T]) *ListPropRef[T]

NewListProp declares a list property and binds its element codec.

func (*ListPropRef[T]) FromSlice

func (p *ListPropRef[T]) FromSlice(items []T) List[T]

FromSlice copies items into an owned encoded collection for assignment. Reads through Get do not make this copy.

func (*ListPropRef[T]) SetSlice

func (p *ListPropRef[T]) SetSlice(e *Editor, items []T)

SetSlice replaces the property's list with the supplied elements.

type ListProperty

type ListProperty[E any] interface {
	// contains filtered or unexported methods
}

ListProperty selects a scalar or record list editor from its property type.

type ListType

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

ListType is schema metadata for positional values. The legacy Fast1 codec does not acquire List encoding support by declaring this type.

func ListOf

func ListOf(itemType AnyType) *ListType

ListOf constructs the logical list type for the supplied elements.

func (*ListType) Add

func (typ *ListType) Add(uint64, uint64) uint64

Add panics because ListType does not support scalar word arithmetic.

func (*ListType) FormatValue

func (typ *ListType) FormatValue(*FmtContext, uint64) string

FormatValue panics because ListType does not support scalar word formatting.

func (*ListType) ItemType

func (typ *ListType) ItemType() AnyType

ItemType returns the element type.

func (*ListType) MapKeyType

func (typ *ListType) MapKeyType() AnyType

MapKeyType returns nil. This type has no dictionary keys.

func (*ListType) MapProp

func (typ *ListType) MapProp(uint64) PropImpl

MapProp returns nil. Only entity types resolve keys to schema properties.

func (*ListType) MapValueType

func (typ *ListType) MapValueType(uint64) AnyType

MapValueType returns nil. This type has no dictionary values.

func (*ListType) Model

func (typ *ListType) Model() *Model

Model returns nil. This type has no entity model.

func (*ListType) Name

func (typ *ListType) Name() string

Name returns the logical type name.

func (*ListType) Schema

func (typ *ListType) Schema() *Schema

Schema returns the associated schema, if any.

func (*ListType) Sign

func (typ *ListType) Sign(uint64) int

Sign panics because ListType does not support scalar word arithmetic.

func (*ListType) String

func (typ *ListType) String() string

String returns the logical type name for display.

func (*ListType) Sub

func (typ *ListType) Sub(uint64, uint64) uint64

Sub panics because ListType does not support scalar word arithmetic.

func (*ListType) ValueKind

func (typ *ListType) ValueKind() ValueKind

ValueKind returns the storage category for this type.

type ListValue

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

ListValue borrows a list property without constructing a slice or converting its encoding. Its lifetime is the source record's lifetime. Scalar and string elements are read without allocations; aggregate elements use GetValue's encoding.

func (ListValue) At

func (l ListValue) At(index int) values.Value

At reads one element; MessagePack and Compact2 require a linear scan. Prefer Iter for sequential access. The returned string/bytes may borrow source data.

func (ListValue) Iter

func (l ListValue) Iter() ListValueIterator

Iter starts a traversal of the borrowed list.

func (ListValue) Len

func (l ListValue) Len() int

Len returns the number of elements in the list.

func (ListValue) Missing

func (l ListValue) Missing() bool

Missing reports whether there is a stored list value.

type ListValueIterator

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

ListValueIterator visits scalar elements without allocating or rescanning earlier elements. Keep it as a local value; it borrows the list's source data.

func (*ListValueIterator) Next

func (it *ListValueIterator) Next() (values.Value, bool)

Next yields the next element and returns false at the end.

type LocalID

type LocalID uint64

LocalID identifies a property within a model.

type MachineStringType

type MachineStringType = ScalarDataType

MachineStringType is the scalar-data type used for native strings.

func NewMachineStringType

func NewMachineStringType[T ~string](name string) *MachineStringType

NewMachineStringType defines a string type backed by a Go string or named string type.

type Map

type Map[K comparable, V any] struct {
	// contains filtered or unexported fields
}

Map is a 16-byte borrowed view. Lookup and iteration read the stored encoding; no Go map or intermediate encoding is constructed. Retain the owning Record with Own before retaining this view across a transaction boundary.

func (Map[K, V]) Get

func (m Map[K, V]) Get(key K) V

Get returns the value for key or its zero value when absent.

func (Map[K, V]) Iter

func (m Map[K, V]) Iter() iter.Seq2[K, V]

Iter yields key/value pairs from the borrowed dictionary.

func (Map[K, V]) Keys

func (m Map[K, V]) Keys() iter.Seq[K]

Keys visits keys without decoding values, including dynamic JSON values.

func (Map[K, V]) Len

func (m Map[K, V]) Len() int

Len returns the number of entries.

func (Map[K, V]) Lookup

func (m Map[K, V]) Lookup(key K) (out V, found bool)

Lookup reads key and distinguishes a missing entry from a present zero.

func (Map[K, V]) Missing

func (m Map[K, V]) Missing() bool

Missing reports whether the dictionary property is absent.

type MapCodec

type MapCodec[K comparable, V any] struct {
	// contains filtered or unexported fields
}

MapCodec is reusable metadata for scalar, record, or nested-map values. Construct it during schema setup; views retain only their 16-byte cell.

func NewMapCodec

func NewMapCodec[K comparable, V any](typ *MapType, key values.Codec[K], value values.Codec[V]) *MapCodec[K, V]

NewMapCodec binds key and value codecs to an existing map type.

func NewNestedMapCodec

func NewNestedMapCodec[K comparable, K2 comparable, V any](keyType AnyType, key values.Codec[K], inner *MapCodec[K2, V]) *MapCodec[K, Map[K2, V]]

NewNestedMapCodec builds an outer map whose values are borrowed typed maps.

func NewRecordMapCodec

func NewRecordMapCodec[K comparable](typ *MapType, key values.Codec[K]) *MapCodec[K, Record]

NewRecordMapCodec constructs a dictionary codec whose values are model records.

func (*MapCodec[K, V]) Prop

func (c *MapCodec[K, V]) Prop(schema *Schema, code uint64, name string, flags ...PropFlag) *MapPropRef[K, V]

Prop declares a typed map. Explicit flags replace the default zero-entry retention policy, allowing existing schemas to keep their storage contract.

func (*MapCodec[K, V]) Type

func (c *MapCodec[K, V]) Type() *MapType

Type returns the logical dictionary type.

type MapEditor

type MapEditor[K comparable, V any] struct {
	// contains filtered or unexported fields
}

MapEditor buffers entry changes. Reads observe the buffer immediately; encoded dictionaries and their parent records are rebuilt only on snapshot/save.

func EditMap

func EditMap[K comparable, K2 comparable, V any](outer *MapEditor[K, Map[K2, V]], key K) *MapEditor[K2, V]

EditMap opens an attached nested dictionary, returning nil for a missing key. The free function infers both maps' key/value types from the outer editor.

func EditOrCreateMap

func EditOrCreateMap[K comparable, K2 comparable, V any](outer *MapEditor[K, Map[K2, V]], key K) *MapEditor[K2, V]

EditOrCreateMap opens the nested dictionary at key or creates it when absent.

func NewMap

func NewMap[K comparable, K2 comparable, V any](outer *MapEditor[K, Map[K2, V]], key K) *MapEditor[K2, V]

NewMap explicitly creates a nested dictionary. Existing entries panic.

func (*MapEditor[K, V]) Clear

func (m *MapEditor[K, V]) Clear()

Clear leaves an empty dictionary. Editor.Delete removes the property itself.

func (*MapEditor[K, V]) Delete

func (m *MapEditor[K, V]) Delete(key K) bool

Delete removes key and reports whether it was present.

func (*MapEditor[K, V]) Edit

func (m *MapEditor[K, V]) Edit(key K) *Editor

Edit opens a record-valued entry. Missing/null entries return nil; New and EditOrCreate explicitly create entries. Scalar-valued maps reject this API.

func (*MapEditor[K, V]) EditOrCreate

func (m *MapEditor[K, V]) EditOrCreate(key K) *Editor

EditOrCreate opens the record at key or creates one if absent.

func (*MapEditor[K, V]) Get

func (m *MapEditor[K, V]) Get(key K) V

Get reads a key and returns the zero value when it is absent.

func (*MapEditor[K, V]) Iter

func (m *MapEditor[K, V]) Iter() iter.Seq2[K, V]

Iter yields the current dictionary entries, including buffered changes.

func (*MapEditor[K, V]) Len

func (m *MapEditor[K, V]) Len() int

Len counts the entries visible through the editor.

func (*MapEditor[K, V]) Lookup

func (m *MapEditor[K, V]) Lookup(key K) (V, bool)

Lookup reads a key including pending edits and reports whether it exists.

func (*MapEditor[K, V]) New

func (m *MapEditor[K, V]) New(key K) *Editor

New creates a record at key and panics if an entry already exists.

func (*MapEditor[K, V]) Set

func (m *MapEditor[K, V]) Set(key K, v V)

Set preserves zero values as present dictionary entries.

func (*MapEditor[K, V]) SetNull

func (m *MapEditor[K, V]) SetNull(key K)

SetNull stores an explicit null JSON entry. Lookup then returns (nil, true); Delete removes it. Non-JSON dictionaries reject null rather than silently zeroing.

type MapPropRef

type MapPropRef[K comparable, V any] struct {
	*PropRef[Map[K, V]]
	// contains filtered or unexported fields
}

MapPropRef binds a schema property to typed dictionary access.

func NewJSONMapProp

func NewJSONMapProp[K comparable](schema *Schema, code uint64, name string, keyType AnyType, key values.Codec[K]) *MapPropRef[K, any]

NewJSONMapProp borrows the dictionary and decodes only the selected dynamic entry. Scalar/record maps have allocation-free access; dynamic object trees allocate when materialized as any. Nil is a present JSON null, not deletion.

func NewMapProp

func NewMapProp[K comparable, V any](schema *Schema, code uint64, name string, typ *MapType, key values.Codec[K], value values.Codec[V]) *MapPropRef[K, V]

NewMapProp declares a typed scalar dictionary. Keys may be strings or integers, including domain enums; custom MessagePack key codecs retain their semantics.

func NewRecordMapProp

func NewRecordMapProp[K comparable](schema *Schema, code uint64, name string, typ *MapType, key values.Codec[K]) *MapPropRef[K, Record]

NewRecordMapProp declares a record-valued dictionary property and returns its accessor.

func (*MapPropRef[K, V]) Codec

func (p *MapPropRef[K, V]) Codec() *MapCodec[K, V]

Codec returns the key and value conversion rules for this property.

func (*MapPropRef[K, V]) FromMap

func (p *MapPropRef[K, V]) FromMap(m map[K]V) Map[K, V]

FromMap creates an owned encoded dictionary for whole-property assignment. Ordinary borrowed reads and per-entry edits do not materialize this map.

type MapType

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

MapType describes a dictionary's key and element types.

func MapOf

func MapOf(keyType AnyScalarType, itemType AnyType) *MapType

MapOf constructs the logical dictionary type for the supplied keys and elements.

func (*MapType) Add

func (typ *MapType) Add(lhs, rhs uint64) uint64

Add panics because MapType does not support scalar word arithmetic.

func (*MapType) FormatValue

func (typ *MapType) FormatValue(fc *FmtContext, value uint64) string

FormatValue panics because MapType does not support scalar word formatting.

func (*MapType) ItemType

func (typ *MapType) ItemType() AnyType

ItemType returns the element type.

func (*MapType) MapKeyType

func (typ *MapType) MapKeyType() AnyType

MapKeyType returns the type of a key used to look up an entry.

func (*MapType) MapProp

func (typ *MapType) MapProp(key uint64) PropImpl

MapProp returns nil. Only entity types resolve keys to schema properties.

func (*MapType) MapValueType

func (typ *MapType) MapValueType(key uint64) AnyType

MapValueType returns the dictionary element type for every key.

func (*MapType) Model

func (typ *MapType) Model() *Model

Model returns nil. This type has no entity model.

func (*MapType) Name

func (typ *MapType) Name() string

Name returns the logical type name.

func (*MapType) Schema

func (typ *MapType) Schema() *Schema

Schema returns the associated schema, if any.

func (*MapType) Sign

func (typ *MapType) Sign(v uint64) int

Sign panics because MapType does not support scalar word arithmetic.

func (*MapType) String

func (typ *MapType) String() string

String returns the logical type name for display.

func (*MapType) Sub

func (typ *MapType) Sub(lhs, rhs uint64) uint64

Sub panics because MapType does not support scalar word arithmetic.

func (*MapType) ValueKind

func (typ *MapType) ValueKind() ValueKind

ValueKind returns the storage category for this type.

type Model

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

Model describes which schema properties belong to a record type and how their names resolve.

func NewModel

func NewModel(schema *Schema, entityType *EntityType, build func(b *ModelBuilder)) *Model

NewModel registers the entity type's model after build selects its properties. Each entity type can have only one model.

func (*Model) AllProps

func (model *Model) AllProps() []PropImpl

AllProps returns the model's declared properties.

func (*Model) MustPropByCode

func (model *Model) MustPropByCode(key uint64) PropImpl

MustPropByCode looks up a property and panics if the code is unknown.

func (*Model) Name

func (model *Model) Name() string

Name returns the registered name.

func (*Model) NativeStruct

func (model *Model) NativeStruct(t reflect.Type) *NativeStruct

NativeStruct resolves only an explicitly registered projection. Call after NewModel; tag validation occurs when that model is declared.

func (*Model) PrimaryKey

func (model *Model) PrimaryKey() PropImpl

PrimaryKey returns the explicitly stored key property, or nil for a model whose records do not carry database identity.

func (*Model) PropByCode

func (model *Model) PropByCode(key uint64) PropImpl

PropByCode looks up a property by its stored code and returns nil if it is unknown.

func (*Model) PropByName

func (model *Model) PropByName(name string) PropImpl

PropByName resolves every accepted property name: the model-local name, the original unqualified name, the full colon-qualified name, and its underscore spelling. Renaming a property locally preserves the other names.

func (*Model) PropBySelector

func (model *Model) PropBySelector(name string) PropImpl

PropBySelector resolves exactly the names enumerated by Selectors.

func (*Model) PropFlags

func (model *Model) PropFlags(key PropCode) PropFlag

PropFlags returns the model-specific options for a declared property.

func (*Model) RegisterNativeFields

func (model *Model) RegisterNativeFields(generated ...*nativebind.GeneratedFields)

RegisterNativeFields installs generated getters/setters for registered structs and their inline embeddings. Call after RegisterNativeType and before any binding or projection is built, including through a containing model. Missing types keep reflected access; supplied bindings must match exactly.

func (*Model) RegisterNativeType

func (model *Model) RegisterNativeType(t reflect.Type, fields ...map[PropCode]string)

RegisterNativeType attaches a Go struct after the logical model is declared. An omitted or nil field map uses kvo tags. An explicit map associates each model property with a direct exported Go field; other fields stay unexposed. Registration compiles and owns the mapping, so later map edits have no effect. Call during single-threaded setup, before constructing bindings or accessing records. Duplicate registrations panic.

func (*Model) RowName

func (model *Model) RowName() string

RowName is an optional virtual row type name; it does not change stored identity.

func (*Model) Selectors

func (model *Model) Selectors() iter.Seq2[string, PropImpl]

Selectors enumerates the identifier-safe property names in lexical order. Each alias identifies the same model-specific property. Colon-qualified names remain available through PropByName and native mapping tags, not dot access.

func (*Model) Type

func (model *Model) Type() AnyType

Type returns the model's logical entity type.

type ModelBuilder

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

ModelBuilder selects properties and their names while NewModel builds a model.

func (*ModelBuilder) Inline

func (b *ModelBuilder) Inline(model *Model)

Inline includes another model's properties directly, preserving names and storage policies. It adds no container property or wire nesting.

func (*ModelBuilder) Prop

func (b *ModelBuilder) Prop[P PropertyCode](property P, opts ...any)

Prop includes a typed property reference or a schema declaration. Numeric codes are not properties; resolve dynamic codes through Schema first.

func (*ModelBuilder) SetRowName

func (b *ModelBuilder) SetRowName(name string)

SetRowName overrides the generated row type name for this model.

type ModelDefinition

type ModelDefinition struct {
	Name  string
	Props []*PropInstance
}

ModelDefinition lists the property instances of a model.

type NativeField

type NativeField struct {
	Index                    int
	Path                     []int
	Prop                     PropImpl
	Compact                  bool
	PresenceIsSignificant    bool
	KeepDictionaryZeroValues bool
}

NativeField binds one explicit struct field to a property of its object model. Index addresses a direct field, or is -1 when Path traverses inlined structs.

func (NativeField) FieldPath

func (f NativeField) FieldPath() []int

FieldPath returns the complete Go field path, including explicit inline layers.

type NativeSchema

type NativeSchema interface {
	NativeFields(reflect.Type) *nativebind.Struct
	NativeType(reflect.Type) *values.Type
}

NativeSchema is implemented by evmbind.Schema. It connects a KVO projection to the same field operations and nominal type used by EVM host bindings.

type NativeStruct

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

NativeStruct is immutable, validated tag metadata. Persistent tables compile this metadata into a strict native conversion plan by Bind.

func (*NativeStruct) Fields

func (n *NativeStruct) Fields() []NativeField

Fields returns a copy, so a binding compiler cannot modify shared schema data.

func (*NativeStruct) Type

func (n *NativeStruct) Type() reflect.Type

Type returns the bound native Go type.

type Optional

type Optional[T any] struct {
	Value   T
	Present bool
}

Optional is used only on properties marked PresenceIsSignificant. It adds no wire type: Present controls whether the ordinary value is stored at all.

type Projection

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

Projection binds properties to a Go struct or its MessagePack representation. It does not provide a full row2 storage codec: the model may omit stored Go fields.

func Project

func Project(t reflect.Type, m *Model, fields FieldMap) *Projection

Project shares default projections (nil fields) by Go type and model. Explicit field maps create independent configurations; build those once and retain them, just like WithGenerated and WithNativeSchema configurations.

func (*Projection) DecodeProperty

func (p *Projection) DecodeProperty(dst reflect.Value, r Record, key uint64)

DecodeProperty panics on error. Use TryDecodeProperty to handle errors explicitly.

func (*Projection) DirectMessagePack

func (p *Projection) DirectMessagePack() bool

DirectMessagePack reports whether the binding can read MessagePack fields without its fallback decoder.

func (*Projection) HasNativeField

func (p *Projection) HasNativeField(index int) bool

HasNativeField reports whether a projection exposes a direct Go field index. EDB uses this once during registration to avoid decoding unexposed row keys.

func (*Projection) MessagePack

func (p *Projection) MessagePack(raw []byte) Record

MessagePack opens the MessagePack bytes using the projection's field mapping.

func (*Projection) NativeFieldIndex

func (p *Projection) NativeFieldIndex(key uint64) int

NativeFieldIndex resolves a property code to its bound Go struct field index.

func (*Projection) Record

func (p *Projection) Record(ptr reflect.Value) Record

Record views the supplied pointer to the bound Go struct.

func (*Projection) TryDecodeProperty

func (p *Projection) TryDecodeProperty(dst reflect.Value, r Record, key uint64) error

TryDecodeProperty decodes just the property identified by key into its native destination.

func (*Projection) TryDecodeRecord

func (p *Projection) TryDecodeRecord(r Record, dst reflect.Value) error

TryDecodeRecord has the same semantics as Binding.TryDecodeRecord and uses this projection's field mapping when decoding modeled data.

func (Projection) WithNativeSchema

func (p Projection) WithNativeSchema(s NativeSchema) *Projection

WithNativeSchema returns a copy that uses the supplied native field bindings.

type Prop

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

Prop holds the shared declaration of one named schema property.

func (*Prop) AnyType

func (p *Prop) AnyType() AnyType

AnyType returns the property's logical type.

func (*Prop) Code

func (p *Prop) Code() PropCode

Code returns the stable numeric property identifier.

func (*Prop) DefaultFlags

func (p *Prop) DefaultFlags() PropFlag

DefaultFlags returns the flags applied when adding this property to a model.

func (*Prop) FullName

func (p *Prop) FullName() string

FullName returns the registered property name including its namespace.

func (*Prop) Name

func (p *Prop) Name() string

Name returns the registered name.

func (*Prop) TypeModel

func (p *Prop) TypeModel() *Model

TypeModel returns the model associated with the property's type, when present.

func (*Prop) ValueKind

func (p *Prop) ValueKind() ValueKind

ValueKind returns the storage category of the property's type.

type PropBuilder

type PropBuilder struct{ Flags PropFlag }

PropBuilder supplies declaration defaults shared by every model using a property.

type PropCode

type PropCode = uint64

PropCode identifies the same property across records and storage formats. Zero and the runtime range are reserved.

func CodeOf

func CodeOf(prop any) PropCode

CodeOf resolves a property reference at a schema/configuration boundary. Codec and dynamic-key loops should keep their numeric codes directly.

func NewProp

func NewProp(schema *Schema, code PropCode, name string, typ AnyType, build func(b *PropBuilder)) PropCode

NewProp registers a property. Its code and name must be unique in the schema.

type PropFlag

type PropFlag int

PropFlag selects storage and presence options for a model property.

const (
	PropDense PropFlag = 1 << iota
	PropRequired
	// Compact selects Compact storage for this child and its descendants.
	Compact
	// PresenceIsSignificant keeps an explicitly stored zero distinct from absence.
	PresenceIsSignificant
	// KeepDictionaryZeroValues retains zero-valued entries in this dictionary.
	// It applies to string- and numeric-keyed Map properties, not to the
	// presence of the property itself or to nested dictionaries in its values.
	KeepDictionaryZeroValues
	// PrimaryKey declares an ordinary stored property as this model's database
	// key. It preserves explicit zero values; models may omit a key entirely.
	PrimaryKey
)

Property flags select dense layout or mark a property as required.

type PropImpl

type PropImpl interface {
	Name() string
	FullName() string
	Code() PropCode
	AnyType() AnyType
	TypeModel() *Model
	ValueKind() ValueKind
}

PropImpl describes a property's name, code, and logical value type.

type PropInstance

type PropInstance struct {
	Flags    PropFlag
	Prop     PropImpl
	Dense    bool
	Required bool
	LocalID  LocalID
	// contains filtered or unexported fields
}

PropInstance describes one property's placement and flags in a particular model.

func (*PropInstance) PropInstance

func (pi *PropInstance) PropInstance() *PropInstance

PropInstance returns pi.

type PropName

type PropName string

PropName gives a namespaced property its local field name on this model.

type PropOption

type PropOption interface {
	// contains filtered or unexported methods
}

PropOption configures a property within a model.

type PropRef

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

PropRef is a shared, typed access descriptor for one declared property. It is constructed once, never per record. Its result type can be a scalar or a borrowed view; it does not imply decoding the owning record.

func BindProp

func BindProp[T any](schema *Schema, code uint64, codec values.Codec[T]) *PropRef[T]

BindProp attaches reflection-free scalar conversion to an existing property. Type compatibility is checked here, never on the hot access path.

func BindRecordProp

func BindRecordProp(schema *Schema, code uint64) *PropRef[Record]

BindRecordProp returns child records as views, without decoding their structs.

func NewRecordProp

func NewRecordProp(schema *Schema, code uint64, name string, typ AnyType) *PropRef[Record]

NewRecordProp registers an entity-valued property and returns its child-record accessor.

func NewScalarProp

func NewScalarProp[T any](schema *Schema, code uint64, name string, typ AnyType, codec values.Codec[T]) *PropRef[T]

NewScalarProp declares a property and returns its typed access descriptor.

func (*PropRef[T]) Code

func (p *PropRef[T]) Code() uint64

Code returns the stable property code used for storage and lookup.

func (*PropRef[T]) Get

func (p *PropRef[T]) Get(r Record) T

Get reads the property through its typed access descriptor.

type Property

type Property[T any] interface {
	Code() uint64
	Get(Record) T
	// contains filtered or unexported methods
}

Property is implemented by typed codes and shared access descriptors. Generic methods keep the concrete property type; they do not box it.

type PropertyCode

type PropertyCode interface{ Code() PropCode }

PropertyCode is shared by typed property references and schema declarations.

type Record

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

Record is a 16-byte typed cell: a GC-visible data pointer plus a physical representation ID and byte length. Model and binding metadata are shared. Encoded views borrow their input; Own copies only when ownership is needed. A database primary key is available only when stored as a modeled property.

func Encoded

func Encoded(v row2.View) Record

Encoded opens a row2 view without a schema or native binding.

func FromValue

func FromValue(v values.Value) Record

FromValue validates that a typed cell carries a registered KVO representation.

func TryFromValue

func TryFromValue(v values.Value) (Record, bool)

TryFromValue checks a cell's representation without interpreting its data.

func (Record) Child

func (r Record) Child(step row2.Step) Record

Child follows a path step to a nested record.

func (Record) Clone

func (r Record) Clone() Record

Clone returns an independent snapshot, including when the source already owns its storage. Encoded records keep their codec, binding, and unknown fields. Native records keep their Go type and copy their data graph, including fields outside the model. Maps, slices, pointers, interfaces, and strings are detached. Non-nil functions, channels, and unsafe pointers cannot be cloned and panic. No serialization or user codec is invoked for native objects.

Use Own for retention without an independent mutable snapshot. Fastest is an access hint and can retain an existing native or decoded object unchanged.

func (Record) Edit

func (r Record) Edit() *Editor

Edit opens an editor. Edits to a native struct change that struct; edits to encoded rows can be read back from the editor.

func (Record) Fast

func (r Record) Fast() Record

Fast keeps Fast2 storage when available and otherwise uses Record.Fastest.

func (Record) Fastest

func (r Record) Fastest() Record

Fastest materializes the native representation when bound, or indexed memory otherwise.

func (Record) Get

func (r Record) Get[T any, P Property[T]](p P) T

Get reads the property through its typed access descriptor.

func (Record) GetAs

func (r Record) GetAs(key uint64, enc row2.Encoding) values.Value

GetAs reads a numeric property using the supplied wire encoding.

func (Record) GetOwnedString

func (r Record) GetOwnedString(key uint64) values.Value

GetOwnedString reads a string property and detaches it from borrowed record storage when necessary.

func (Record) GetValue

func (r Record) GetValue(key uint64) values.Value

GetValue reads a property by numeric code using its model encoding.

func (Record) Has

func (r Record) Has(key uint64) bool

Has reports whether the field is present, including a stored zero value.

func (Record) ListValue

func (r Record) ListValue(key uint64) ListValue

ListValue returns a borrowed view of a modeled list property. Unlike GetValue, it does not materialize the list. Retain the record with Own before retaining its list beyond the source transaction. It panics for non-list properties.

func (Record) MessagePack

func (r Record) MessagePack() []byte

MessagePack returns the borrowed original payload, or nil for another representation. It preserves unmodeled fields without re-encoding.

func (Record) Missing

func (r Record) Missing() bool

Missing reports whether the handle refers to no record.

func (Record) Model

func (r Record) Model() *Model

Model returns the logical model independently of native binding or encoding.

func (Record) Native

func (r Record) Native() any

Native returns the Go representation provided by the native binding.

func (Record) NativeField

func (r Record) NativeField(key uint64) (t reflect.Type, address unsafe.Pointer, err error)

NativeField addresses an exposed field in a live Go object. It does not decode encoded records or unwrap optional values. The returned address has exactly t.

func (Record) NativeModel

func (r Record) NativeModel() *Model

NativeModel returns the model from the record's native binding, or nil if it has none.

func (Record) NativePointer

func (r Record) NativePointer() any

NativePointer returns the live pointer of a native-backed record, including a typed nil pointer. Other representations return nil without decoding.

func (Record) NativeType

func (r Record) NativeType() *values.Type

NativeType returns the VM type supplied by the native record representation.

func (Record) Own

func (r Record) Own() Record

Own returns a view independent of borrowed encoded storage. It copies the payload, including unknown properties, without decoding it. Already owned data is returned unchanged; this is not a deep clone of mutable Go objects.

func (Record) OwnsData

func (r Record) OwnsData() bool

OwnsData reports whether the record can outlive its borrowed input.

func (Record) Snapshot

func (r Record) Snapshot() row2.View

Snapshot returns a row2 view of the current record.

func (Record) ToJSON

func (r Record) ToJSON(model *Model, options JSONOptions) map[string]any

ToJSON panics on error. Use TryToJSON to handle errors explicitly.

func (Record) TrySetNativeValue

func (r Record) TrySetNativeValue(step row2.Step, value values.Value) (err error)

TrySetNativeValue writes a modeled native property without creating an editor. It keeps the editor's scalar conversion and string-ownership rules. Native callers own persistence and change tracking, as for an ordinary struct write.

func (Record) TryToJSON

func (r Record) TryToJSON(model *Model, options JSONOptions) (out map[string]any, err error)

TryToJSON converts the record to a JSON object using the model and reports conversion errors.

func (Record) Value

func (r Record) Value() values.Value

Value transports the record in the shared cell without boxing.

func (Record) WithModel

func (r Record) WithModel(m *Model) Record

WithModel returns a handle interpreted with the specified model.

type RecordCursor

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

RecordCursor traverses object elements without requiring their native Go struct type or decoding them. Each element carries its own model metadata.

func (RecordCursor) CloneSlice

func (c RecordCursor) CloneSlice() []Record

CloneSlice makes independent copies of the available records.

func (RecordCursor) Iter

func (c RecordCursor) Iter() iter.Seq[Record]

Iter returns a single-pass sequence over a copy of the current position.

func (RecordCursor) Len

func (c RecordCursor) Len() int

Len reports the number of elements available for traversal.

func (*RecordCursor) Next

func (c *RecordCursor) Next() (Record, bool)

Next advances once and returns false at the end.

func (RecordCursor) OwnedSlice

func (c RecordCursor) OwnedSlice() []Record

OwnedSlice retains each element with Own; native mutable objects may still be shared. Use CloneSlice for independent records, including native objects.

func (RecordCursor) Slice

func (c RecordCursor) Slice() []Record

Slice materializes the available elements. Their contents may still borrow record storage.

type RecordList

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

RecordList is a 16-byte borrowed view of object elements. Each element carries its KVO model; no native Go struct type parameter is needed.

func (RecordList) CloneSlice

func (l RecordList) CloneSlice() []Record

CloneSlice makes independent copies of the available records.

func (RecordList) Cursor

func (l RecordList) Cursor() RecordCursor

Cursor starts an independent traversal over the list.

func (RecordList) Iter

func (l RecordList) Iter() iter.Seq[Record]

Iter returns a single-pass sequence. Reusing this sequence resumes its position; call Iter again to start a separate traversal.

func (RecordList) Len

func (l RecordList) Len() int

Len reports the number of elements available for traversal.

func (RecordList) Missing

func (l RecordList) Missing() bool

Missing reports whether the list property is absent.

func (RecordList) OwnedSlice

func (l RecordList) OwnedSlice() []Record

OwnedSlice materializes records that can outlive borrowed storage. Native objects can still be shared.

func (RecordList) Slice

func (l RecordList) Slice() []Record

Slice materializes the available elements. Their contents may still borrow record storage.

func (RecordList) Value

func (l RecordList) Value() values.Value

Value returns the guest value carrying the list view.

type RecordListEditor

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

RecordListEditor keeps element editors attached until the list is replaced or structurally changed. Append/RemoveAt/Clear invalidate existing element editors.

func (*RecordListEditor) Append

func (l *RecordListEditor) Append(r Record)

Append appends a clone of a nonmissing record of the list's model.

func (*RecordListEditor) Clear

func (l *RecordListEditor) Clear()

Clear removes all records from the list.

func (*RecordListEditor) Edit

func (l *RecordListEditor) Edit(index int) *Editor

Edit opens a child editor for the record at index.

func (*RecordListEditor) Get

func (l *RecordListEditor) Get(index int) Record

Get returns the record at index.

func (*RecordListEditor) Iter

func (l *RecordListEditor) Iter() iter.Seq[Record]

Iter yields records in list order.

func (*RecordListEditor) Len

func (l *RecordListEditor) Len() int

Len counts the records in the edited list.

func (*RecordListEditor) New

func (l *RecordListEditor) New() *Editor

New appends an empty record and returns its editor.

func (*RecordListEditor) RemoveAt

func (l *RecordListEditor) RemoveAt(index int)

RemoveAt removes the record at index.

type RecordListPropRef

type RecordListPropRef struct {
	*PropRef[RecordList]
	// contains filtered or unexported fields
}

RecordListPropRef selects a list of records of one entity model.

func BindRecordListProp

func BindRecordListProp(schema *Schema, code uint64) *RecordListPropRef

BindRecordListProp binds an existing record-list property to a typed list accessor.

func NewRecordListProp

func NewRecordListProp(schema *Schema, code uint64, name string, typ AnyType) *RecordListPropRef

NewRecordListProp registers a record-list property and returns its accessor.

type ScalarConverter

type ScalarConverter[T any] interface {
	ValueToScalar(value T) uint64
	ScalarToValue(scalar uint64) T
}

ScalarConverter translates a Go value to and from its KVO word representation.

type ScalarDataType

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

ScalarDataType describes a string or byte slice; both are bounded byte spans.

func NewBytesType

func NewBytesType[T ~[]byte](name string) *ScalarDataType

NewBytesType declares binary data separately from text, without a new wire tag.

func (*ScalarDataType) Add

func (typ *ScalarDataType) Add(lhs, rhs uint64) uint64

Add panics because ScalarDataType does not support scalar word arithmetic.

func (*ScalarDataType) FormatValue

func (typ *ScalarDataType) FormatValue(fc *FmtContext, value uint64) string

FormatValue panics because ScalarDataType does not support scalar word formatting.

func (*ScalarDataType) ItemType

func (typ *ScalarDataType) ItemType() AnyType

ItemType returns nil. This type has no uniform element type.

func (*ScalarDataType) MapKeyType

func (typ *ScalarDataType) MapKeyType() AnyType

MapKeyType returns nil. This type has no dictionary keys.

func (*ScalarDataType) MapProp

func (typ *ScalarDataType) MapProp(key uint64) PropImpl

MapProp returns nil. Only entity types resolve keys to schema properties.

func (*ScalarDataType) MapValueType

func (typ *ScalarDataType) MapValueType(key uint64) AnyType

MapValueType returns nil. This type has no dictionary values.

func (*ScalarDataType) Model

func (typ *ScalarDataType) Model() *Model

Model returns nil. This type has no entity model.

func (*ScalarDataType) Name

func (typ *ScalarDataType) Name() string

Name returns the logical type name.

func (*ScalarDataType) NativeType

func (typ *ScalarDataType) NativeType() reflect.Type

NativeType returns the corresponding Go type.

func (*ScalarDataType) Schema

func (typ *ScalarDataType) Schema() *Schema

Schema returns nil. This scalar type is independent of a schema.

func (*ScalarDataType) Sign

func (typ *ScalarDataType) Sign(v uint64) int

Sign panics because ScalarDataType does not support scalar word arithmetic.

func (*ScalarDataType) String

func (typ *ScalarDataType) String() string

String returns the logical type name for display.

func (*ScalarDataType) Sub

func (typ *ScalarDataType) Sub(lhs, rhs uint64) uint64

Sub panics because ScalarDataType does not support scalar word arithmetic.

func (*ScalarDataType) ValueKind

func (typ *ScalarDataType) ValueKind() ValueKind

ValueKind returns the storage category for this type.

type Schema

type Schema struct {
	TPropCode AnyType
	// contains filtered or unexported fields
}

Schema holds the models and stable property codes shared by related records. Build the schema before binding records.

func NewSchema

func NewSchema() *Schema

NewSchema creates an empty schema with its own property-code type.

func (*Schema) Models

func (schema *Schema) Models() []*Model

Models returns the schema's entity models in name order.

func (*Schema) MustPropByCode

func (schema *Schema) MustPropByCode(code PropCode) PropImpl

MustPropByCode looks up a property and panics if the code is unknown.

func (*Schema) PropByCode

func (schema *Schema) PropByCode(code PropCode) PropImpl

PropByCode looks up a property by its stored code and returns nil if it is unknown.

type SignedPropRef

type SignedPropRef[T values.Signed] struct {
	// contains filtered or unexported fields
}

SignedPropRef identifies a signed integer property by its stable schema code.

func BindSignedProp

func BindSignedProp[T values.Signed](schema *Schema, code uint64) SignedPropRef[T]

BindSignedProp binds an existing property and checks its compatibility with the signed integer codec.

func NewSignedProp

func NewSignedProp[T values.Signed](schema *Schema, code uint64, name string, typ AnyType) SignedPropRef[T]

NewSignedProp registers a signed integer property and returns its typed accessor.

func (SignedPropRef[T]) Code

func (p SignedPropRef[T]) Code() uint64

Code returns the stable property code.

func (SignedPropRef[T]) Get

func (p SignedPropRef[T]) Get(r Record) T

Get reads the typed value directly from the record.

func (SignedPropRef[T]) Set

func (p SignedPropRef[T]) Set(e *Editor, v T)

Set writes the typed value through the editor.

type StringPropRef

type StringPropRef[T ~string] struct {
	// contains filtered or unexported fields
}

StringPropRef identifies a string property by its stable schema code.

func BindStringProp

func BindStringProp[T ~string](schema *Schema, code uint64) StringPropRef[T]

BindStringProp binds an existing property and checks its compatibility with the string codec.

func NewStringProp

func NewStringProp[T ~string](schema *Schema, code uint64, name string, typ AnyType) StringPropRef[T]

NewStringProp registers a string property and returns its typed accessor.

func (StringPropRef[T]) Code

func (p StringPropRef[T]) Code() uint64

Code returns the stable property code.

func (StringPropRef[T]) Get

func (p StringPropRef[T]) Get(r Record) T

Get reads the typed value directly from the record.

func (StringPropRef[T]) Set

func (p StringPropRef[T]) Set(e *Editor, v T)

Set writes the typed value through the editor.

type TimePropRef

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

TimePropRef returns time.Time directly, without parsing or reflection.

func NewTimeProp

func NewTimeProp(schema *Schema, code uint64, name string) TimePropRef

NewTimeProp declares a timestamp property using TTimestamp.

func (TimePropRef) Code

func (p TimePropRef) Code() uint64

Code returns the stable schema code for the timestamp property.

func (TimePropRef) Get

func (p TimePropRef) Get(r Record) time.Time

Get reads the stored timestamp as a Go time.

type UnsignedPropRef

type UnsignedPropRef[T values.Unsigned] struct {
	// contains filtered or unexported fields
}

UnsignedPropRef identifies a unsigned integer property by its stable schema code.

func BindUnsignedProp

func BindUnsignedProp[T values.Unsigned](schema *Schema, code uint64) UnsignedPropRef[T]

BindUnsignedProp binds an existing property and checks its compatibility with the unsigned integer codec.

func NewUnsignedProp

func NewUnsignedProp[T values.Unsigned](schema *Schema, code uint64, name string, typ AnyType) UnsignedPropRef[T]

NewUnsignedProp registers a unsigned integer property and returns its typed accessor.

func (UnsignedPropRef[T]) Code

func (p UnsignedPropRef[T]) Code() uint64

Code returns the stable property code.

func (UnsignedPropRef[T]) Get

func (p UnsignedPropRef[T]) Get(r Record) T

Get reads the typed value directly from the record.

func (UnsignedPropRef[T]) Set

func (p UnsignedPropRef[T]) Set(e *Editor, v T)

Set writes the typed value through the editor.

type ValueKind

type ValueKind int

ValueKind describes the representation a logical property uses.

const (
	ValueKindUnknown ValueKind = iota
	ValueKindWord
	ValueKindMap
	ValueKindScalarData
	ValueKindPIIData
	ValueKindList
)

Property kinds distinguish words, scalar data, maps, and lists.

type ValuePropRef

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

ValuePropRef keeps the shared carrier for properties whose access type is still an encoded aggregate or dynamic value. Typed collection traversal is available for lists; maps and arbitrary JSON retain their raw API semantics.

func BindValueProp

func BindValueProp(schema *Schema, code uint64) ValuePropRef

BindValueProp binds an existing property to its runtime value representation.

func NewValueProp

func NewValueProp(schema *Schema, code uint64, name string, typ AnyType) ValuePropRef

NewValueProp declares a property accessed through its runtime value representation.

func (ValuePropRef) Code

func (p ValuePropRef) Code() uint64

Code returns the stable property code used for storage and lookup.

func (ValuePropRef) Get

func (p ValuePropRef) Get(r Record) values.Value

Get reads the property through its typed access descriptor.

type WordAdder

type WordAdder = func(lhs, rhs uint64) uint64

WordAdder applies addition in the logical type's word representation.

type WordFormatter

type WordFormatter = func(fc *FmtContext, v uint64) string

WordFormatter renders a stored word according to its logical type.

type WordSigner

type WordSigner = func(v uint64) int

WordSigner reports the sign of a word interpreted as the logical type.

type WordSubtractor

type WordSubtractor = func(lhs, rhs uint64) uint64

WordSubtractor computes a difference between two words of the same logical type.

type WordType

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

WordType describes a scalar stored in one word, with type-specific formatting and arithmetic.

func NewFloatType

func NewFloatType[T FloatValue](name string, formatter func(fc *FmtContext, v T) string) *WordType

NewFloatType defines a floating-point word type with a Go formatter.

func NewIntStringerType

func NewIntStringerType[T IntegerStringer](name string) *WordType

NewIntStringerType defines an integer type whose Go String method supplies the display text.

func NewIntType

func NewIntType[T IntegerValue](name string, formatter func(fc *FmtContext, v T) string) *WordType

NewIntType defines an integer type with a Go formatter and integer arithmetic.

func NewScalarSubtype

func NewScalarSubtype[T any](name string, base *WordType) *WordType

NewScalarSubtype gives a new logical identity and native Go type to the operations of base.

func NewScalarType

func NewScalarType[T any](name string, formatter WordFormatter, subtractor WordSubtractor, adder WordAdder, signer WordSigner) *WordType

NewScalarType defines a distinct single-word type using the supplied formatting and arithmetic operations.

func NewUnknownTypeWithErrorCode

func NewUnknownTypeWithErrorCode(errorCode string) *WordType

NewUnknownTypeWithErrorCode defines a word type that prints the raw hexadecimal value with the supplied diagnostic code.

func (*WordType) Add

func (typ *WordType) Add(lhs, rhs uint64) uint64

Add adds two words using the registered addition rule.

func (*WordType) FormatValue

func (typ *WordType) FormatValue(fc *FmtContext, v uint64) string

FormatValue uses the registered formatter to render the stored word.

func (*WordType) ItemType

func (typ *WordType) ItemType() AnyType

ItemType returns nil. This type has no uniform element type.

func (*WordType) MapKeyType

func (typ *WordType) MapKeyType() AnyType

MapKeyType returns nil. This type has no dictionary keys.

func (*WordType) MapProp

func (typ *WordType) MapProp(key uint64) PropImpl

MapProp returns nil. Only entity types resolve keys to schema properties.

func (*WordType) MapValueType

func (typ *WordType) MapValueType(key uint64) AnyType

MapValueType returns nil. This type has no dictionary values.

func (*WordType) Model

func (typ *WordType) Model() *Model

Model returns nil. This type has no entity model.

func (*WordType) MulInt

func (typ *WordType) MulInt(lhs uint64, rhs int64) uint64

MulInt multiplies the word by a signed integer.

func (*WordType) Name

func (typ *WordType) Name() string

Name returns the logical type name.

func (*WordType) NativeType

func (typ *WordType) NativeType() reflect.Type

NativeType returns the corresponding Go type.

func (*WordType) Neg

func (typ *WordType) Neg(v uint64) uint64

Neg negates v using the registered subtraction rule.

func (*WordType) Schema

func (typ *WordType) Schema() *Schema

Schema returns nil. This scalar type is independent of a schema.

func (*WordType) Sign

func (typ *WordType) Sign(v uint64) int

Sign returns the sign of a word using the registered sign rule.

func (*WordType) String

func (typ *WordType) String() string

String returns the logical type name for display.

func (*WordType) Sub

func (typ *WordType) Sub(lhs, rhs uint64) uint64

Sub subtracts rhs from lhs using the registered subtraction rule.

func (*WordType) ValueKind

func (typ *WordType) ValueKind() ValueKind

ValueKind returns the storage category for this type.

Directories

Path Synopsis
codec
fast1
Package fast1 implements the original KVO word-map storage format.
Package fast1 implements the original KVO word-map storage format.
msgpack
Package msgpack implements EDB's MessagePack struct encoding.
Package msgpack implements EDB's MessagePack struct encoding.
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.

Jump to

Keyboard shortcuts

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