orm

package module
v0.3.2 Latest Latest
Warning

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

Go to latest
Published: Feb 28, 2026 License: MIT Imports: 12 Imported by: 2

README

orm

Generics-based ORM for Go with type-safe Model[T], auto-registration, auto-serialization, and multi-backend support.

import "github.com/hanzoai/orm"

Install

go get github.com/hanzoai/orm@latest

Quick Start

Define a model
type User struct {
    orm.Model[User]
    Name   string `json:"name"`
    Email  string `json:"email"`
    Status string `json:"status" orm:"default:active"`
}

func init() {
    orm.Register[User]("user")
}
Connect to a backend
import ormdb "github.com/hanzoai/orm/db"

// SQLite (embedded, zero config)
db, err := orm.OpenSQLite(&ormdb.SQLiteDBConfig{
    Path:   "data/app.db",
    Config: ormdb.SQLiteConfig{BusyTimeout: 5000, JournalMode: "WAL"},
})

// ZAP binary protocol (PostgreSQL, MongoDB, Redis, ClickHouse via sidecar)
db, err := orm.OpenZap(&ormdb.ZapConfig{
    Addr:    "localhost:9651",
    Backend: ormdb.ZapSQL,        // or ZapDocumentDB, ZapKV, ZapDatastore
})
CRUD
// Create
user := orm.New[User](db)
user.Name = "Alice"
user.Email = "alice@example.com"
user.Create()

// Read
got, err := orm.Get[User](db, user.Id())

// Update
got.Name = "Alice Smith"
got.Update()

// Delete
got.Delete()
Query
q := orm.TypedQuery[User](db)
found, err := q.Filter("Status=", "active").Get()
Lifecycle Hooks
func (u *User) BeforeCreate() error {
    // validate, set defaults, etc.
    return nil
}

func (u *User) AfterCreate() error {
    // send welcome email, etc.
    return nil
}
Auto-Serialization

Fields with orm:"serialize" and a corresponding _ storage field are automatically marshaled/unmarshaled:

type Product struct {
    orm.Model[Product]
    Variants  []Variant `json:"variants" orm:"serialize" datastore:"-"`
    Variants_ string    `json:"-" datastore:"variants"`
}
Struct Tag Defaults
type PaymentIntent struct {
    orm.Model[PaymentIntent]
    Status   string `json:"status"   orm:"default:requires_payment_method"`
    Currency string `json:"currency" orm:"default:usd"`
}
Caching

Built-in read-through cache with memory LRU and Redis/Valkey backends:

orm.Register[User]("user", orm.WithCache[User](orm.CacheConfig{
    TTL:     5 * time.Minute,
    MaxSize: 10000,
}))
Validation
import "github.com/hanzoai/orm/val"

v := val.NewValidator()
v.CheckString("email", user.Email).Required().Email()
v.CheckString("name", user.Name).Required().MinLen(2)
if err := v.Error(); err != nil {
    return err
}

Backends

Backend Driver Use Case
SQLite orm.OpenSQLite Embedded, single-node, development
PostgreSQL orm.OpenZap + ZapSQL Production SQL via ZAP sidecar
MongoDB/FerretDB orm.OpenZap + ZapDocumentDB Document storage via ZAP sidecar
Redis/Valkey orm.OpenZap + ZapKV KV storage via ZAP sidecar
ClickHouse orm.OpenZap + ZapDatastore Analytics via ZAP sidecar
ZAP Binary Protocol

ZAP eliminates JSON serialization overhead by encoding structs directly into a binary format over RPC. A zap-sidecar process proxies requests to the actual database backends.

App ──ZAP binary──▸ zap-sidecar ──native──▸ PostgreSQL/MongoDB/Redis/ClickHouse

Benefits:

  • Zero-copy binary encoding (no JSON marshal/unmarshal for storage)
  • Single ORM interface across SQL, document, KV, and columnar backends
  • Native complex types (slices, maps, nested structs) without Foo/Foo_ pairs

Packages

Package Description
orm Core Model[T], registration, hooks, cache, serialization
orm/db Database interfaces, SQLite driver, ZAP driver
orm/val Struct field validation
orm/internal/json JSON encode/decode helpers
orm/internal/reflect Reflection utilities

Documentation

Full docs at hanzo.ai/docs/services/orm

License

MIT

Documentation

Overview

Package orm provides a generics-based ORM with auto-registration, auto-serialization of underscore fields, lifecycle hooks, and optional KV cache. It is designed to be extracted from and remain backward-compatible with github.com/hanzoai/commerce.

Index

Constants

View Source
const CacheKeyPrefix = "orm"

CacheKeyPrefix is prepended to all cache keys.

View Source
const DefaultEntityTTL = 5 * time.Minute

DefaultEntityTTL is the default TTL for cached entities.

View Source
const DefaultQueryTTL = 1 * time.Minute

DefaultQueryTTL is the default TTL for cached query results.

Variables

View Source
var (
	// ErrNotFound is returned when an entity is not found.
	ErrNotFound = errors.New("orm: entity not found")

	// ErrAlreadyRegistered is returned when a kind is registered twice.
	ErrAlreadyRegistered = errors.New("orm: kind already registered")
)
View Source
var OpenPostgres = OpenSQL

OpenPostgres is an alias for OpenSQL (backward compatibility).

Functions

func ApplyDefaults

func ApplyDefaults[T any](entity *T)

ApplyDefaults sets default values on entity from: 1. orm:"default:value" struct tags (parsed at registration) 2. Defaulter interface (custom Defaults() method)

func CloneFromJSON added in v0.3.0

func CloneFromJSON[T any](data []byte) (*T, error)

CloneFromJSON creates a new T from JSON data.

func DeserializeFields

func DeserializeFields(entity interface{}) error

DeserializeFields unmarshals all registered serialized fields (Foo_ → Foo). Called automatically after Get/GetById.

For each pair in ModelMeta.Serialized:

  • Read the string from the underscore field
  • Unmarshal into the JSON field

func EntityCacheKey

func EntityCacheKey(namespace, kind, id string) string

EntityCacheKey returns the cache key for an entity.

func Get

func Get[T any](db DB, id string) (*T, error)

Get retrieves an entity of type T by its string ID.

func GetOrCreate added in v0.3.0

func GetOrCreate[T any](db DB, id string, defaults func(*T)) (*T, bool, error)

GetOrCreate retrieves an entity by ID, or creates it with defaults if not found. Returns (entity, created, error).

func GetOrUpdate added in v0.3.0

func GetOrUpdate[T any](db DB, id string, fn func(*T)) (*T, error)

GetOrUpdate retrieves an entity by ID, applies fn, and updates it.

func HashQuery

func HashQuery(queryStr string) string

HashQuery produces a deterministic hash of a query for cache keying.

func Kind

func Kind[T any]() string

Kind returns the registered kind string for type T.

func Kinds

func Kinds() []string

Kinds returns all registered kind strings.

func MustGet added in v0.3.0

func MustGet[T any](db DB, id string) *T

MustGet retrieves an entity by ID or panics.

func New

func New[T any](db DB) *T

New creates a new instance of T, wired to db, with defaults applied. This replaces the per-model New() function and model.go boilerplate.

func QueryCacheKey

func QueryCacheKey(namespace, kind, queryHash string) string

QueryCacheKey returns the cache key for a query.

func Register

func Register[T any](kind string, opts ...Option[T])

Register records type T under the given kind string. Must be called from init() or before any ORM operations.

func SerializeFields

func SerializeFields(entity interface{}) error

SerializeFields marshals all registered serialized fields (Foo → Foo_). Called automatically before Put().

For each pair in ModelMeta.Serialized:

  • Marshal the JSON field value to a JSON string
  • Store the string in the underscore field

func SetCache

func SetCache(cache CacheLayer)

SetCache sets the global cache layer.

func Zero added in v0.3.0

func Zero[T any]() *T

Zero returns a new zero-value instance of T (not wired to any DB).

Types

type AfterCreator

type AfterCreator interface {
	AfterCreate() error
}

AfterCreator is called after a new entity is persisted.

type AfterDeleter

type AfterDeleter interface {
	AfterDelete() error
}

AfterDeleter is called after an entity is deleted.

type AfterUpdater

type AfterUpdater[T any] interface {
	AfterUpdate(prev *T) error
}

AfterUpdater is called after an entity update, receiving a clone of the previous state.

type BeforeCreator

type BeforeCreator interface {
	BeforeCreate() error
}

BeforeCreator is called before a new entity is persisted.

type BeforeDeleter

type BeforeDeleter interface {
	BeforeDelete() error
}

BeforeDeleter is called before an entity is deleted.

type BeforeUpdater

type BeforeUpdater[T any] interface {
	BeforeUpdate(prev *T) error
}

BeforeUpdater is called before an entity update, receiving a clone of the previous state. The type parameter allows strongly-typed prev values.

type CacheConfig

type CacheConfig struct {
	Enabled   bool
	EntityTTL int // seconds, 0 = use global default
	QueryTTL  int // seconds, 0 = use global default
}

CacheConfig controls per-model caching behavior.

type CacheLayer

type CacheLayer interface {
	// GetEntity returns a cached entity, or false if not found.
	GetEntity(ctx context.Context, kind, id string) ([]byte, bool, error)

	// SetEntity caches an entity.
	SetEntity(ctx context.Context, kind, id string, data []byte, ttl time.Duration) error

	// InvalidateEntity removes a cached entity and all queries for its kind.
	InvalidateEntity(ctx context.Context, kind, id string) error

	// InvalidateKind removes all cached queries for a kind.
	InvalidateKind(ctx context.Context, kind string) error

	// GetQuery returns cached query results, or false if not found.
	GetQuery(ctx context.Context, kind, queryHash string) ([]byte, bool, error)

	// SetQuery caches query results.
	SetQuery(ctx context.Context, kind, queryHash string, data []byte, ttl time.Duration) error

	// Close releases resources.
	Close() error
}

CacheLayer provides read-through/write-through caching for entities and queries.

func GetCache

func GetCache() CacheLayer

GetCache returns the global cache layer (may be nil).

type DB

type DB interface {
	// Get loads the entity identified by key into dst.
	Get(ctx context.Context, key Key, dst interface{}) error

	// Put persists src under key, returning the (possibly updated) key.
	Put(ctx context.Context, key Key, src interface{}) (Key, error)

	// Delete removes the entity identified by key.
	Delete(ctx context.Context, key Key) error

	// Query returns a new query builder for the given kind.
	Query(kind string) Query

	// NewKey creates a key with the given kind, string ID, int ID, and parent.
	NewKey(kind string, stringID string, intID int64, parent Key) Key

	// NewIncompleteKey creates an incomplete key (ID allocated on put).
	NewIncompleteKey(kind string, parent Key) Key

	// AllocateIDs pre-allocates n IDs for the given kind.
	AllocateIDs(kind string, parent Key, n int) ([]Key, error)

	// RunInTransaction executes fn inside a transaction.
	RunInTransaction(ctx context.Context, fn func(tx DB) error) error

	// Close releases resources.
	Close() error
}

DB is the minimal database interface the ORM requires. Implementations exist for SQLite, PostgreSQL, MongoDB, and the legacy Hanzo Datastore. Commerce's datastore.Datastore satisfies this via a thin adapter.

func AdaptDB

func AdaptDB(d ormdb.DB) DB

AdaptDB wraps any db.DB to satisfy the root orm.DB interface.

func OpenSQL added in v0.3.2

func OpenSQL(cfg *ormdb.SQLConfig) (DB, error)

OpenSQL creates an orm.DB backed by SQL (PostgreSQL via pgx).

func OpenSQLite

func OpenSQLite(cfg *ormdb.SQLiteDBConfig) (DB, error)

OpenSQLite creates an orm.DB backed by SQLite.

func OpenZap added in v0.2.0

func OpenZap(cfg *ormdb.ZapConfig) (DB, error)

OpenZap creates an orm.DB backed by ZAP binary protocol. Connects to a zap-sidecar and uses Cap'n Proto transport, eliminating JSON serialization overhead for storage operations.

type Defaulter

type Defaulter interface {
	Defaults()
}

Defaulter is implemented by models that need custom default values beyond what orm:"default:..." tags provide.

type Iterator

type Iterator interface {
	Next(dst interface{}) (Key, error)
}

Iterator iterates over query results.

type KVCache

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

KVCache is a Redis/Valkey-backed cache layer using hanzoai/kv-go.

func NewKVCache

func NewKVCache(cfg KVCacheConfig) (*KVCache, error)

NewKVCache creates a new Redis/Valkey cache layer.

func NewKVCacheFromClient

func NewKVCacheFromClient(client *kv.Client, prefix string) *KVCache

NewKVCacheFromClient creates a KVCache from an existing kv.Client.

func (*KVCache) Close

func (c *KVCache) Close() error

func (*KVCache) GetEntity

func (c *KVCache) GetEntity(ctx context.Context, kind, id string) ([]byte, bool, error)

func (*KVCache) GetQuery

func (c *KVCache) GetQuery(ctx context.Context, kind, queryHash string) ([]byte, bool, error)

func (*KVCache) InvalidateEntity

func (c *KVCache) InvalidateEntity(ctx context.Context, kind, id string) error

func (*KVCache) InvalidateKind

func (c *KVCache) InvalidateKind(ctx context.Context, kind string) error

func (*KVCache) SetEntity

func (c *KVCache) SetEntity(ctx context.Context, kind, id string, data []byte, ttl time.Duration) error

func (*KVCache) SetQuery

func (c *KVCache) SetQuery(ctx context.Context, kind, queryHash string, data []byte, ttl time.Duration) error

type KVCacheConfig

type KVCacheConfig struct {
	Addr     string
	Password string
	DB       int
	Prefix   string // key prefix, default "orm"
	PoolSize int
}

KVCacheConfig configures the Redis/Valkey cache backend.

type Key

type Key interface {
	Kind() string
	StringID() string
	IntID() int64
	Parent() Key
	Namespace() string
	Encode() string
}

Key identifies an entity in the datastore.

type LegacyEntity

type LegacyEntity interface {
	LegacyKind
	Id() string
	JSON() []byte
	JSONString() string
}

LegacyEntity matches the subset of mixin.Entity needed for interop. Commerce's REST layer and query system use this interface.

type LegacyKind

type LegacyKind interface {
	Kind() string
}

LegacyKind matches the mixin.Kind interface.

type MemoryCache

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

MemoryCache is an in-memory LRU cache layer.

func NewMemoryCache

func NewMemoryCache(maxSize int) *MemoryCache

NewMemoryCache creates a new in-memory cache with the given maximum number of entries.

func (*MemoryCache) Close

func (c *MemoryCache) Close() error

func (*MemoryCache) GetEntity

func (c *MemoryCache) GetEntity(_ context.Context, kind, id string) ([]byte, bool, error)

func (*MemoryCache) GetQuery

func (c *MemoryCache) GetQuery(_ context.Context, kind, queryHash string) ([]byte, bool, error)

func (*MemoryCache) InvalidateEntity

func (c *MemoryCache) InvalidateEntity(_ context.Context, kind, id string) error

func (*MemoryCache) InvalidateKind

func (c *MemoryCache) InvalidateKind(_ context.Context, kind string) error

func (*MemoryCache) Len

func (c *MemoryCache) Len() int

Len returns the number of entries in the cache.

func (*MemoryCache) SetEntity

func (c *MemoryCache) SetEntity(_ context.Context, kind, id string, data []byte, ttl time.Duration) error

func (*MemoryCache) SetQuery

func (c *MemoryCache) SetQuery(_ context.Context, kind, queryHash string, data []byte, ttl time.Duration) error

type Model

type Model[T any] struct {

	// Persisted fields
	Id_       string    `json:"id,omitempty"`
	CreatedAt time.Time `json:"createdAt,omitempty"`
	UpdatedAt time.Time `json:"updatedAt,omitempty"`
	Deleted   bool      `json:"deleted,omitempty"`
	// contains filtered or unexported fields
}

Model is a generic mixin embedded in every ORM entity. It replaces mixin.Model from commerce with type-safe generics.

Usage:

type PaymentIntent struct {
    orm.Model[PaymentIntent]
    Amount   int64  `json:"amount"`
    Currency string `json:"currency" orm:"default:usd"`
}

func init() { orm.Register[PaymentIntent]("payment-intent") }

func (*Model[T]) Clone

func (m *Model[T]) Clone() *T

Clone creates a deep copy of the entity via JSON round-trip.

func (*Model[T]) Create

func (m *Model[T]) Create() error

Create persists a new entity, executing Before/AfterCreate hooks.

func (*Model[T]) CreateCtx added in v0.3.0

func (m *Model[T]) CreateCtx(ctx context.Context) error

CreateCtx persists a new entity with context, executing Before/AfterCreate hooks.

func (*Model[T]) Created

func (m *Model[T]) Created() bool

Created returns true if the entity has been persisted at least once.

func (*Model[T]) DB

func (m *Model[T]) DB() DB

DB returns the database this model is wired to.

func (*Model[T]) Delete

func (m *Model[T]) Delete() error

Delete removes the entity, executing Before/AfterDelete hooks.

func (*Model[T]) DeleteCtx added in v0.3.0

func (m *Model[T]) DeleteCtx(ctx context.Context) error

DeleteCtx removes the entity with context, executing Before/AfterDelete hooks.

func (*Model[T]) Exists

func (m *Model[T]) Exists() (bool, error)

Exists checks if the entity exists in the database.

func (*Model[T]) Get

func (m *Model[T]) Get(key Key) error

Get loads the entity by its current key.

func (*Model[T]) GetById

func (m *Model[T]) GetById(id string) error

GetById loads the entity by its string ID.

func (*Model[T]) Id

func (m *Model[T]) Id() string

Id returns the entity's string ID, allocating a new key if needed.

func (*Model[T]) Init

func (m *Model[T]) Init(db DB)

Init wires the model to a database. Called by New[T] and by the compat layer.

func (*Model[T]) IsMock

func (m *Model[T]) IsMock() bool

IsMock returns whether the model is in mock mode.

func (*Model[T]) JSON

func (m *Model[T]) JSON() []byte

JSON serializes the entity to JSON bytes.

func (*Model[T]) JSONString

func (m *Model[T]) JSONString() string

JSONString serializes the entity to a JSON string.

func (*Model[T]) Key

func (m *Model[T]) Key() Key

Key returns the entity's datastore key, allocating one if necessary.

func (Model[T]) Kind

func (m Model[T]) Kind() string

Kind returns the registered kind string for T.

func (*Model[T]) MustCreate added in v0.3.0

func (m *Model[T]) MustCreate()

MustCreate persists a new entity or panics.

func (*Model[T]) MustDelete added in v0.3.0

func (m *Model[T]) MustDelete()

MustDelete removes the entity or panics.

func (*Model[T]) MustUpdate added in v0.3.0

func (m *Model[T]) MustUpdate()

MustUpdate persists changes or panics.

func (*Model[T]) Namespace added in v0.3.0

func (m *Model[T]) Namespace() string

Namespace returns the entity's namespace for multi-tenant isolation.

func (*Model[T]) Parent

func (m *Model[T]) Parent() Key

Parent returns the parent key.

func (*Model[T]) Put

func (m *Model[T]) Put() error

Put persists the entity, setting timestamps.

func (*Model[T]) PutCtx added in v0.3.0

func (m *Model[T]) PutCtx(ctx context.Context) error

PutCtx persists the entity with context, setting timestamps.

func (*Model[T]) Query

func (m *Model[T]) Query() *ModelQuery[T]

Query returns a typed model query for this entity.

func (*Model[T]) SetDB

func (m *Model[T]) SetDB(db DB)

SetDB replaces the database reference (used during transaction rebinding).

func (*Model[T]) SetId

func (m *Model[T]) SetId(id string)

SetId sets the entity's ID directly and invalidates the cached key.

func (*Model[T]) SetKey

func (m *Model[T]) SetKey(key Key)

SetKey sets the entity's key.

func (*Model[T]) SetMock

func (m *Model[T]) SetMock(mock bool)

SetMock enables mock mode (no actual DB operations).

func (*Model[T]) SetNamespace added in v0.3.0

func (m *Model[T]) SetNamespace(ns string)

SetNamespace sets the entity's namespace for multi-tenant isolation.

func (*Model[T]) SetParent

func (m *Model[T]) SetParent(parent Key)

SetParent sets the parent key.

func (*Model[T]) Update

func (m *Model[T]) Update() error

Update persists changes, executing Before/AfterUpdate hooks.

func (*Model[T]) UpdateCtx added in v0.3.0

func (m *Model[T]) UpdateCtx(ctx context.Context) error

UpdateCtx persists changes with context, executing Before/AfterUpdate hooks. The hooks receive the old entity state (from last DB load) for diffing.

type ModelMeta

type ModelMeta struct {
	Kind        string
	Type        reflect.Type // the concrete struct type T (not *T)
	StringKey   bool
	ParentFn    func(DB) Key          // optional parent key factory
	InitFn      func(DB, interface{}) // optional custom init
	DefaultsFn  func(interface{})     // optional custom defaults
	Defaults    map[string]string     // field name → default value from tags
	Serialized  map[string]string     // JSON field name → underscore field name
	CacheConfig *CacheConfig          // per-model cache settings (nil = use global)
}

ModelMeta holds parsed metadata for a registered model type.

func Lookup

func Lookup(kind string) (*ModelMeta, bool)

Lookup returns the metadata for kind.

func LookupType

func LookupType(typ reflect.Type) (*ModelMeta, bool)

LookupType returns the metadata for the given type.

func MustLookup

func MustLookup(kind string) *ModelMeta

MustLookup returns the metadata for kind or panics.

type ModelQuery

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

ModelQuery is a typed query wrapper for a single model type. It provides a fluent interface for filtering, ordering, and retrieving entities.

func TypedQuery

func TypedQuery[T any](db DB) *ModelQuery[T]

TypedQuery returns a new query builder for type T.

func (*ModelQuery[T]) Ancestor

func (q *ModelQuery[T]) Ancestor(key Key) *ModelQuery[T]

Ancestor restricts the query to descendants of the given key.

func (*ModelQuery[T]) ById

func (q *ModelQuery[T]) ById(id string) (bool, error)

ById retrieves an entity by its string ID.

func (*ModelQuery[T]) Count added in v0.3.0

func (q *ModelQuery[T]) Count(ctx context.Context) (int, error)

Count returns the number of matching entities.

func (*ModelQuery[T]) Filter

func (q *ModelQuery[T]) Filter(filterStr string, value interface{}) *ModelQuery[T]

Filter adds a filter condition.

func (*ModelQuery[T]) First added in v0.3.0

func (q *ModelQuery[T]) First() (*T, error)

First returns the first matching entity as a new instance, or ErrNotFound.

func (*ModelQuery[T]) Get

func (q *ModelQuery[T]) Get() (bool, error)

Get retrieves the first matching entity into the model.

func (*ModelQuery[T]) GetAll added in v0.3.0

func (q *ModelQuery[T]) GetAll(ctx context.Context) ([]*T, error)

GetAll returns all matching entities.

func (*ModelQuery[T]) IdExists

func (q *ModelQuery[T]) IdExists(id string) (Key, bool, error)

IdExists checks if the given ID exists.

func (*ModelQuery[T]) Inner

func (q *ModelQuery[T]) Inner() Query

Inner returns the underlying Query for advanced operations.

func (*ModelQuery[T]) KeyExists

func (q *ModelQuery[T]) KeyExists(key Key) (bool, error)

KeyExists checks if the given key exists.

func (*ModelQuery[T]) Limit

func (q *ModelQuery[T]) Limit(limit int) *ModelQuery[T]

Limit sets the maximum number of results.

func (*ModelQuery[T]) Offset

func (q *ModelQuery[T]) Offset(offset int) *ModelQuery[T]

Offset sets the number of results to skip.

func (*ModelQuery[T]) Order

func (q *ModelQuery[T]) Order(fieldPath string) *ModelQuery[T]

Order adds an ordering clause.

type NoopCache

type NoopCache struct{}

NoopCache is a cache layer that does nothing. Used when caching is disabled.

func (*NoopCache) Close

func (c *NoopCache) Close() error

func (*NoopCache) GetEntity

func (c *NoopCache) GetEntity(_ context.Context, _, _ string) ([]byte, bool, error)

func (*NoopCache) GetQuery

func (c *NoopCache) GetQuery(_ context.Context, _, _ string) ([]byte, bool, error)

func (*NoopCache) InvalidateEntity

func (c *NoopCache) InvalidateEntity(_ context.Context, _, _ string) error

func (*NoopCache) InvalidateKind

func (c *NoopCache) InvalidateKind(_ context.Context, _ string) error

func (*NoopCache) SetEntity

func (c *NoopCache) SetEntity(_ context.Context, _, _ string, _ []byte, _ time.Duration) error

func (*NoopCache) SetQuery

func (c *NoopCache) SetQuery(_ context.Context, _, _ string, _ []byte, _ time.Duration) error

type Option

type Option[T any] interface {
	// contains filtered or unexported methods
}

Option configures model registration.

func WithCache

func WithCache[T any](cfg CacheConfig) Option[T]

WithCache configures per-model cache settings.

func WithDefaults

func WithDefaults[T any](fn func(*T)) Option[T]

WithDefaults sets a custom defaults function called on New().

func WithInit

func WithInit[T any](fn func(DB, *T)) Option[T]

WithInit sets a custom initialization function called after New().

func WithParent

func WithParent[T any](fn func(DB) Key) Option[T]

WithParent sets a function that returns the parent key for new entities.

func WithStringKey

func WithStringKey[T any]() Option[T]

WithStringKey configures the model to use string IDs instead of auto-allocated int64 IDs.

type Query

type Query interface {
	Filter(filterStr string, value interface{}) Query
	Order(fieldPath string) Query
	Limit(limit int) Query
	Offset(offset int) Query
	Ancestor(ancestor Key) Query
	KeysOnly() Query

	// GetAll executes the query, populating dst (pointer to slice).
	// Returns the matching keys.
	GetAll(ctx context.Context, dst interface{}) ([]Key, error)

	// First returns the first matching entity.
	First(dst interface{}) (Key, bool, error)

	// Count returns the number of matching entities.
	Count(ctx context.Context) (int, error)

	// ById finds an entity by its encoded ID.
	ById(id string, dst interface{}) (Key, bool, error)

	// IdExists checks whether the given ID exists.
	IdExists(id string) (Key, bool, error)

	// KeyExists checks whether the given key exists.
	KeyExists(key Key) (bool, error)
}

Query is a fluent query builder.

Directories

Path Synopsis
Package db provides a multi-layer database abstraction supporting: - User-level SQLite with sqlite-vec for personal data and vector search - Organization-level SQLite for shared tenant data - PostgreSQL with pgvector for scalable deployments - MongoDB/FerretDB for document storage - Hanzo Datastore (ClickHouse) for deep analytics
Package db provides a multi-layer database abstraction supporting: - User-level SQLite with sqlite-vec for personal data and vector search - Organization-level SQLite for shared tenant data - PostgreSQL with pgvector for scalable deployments - MongoDB/FerretDB for document storage - Hanzo Datastore (ClickHouse) for deep analytics
Package engine provides an xorm-compatible API layer for hanzo/orm.
Package engine provides an xorm-compatible API layer for hanzo/orm.
internal
json
Package json provides JSON encoding/decoding utilities.
Package json provides JSON encoding/decoding utilities.
reflect
Package reflect provides reflection utilities for struct manipulation.
Package reflect provides reflection utilities for struct manipulation.
Package names provides naming convention mappers for converting between Go struct field names and database column/table names.
Package names provides naming convention mappers for converting between Go struct field names and database column/table names.
Package val provides struct field validation utilities.
Package val provides struct field validation utilities.

Jump to

Keyboard shortcuts

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