Documentation
¶
Overview ¶
Package orm is a Django-style ORM for Go: a model is a plain struct, its manager a package-level value, and its queries lazy, immutable QuerySets read with Django's lookups.
var Users = orm.For[User]()
adults, err := Users.Filter(orm.Q{"age__gte": 18}).OrderBy("-age").All(ctx)
u, err := Users.Get(ctx, orm.Q{"email": e})
Connections are database/sql's: a model reads and writes through the database added under its name (orm.AddDatabase; the default unless the model names another), or the one a context carries (orm.WithDB).
Index ¶
- Constants
- Variables
- func AddDatabase(name string, db *DB, opts ...DatabaseOption)
- func ApplyMigrations(ctx context.Context, d *DB, target string, migrations ...migration.Migration) error
- func Atomic(ctx context.Context, fn func(ctx context.Context) error, opts ...TxOption) error
- func AtomicOn(ctx context.Context, db *DB, fn func(ctx context.Context) error, ...) error
- func Check(models ...AnyManager) error
- func ConnFor[T any](name string) func(*Databases) *T
- func CreateTables(ctx context.Context, models ...AnyManager) error
- func Database(name string) func(*vuka.Type)
- func Entity(t *vuka.Type)
- func Exec(ctx context.Context, sql string, args ...any) (int64, error)
- func ExecOn(ctx context.Context, s DBSchema, sql string, args ...any) (int64, error)
- func FieldName[T any](p Path[T]) string
- func Generated[T any]() bool
- func HandleOf[T any](s *Databases) *T
- func Handles() []reflect.Type
- func LikePattern(before, after string) func(any) any
- func LoadRelated[T any](ctx context.Context, rows []*T, specs ...any) error
- func LoadRelation[T any](ctx context.Context, rows []*T, relation string) error
- func LookupPath(p vuka.FieldPath) string
- func MakeHandle(s *Databases, t reflect.Type) reflect.Value
- func Migrate(ctx context.Context, opts ...MigrateOption) error
- func MySQLDSN(dsn string) string
- func Observe(fn Observer) (stop func())
- func ObserveState(fn func(StateEvent)) (stop func())
- func OnCommit(ctx context.Context, fn func(ctx context.Context)) error
- func OnMirrorError(fn func(ctx context.Context, e MirrorError)) (stop func())
- func Operand(v any) any
- func OptValue[V any](o vuka.Option[V]) any
- func Optional[T any](row T, err error) (vuka.Option[T], error)
- func Orderings(os ...Ordering) []any
- func P[T any](c Cond) vuka.Pred[T]
- func ParseURL(url string) (dialect, dsn string, err error)
- func PathName(v any) string
- func Primary(ctx context.Context) context.Context
- func PtrValue[V any](p *V) any
- func Raw[R any](ctx context.Context, sql string, args ...any) ([]R, error)
- func RawIter[R any](ctx context.Context, sql string, args ...any) iter.Seq2[R, error]
- func RawIterOn[R any](ctx context.Context, s DBSchema, sql string, args ...any) iter.Seq2[R, error]
- func RawOn[R any](ctx context.Context, s DBSchema, sql string, args ...any) ([]R, error)
- func RawRow[R any](ctx context.Context, sql string, args ...any) (R, error)
- func Register[T any]()
- func RegisterDriver(dialect, sqlDriver string)
- func RegisterDriverHooks(dialect string, h DriverHooks)
- func RegisterLookup(name string, fn LookupFunc, opts ...LookupOption)
- func RegisterScanner[T any](cols []string, make func() RowScanner[T])
- func Scope(ctx context.Context) context.Context
- func ServeCLI()
- func SetFieldOptions(fn FieldOptionsFunc)deprecated
- func Transaction(ctx context.Context, fn func(ctx context.Context) error, opts ...TxOption) error
- func Using(ctx context.Context, name string) context.Context
- func WatchRepeats(ctx context.Context, n int, ...) context.Context
- func WithDB(ctx context.Context, db *DB) context.Context
- func WithDatabases(ctx context.Context, s *Databases) context.Context
- func WithMirror(ctx context.Context, db *DB) context.Context
- func WithObserver(ctx context.Context, fn Observer) context.Context
- func WithTimeout(ctx context.Context, d time.Duration) context.Context
- type AfterCreater
- type AfterDeleter
- type AfterSaver
- type Agg
- type AggOption
- type Alias
- type AnnotationValue
- func (v AnnotationValue[T]) Asc() ExprOrder
- func (v AnnotationValue[T]) Between(a, b T) Cond
- func (v AnnotationValue[T]) Desc() ExprOrder
- func (v AnnotationValue[T]) Gt(x T) Cond
- func (v AnnotationValue[T]) Gte(x T) Cond
- func (v AnnotationValue[T]) Lt(x T) Cond
- func (v AnnotationValue[T]) Lte(x T) Cond
- type AnyManager
- type Arg
- type Assignment
- type AutoNow
- type AutoNowAdd
- type Base
- func (b *Base[Self]) Add(ctx context.Context, relation any, related ...any) error
- func (*Base[Self]) DeclaredFieldAttrs(t reflect.Type, registered map[string][]any) map[string][]any
- func (b *Base[Self]) Delete(ctx context.Context) error
- func (b *Base[Self]) Load(ctx context.Context, specs ...any) error
- func (b *Base[Self]) Refresh(ctx context.Context) error
- func (b *Base[Self]) Remove(ctx context.Context, relation any, related ...any) error
- func (b *Base[Self]) Save(ctx context.Context) error
- func (b *Base[Self]) SaveFields(ctx context.Context, fields ...any) error
- func (b *Base[Self]) Set(ctx context.Context, relation any, related ...any) error
- func (b *Base[Self]) Using(sc DBSchema) *Self
- type BaseRouter
- type BeforeCreater
- type BeforeDeleter
- type BeforeSaver
- type Breaker
- type CLIRequest
- type CSV
- type CSVElem
- type CaseExpr
- type CastType
- type Cell
- type Change
- type ChangeKind
- type Char
- type Codec
- type Col
- type Column
- type ColumnOf
- type ColumnTyper
- type CompareTerm
- type Cond
- type Conn
- func (c Conn) DB() (*DB, error)
- func (Conn) Deadline() (time.Time, bool)
- func (Conn) Done() <-chan struct{}
- func (Conn) Err() error
- func (c Conn) Exec(ctx context.Context, sql string, args ...any) (int64, error)
- func (c Conn) Name() string
- func (c Conn) Ping(ctx context.Context) error
- func (c Conn) Stats() (DBStats, error)
- func (c Conn) Value(key any) any
- func (c Conn) With(ctx context.Context) context.Context
- type DB
- type DBScanner
- type DBSchema
- type DBStats
- type DBType
- type DBValuer
- type DatabaseOption
- type DatabaseSpec
- type Databases
- func (s *Databases) Add(name string, db *DB, opts ...DatabaseOption)
- func (s *Databases) AddRouter(r Router) *Databases
- func (s *Databases) Apply(opts ...OpenOption) *Databases
- func (s *Databases) Check() error
- func (s *Databases) Close(ctx context.Context) error
- func (s *Databases) Conn(name string) Conn
- func (s *Databases) Lookup(name string) (*DB, error)
- func (s *Databases) Names() []string
- func (s *Databases) Remove(name string)
- func (s *Databases) Route(table string, r Route)
- func (s *Databases) RouteFor(table string) (Route, bool)
- func (s *Databases) Start(ctx context.Context) error
- func (s *Databases) Stats() []DBStats
- func (s *Databases) StatsOf(name string) (DBStats, error)
- func (s *Databases) Stop(ctx context.Context) error
- func (s *Databases) Unroute(table string)
- type DateExpr
- func (e DateExpr) Add(d time.Duration) DateExpr
- func (e DateExpr) AddDays(n int) DateExpr
- func (e DateExpr) AddMonths(n int) DateExpr
- func (e DateExpr) Asc() ExprOrder
- func (e DateExpr) Between(a, b any) Cond
- func (e DateExpr) Desc() ExprOrder
- func (e DateExpr) Eq(v any) Cond
- func (e DateExpr) Ge(v any) Cond
- func (e DateExpr) Gt(v any) Cond
- func (e DateExpr) Gte(v any) Cond
- func (e DateExpr) Le(v any) Cond
- func (e DateExpr) Lt(v any) Cond
- func (e DateExpr) Lte(v any) Cond
- func (e DateExpr) Ne(v any) Cond
- func (e DateExpr) String() string
- type DateField
- type Datetime
- type DefaultValue
- type Defaults
- type Dialect
- type DialectName
- type Dialects
- type Dims
- type Document
- type DriverHooks
- type DualOption
- type Elements
- type Error
- type ErrorClass
- type ExistsCond
- type ExplainOption
- type Expr
- type ExprOrder
- type Extension
- type FK
- func (f *FK[T]) Get(ctx context.Context) vuka.Result[T]
- func (f FK[T]) ID() int64
- func (f FK[T]) IsSet() bool
- func (f FK[T]) Key() any
- func (f FK[T]) Loaded() bool
- func (f FK[T]) MarshalJSON() ([]byte, error)
- func (f FK[T]) Related() *T
- func (f *FK[T]) Scan(src any) error
- func (f *FK[T]) Set(row *T)
- func (f *FK[T]) SetID(key any)
- func (f FK[T]) String() string
- func (f *FK[T]) UnmarshalJSON(b []byte) error
- func (f FK[T]) Value() (driver.Value, error)
- type Field
- func (f Field[V]) Asc() string
- func (f Field[V]) Between(a, b V) Cond
- func (f Field[V]) Desc() string
- func (f Field[V]) Eq(v V) Cond
- func (f Field[V]) EqCol(c ColumnOf[V]) Cond
- func (f Field[V]) Expr() Expr
- func (f Field[V]) Gt(v V) Cond
- func (f Field[V]) Gte(v V) Cond
- func (f Field[V]) In(vs ...V) Cond
- func (f Field[V]) InQuery(sub subquerier) Cond
- func (f Field[V]) IsNull(null bool) Cond
- func (f Field[V]) Lt(v V) Cond
- func (f Field[V]) Lte(v V) Cond
- func (f Field[V]) Name() string
- func (f Field[V]) Ne(v V) Cond
- func (f Field[V]) Range(lo, hi V) Cond
- func (f Field[V]) Source() *Source
- func (f Field[V]) String() string
- type FieldAttr
- type FieldInfo
- type FieldOptions
- type FieldOptionsFunc
- type Fn
- type ForOption
- type FullText
- type FuncDef
- type FuncOf
- type FuncOption
- type Fusion
- type HNSW
- type HeadlineOption
- type IVFFlat
- type Index
- type Int
- type IntSize
- type JSON
- type JoinKind
- type JoinOn
- type Joinable
- type Kind
- type LongText
- type LookupFunc
- type LookupOption
- type M2M
- func (m *M2M[T]) Add(ctx context.Context, related ...any) error
- func (m M2M[T]) All(ctx context.Context) vuka.Result[[]T]
- func (m *M2M[T]) Clear(ctx context.Context) error
- func (m M2M[T]) Loaded() bool
- func (m M2M[T]) MarshalJSON() ([]byte, error)
- func (m M2M[T]) Query() Query[T]
- func (m M2M[T]) Related() *T
- func (m *M2M[T]) Remove(ctx context.Context, related ...any) error
- func (m M2M[T]) Rows() []T
- func (m *M2M[T]) Set(ctx context.Context, related ...any) error
- type Manager
- func (m *Manager[T]) BulkCreate(ctx context.Context, rows []*T) error
- func (m *Manager[T]) ColumnValues(row *T) map[string]any
- func (a *Manager) Columns() []string
- func (qs Manager) Count(ctx context.Context) (int64, error)
- func (qs Manager) CountSQL(ctx context.Context) (Statement, error)
- func (m *Manager[T]) Create(ctx context.Context, row *T) error
- func (qs Manager) Delete(ctx context.Context) (int64, error)
- func (qs Manager) DeleteSQL(ctx context.Context) (Statement, error)
- func (a *Manager) Err() error
- func (qs Manager) Exists(ctx context.Context) (bool, error)
- func (qs Manager) ExistsSQL(ctx context.Context) (Statement, error)
- func (qs Manager) Explain(ctx context.Context, opts ...ExplainOption) (Plan, error)
- func (a *Manager) Fields() []FieldInfo
- func (m *Manager[T]) GetOrCreate(ctx context.Context, lookup Q, defaults Defaults) (row T, created bool, err error)
- func (a *Manager) Info() ModelInfo
- func (m *Manager[T]) Manager() *Manager[T]
- func (m *Manager[T]) OnChange(fn func(ctx context.Context, c Change[T])) (stop func())
- func (a *Manager) PKColumn() string
- func (m *Manager[T]) Raw(sql string, args ...any) RawQuerySet[T]
- func (m *Manager[T]) Remove(ctx context.Context, row *T) error
- func (qs Manager) SQL(ctx context.Context) (string, []any, error)
- func (m *Manager[T]) Save(ctx context.Context, row *T) error
- func (a *Manager) TableName() string
- func (m *Manager[T]) UpdateOrCreate(ctx context.Context, lookup Q, defaults Defaults) (row T, created bool, err error)
- type Meta
- type Metric
- type MigrateOption
- type MirrorError
- type Model
- func (s *Model[T]) Add(ctx context.Context, relation any, related ...any) error
- func (*Model[T]) DeclaredFieldAttrs(t reflect.Type, registered map[string][]any) map[string][]any
- func (s *Model[T]) Delete(ctx context.Context) error
- func (s *Model[T]) Load(ctx context.Context, specs ...any) error
- func (s *Model[T]) Refresh(ctx context.Context) error
- func (s *Model[T]) Remove(ctx context.Context, relation any, related ...any) error
- func (s *Model[T]) Save(ctx context.Context) error
- func (s *Model[T]) SaveFields(ctx context.Context, fields ...any) error
- func (s *Model[T]) Set(ctx context.Context, relation any, related ...any) error
- func (s *Model[T]) Using(sc DBSchema) *T
- type ModelAnnotation
- type ModelAttr
- type ModelConfig
- type ModelInfo
- type Null
- type NumExpr
- type Number
- type NumberField
- type Observer
- type OpenOption
- type OptCell
- type OrderTerm
- type Orderable
- type OrderedExpr
- func CosineDistance(field string, v Vector) OrderedExpr[float64]
- func InnerProduct(field string, v Vector) OrderedExpr[float64]
- func L2Distance(field string, v Vector) OrderedExpr[float64]
- func Ordered[R Orderable](e Expr) OrderedExpr[R]
- func SearchRank(d Document, q TextQuery) OrderedExpr[float64]
- func Similarity(field, term string) OrderedExpr[float64]
- type OrderedFuncOf
- type OrderedTerm
- func (t OrderedTerm[T, V]) Add(x any) OrderedTerm[T, V]
- func (t OrderedTerm[T, V]) As(name string) OrderedTerm[T, V]
- func (t OrderedTerm[T, V]) Div(x any) OrderedTerm[T, V]
- func (t OrderedTerm[T, V]) Ge(v V) vuka.Pred[T]
- func (t OrderedTerm[T, V]) GeF(o Arg[T, V]) vuka.Pred[T]
- func (t OrderedTerm[T, V]) Gt(v V) vuka.Pred[T]
- func (t OrderedTerm[T, V]) GtF(o Arg[T, V]) vuka.Pred[T]
- func (t OrderedTerm[T, V]) Le(v V) vuka.Pred[T]
- func (t OrderedTerm[T, V]) LeF(o Arg[T, V]) vuka.Pred[T]
- func (t OrderedTerm[T, V]) Lt(v V) vuka.Pred[T]
- func (t OrderedTerm[T, V]) LtF(o Arg[T, V]) vuka.Pred[T]
- func (t OrderedTerm[T, V]) Mul(x any) OrderedTerm[T, V]
- func (t OrderedTerm[T, V]) Range(lo, hi V) vuka.Pred[T]
- func (t OrderedTerm[T, V]) Sub(x any) OrderedTerm[T, V]
- type Ordering
- type Outcome
- type PK
- type PageOption
- func DefaultSize(n int) PageOption
- func DefaultSort(fields ...string) PageOption
- func DefaultSortBy[T any](sorts ...vuka.Order[T]) PageOption
- func MaxSize(n int) PageOption
- func Searchable(fields ...string) PageOption
- func SearchableBy[T any](fields ...Path[T]) PageOption
- func Sortable(fields ...string) PageOption
- func SortableBy[T any](fields ...Path[T]) PageOption
- type PageRequest
- type PageResult
- type Path
- type Plan
- type PlanFormat
- type PlanResult
- type Pool
- type Pred
- type PredOp
- type Predicate
- type PrefetchSpec
- type PtrCell
- type Q
- type Querydeprecated
- func (q Query[T]) Aggregate[R any](ctx context.Context, cols ...Col[T, R]) vuka.Result[R]
- func (q Query[T]) AggregateSQL[R any](ctx context.Context, cols ...Col[T, R]) vuka.Result[Statement]
- func (q Query[T]) All(ctx context.Context) vuka.Result[[]T]
- func (q Query[T]) Annotate(as ...ModelAnnotation[T]) Query[T]
- func (q Query[T]) AnnotateAs(as ...Alias) Query[T]
- func (q Query[T]) BulkCreate(ctx context.Context, rows ...*T) error
- func (q Query[T]) Count(ctx context.Context) vuka.Result[int64]
- func (q Query[T]) CountSQL(ctx context.Context) vuka.Result[Statement]
- func (q Query[T]) Create(ctx context.Context, row *T) error
- func (q Query[T]) Delete(ctx context.Context) vuka.Result[int64]
- func (q Query[T]) DeleteSQL(ctx context.Context) vuka.Result[Statement]
- func (q Query[T]) Distinct() Query[T]
- func (q Query[T]) Exclude(ps ...vuka.Pred[T]) Query[T]
- func (q Query[T]) Exists(ctx context.Context) vuka.Result[bool]
- func (q Query[T]) ExistsSQL(ctx context.Context) vuka.Result[Statement]
- func (q Query[T]) Explain(ctx context.Context, opts ...ExplainOption) vuka.Result[Plan]
- func (q Query[T]) Filter(ps ...vuka.Pred[T]) Query[T]
- func (q Query[T]) First(ctx context.Context) vuka.Result[vuka.Option[T]]
- func (q Query[T]) Get(ctx context.Context, ps ...vuka.Pred[T]) vuka.Result[T]
- func (q Query[T]) GetOrCreate(ctx context.Context, row T, match ...Path[T]) vuka.Result[Outcome[T]]
- func (q Query[T]) GroupBy(groups ...any) Query[T]
- func (q Query[T]) Having(ps ...vuka.Pred[T]) Query[T]
- func (q Query[T]) Hybrid(doc SearchDoc[T], text string, field Path[T], v Vector, opts ...SearchOption) Query[T]
- func (q Query[T]) Iter(ctx context.Context) iter.Seq2[T, error]
- func (q Query[T]) Limit(n int) Query[T]
- func (q Query[T]) Manager() *Manager[T]
- func (q Query[T]) Nearest(field Path[T], v Vector, opts ...SearchOption) Query[T]
- func (q Query[T]) Offset(n int) Query[T]
- func (q Query[T]) On(s DBSchema) Query[T]
- func (q Query[T]) OnChange(fn func(ctx context.Context, c Change[T])) (stop func())
- func (q Query[T]) Order(terms ...OrderTerm) Query[T]
- func (q Query[T]) OrderBy(sorts ...Sort[T]) Query[T]
- func (q Query[T]) Paginate(ctx context.Context, r PageRequest, opts ...PageOption) vuka.Result[PageResult[T]]
- func (q Query[T]) PrefetchRelated(specs ...any) Query[T]
- func (q Query[T]) QuerySet() QuerySet[T]
- func (q Query[T]) Raw(ctx context.Context, sql string, args ...any) vuka.Result[[]T]
- func (q Query[T]) SQL(ctx context.Context) vuka.Result[Statement]
- func (q Query[T]) SelectRelated(rels ...Path[T]) Query[T]
- func (q Query[T]) Unfiltered() Query[T]
- func (q Query[T]) Update(ctx context.Context, sets ...Assignment[T]) vuka.Result[int64]
- func (q Query[T]) UpdateOrCreate(ctx context.Context, row T, match ...Path[T]) vuka.Result[Outcome[T]]
- func (q Query[T]) UpdateSQL(ctx context.Context, sets ...Assignment[T]) vuka.Result[Statement]
- func (q Query[T]) Values[R any](ctx context.Context, cols ...Col[T, R]) vuka.Result[[]R]
- func (q Query[T]) ValuesSQL[R any](ctx context.Context, cols ...Col[T, R]) vuka.Result[Statement]
- func (q Query[T]) Where(conds ...Cond) Query[T]
- func (q Query[T]) With(f func(QuerySet[T]) QuerySet[T]) Query[T]
- type QueryInfo
- type QuerySet
- func (qs QuerySet[T]) Aggregate(ctx context.Context, aggs ...Agg) (Result, error)
- func (qs QuerySet[T]) AggregateSQL(ctx context.Context, aggs ...Agg) (Statement, error)
- func (qs QuerySet[T]) All(ctx context.Context) ([]T, error)
- func (qs QuerySet[T]) Annotate(value any, es ...Expr) QuerySet[T]
- func (qs QuerySet[T]) AnnotateAs(as ...Alias) QuerySet[T]
- func (qs QuerySet) Count(ctx context.Context) (int64, error)
- func (qs QuerySet) CountSQL(ctx context.Context) (Statement, error)
- func (qs QuerySet[T]) CursorPage(ctx context.Context, after, before string, first, last int) (rows []T, cursors []string, more bool, err error)
- func (qs QuerySet) Delete(ctx context.Context) (int64, error)
- func (qs QuerySet) DeleteSQL(ctx context.Context) (Statement, error)
- func (qs QuerySet[T]) Distinct() QuerySet[T]
- func (qs QuerySet[T]) Exclude(conds ...Cond) QuerySet[T]
- func (qs QuerySet) Exists(ctx context.Context) (bool, error)
- func (qs QuerySet) ExistsSQL(ctx context.Context) (Statement, error)
- func (qs QuerySet) Explain(ctx context.Context, opts ...ExplainOption) (Plan, error)
- func (qs QuerySet[T]) Filter(conds ...Cond) QuerySet[T]
- func (qs QuerySet[T]) First(ctx context.Context) (T, error)
- func (qs QuerySet[T]) Get(ctx context.Context, conds ...Cond) (T, error)
- func (qs QuerySet[T]) GroupBy(names ...any) QuerySet[T]
- func (qs QuerySet[T]) Having(conds ...Cond) QuerySet[T]
- func (qs QuerySet[T]) Hybrid(doc Document, text TextQuery, field string, v Vector, opts ...SearchOption) QuerySet[T]
- func (qs QuerySet[T]) Iter(ctx context.Context) iter.Seq2[T, error]
- func (qs QuerySet[T]) Join(j Joinable, kind ...JoinKind) QuerySet[T]
- func (qs QuerySet[T]) Limit(n int) QuerySet[T]
- func (qs QuerySet[T]) Nearest(field string, v Vector, opts ...SearchOption) QuerySet[T]
- func (qs QuerySet[T]) Offset(n int) QuerySet[T]
- func (qs QuerySet[T]) Order(terms ...OrderTerm) QuerySet[T]
- func (qs QuerySet[T]) OrderBy(fields ...any) QuerySet[T]
- func (qs QuerySet[T]) PrefetchRelated(specs ...any) QuerySet[T]
- func (qs QuerySet) SQL(ctx context.Context) (string, []any, error)
- func (qs QuerySet[T]) SelectRelated(paths ...any) QuerySet[T]
- func (qs QuerySet[T]) Unfiltered() QuerySet[T]
- func (qs QuerySet[T]) Update(ctx context.Context, values Set) (int64, error)
- func (qs QuerySet[T]) UpdateSQL(ctx context.Context, values Set) (Statement, error)
- func (qs QuerySet[T]) Values[R any](fields ...any) Values[T, R]
- type RawOption
- type RawQuerySet
- type Rel
- type RelationPath
- func (r RelationPath) Avg(field any) Expr
- func (r RelationPath) Count() Expr
- func (r RelationPath) CountRows() Expr
- func (r RelationPath) Eq(v any) Cond
- func (r RelationPath) Exists() Expr
- func (r RelationPath) Max(field any) Expr
- func (r RelationPath) Min(field any) Expr
- func (r RelationPath) On(conds ...Cond) JoinOn
- func (r RelationPath) Source() *Source
- func (r RelationPath) Sum(field any) Expr
- func (r RelationPath) Where(conditions ...Cond) RelationPath
- type ReplicaStats
- type Result
- type Retry
- type Route
- type Router
- type RowScanner
- type RowWriter
- type SQLExpr
- func (e SQLExpr[T]) Asc() ExprOrder
- func (e SQLExpr[T]) Desc() ExprOrder
- func (e SQLExpr[T]) Eq(v any) Cond
- func (e SQLExpr[T]) For(d DialectName) SQLExpr[T]
- func (e SQLExpr[T]) Gt(v any) Cond
- func (e SQLExpr[T]) Gte(v any) Cond
- func (e SQLExpr[T]) Lt(v any) Cond
- func (e SQLExpr[T]) Lte(v any) Cond
- func (e SQLExpr[T]) Ne(v any) Cond
- type Schema
- type SchemaCodec
- type SchemaError
- type SchemaField
- type SchemaScanner
- type SchemaValuer
- type SearchDoc
- func (s SearchDoc[T]) Add(o SearchDoc[T]) SearchDoc[T]
- func (s SearchDoc[T]) Config(c string) SearchDoc[T]
- func (s SearchDoc[T]) Document() Document
- func (s SearchDoc[T]) Matches(q string) vuka.Pred[T]
- func (s SearchDoc[T]) MatchesQuery(q TextQuery) vuka.Pred[T]
- func (s SearchDoc[T]) Rank(q string) OrderedTerm[T, float64]
- func (s SearchDoc[T]) RankQuery(q TextQuery) OrderedTerm[T, float64]
- func (s SearchDoc[T]) Weight(w string) SearchDoc[T]
- type SearchOf
- type SearchOption
- func Candidates(n int) SearchOption
- func DistanceAs(alias string) SearchOption
- func EfSearch(n int) SearchOption
- func HybridWeights(text, vector float64) SearchOption
- func K(k int) SearchOption
- func MaxDistance(d float64) SearchOption
- func Probes(n int) SearchOption
- func RRF(k int) SearchOption
- func RankAs(alias string) SearchOption
- func ScoreAs(alias string) SearchOption
- type Session
- type Set
- type Skip
- type SlowQuery
- type Slug
- type Sort
- type Source
- type State
- type StateEvent
- type Statement
- type StringTerm
- func (t StringTerm[T, V]) As(name string) StringTerm[T, V]
- func (t StringTerm[T, V]) Contains(s V) vuka.Pred[T]
- func (t StringTerm[T, V]) EndsWith(s V) vuka.Pred[T]
- func (t StringTerm[T, V]) IContains(s V) vuka.Pred[T]
- func (t StringTerm[T, V]) IEndsWith(s V) vuka.Pred[T]
- func (t StringTerm[T, V]) IExact(s V) vuka.Pred[T]
- func (t StringTerm[T, V]) IStartsWith(s V) vuka.Pred[T]
- func (t StringTerm[T, V]) StartsWith(s V) vuka.Pred[T]
- type SwitchExpr
- type TSVector
- type Term
- func (t Term[T, V]) As(name string) Term[T, V]
- func (t Term[T, V]) Asc() TermOrder[T]
- func (t Term[T, V]) Desc() TermOrder[T]
- func (t Term[T, V]) Eq(v V) vuka.Pred[T]
- func (t Term[T, V]) EqF(o Arg[T, V]) vuka.Pred[T]
- func (t Term[T, V]) Expr() Expr
- func (t Term[T, V]) Get(T) V
- func (t Term[T, V]) In(vs ...V) vuka.Pred[T]
- func (t Term[T, V]) IsNull() vuka.Pred[T]
- func (t Term[T, V]) Ne(v V) vuka.Pred[T]
- func (t Term[T, V]) NeF(o Arg[T, V]) vuka.Pred[T]
- func (t Term[T, V]) NotNull() vuka.Pred[T]
- type TermOrder
- type TextExpr
- type TextField
- func (f TextField[V]) Contains(s string) Cond
- func (f TextField[V]) EndsWith(s string) Cond
- func (f TextField[V]) IContains(s string) Cond
- func (f TextField[V]) IEndsWith(s string) Cond
- func (f TextField[V]) IExact(s string) Cond
- func (f TextField[V]) IStartsWith(s string) Cond
- func (f TextField[V]) StartsWith(s string) Cond
- type TextFuncOf
- type TextQuery
- type TimeField
- func (f TimeField) Add(d time.Duration) DateExpr
- func (f TimeField) AddDays(n int) DateExpr
- func (f TimeField) AddMonths(n int) DateExpr
- func (f TimeField) Between(a, b any) Cond
- func (f TimeField) Eq(v any) Cond
- func (f TimeField) Gt(v any) Cond
- func (f TimeField) Gte(v any) Cond
- func (f TimeField) Lt(v any) Cond
- func (f TimeField) Lte(v any) Cond
- func (f TimeField) Ne(v any) Cond
- type Timeout
- type Trigram
- type TxOn
- type TxOption
- type TypedExpr
- func (t TypedExpr[R]) As(alias string) Alias
- func (t TypedExpr[R]) Asc() ExprOrder
- func (t TypedExpr[R]) Desc() ExprOrder
- func (t TypedExpr[R]) Eq(v R) Cond
- func (t TypedExpr[R]) In(vs ...R) Cond
- func (t TypedExpr[R]) IsNull() Cond
- func (t TypedExpr[R]) Ne(v R) Cond
- func (t TypedExpr[R]) NotNull() Cond
- func (t TypedExpr[R]) Over(w Window) TypedExpr[R]
- type Unique
- type UniqueTogether
- type Validator
- type Values
- func (vq Values[T, R]) All(ctx context.Context) ([]R, error)
- func (vq Values[T, R]) Annotate(name any, es ...Expr) Values[T, R]
- func (vq Values[T, R]) Distinct() Values[T, R]
- func (vq Values[T, R]) Exclude(conds ...Cond) Values[T, R]
- func (vq Values[T, R]) Explain(ctx context.Context, opts ...ExplainOption) (Plan, error)
- func (vq Values[T, R]) Filter(conds ...Cond) Values[T, R]
- func (vq Values[T, R]) GroupBy(names ...any) Values[T, R]
- func (vq Values[T, R]) Having(conds ...Cond) Values[T, R]
- func (vq Values[T, R]) Iter(ctx context.Context) iter.Seq2[R, error]
- func (vq Values[T, R]) Join(j Joinable, kind ...JoinKind) Values[T, R]
- func (vq Values[T, R]) Limit(n int) Values[T, R]
- func (vq Values[T, R]) Offset(n int) Values[T, R]
- func (vq Values[T, R]) OrderBy(fields ...any) Values[T, R]
- func (vq Values[T, R]) SQL(ctx context.Context) (string, []any, error)
- type Vector
- type WhenClause
- type Window
Constants ¶
const ( DefaultMaxOpen = 20 DefaultMaxIdle = 20 DefaultMaxLifetime = time.Hour )
Pool defaults: a cap on connections, so a burst of requests can't exhaust the server's.
const ( Cascade = "cascade" SetNull = "set_null" Restrict = "restrict" )
What deleting a related row does to the rows holding its key (Rel's OnDelete).
const CLIEnv = "ORM_CLI_REQUEST"
CLIEnv is the variable the orm command sets to run a program as its migration tool (makemigrations, migrate, showmigrations, sqlmigrate), holding a JSON CLIRequest.
Variables ¶
var ( AsInt = CastType{/* contains filtered or unexported fields */} AsFloat = CastType{/* contains filtered or unexported fields */} AsText = CastType{/* contains filtered or unexported fields */} AsDate = CastType{/* contains filtered or unexported fields */} AsDateTime = CastType{/* contains filtered or unexported fields */} )
The types Cast converts to. AsDecimal and AsType make others.
var ( ErrNotFound error = NotFound ErrMultipleFound error = MultipleFound ErrConflict error = Conflict ErrInvalid error = Invalid )
The kinds as error values, for errors.Is.
var ( Lower = TextFunc("lower", Arity(1)).Transform() Upper = TextFunc("upper", Arity(1)).Transform() Trim = TextFunc("trim", Arity(1)).Transform() Length = OrderedFunc[int64]("length", Arity(1), Template("mysql", "CHAR_LENGTH({0})"), Template("", "length({0})")).Transform() Abs = OrderedFunc[float64]("abs", Arity(1)).Transform() Year = OrderedFunc[int]("year", Arity(1), Template("postgres", "CAST(EXTRACT(YEAR FROM {0}) AS INTEGER)"), Template("mysql", "year({0})"), Template("sqlite", "CAST(strftime('%Y', {0}) AS INTEGER)")).Transform() Month = OrderedFunc[int]("month", Arity(1), Template("postgres", "CAST(EXTRACT(MONTH FROM {0}) AS INTEGER)"), Template("mysql", "month({0})"), Template("sqlite", "CAST(strftime('%m', {0}) AS INTEGER)")).Transform() Day = OrderedFunc[int]("day", Arity(1), Template("postgres", "CAST(EXTRACT(DAY FROM {0}) AS INTEGER)"), Template("mysql", "day({0})"), Template("sqlite", "CAST(strftime('%d', {0}) AS INTEGER)")).Transform() Coalesce = Func[any]("coalesce") )
Functions every model can use, transforms all: Q{"name__lower": "ali"}, Q{"created_at__year": 2026}, Q{"created_at__date": "2026-10-06"}. Called, each is typed: orm.Lower(orm.F("name")).StartsWith("a"); Of gives the untyped call. Date's value is the date as text, YYYY-MM-DD, which every database compares with a date.
var Clock = time.Now
Clock is the time auto_now and auto_now_add fields take.
var Date dateFunction = func(args ...any) DateExpr { e := dateLegacy(args...) if len(args) != 1 { return DateExpr{OrderedExpr: e, base: dateLegacy.Of(args...), kind: "base"} } return DateExpr{OrderedExpr: e, base: args[0], kind: "date"} }
Date retains its function and transform API and adds calendar arithmetic.
var Default = NewDatabases()
Default is the program's databases: those AddDatabase adds, queried by every context without WithDatabases.
var ErrCursor error = cursorError{}
ErrCursor is a cursor CursorPage can't read: malformed, or made for another ordering. It is the client's error: a route answers 400, a GraphQL field's error is BAD_USER_INPUT.
var ErrUnfiltered = errors.New("orm: no condition")
ErrUnfiltered is the error of an Update or Delete with no condition: one that would change every row of the table. Unfiltered says that is what is meant.
var MigrateWait = 30 * time.Second
MigrateWait is how long Migrate (and Verify) wait for a database to answer.
var MigrationsTable = "orm_migrations"
MigrationsTable is the table recording each database's applied migrations. Set it before migrating to keep a history recorded under another name.
Functions ¶
func AddDatabase ¶
func AddDatabase(name string, db *DB, opts ...DatabaseOption)
AddDatabase adds db to Default as name.
func ApplyMigrations ¶
func ApplyMigrations(ctx context.Context, d *DB, target string, migrations ...migration.Migration) error
ApplyMigrations takes d through migrations (one database's) as orm migrate does: to target (a name, or its leading number), applying those up to it and unapplying those after; "zero" unapplies them all, "" applies them all. For tools and tests.
func Atomic ¶
Atomic runs fn in a transaction: committed when fn returns nil, rolled back when it returns an error or panics. Queries take part when they use the ctx fn is given. The first write inside it picks the database (each model's write database, as it routes); reads before it run outside, on the models' write databases, and a write to another database fails: a transaction spans one database. TxOn names it from the start; Retry retries deadlocks. Inside another Atomic it is a savepoint, rolled back alone. OnCommit runs work once it commits.
func AtomicOn ¶
func AtomicOn(ctx context.Context, db *DB, fn func(ctx context.Context) error, opts ...TxOption) error
AtomicOn is Atomic on a given database.
func Check ¶
func Check(models ...AnyManager) error
Check is what keeps the ORM from mapping the program's models — those Register added, and models — joined: run it at start up, so a model it can't map fails there rather than on its first query.
func ConnFor ¶
ConnFor declares T (a struct embedding orm.Conn) the handle of the database name, as @orm.Database does, and returns its constructor from a Databases, for a DI container.
type Analytics struct{ orm.Conn }
app.Provide(orm.ConnFor[Analytics]("analytics"))
func CreateTables ¶
func CreateTables(ctx context.Context, models ...AnyManager) error
CreateTables creates the models' tables, and the tables between their many-to-many relations, where they are not already, and the extensions CreateExtension declared for the models' databases: for tests and tools. Foreign keys are made between the tables it makes only. A deployed schema changes through migrations (orm.Migrate).
func Database ¶
Database is a Vuka type decorator naming the database a connection handle (a struct embedding orm.Conn) is on; ormweb provides it, made from the app's Databases, to whatever takes a *T.
@orm.Database("analytics")
type Analytics struct{ orm.Conn }
func Entity ¶
Entity is a type decorator registering a Vuka model at start-up, so Check and the migration commands know it without orm generate; an @orm.Meta{…} on the type is its Meta.
@orm.Meta{Table: "posts", Ordering: []string{"-published"}}
@orm.Entity
type Post struct { orm.Base; … }
func Exec ¶
Exec runs sql, a write or DDL, on the default database (or the one an option among args names, as Raw's do), inside ctx's transaction when there is one, and says how many rows it changed. A raw write is the database's alone: OnChange hears nothing of it and no mirror repeats it.
func FieldName ¶
FieldName is a field reference's lookup path (Post.Author.Name → "author__name"), for the ORM's string APIs.
func Generated ¶
Generated is whether T's rows are read by a generated scanner: one is registered and reads the model's columns.
func Handles ¶
Handles is the connection handle types declared (@orm.Database, ConnFor), for a framework to provide.
func LikePattern ¶
LikePattern is a LookupValue making the value a LIKE pattern matching it literally, between before and after (% for any run): its own %, _ and ! escaped by !, so the lookup's SQL ends with ESCAPE '!'.
func LoadRelated ¶ added in v2.1.0
LoadRelated loads relations into rows read already, as PrefetchRelated loads them into a query's rows: each relation in one query for all of them (per 1000 keys), by typed field (PostColumns.Tags), reference, name or orm.Prefetch. The rows are queried on the first one's schema.
err := orm.LoadRelated(ctx, posts, "author", "tags")
What a GraphQL field holding a relation resolves through: the rows of a level of the query, loaded together (graphql.Related).
func LoadRelation ¶ added in v2.1.0
LoadRelation is LoadRelated of one relation, by its Go field's name or its lookup name: what the code Vuka generates for a GraphQL field of an orm model holding a relation passes graphql.Related.
func LookupPath ¶
LookupPath is a field reference's path as lookups write it: author__name.
func MakeHandle ¶
MakeHandle is a *T of the handle type t on s.
func Migrate ¶
func Migrate(ctx context.Context, opts ...MigrateOption) error
Migrate applies the registered migrations to ctx's databases (Default, or WithDatabases's), at start up before the program serves: those not yet recorded in each database's MigrationsTable, each after its dependencies. The program's migrations package registers them: import it.
import _ "example.com/shop/migrations"
if err := orm.Migrate(ctx); err != nil {
log.Fatal(err)
}
It waits up to MigrateWait for each database to answer. A migration runs in a transaction where the database can roll DDL back (Postgres, SQLite; MySQL commits each statement). Replicas starting together take turns under a lock (Postgres advisory, MySQL GET_LOCK). orm migrate applies them (or unapplies them, back to a migration) on demand.
func MySQLDSN ¶
MySQLDSN is a go-sql-driver DSN as the ORM reads MySQL: parseTime on, which time fields need, and, unless the DSN names a charset or a collation, charset=utf8mb4 with no collation. The driver otherwise greets the server in utf8mb4_general_ci, while MySQL 8 and later make tables in their default, utf8mb4_0900_ai_ci: a string the server derives in the connection's collation (a JSON_TABLE column) then can't be compared with a column (Error 1267, illegal mix of collations). SET NAMES utf8mb4 takes the server's default collation for utf8mb4, the one its tables have: MySQL 8.0, 8.4 and 9 and MariaDB alike. A DSN's own charset or collation is left as it is.
func Observe ¶
func Observe(fn Observer) (stop func())
Observe has fn see every statement the program's queries run, whatever their context: the hook a framework's tracer or debug toolbar plugs into. It returns what stops it.
func ObserveState ¶
func ObserveState(fn func(StateEvent)) (stop func())
ObserveState calls fn on each change of a supervised database's state: for metrics and alerts (the supervisor logs them too). It returns what stops it.
func OnCommit ¶
OnCommit runs fn once ctx's transaction commits — at once outside one; a rolled back transaction never runs it, nor a savepoint's rolled back part. The way to send mail or enqueue work (an outbox) only for writes that stay.
func OnMirrorError ¶
func OnMirrorError(fn func(ctx context.Context, e MirrorError)) (stop func())
OnMirrorError calls fn for each mirrored write that fails, beside the log: the place to queue the table for a re-sync. It returns what stops it.
func Operand ¶
Operand is v as the engine takes a value that may be an expression: a typed field or field reference as the field, an Expr as is, an orm.FK its key, an Option its value, anything else as is (bound, and typed by the engine where it must be, as in Case results on Postgres).
func OptValue ¶
OptValue is an Option field's value for the driver, for generated writers: nil for None, else the value.
func Optional ¶
Optional is a row First or Get found as an Option, None when ErrNotFound says there is none; other errors stay errors:
p, err := orm.Optional(orm.Objects[Post]().Filter(f.Slug.Eq(slug)).First(ctx))
if err != nil { … }
if post, ok := p.Get(); ok { … }
func Orderings ¶
Orderings is the terms as OrderBy takes them.
qs.OrderBy(orm.Orderings(orm.Ordering{Path: []string{"age"}, Desc: true})...)
func P ¶
P is an ORM condition as a predicate on T, beside field references' own: Q, Or, Exists, Match — whatever has no Vuka form.
Post.Objects.Filter(Post.Views.Gt(10), orm.P[Post](orm.Q{"title__iregex": "^go"}))
func ParseURL ¶
ParseURL is a database URL's dialect and the DSN its driver takes, as ConnectURL reads it.
func PathName ¶
PathName is a field reference's lookup path, a named term's name, or a string as is; "" for an unnamed term.
func Primary ¶
Primary has ctx's reads go where the models write: never to a replica, nor a read database a Meta or router names. For a read that must see a write just made outside a Scope.
func PtrValue ¶
PtrValue is a pointer field's value for the driver, for generated writers: nil for nil, the pointer for a driver.Valuer, else what it points to.
func Raw ¶
Raw is the rows sql reads, read into R as Values reads them: a scalar for one column, a struct (a field per column, by orm path tag, db or column tag, name or column; Option or a pointer for a NULL), map[string]any keyed by column, or []any. ? marks each argument (written as the database's, $1 on Postgres; values are always bound), ?? is a literal ?. A column the struct has no field for is an error, unless Loose.
It reads the default database (its replica, outside a transaction or a Scope that wrote it), or the one an option among args names: orm.On("analytics"), or a connection handle (a struct embedding orm.Conn); Timeout bounds it. Using, transactions and observers apply as to any query.
n, err := orm.Raw[int64](ctx, "SELECT COUNT(*) FROM users WHERE is_active = ?", true)
sales, err := orm.Raw[Sale](ctx, "SELECT day, SUM(total) AS total FROM sales GROUP BY day", orm.On("analytics"))
func RawOn ¶
RawOn is Raw on schema s's database.
n, err := orm.RawOn[int64](ctx, Legacy, "SELECT COUNT(*) FROM auth_user WHERE is_active = ?", true)
func Register ¶
func Register[T any]()
Register adds the model T to the program's models: Check reports when the ORM can't map it, and orm makemigrations plans its table without a package-level orm.For. orm generate writes a Register for every type embedding orm.Model in the module's packages (the orm command overlays them when it builds the program as its migration tool); Objects registers too.
func RegisterDriver ¶
func RegisterDriver(dialect, sqlDriver string)
RegisterDriver names the database/sql driver Connect opens for a dialect. The driver packages (orm/postgres, orm/mysql, orm/sqlite) register theirs: blank-import the one the program opens.
import _ "github.com/vuka-lang/orm/v2/postgres"
func RegisterDriverHooks ¶
func RegisterDriverHooks(dialect string, h DriverHooks)
RegisterDriverHooks gives the ORM a driver's hooks for a dialect; the driver packages register theirs.
func RegisterLookup ¶
func RegisterLookup(name string, fn LookupFunc, opts ...LookupOption)
RegisterLookup adds a lookup to Q keys and Where, Django's register_lookup: Q{"title__unaccent_icontains": "cafe"}, orm.Where(e, "unaccent_icontains", "cafe"). Its name is lowercase letters, digits and single underscores; registering a name again replaces it, and a built-in lookup's name panics. Transforms (a function's Transform) go before it as before a built-in lookup: Q{"title__lower__unaccent_icontains": "cafe"}.
orm.RegisterLookup("unaccent_icontains", func(lhs string, rhs func() string, d orm.Dialect) (string, bool) {
if d.Name() != "postgres" {
return "", false
}
return "unaccent(" + lhs + ") ILIKE unaccent(" + rhs() + ") ESCAPE '!'", true
}, orm.LookupValue(orm.LikePattern("%", "%")))
func RegisterScanner ¶
func RegisterScanner[T any](cols []string, make func() RowScanner[T])
RegisterScanner installs a generated scanner for T, reading cols in order. A scanner whose columns aren't the model's (the model changed after the code was generated) is ignored and rows are read by reflection.
func Scope ¶
Scope starts a read-your-writes scope on ctx, a request's: once a query with it (or a context made from it) writes a model, its reads of that model go to the database written, not a replica or a read database; raw reads of a database written go to its primary. Middleware starts one per request (ormweb does). ReadYourWrites(false) on the Databases turns it off.
func ServeCLI ¶
func ServeCLI()
ServeCLI makes the program the orm command's migration tool when CLIEnv is set: it does what the request asks and exits, before main runs. The command calls it from an init it overlays into the program's main package; programs don't.
func SetFieldOptions
deprecated
func SetFieldOptions(fn FieldOptionsFunc)
SetFieldOptions installs fn as the source of field options beside the struct tags. Set it before the first query: a model's metadata is read once. orm generate reads tags only, so a model whose columns fn renames is read by reflection rather than by its generated scanner.
Deprecated: declare a model's field attributes in its Schema method (s.Field(&p.Title, orm.Char{Max: 200})), as values of a FieldAttr of your own where the ORM has none; what only the running program knows (a column a legacy table lacks) a model attribute decides through ModelConfig.Fields.
func Transaction ¶
Transaction is Atomic: fn run in a transaction, committed when it returns nil, rolled back when it returns an error or panics.
err := orm.Transaction(ctx, func(ctx context.Context) error {
p, err := orm.For[Post]().Get(ctx, PostColumns.Slug.Eq(slug))
if err != nil {
return err
}
p.Published = time.Now()
return p.Save(ctx)
}, orm.Retry(3))
func WatchRepeats ¶
func WatchRepeats(ctx context.Context, n int, warn func(ctx context.Context, sql string, times int)) context.Context
WatchRepeats is ctx warning, through warn, when its queries run the same statement n times: a statement reading related rows one parent at a time, an N+1, which SelectRelated or PrefetchRelated read in one. Give it a request's context; warn is called once per statement.
ctx = orm.WatchRepeats(ctx, 5, func(ctx context.Context, sql string, n int) {
slog.WarnContext(ctx, "orm: N+1", "sql", sql, "times", n)
})
func WithDB ¶
WithDB has every model in ctx's queries use db, whatever database it is on: for tests and tools.
func WithDatabases ¶
WithDatabases has ctx's queries find their databases in s instead of Default.
func WithMirror ¶
WithMirror has every model's writes in ctx repeated on db, as Mirror does by name: for tests and tools.
func WithObserver ¶
WithObserver has fn see every statement queries with ctx run, after the observers ctx already has.
Types ¶
type AfterCreater ¶
The hooks a model may have, promoted from embedded structs like any method. A Before hook's error stops the write.
type AfterDeleter ¶
The hooks a model may have, promoted from embedded structs like any method. A Before hook's error stops the write.
type AfterSaver ¶
The hooks a model may have, promoted from embedded structs like any method. A Before hook's error stops the write.
type Agg ¶
type Agg struct {
// contains filtered or unexported fields
}
Agg is an aggregate: of a field (Count, Sum, Avg, Min, Max), or any aggregate expression (AggOf).
func AggOf ¶
AggOf is an aggregate expression under a key of your own, for the aggregates the database has beyond the five:
var Names = orm.Function("names",
orm.Template("postgres", "string_agg({0}, ', ')"),
orm.Template("", "GROUP_CONCAT({0}, ', ')"), // SQLite
orm.Template("mysql", "GROUP_CONCAT({0} SEPARATOR ', ')")) // a literal: MySQL takes no argument here
r, _ := Users.Aggregate(ctx, orm.AggOf("names", Names.Of(orm.F("name"))))
func Count ¶
Count, Sum, Avg, Min and Max aggregate a field: a name ("age", "books__id"), a typed field (of the queried model or one it joins), or an expression. Count is SQL's COUNT(col), which skips NULLs, so a LEFT JOIN's missing rows count 0.
Category.Objects.Join(…).Values[CategoryProducts](CategoryColumns.Name, orm.Count(ProductColumns.ID, orm.Distinct))
func (Agg) Distinct ¶
Distinct aggregates each distinct value once, Django's distinct=True: COUNT(DISTINCT …), so a row reached twice through joins counts once.
type AggOption ¶ added in v2.16.0
type AggOption int
AggOption shapes an aggregate: Distinct.
const Distinct AggOption = 1
Distinct aggregates each distinct value once: orm.Count(ProductColumns.ID, orm.Distinct) is COUNT(DISTINCT …), so a row a join repeats counts once.
type Alias ¶
type Alias struct {
// contains filtered or unexported fields
}
Alias is an expression under a name, As's: AnnotateAs annotates the query with it.
type AnnotationValue ¶ added in v2.2.0
AnnotationValue is a typed name for a query annotation. Annotation constructs one; ModelAnnotation[T] is the model-term interface.
func Annotation ¶
func Annotation[T any](name string, e Expr) AnnotationValue[T]
Annotation names an expression and returns its typed filter/order handle.
func Ref ¶ added in v2.2.0
func Ref[T any](name string) AnnotationValue[T]
Ref refers to an annotation already added to the query.
func (AnnotationValue[T]) Asc ¶ added in v2.2.0
func (v AnnotationValue[T]) Asc() ExprOrder
func (AnnotationValue[T]) Between ¶ added in v2.2.0
func (v AnnotationValue[T]) Between(a, b T) Cond
func (AnnotationValue[T]) Desc ¶ added in v2.2.0
func (v AnnotationValue[T]) Desc() ExprOrder
func (AnnotationValue[T]) Gt ¶ added in v2.2.0
func (v AnnotationValue[T]) Gt(x T) Cond
func (AnnotationValue[T]) Gte ¶ added in v2.2.0
func (v AnnotationValue[T]) Gte(x T) Cond
func (AnnotationValue[T]) Lt ¶ added in v2.2.0
func (v AnnotationValue[T]) Lt(x T) Cond
func (AnnotationValue[T]) Lte ¶ added in v2.2.0
func (v AnnotationValue[T]) Lte(x T) Cond
type AnyManager ¶
type AnyManager interface {
Err() error
// contains filtered or unexported methods
}
AnyManager is a manager of any model, as CreateTables and ormtest take it.
type Arg ¶
type Arg[T, V any] interface{ Get(T) V }
Arg is a field reference of T, or a typed expression over T, of Go type V: Post.Title, Post.Author.Name, fn.Lower(Post.Title). Functions taking one keep V, so their results stay typed.
type Assignment ¶
type Assignment[T any] struct { // contains filtered or unexported fields }
Assignment is a field set to a value or an expression, for Update.
func Assign ¶
func Assign[T, V any](f Arg[T, V], v V) Assignment[T]
Assign sets field f to v; AssignF to a field or term.
type AutoNow ¶
type AutoNow struct{}
AutoNow sets the field to the time on every save; AutoNowAdd on create.
func (AutoNow) Apply ¶
func (AutoNow) Apply(o *FieldOptions)
type AutoNowAdd ¶
type AutoNowAdd struct{}
The field attributes: what a struct tag says, as typed values given to s.Field in a model's Schema method,
func (p *Post) Schema(s *orm.Schema) {
s.Field(&p.ID, orm.PK{})
s.Field(&p.Title, orm.Char{Max: 200, Label: "Title"})
s.Field(&p.Author, orm.Rel{OnDelete: orm.Cascade, Related: "posts"})
}
or, in Vuka, written after the field:
type Post struct {
orm.Base
ID int64 @orm.PK
Title string @orm.Char{Max: 200, Label: "Title"}
Status string @orm.Char{Max: 20, Default: "draft", Choices: []string{"draft", "published"}}
Slug string @orm.Slug{Unique: true}
Body string @orm.LongText
Author orm.FK[User] @orm.Rel{OnDelete: orm.Cascade, Related: "posts"}
Views int @orm.Int{Min: Some(0), Default: 0}
Published time.Time @orm.Datetime{DefaultNow: true, Precision: 3}
}
Each is a FieldAttr, applied in order: a later one's set members win, an empty member never undoes an earlier one. They win over the field's tags; SetFieldOptions wins over them. One without members is written orm.PK{} (@orm.PK in Vuka), one of a named type by conversion: orm.Column("headline"), orm.Dims(384).
func (AutoNowAdd) Apply ¶
func (AutoNowAdd) Apply(o *FieldOptions)
type Base ¶
Base is a Vuka model's base, Model under another name: Post.Objects is the static Vuka gives every type embedding it, the model's manager (Objects[Post]()). Embed it as orm.Base (Vuka fills in the type):
type Post struct {
orm.Base @orm.Meta{Table: "posts", Ordering: []string{"-published"}}
ID int64
Title string @orm.Char{Max: 200}
}
posts := Post.Objects.Filter(Post.Title.Contains("go")).All(ctx)?
p.Save(ctx)?
The attributes become the model's Schema method; Post.Title is the generated typed field PostColumns.Title. Rows have Model's methods: Save, SaveFields, Refresh, Delete, Load, Add, Remove, Set, Using.
func (*Base[Self]) Add ¶
Add, Remove and Set change the row's many-to-many links, the relation named by reference or name. An orm.M2M field has them itself.
func (*Base[Self]) DeclaredFieldAttrs ¶
DeclaredFieldAttrs is Model's, for a Vuka model.
func (*Base[Self]) Load ¶
Load loads relations into the row, by reference (Post.Tags), name or orm.Prefetch.
func (*Base[Self]) SaveFields ¶
SaveFields updates only the fields named: typed fields (PostColumns.Title), references or names.
type BaseRouter ¶
type BaseRouter struct{}
BaseRouter is a Router with no opinion that allows everything: embed it and override what the router decides.
func (BaseRouter) AllowMigrate ¶
func (BaseRouter) AllowMigrate(string, ModelInfo) bool
func (BaseRouter) AllowRelation ¶
func (BaseRouter) AllowRelation(a, b ModelInfo) bool
type BeforeCreater ¶
The hooks a model may have, promoted from embedded structs like any method. A Before hook's error stops the write.
type BeforeDeleter ¶
The hooks a model may have, promoted from embedded structs like any method. A Before hook's error stops the write.
type BeforeSaver ¶
The hooks a model may have, promoted from embedded structs like any method. A Before hook's error stops the write.
type Breaker ¶
Breaker is the circuit breaker on a database's statements: after Failures connection errors in a row (5) it opens, and statements fail at once, Unavailable, for Cooldown (5s); then one statement probes, and its success closes it. Only connection errors count — a refused or reset connection, a timeout, a dropped one — never a query's own.
type CLIRequest ¶
type CLIRequest struct {
Command string `json:"command"` // plan, migrate, show, sql
// DB is the migrations' database ("" the default).
DB string `json:"db"`
// Models is plan's: the databases (orm.On names) the models of DB's
// migrations are on: "" and the default's name for the default.
Models []string `json:"models,omitempty"`
Dialect string `json:"dialect,omitempty"` // plan, sql
// Number, Name, Package and Empty name and shape plan's migration;
// Interactive asks about renames on stdin, and migrate's confirmation
// before it unapplies migrations.
Number int `json:"number,omitempty"`
Name string `json:"name,omitempty"`
Package string `json:"package,omitempty"`
Empty bool `json:"empty,omitempty"`
Interactive bool `json:"interactive,omitempty"`
// Target is migrate's: the migration to take DB to ("zero" for
// none); every database's pending ones when empty. sql's: the
// migration to print.
Target string `json:"target,omitempty"`
Backwards bool `json:"backwards,omitempty"` // sql
// Conns is the URL of each migrations database ("" the default's),
// for migrate and show to connect (see ConnectURL).
Conns map[string]string `json:"conns,omitempty"`
Out string `json:"out,omitempty"` // plan: the file its PlanResult goes to
}
CLIRequest is what the orm command asks of a program run as its migration tool.
type CSV ¶
type CSV[E CSVElem] struct{ V []E }
CSV is a column holding a list as comma-separated text ("7,9,11"), for legacy tables that keep lists in a string: read and write V; the field marshals as the list. A nil V is NULL, an empty non-nil V ""; reading trims spaces around the commas.
type Letter struct {
ID int64
PlacementIDs orm.CSV[int64]
}
func (CSV[E]) MarshalJSON ¶
func (*CSV[E]) UnmarshalJSON ¶
type CSVElem ¶
type CSVElem interface {
~int | ~int8 | ~int16 | ~int32 | ~int64 | ~uint | ~uint16 | ~uint32 | ~uint64 | ~string
}
CSVElem is what a CSV column's list may hold.
type CaseExpr ¶
type CaseExpr struct {
// contains filtered or unexported fields
}
CaseExpr is a Case.
func Case ¶
func Case(whens ...WhenClause) *CaseExpr
Case is the first of its branches whose condition holds, Django's Case: each When's result, else Else's, else NULL.
orm.Case(
orm.When(orm.Q{"orders__total__gte": 1000}, "gold"),
orm.When(orm.Q{"age__gte": 18}, "silver"),
).Else("bronze")
type CastType ¶
type CastType struct {
// contains filtered or unexported fields
}
CastType is a type Cast converts to, spelled for each database.
func AsDecimal ¶
AsDecimal is a fixed-point number of precision digits, scale of them after the point (NUMERIC on SQLite, which keeps no scale).
func AsType ¶
AsType is a database type written as the database spells it, the same on every database: AsType("CHAR(20)"), AsType("UUID"). It takes a type name and its size only, never anything else. MySQL's CAST knows few types (CHAR, SIGNED, UNSIGNED, DECIMAL, DOUBLE, DATE, DATETIME, TIME, JSON, BINARY): no VARCHAR, no INT.
type Cell ¶
type Cell[V any] struct{ P *V }
Cell is a scan destination for a field of type V, for generated scanners: the common types convert without reflection, any other through the ORM's own conversion, NULL to the zero value.
type Change ¶
type Change[T any] struct { Kind ChangeKind Row *T Count int64 Keys []any // BulkUpdated Rows []T // BulkDeleted }
Change is a write OnChange hears: the row for Created, Updated and Deleted; for the bulk kinds, how many rows, and which: the keys of the rows an Update matched, the rows a Delete removed, as found just before the write.
type ChangeKind ¶
type ChangeKind int
ChangeKind is what a write did.
const ( Created ChangeKind = iota + 1 // a row, by Create or BulkCreate Updated // a row, by Save Deleted // a row, by Remove BulkUpdated // rows, by a QuerySet's Update BulkDeleted // rows, by a QuerySet's Delete )
type Char ¶
type Char struct {
Max, Min int
Unique, Index, Null bool
Column string
Comment, Label, Help string
Default any
Choices []string
Pattern string
Trim, Lower bool
Collation string
}
Char is a VARCHAR of Max characters (a write holding more is refused), unique or indexed. Min is the fewest characters a write may hold, Choices the values it may take, Pattern a regular expression it matches; Trim and Lower normalize it as it is written; Collation is the column's (utf8mb4_bin, "C", NOCASE).
func (Char) Apply ¶
func (x Char) Apply(o *FieldOptions)
type Codec ¶
Codec adapts a field's value under a names set: its Go value G is written as DB (To) and read back as G (From), so a field keeps one Go type while its database form differs per schema — a status string kept as an integer code on a legacy table, a time kept as text. Unlike a SchemaValuer the field's Go type is untouched: the conversion rides the field, set under a names set, not the type.
orm.Codec[string, int64]{
To: func(s string) (int64, error) { return codes[s], nil },
From: func(c int64) (string, error) { return names[c], nil },
}
A field codec wins over the field type's own SchemaValuer/SchemaScanner and DBValuer: the codec is the field-level instruction, applied in place of the type's.
type Col ¶
type Col[T, R any] struct { // contains filtered or unexported fields }
Col is a column of a Values or Aggregate result R: Into(R.Field, source).
func Into ¶
Into reads src — a field reference of T or a term — into the field dst of the result R. Both are of type V, so a count goes into an int64.
type Stats struct { Author string; Posts int64 }
stats := Post.Objects.Values[Stats](ctx, orm.Into(Stats.Author, Post.Author.Name), orm.Into(Stats.Posts, fn.Count(Post.ID)))?
type Column ¶
type Column string
Column names the column.
func (Column) Apply ¶
func (x Column) Apply(o *FieldOptions)
type ColumnOf ¶ added in v2.16.0
ColumnOf is a typed field or expression of V values, which EqCol compares with a field.
type ColumnTyper ¶
ColumnTyper is the column's database type on dialect d, as migrations make it: "" leaves the type the ORM would choose.
type CompareTerm ¶
CompareTerm is a Term of a type ordering itself (time.Time).
func CompareTermOf ¶
func CompareTermOf[T any, V interface{ Compare(V) int }](e any) CompareTerm[T, V]
func (CompareTerm[T, V]) As ¶
func (t CompareTerm[T, V]) As(name string) CompareTerm[T, V]
func (CompareTerm[T, V]) Ge ¶
func (t CompareTerm[T, V]) Ge(v V) vuka.Pred[T]
func (CompareTerm[T, V]) Gt ¶
func (t CompareTerm[T, V]) Gt(v V) vuka.Pred[T]
func (CompareTerm[T, V]) Le ¶
func (t CompareTerm[T, V]) Le(v V) vuka.Pred[T]
func (CompareTerm[T, V]) Lt ¶
func (t CompareTerm[T, V]) Lt(v V) vuka.Pred[T]
type Cond ¶
type Cond interface {
// contains filtered or unexported methods
}
Cond is a condition a QuerySet filters by: a Q, or Or / Not / And of conditions.
func Match ¶
Match holds when the document matches the query, Django's SearchVector(…) = SearchQuery(…): on Postgres the tsvector @@ the tsquery, on MySQL MATCH … AGAINST in boolean mode, on SQLite the FTS5 table of a model declaring the document (a LIKE per word otherwise).
Posts.Filter(orm.Match(orm.SearchVector("title", "body"), orm.SearchQuery(`go -java "web server"`)))
type Conn ¶
type Conn struct {
// contains filtered or unexported fields
}
Conn is a handle on one database of a Databases: embed it in a type of your own to inject that database by type (a framework's DI), and name it with @orm.Database("analytics") in Vuka or ConnFor in Go.
@orm.Database("analytics")
type Analytics struct{ orm.Conn }
rows := orm.Raw[Sales](a.With(ctx), "SELECT day, SUM(total) AS total FROM sales GROUP BY day")?
A Conn is a context.Context too (background, with its database): pass it where a context goes, or With(ctx) for a request's.
type DB ¶
type DB struct {
// contains filtered or unexported fields
}
DB is a database the ORM queries: a *sql.DB and its dialect, and, for one Declare opened, the supervisor keeping its pool (see Pool).
func Connect ¶
Connect opens dsn on dialect ("postgres", "mysql", "sqlite") through the driver its package registered, as the ORM reads it: MySQL as MySQLDSN sets it, in-memory SQLite on one connection (each would be a database of its own), others with Pool's default caps (DefaultMaxOpen, DefaultMaxIdle, DefaultMaxLifetime; the *sql.DB's setters change them). It doesn't ping.
func ConnectURL ¶
ConnectURL opens a database by URL: postgres://… (or postgresql://), mysql://user:pass@tcp(host:3306)/db?… (the driver's DSN after mysql://), sqlite:path, sqlite://path or sqlite::memory:. Any pool_* (and breaker_*, startup_wait) parameters are read as the pool's, as a declared database reads them, and never reach the driver's DSN.
type DBScanner ¶
DBScanner reads the column's value, as the driver gives it (nil for NULL unless the field is a pointer or an Option, which are nil and None then).
type DBSchema ¶
type DBSchema struct {
DB string // the database added under that name; "" the default
Names string // the names set; "" the default naming
Unmanaged bool // the tables are the database's own: never migrated
}
DBSchema is a database the models are queried on and the names they have there: one set of Go models, relations declared on them, over schemas that name their tables and columns apart.
var Legacy = orm.DBSchema{DB: "legacy", Names: "legacy", Unmanaged: true}
type User struct {
ID int64
Phone string `legacy:"tel_no"` // the column there
Bio string `legacy:"-"` // no such column there
Code string `gorm:"-" legacy:"code"` // there only
City string `legacy:"profile__city"` // read through a relation there
Profile *Profile `gorm:"foreignKey:UserID"`
Groups []Group `gorm:"many2many:user_groups" legacy:"many2many:auth_user_groups;joinReferences:group_id"`
}
func (User) LegacyTableName() string { return "auth_user" }
users, err := orm.Of[User](Legacy).Filter(orm.Q{"groups__name": "staff"}).All(ctx)
Queries name Go fields, default names and relation paths whatever the schema; the ORM writes them in the schema's names. A field read through a relation is read-only there: Create and Save skip it, and Update refuses it.
func (DBSchema) Verify ¶
Verify checks that the models (values or pointers of their types) map onto the schema — no tag naming no field, relation to a model by no field of it, column read through no relation, or two relations claiming one inverse name — and, when ctx has its database, once it answers (waiting for it as Migrate does), that the database can make their columns, indexes and generated columns (a vector on MySQL can't be) and has their extensions. Run it at start up, after Migrate, which may install what it checks for.
if err := Legacy.Verify(ctx, User{}, Profile{}, Group{}); err != nil {
log.Fatal(err)
}
type DBStats ¶
type DBStats struct {
Name string `json:"name"`
Dialect string `json:"dialect"`
Default bool `json:"default"`
Supervised bool `json:"supervised"` // declared (Declare), not added
State State `json:"state"`
Breaker string `json:"breaker"` // closed, open, half-open
Failures int `json:"failures"`
LastError string `json:"last_error,omitempty"`
Pool sql.DBStats `json:"pool"`
Replicas []ReplicaStats `json:"replicas,omitempty"`
}
DBStats is a database's pool, as Stats reports it.
type DBType ¶
type DBType string
DBType is the column's database type, written as is (jsonb, CHAR(2)).
func (DBType) Apply ¶
func (x DBType) Apply(o *FieldOptions)
type DBValuer ¶
DBValuer gives the value written to the column for the dialect d (d.Name() is "postgres", "mysql" or "sqlite"): on Create, Save and Update, and for the conditions comparing the field (Eq, In, Gt, …).
type DatabaseOption ¶
type DatabaseOption interface {
// contains filtered or unexported methods
}
DatabaseOption tunes a database: one added (AsDefault) or declared (AsDefault, ReadOnly, Replicas, Pool, Credentials, Session, Timeout, SlowQuery).
func AsDefault ¶
func AsDefault() DatabaseOption
AsDefault makes the database the default: the one models without On query. Without one, the only database is the default.
func Credentials ¶
func Credentials(fn func(ctx context.Context) (user, password string, err error)) DatabaseOption
Credentials supplies the user and password of every new connection (a rotating secret, a cloud IAM token), asked for each one the pool opens; they replace the URL's.
func ReadOnly ¶
func ReadOnly() DatabaseOption
ReadOnly refuses writes to the database: a reporting copy. The ORM refuses its own writes (Create, Save, Update, Delete, Exec), and a declared database's connections are read-only on the server too, so raw SQL (Raw, RawRow) can't write either: MySQL's sessions run SET SESSION TRANSACTION READ ONLY, Postgres's set default_transaction_read_only, SQLite's set PRAGMA query_only. A statement can still undo those for its own connection; only the database's grants (a user allowed SELECT alone) are a boundary an attacker running SQL can't cross. A database added with Add gets the ORM's refusal alone.
func Replicas ¶
func Replicas(urls ...string) DatabaseOption
Replicas gives the database read replicas, by URL: reads outside a transaction (and a Scope that wrote) go to the healthy one least in use, the primary when none is; a replica failing its health ping is left out until it answers again.
type DatabaseSpec ¶
type DatabaseSpec struct {
// contains filtered or unexported fields
}
DatabaseSpec is a database Declare declared: opened, supervised, by the Databases' Start.
func Declare ¶
func Declare(name, url string, opts ...DatabaseOption) *DatabaseSpec
Declare declares the database name at url (as ConnectURL reads it; pool settings may ride as URL parameters, see Pool), for OpenDatabases or NewDatabases. Its pool is supervised: see Pool.
dbs, err := orm.OpenDatabases(ctx,
orm.Declare("main", os.Getenv("DATABASE_URL"), orm.AsDefault(),
orm.Replicas(os.Getenv("REPLICA_URL")), orm.Pool{MaxOpen: 20, Acquire: 2 * time.Second}),
orm.Declare("analytics", "postgres://…/analytics?pool_max=5", orm.ReadOnly()))
type Databases ¶
type Databases struct {
// contains filtered or unexported fields
}
Databases is the named databases models query: the default, and others a model names with On (or Meta.DB, or a DBSchema). A program has one, Default, which AddDatabase fills; a process serving several apps (tests, a gateway) gives each its own and puts it on the app's contexts with WithDatabases, so one manager queries the database of the app serving the request.
db, err := orm.Connect("postgres", os.Getenv("DATABASE_URL"))
orm.AddDatabase("main", db, orm.AsDefault())
func DatabasesOf ¶
DatabasesOf is ctx's Databases: WithDatabases's, else Default.
func NewDatabases ¶
func NewDatabases(opts ...OpenOption) *Databases
NewDatabases is a set of databases: empty, or of the databases Declare declares (opened by Start) and the routers and settings the options give.
func OpenDatabases ¶
func OpenDatabases(ctx context.Context, opts ...OpenOption) (*Databases, error)
OpenDatabases is the databases opts declare, opened (NewDatabases, then Start). With none declared it reads DATABASE_URL (the default, "default") and DATABASE_URL_<NAME> (database name, lowercased), as the orm command does.
func (*Databases) Add ¶
func (s *Databases) Add(name string, db *DB, opts ...DatabaseOption)
Add adds db as name, replacing a database of that name.
func (*Databases) Apply ¶
func (s *Databases) Apply(opts ...OpenOption) *Databases
Apply applies opts to s (before Start, for the databases it declares).
func (*Databases) Check ¶
Check is what keeps s from serving the program's models: a Meta, For option, Route or connection handle naming a database s doesn't declare, and relations across databases that aren't CrossDB or a router refuses. Start runs it.
func (*Databases) Close ¶
Close closes the databases Start opened, gracefully: new statements fail Unavailable, those running finish until ctx's deadline, then the pools close. Databases added with Add are the caller's to close.
func (*Databases) Lookup ¶
Lookup is the database name: "" the default (the one AsDefault marked, else the only one).
func (*Databases) Route ¶
Route routes table: its models read and write r.DB, and their writes are repeated on r.Mirror (see Mirror).
orm.Default.Route("categories", orm.Route{DB: "legacy", Mirror: "main"})
func (*Databases) Start ¶
Start opens the databases declared and not yet open, supervised, waits up to each one's StartupWait for it to answer (one that doesn't is opened Down, and reconnects in the background), then runs the OnOpen hooks. It runs Check first: a model naming a database no one declared fails it. With nothing declared or added it reads the environment (FromEnv). A framework calls it on start (it is a Starter).
type DateExpr ¶ added in v2.2.0
type DateExpr struct {
OrderedExpr[string]
// contains filtered or unexported fields
}
DateExpr is a date or timestamp, with portable calendar arithmetic.
func TodayIn ¶ added in v2.2.0
TodayIn computes today's local wall date in Go. It binds that date as a value, so the database connection's timezone does not change it.
type DateField ¶
type DateField struct {
AutoNow, AutoNowAdd, DefaultNow bool
Unique, Index, Null bool
Column string
Comment, Label, Help string
Default any
}
DateField is a DATE column of a time.Time field: the day, without the time (orm.Date is the lookup transform). AutoNow sets it to today on every save, AutoNowAdd on create, DefaultNow on create when it is empty and in the table (DEFAULT CURRENT_DATE).
func (DateField) Apply ¶
func (x DateField) Apply(o *FieldOptions)
type Datetime ¶
type Datetime struct {
AutoNow, AutoNowAdd, DefaultNow bool
Precision int
UTC bool
Unique, Index, Null bool
Column string
Comment, Label, Help string
Default any
}
Datetime is a timestamp column of a time.Time field. AutoNow sets it to now on every save, AutoNowAdd on create, DefaultNow on create when it is empty and in the table (DEFAULT CURRENT_TIMESTAMP). Precision is its fractional digits, 1–6 (0: the database's default, microseconds; times are cut to it as they are written); UTC writes and reads it in UTC.
func (Datetime) Apply ¶
func (x Datetime) Apply(o *FieldOptions)
type DefaultValue ¶
type DefaultValue struct {
SQL string
// contains filtered or unexported fields
}
DefaultValue is a column default, from DefaultTo or DefaultSQL.
func DefaultSQL ¶
func DefaultSQL(sql string) DefaultValue
DefaultSQL is a column default written in SQL: @orm.DefaultSQL("CURRENT_TIMESTAMP").
func DefaultTo ¶
func DefaultTo(v any) DefaultValue
DefaultTo is the column default v, a Go value written as a SQL literal: @orm.DefaultTo(0), @orm.DefaultTo("draft"), @orm.DefaultTo(false). A row Create writes with the field at its zero value takes v too.
func (DefaultValue) Apply ¶
func (x DefaultValue) Apply(o *FieldOptions)
type Defaults ¶
Defaults is the fields GetOrCreate sets on a row it creates, beyond those of its lookup.
type Dialect ¶
type Dialect interface {
Name() string
// Placeholder is the n-th argument's marker, from 1.
Placeholder(n int) string
Quote(ident string) string
// ILike matches col against a LIKE pattern, ignoring case.
ILike(col, pattern string) string
// Returning is whether INSERT … RETURNING gives back the new key.
Returning() bool
// NoLimit is the LIMIT to put before an OFFSET with no limit; empty
// when OFFSET may stand alone.
NoLimit() string
// Violation reads a constraint error: unique or foreign key, and the
// column it names when it names one.
Violation(err error) (kind violation, column string)
}
Dialect is what differs between the databases the ORM speaks to.
func DialectFor ¶
DialectFor is the dialect of a driver name: "postgres" (or "postgresql", "pgx"), "mysql" or "sqlite"; a server version after a slash (mysql/9.3.0, as migrations take it) is left out.
type DialectName ¶ added in v2.16.0
type DialectName string
DialectName names a database's SQL: MySQL, Postgres, SQLite.
const ( MySQL DialectName = "mysql" Postgres DialectName = "postgres" SQLite DialectName = "sqlite" )
type Dialects ¶ added in v2.16.0
type Dialects map[DialectName]string
Dialects is a SQL fragment per database, for SQLFor.
type Dims ¶
type Dims int
Dims is a vector field's dimensions.
func (Dims) Apply ¶
func (x Dims) Apply(o *FieldOptions)
type Document ¶
type Document struct {
// contains filtered or unexported fields
}
Document is a SearchVector.
func SearchVector ¶
SearchVector is fields as a document to search, Django's SearchVector: Match, SearchRank and Headline read it, and an index or a generated column may hold it. On Postgres it is a tsvector; elsewhere the fields' text.
doc := orm.SearchVector("title").Weight("A").Add(orm.SearchVector("body").Weight("B")).Config("english")
type DriverHooks ¶
type DriverHooks struct {
Credentials func(dsn, user, password string) (string, error)
Classify func(err error) ErrorClass // OtherError for one it doesn't know
}
DriverHooks is what a driver package teaches the ORM about its driver: how to put a user and password into a DSN (for Credentials), and how to read its errors.
type DualOption ¶
type DualOption = ForOption
DualOption tunes a Dual route. The mirror options (MirrorUnder, MirrorTable) and Names are the ones that carry over; it is ForOption so the same helpers serve For, Of and Dual.
type Elements ¶
Elements configures an elements relation on a slice field: Column is the owner's column (a JSON array or comma-separated string) holding the related rows' keys, and Ref the related model's field they refer to (its primary key otherwise). The attribute form of orm:"elements:<column>[,<ref>]":
Tags []Tag @orm.Elements{Column: "tag_ids"}
func (Elements) Apply ¶
func (x Elements) Apply(o *FieldOptions)
type Error ¶
type Error struct {
Kind Kind
Model string // the model's name, when there is one
Message string
// Fields is the messages of the columns the error is about: a
// Conflict's column "already exists", an Invalid's "does not exist".
Fields map[string][]string
Err error // the cause: the driver's error, when there is one
}
Error is an error the ORM gives a meaning: its Kind, a message for people, the fields (by column) it is about, and the database's error under it.
type ErrorClass ¶
type ErrorClass int
ErrorClass is what an error says about the connection it came on.
const ( // OtherError: the database answered (a bad query, a constraint). OtherError ErrorClass = iota // ConnError: the connection failed — refused, reset, timed out, // dropped. The breaker counts these; reads are retried once. ConnError // RetryableError: the database aborted the transaction for a // deadlock or a serialization failure; Retry runs it again. RetryableError )
func Classify ¶
func Classify(err error) ErrorClass
Classify is what err says about its connection: the drivers' hooks' reading, else the ORM's own of database/sql's, the network's and the databases' codes.
type ExistsCond ¶
type ExistsCond struct {
// contains filtered or unexported fields
}
ExistsCond is Exists: a condition, and an Expr for Annotate.
func Exists ¶
func Exists(s subquerier) ExistsCond
Exists holds when the query has a row; with OuterRef, a row related to the outer one.
Users.Filter(orm.Exists(Posts.Filter(orm.Q{"author_id": orm.OuterRef("id"), "published": true})))
type ExplainOption ¶ added in v2.16.0
type ExplainOption interface {
// contains filtered or unexported methods
}
ExplainOption tunes Explain: Analyze, Format.
func Analyze ¶ added in v2.16.0
func Analyze() ExplainOption
Analyze runs the statement to report what it did, not only what the database expects: Postgres's EXPLAIN (ANALYZE, BUFFERS), MySQL's EXPLAIN ANALYZE. It runs inside a transaction that is always rolled back, so an Update or Delete changes nothing.
func Format ¶ added in v2.16.0
func Format(f PlanFormat) ExplainOption
Format asks for the plan as f: with PlanJSON, Plan.JSON holds it.
type Expr ¶
type Expr interface {
// contains filtered or unexported methods
}
Expr is a SQL expression a query computes: a field (F), a function call (a typed Func called, a Function's Of), a template (SQL), a Case or a Switch. Exprs go where values go — a Q's value, Where, Annotate, Update's Set, Aggregate — and nest.
func Cast ¶
Cast converts v (a field, an expression, or a value) to type t:
Users.Annotate("age_text", orm.Cast(orm.F("age"), orm.AsText)).
Filter(orm.Q{"age_text__startswith": "2"})
Orders.Filter(orm.Where(orm.Cast(orm.F("created_at"), orm.AsDate), "exact", day))
orm.Cast("12.5", orm.AsDecimal(10, 2))
func ExprOf ¶
ExprOf is v as an expression: a typed field (PostColumns.Title) or field reference as the field (F), a typed expression or Expr as itself, anything else a bound value. Expressions and conditions taking values (functions, SQL, Q's values, Case, Set) take typed fields and field references directly, the same way: orm.Lower(PostColumns.Title).
func F ¶
F is a field of the model, or an annotation, as an expression: Q{"age__gt": orm.F("min_age")} compares two columns, and Set{"views": orm.SQL("{0} + 1", orm.F("views"))} adds to one.
func FilteredRelation ¶
FilteredRelation is a relation (a path of them, posts__comments) whose related rows are only those where cond holds, Django's FilteredRelation: annotate it under a name, then name the related fields through it. cond names the related model's own fields. Reading through it joins with cond in the ON, so rows without a match keep a row of NULLs; filtering through a relation holding many rows asks EXISTS one matching.
Users.Annotate("active_apps", orm.FilteredRelation("applications", orm.Q{"status": "active"})).
Annotate("n", orm.Count("active_apps__id")).Values[[]any]("name", "n")
func SQL ¶
SQL is an expression written in SQL: {0}, {1}, … stand for args, each an Expr or a value sent as an argument ({{ and }} are literal braces). It is the escape hatch for what a Func can't say; never build the template from user input.
orm.SQL("{0} + {1}", orm.F("views"), 1)
func Subquery ¶
func Subquery(s subquerier) Expr
Subquery is a query as a value of another: in a filter, an annotation or an update. A QuerySet gives its primary keys, Values its columns; OuterRef reads the query it stands in.
latest := Posts.Filter(orm.Q{"author_id": orm.OuterRef("id")}).OrderBy("-created_at").Limit(1)
Users.Annotate("latest_title", orm.Subquery(latest.Values[string]("title")))
Users.Filter(orm.Q{"id__in": Posts.Filter(orm.Q{"published": true}).Values[int64]("author_id")})
type ExprOrder ¶
type ExprOrder struct {
// contains filtered or unexported fields
}
ExprOrder is an expression to order by and its direction.
type Extension ¶
Extension is a Postgres extension CreateExtension declared.
func CreateExtension ¶
CreateExtension declares a Postgres extension the database needs — "vector" for Vector columns and vector indexes, "pg_trgm" for trigram indexes — Django's CreateExtension: orm makemigrations writes it into the next migration (CreateTables makes it too, with the database's models). Declare it package-level, beside the models, where the autodetector finds it; its Verify fails while the database lacks it. orm.On names the database.
var Vectors = orm.CreateExtension("vector")
type FK ¶
type FK[T any] struct { // contains filtered or unexported fields }
FK is a foreign key to a T, as one field: the column <field>_id holding the related row's key, and that row once loaded (SelectRelated, PrefetchRelated, Get). It implements vuka.Related[T], so a Vuka field reference goes on into T's fields: Post.Author.Name.
type Post struct {
orm.Base
ID int64
Author orm.FK[User] @orm.Rel{OnDelete: orm.Cascade, Related: "posts"}
}
p := Post{Author: orm.FKOf(&ada)}
author := p.Author.Get(ctx)? // loaded once, then kept
posts := Post.Objects.Filter(Post.Author.Name.Eq("ada")).SelectRelated(Post.Author).All(ctx)?
In JSON it is the key. The column is NOT NULL unless Rel{Null: true} (or @orm.Null): an unset FK is then NULL.
func FKOf ¶
FKOf is a foreign key to row: its key is read from the row when the FK is written, so the row may be saved after the FK is made.
func (*FK[T]) Get ¶
Get is the related row: the one held, else read and then held. orm.NotFound when the FK is unset or the row is gone.
func (FK[T]) MarshalJSON ¶
func (FK[T]) Related ¶
func (f FK[T]) Related() *T
Related is the related row when it is loaded, else nil.
func (*FK[T]) Set ¶
func (f *FK[T]) Set(row *T)
Set makes the FK refer to row; SetID to the row of key key.
func (*FK[T]) UnmarshalJSON ¶
type Field ¶
type Field[V any] struct { // contains filtered or unexported fields }
Field is a model's field as a typed lookup. ormgen writes one per column in each model's typed fields (UserColumns.Age, PostColumns.Author().Email), so a misspelled field or a value of the wrong type fails to compile instead of failing the query; the methods build the same conditions as Q:
orm.For[User]().Filter(UserColumns.Age.Gte(18), UserColumns.Name.IContains("al")).
OrderBy(UserColumns.Name.Desc())
A pointer or an Option field is a Field of what it holds (*int and vuka.Option[int] are Field[int]); IsNull matches its NULLs.
func FieldAt ¶
FieldAt is the field at a lookup path (a column, or relations to one: "author__name") of the queried model.
func FieldIn ¶ added in v2.16.0
FieldIn is the field at a lookup path from src's table: the queried model's, or a table a query joins. Generated typed fields call it.
func (Field[V]) EqCol ¶ added in v2.16.0
EqCol holds where the field equals another column or a typed expression of the same type: ProductColumns.Code.EqCol(LegacyItemColumns.Code).
func (Field[V]) InQuery ¶
InQuery matches the values a subquery selects: a QuerySet (its keys) or a Values of one column.
type FieldAttr ¶
type FieldAttr interface{ Apply(o *FieldOptions) }
FieldAttr is a field attribute: any value that says something about a field's column, given to s.Field in the model's Schema method (or written after the field in Vuka). The ORM applies a field's attributes in order, each over what the ones before it set; the built-in ones (orm.Char, orm.Int, orm.Column, …) are FieldAttrs too, and one of another package is used the same way.
type Email struct{ Unique bool }
func (e Email) Apply(o *orm.FieldOptions) {
o.MaxLength, o.Lower, o.Trim = 254, true, true
o.Unique = o.Unique || e.Unique
}
func (u *User) Schema(s *orm.Schema) {
s.Field(&u.Email, Email{Unique: true})
}
An attribute with a method Validate(v any) error checks each value a write gives the field as well: a non-nil error refuses it (Invalid).
type FieldInfo ¶
type FieldInfo struct {
Name string // the Go field's name
Column string
Type reflect.Type
PK bool
Null bool // the column takes NULL
Unique bool
Index bool
// MaxLength and MinLength bound a text's characters (0: no bound);
// Min and Max a number; Choices is the values it may take (nil: any);
// Pattern the regular expression a text matches ("" for none).
MaxLength, MinLength int
Min, Max vuka.Option[int64]
Choices []any
Pattern string
// Default is the column's SQL default ("" for none); Initial its value
// on Create when left empty.
Default string
Initial any
Label, Help, Comment string
AutoNow, AutoNowAdd bool
}
FieldInfo is a model's column as forms, admin pages and tools read it: what its field attributes, tags and SetFieldOptions declare.
type FieldOptions ¶
type FieldOptions struct {
Column string // the column; the field's name in snake_case otherwise
Skip bool // no column (orm:"-")
PK bool
Unique bool
Index bool
UniqueIndex string // a named unique index: fields sharing it are unique together
MaxLength int // a VARCHAR's size, and the most characters a write may hold
Type string // a database type of the program's own
// Default is the SQL literal a row inserted without the column takes,
// in the table migrations make ('draft', 0, CURRENT_TIMESTAMP).
Default string
// Initial is the Go value Create gives the field when it is left at
// its zero value: Default as a value (DefaultTo and the attributes'
// Default set both).
Initial any
AutoNow bool // set to the time on every save
AutoNowAdd bool // set to the time on create
OnDelete string // a foreign key's: cascade, set_null, restrict
Related string // the name of a relation's inverse on the related model
FK string // a relation's column holding the related row's key
Null bool // the column takes NULL (an orm.FK that may be unset)
Through string // a many-to-many's table between
// Elements names an elements relation's column (a JSON array or
// comma-separated string holding the related rows' keys), optionally
// with the related field it refers to as "column,ref": the attribute
// form of orm:"elements:…". JoinForeignKey and JoinReferences are a
// many-to-many's columns for this row's key and the related row's.
Elements string
JoinForeignKey, JoinReferences string
Dims int // a vector's dimensions
// CrossDB marks a relation to a model on another database: its key
// column has no foreign key constraint, and queries never join it.
CrossDB bool
// Comment is the column's comment in the table (Postgres, MySQL);
// Label and Help describe the field to forms and tools (FieldInfo).
Comment, Label, Help string
// Collation is a text column's collation, as the database names it
// (utf8mb4_bin, "C", NOCASE).
Collation string
// The checks a write makes of the field's value (Create, Save, Update,
// BulkCreate): an Invalid error naming the column when one fails.
// Choices is the values it may take; MinLength the fewest characters
// of a text; Min and Max a number's bounds; Pattern a regular
// expression (Go's syntax) a text matches; Checks functions of the
// value, a non-nil error refusing it.
Choices []any
MinLength int
Min, Max vuka.Option[int64]
Pattern string
Checks []func(v any) error
// Trim and Lower normalize a text as it is written: its surrounding
// spaces removed, in lower case.
Trim, Lower bool
// Size is an integer column's width (Small, Medium, Big), over its Go
// type's; Unsigned makes it UNSIGNED on MySQL, and refuses negative
// values on every database.
Size IntSize
Unsigned bool
// Date makes a time.Time field a DATE column. Precision is a
// timestamp's fractional digits (1–6; 0 is the database's default,
// microseconds); UTC writes and reads its times in UTC.
Date bool
Precision int
UTC bool
// Manual is an integer primary key the program sets, not one the
// database counts; UUID a key the ORM sets to a random UUID on create
// when it is empty (a string field).
Manual, UUID bool
// Schemas overrides the field's column under named schemas (names
// sets), keyed by the set's name: what a layer above the ORM declares
// in place of a per-set struct tag (legacy:"column:…;type:…"). The
// override for a set is applied only when the model is read under it
// (orm.Names, orm.Of, a mirror under the set); the default schema is
// untouched. A SchemaField's Codec adapts the value's format there.
Schemas map[string]SchemaField
// contains filtered or unexported fields
}
FieldOptions is what a struct tag says about a field, as a value: the way a layer above the ORM (a language's field attributes, a schema file) declares a model's fields without tags. A zero member leaves the tag's setting; a set one wins over it.
FieldOptions is a FieldAttr itself: its set members applied over another's, as SetFieldOptions's are over a field's attributes.
func (FieldOptions) Apply ¶
func (o FieldOptions) Apply(dst *FieldOptions)
Apply sets o's set members over dst: a string, number or list that isn't empty, a bool that is true, a bound that is present. Checks add up.
type FieldOptionsFunc ¶
type FieldOptionsFunc func(owner reflect.Type, field reflect.StructField) (opts FieldOptions, ok bool)
FieldOptionsFunc supplies a model's field options: ok false for a field it says nothing about. owner is the struct declaring the field (an embedded one's own type for its fields).
type Fn ¶
Fn is a typed function: called with its arguments — each an Expr (F for a field) or a value, sent as a bound argument — it is an expression of type X. Func, OrderedFunc and TextFunc make one.
type ForOption ¶
type ForOption func(*forConfig)
ForOption tunes a model.
func Mirror ¶
Mirror has every write of the model repeated on the database added as name, after it succeeds on the model's own database: a table moving from one database to another keeps both current while reads stay on the first. Reads never use the mirror.
The mirror is written after the write's transaction commits (at once outside one), with the keys the primary gave new rows. A mirror that fails doesn't fail the write: the primary is the truth, and the failure goes to OnMirrorError (and the log) so the table can be re-synced.
A Route routes a table without a code change, for models naming no databases of their own (a program reads its routes from its configuration):
orm.Default.Route("categories", orm.Route{
DB: "legacy", // read, and written first
Mirror: "main", // written after
})
Cutting the table over is swapping the two, then dropping the mirror.
func MirrorTable ¶
MirrorTable names the mirror's table, over the model's: the legacy table a row is mirrored into.
func MirrorUnder ¶
MirrorUnder binds the mirror through a names set: its writes take the columns, types and value codecs the model's fields declare for that set (a legacy schema's). Reads still never use the mirror. It pairs with Mirror (or a Route's) and MirrorTable.
func Names ¶
Names reads the model under a names set (see DBSchema): each field's tag of that key over its default naming, and <Names>TableName (names "legacy": LegacyTableName) over TableName.
type FullText ¶
type FullText struct{ Config string }
FullText is the field's full-text index (Config: Postgres's text search configuration).
func (FullText) Apply ¶
func (FullText) Apply(*FieldOptions)
type FuncDef ¶
type FuncDef struct {
// contains filtered or unexported fields
}
FuncDef is a database function's definition: its name, its SQL on each dialect, how many arguments it takes, whether it aggregates. Function makes an untyped one, called with Of; Func, OrderedFunc and TextFunc make typed ones, called directly.
var Unaccent = orm.Function("unaccent") // unaccent(…)
var Year = orm.Function("year",
orm.Template("postgres", "CAST(EXTRACT(YEAR FROM {0}) AS INTEGER)"),
orm.Template("sqlite", "CAST(strftime('%Y', {0}) AS INTEGER)")) // YEAR(…) on MySQL
Users.Filter(orm.Where(Unaccent.Of(orm.F("name")), "icontains", "jose"))
A FuncDef registered with Transform is also a step of Q keys: Q{"name__unaccent__icontains": "jose"}.
func Function ¶
func Function(name string, opts ...FuncOption) *FuncDef
Function defines an untyped database function, called with Of. Without a Template for the dialect a query runs on it is called as name(args…).
type FuncOf ¶
FuncOf is a function of R values, made by Func.
func Aggregate ¶
func Aggregate[R any](name string, opts ...FuncOption) FuncOf[R]
Aggregate is Func of an aggregate, IsAggregate's: an annotation of it groups, a condition on it is HAVING's, and AggOf takes it to Aggregate. OrderedFunc and TextFunc take IsAggregate for ordered and text aggregates.
var StringAgg = orm.TextFunc("string_agg", orm.IsAggregate(),
orm.Template("postgres", "string_agg({0}, {1})"),
orm.Template("sqlite", "group_concat({0}, {1})"))
Users.Annotate("names", StringAgg(orm.F("name"), ", ")).Values[[]any]("team_id", "names")
func Func ¶
func Func[R any](name string, opts ...FuncOption) FuncOf[R]
Func defines a database function whose value is an R, called directly:
var Levenshtein = orm.Func[int]("levenshtein",
orm.Template("postgres", "levenshtein({0}, {1})"), // fuzzystrmatch
orm.Template("sqlite", "editdist({0}, {1})")) // a Go function: see orm/sqlite's Func
Users.Filter(Levenshtein(orm.F("name"), "jon").Eq(1))
OrderedFunc and TextFunc make functions whose values compare by order and by pattern too. Without a Template it is called as name(args…); with some, on their dialects only.
type FuncOption ¶
type FuncOption func(*FuncDef)
FuncOption shapes a function's definition.
func Arity ¶
func Arity(n int) FuncOption
Arity is how many arguments the function takes: a call with another number fails its query.
func IsAggregate ¶
func IsAggregate() FuncOption
IsAggregate makes the function an aggregate, as Count and Sum are: an annotation of it groups a Values listing it by the other names, and a condition on it is HAVING's.
func Template ¶
func Template(dialect, template string) FuncOption
Template is the function's SQL on a dialect ("postgres", "mysql", "sqlite"; "" for all of them), {0}, {1}, … for its arguments and {*} for all of them. A typed function with Templates is written only where one applies: on another dialect its query fails, naming the function and the dialect.
type Fusion ¶
type Fusion struct {
// contains filtered or unexported fields
}
Fusion is a Fuse.
func Fuse ¶
Fuse is reciprocal-rank fusion of orderings, for hybrid search: each name (a field or an annotation, a leading - for descending) ranks the rows, and a row scores the sum of w/(k + its rank), k 60 and each w 1 unless K and Weights say — order by it descending. Hybrid fuses a text and a vector search with it.
Docs.Annotate("rank", orm.SearchRank(doc, q)).
Annotate("distance", orm.CosineDistance("embedding", v)).
Annotate("score", orm.Fuse("-rank", "distance").Weights(1, 0.5)).OrderBy("-score")
type HNSW ¶
HNSW and IVFFlat are pgvector indexes of a vector field, serving the distance of their Metric (L2 when not given).
func (HNSW) Apply ¶
func (HNSW) Apply(*FieldOptions)
Apply makes the search attributes field attributes: the indexes and the generated document are read from the attributes themselves.
type HeadlineOption ¶
type HeadlineOption func(*headlineOpts)
HeadlineOption shapes a Headline: Marks, MaxWords, HighlightAll.
func HighlightAll ¶
func HighlightAll() HeadlineOption
HighlightAll marks the words in the whole text rather than cutting a headline from it.
func Marks ¶
func Marks(start, stop string) HeadlineOption
Marks are the text put before and after each word found: <b> and </b> otherwise. They are bound arguments, written as given: escape the field's text yourself where it is HTML.
func MaxWords ¶
func MaxWords(n int) HeadlineOption
MaxWords is the most words a headline has: 35 otherwise (at most 64 on SQLite).
type IVFFlat ¶
The search attributes of a Vuka model's fields:
type Doc struct {
orm.Base
ID int64
Title string @orm.Trigram
Body string @orm.FullText{Config: "english"}
Search orm.TSVector @orm.SearchOf{Fields: []string{"title:A", "body:B"}, Config: "english"}
Embedding orm.Vector @orm.Dims(3) @orm.HNSW{Metric: orm.Cosine, M: 16}
}
They are what Indexes() and Generated() say in Go: indexes made by migrations (on Postgres; MySQL a FullText; SQLite none, its searches unindexed), and a generated tsvector column of the fields named.
func (IVFFlat) Apply ¶
func (IVFFlat) Apply(*FieldOptions)
type Index ¶
type Index struct {
// contains filtered or unexported fields
}
Index is an index a model declares in its Indexes() method, Django's Meta.indexes, made and dropped by migrations. It is over fields, named as queries name them (their columns under the schema's names), or expressions:
func (Post) Indexes() []orm.Index {
return []orm.Index{
orm.GinIndex(orm.SearchVector("title", "body").Config("english")).Name("posts_search"),
orm.GinIndex("title").Trigram(),
orm.HnswIndex("embedding").Ops(orm.Cosine).M(16).EfConstruction(64),
orm.FullTextIndex("title", "body"),
}
}
MySQL makes a FullTextIndex, and no trigram or vector index (its trigram lookups are LIKE, and it searches no vectors); a model declaring another kind can't map onto it. SQLite makes none of them: a model declaring a document (a FullTextIndex, a GinIndex of a SearchVector, a generated TSVector) has its FTS5 table instead, <table>_fts, and its vector and trigram searches are unindexed.
func FullTextIndex ¶
FullTextIndex is the fields' full-text index: MySQL's FULLTEXT, which MATCH needs, and on Postgres a GIN index of their tsvector (by Config, simple when not given), which the __search lookup of a field indexed alone uses.
func GinIndex ¶
GinIndex is a Postgres GIN index of fields or expressions: a SearchVector, or text fields with Trigram.
func IvfflatIndex ¶
IvfflatIndex is pgvector's IVFFlat index of a vector field.
func (Index) Apply ¶
func (Index) Apply(o *FieldOptions)
func (Index) EfConstruction ¶
func (Index) M ¶
M is an HNSW index's connections per layer; EfConstruction its candidate list while building; Lists an IVFFlat index's lists.
type Int ¶
type Int struct {
Min, Max any
Size IntSize
Unsigned bool
Choices []int64
Unique, Index, Null bool
Column string
Comment, Label, Help string
Default any
}
Int is an integer column: Min and Max bound its values, an integer each, nil for no bound (@orm.Int{Min: 0, Max: 150}: 0 is a bound like any other); Size is its width over its Go type's (Small, Medium, Big); Unsigned makes it UNSIGNED on MySQL and refuses negative values everywhere; Choices is the values it may take.
func (Int) Apply ¶
func (x Int) Apply(o *FieldOptions)
type JSON ¶
type JSON[T any] struct{ V T }
JSON is a column holding V as JSON, Django's JSONField: jsonb on Postgres, JSON on MySQL, TEXT on SQLite. Read and write V; the field marshals as V alone, so a response carries the value, not a wrapper. A nil V (slice, map or pointer) is NULL, as a nil []byte is.
type Letter struct {
ID int64
PlacementIDs orm.JSON[[]int64]
}
letter.PlacementIDs.V = append(letter.PlacementIDs.V, 7)
func (JSON[T]) MarshalJSON ¶
func (*JSON[T]) UnmarshalJSON ¶
type JoinKind ¶ added in v2.16.0
type JoinKind int
JoinKind is how Join combines a table with the query's rows: Inner keeps the rows with a match, Left keeps every row, a row of NULLs for the joined table's columns where nothing matches.
type JoinOn ¶ added in v2.16.0
type JoinOn struct {
// contains filtered or unexported fields
}
JoinOn is a table to join and the conditions its rows match on.
type Joinable ¶ added in v2.16.0
type Joinable interface {
// contains filtered or unexported methods
}
Joinable is what Join takes: a model's typed fields' On(conds…) (ProductColumns.On(…)), or a relation of the queried model (CategoryColumns.Links(), its ON from the foreign key) with or without an On of extra conditions.
type Kind ¶
type Kind uint8
Kind is what an Error means to the code calling the ORM, whatever the database said. A Kind is an error itself, so errors.Is matches an Error against its kind:
if errors.Is(err, orm.ErrNotFound) { … }
A web framework maps kinds onto HTTP statuses, for example:
Kind HTTP NotFound 404 MultipleFound 409 Conflict 409 (Fields: the column → "already exists") Invalid 422 (Fields: the column → "does not exist", or a check's message) Unavailable 503 (no Error) 500
const ( // NotFound: no row matched a query that needs one (Get, First, // Refresh, Remove of a row gone). NotFound Kind // MultipleFound: Get matched more than one row. MultipleFound // Conflict: a write broke a unique constraint. Conflict // Invalid: a write referred to a row that does not exist (a foreign // key violation), or gave a field a value its checks refuse (Max, // Choices, Pattern, a Validate method; Fields: the columns' messages). Invalid // for it). Unavailable )
type LongText ¶
type LongText struct{}
LongText is an unbounded text column (what a string is by default).
func (LongText) Apply ¶
func (LongText) Apply(o *FieldOptions)
type LookupFunc ¶
LookupFunc writes a custom lookup's condition on dialect d: lhs is the left side's SQL (a column, through any transforms of its key), rhs writes the value — a bound argument's marker, or an Expr's SQL — each call binding it once more, so a lookup naming its value twice calls rhs twice and one ignoring its value binds nothing. ok is false where the lookup has no SQL on d: the query fails, naming the lookup and the dialect.
type LookupOption ¶
type LookupOption func(*customLookup)
LookupOption shapes a custom lookup.
func LookupValue ¶
func LookupValue(fn func(v any) any) LookupOption
LookupValue maps a lookup's value before it is bound (an Expr is never passed through it): LikePattern's, or a value of your own.
type M2M ¶
type M2M[T any] struct { // contains filtered or unexported fields }
M2M is a many-to-many relation to T, as one field: a table between (<table>_<field>, or Rel's Through) holding both keys. Its rows are read with All (held once PrefetchRelated loaded them) or queried with Query; Add, Remove, Set and Clear change the links of a saved row. A field reference goes on into T's fields: Post.Tags.Name.
p.Tags.Add(ctx, &golang, &db)?
tags := p.Tags.All(ctx)?
posts := Post.Objects.Filter(Post.Tags.Name.Eq("go")).PrefetchRelated(Post.Tags).All(ctx)?
func (*M2M[T]) Add ¶
Add links the row to related rows (rows or keys), Remove unlinks them, Set makes them its only links, Clear removes every link.
func (M2M[T]) MarshalJSON ¶
type Manager ¶
Manager is a model's entry point, Django's Model.objects: a QuerySet of every row (its methods are the QuerySet's) and the writes of single rows. It queries the database its model is on (On, Meta.DB; the default otherwise) in the context's Databases.
var Users = orm.For[User]()
orm.AddDatabase("main", db, orm.AsDefault())
u, err := Users.Get(ctx, orm.Q{"email": e})
func For ¶
For is the manager of the model T. Declare it once, package-level; a model the ORM can't map fails every query, and Check (run it at start up) reports it. Its options win over the model's Meta. The first For of a model without Names is its own manager, the one Objects and its rows' writes use.
func Objects ¶
Objects is the model T's manager: Objects[T]() its own (its package-level orm.For[T]() without Names, else one made from its Meta on first use), Objects[T](s) the one on schema s (orm.Of[T](s)). It registers T (see Register).
func Of ¶
Of is the manager of the model T on schema s, made once per model and schema. It finds its database as For's managers do: in the context's Databases.
func (*Manager[T]) BulkCreate ¶
BulkCreate inserts rows in as few statements as it can, setting their primary keys, in batches of up to 500 (fewer for a wide model).
func (*Manager[T]) ColumnValues ¶
ColumnValues is row's columns and their values as the database is sent them (a nil pointer as nil): a snapshot of the row for code that speaks columns, such as a change feed to another system.
func (*Manager) Columns ¶
func (a *Manager) Columns() []string
Columns is the model's columns, in field order.
func (Manager) Delete ¶ added in v2.16.0
Delete removes the matching rows and says how many. With no condition it fails with ErrUnfiltered unless the query is Unfiltered.
func (Manager) DeleteSQL ¶ added in v2.16.0
DeleteSQL is the statement Delete runs, refused as Delete refuses it.
func (*Manager) Err ¶
func (a *Manager) Err() error
Err is what keeps the ORM from mapping the model: nil when it can.
func (Manager) Explain ¶ added in v2.16.0
func (qs Manager) Explain(ctx context.Context, opts ...ExplainOption) (Plan, error)
Explain is the database's plan for the query, as SQL builds it.
func (*Manager) Fields ¶
func (a *Manager) Fields() []FieldInfo
Fields is the model's columns, in field order, as forms and tools read them.
func (*Manager[T]) GetOrCreate ¶
func (m *Manager[T]) GetOrCreate(ctx context.Context, lookup Q, defaults Defaults) (row T, created bool, err error)
GetOrCreate is the row matching lookup, or a new one made from lookup's exact fields and defaults; created says which. A row another request inserted first is read rather than duplicated.
func (*Manager) Info ¶
func (a *Manager) Info() ModelInfo
Info is the model as routers see it: its Meta, with For's On and Mirror over it.
func (*Manager[T]) Manager ¶
Manager is m itself, as Query's Manager was: Post.Objects.Manager() in code written when Post.Objects was a Query.
func (*Manager[T]) OnChange ¶
OnChange calls fn after each write of T's rows, once its transaction commits (at once outside one; never for a rolled-back one): the place to tell live pages, with view.Broadcast. It returns what stops it.
Users.OnChange(func(ctx context.Context, c orm.Change[User]) {
view.Broadcast(ctx, "users", "changed")
})
func (*Manager) PKColumn ¶
func (a *Manager) PKColumn() string
PKColumn is the column of the model's primary key, "" for none.
func (*Manager[T]) Raw ¶
func (m *Manager[T]) Raw(sql string, args ...any) RawQuerySet[T]
Raw is the rows sql reads, as the model's: each column fills the field of that column under the manager's names set (else of that name, or the computed field), and other columns are dropped. ? marks each argument, ?? is a literal ?. The SQL is the schema's own: written for the schema the manager is on.
users, err := orm.Of[User](Legacy).Raw("SELECT * FROM auth_user WHERE tel_no LIKE ?", "255%").All(ctx)
func (*Manager[T]) Remove ¶
Remove deletes row's row, found by primary key. A row of a Model is new again after.
func (Manager) SQL ¶ added in v2.16.0
SQL builds this query and its bound arguments for the context's database. It does not execute the query.
func (*Manager[T]) Save ¶
Save writes every field of row to its row, found by primary key; auto_now fields are set to now.
func (*Manager[T]) UpdateOrCreate ¶
func (m *Manager[T]) UpdateOrCreate(ctx context.Context, lookup Q, defaults Defaults) (row T, created bool, err error)
UpdateOrCreate updates the row matching lookup with defaults, or creates one from lookup's exact fields and defaults (as GetOrCreate), in a transaction; created says which.
type Meta ¶
type Meta struct {
Table string // the table; the plural of the type's name in snake_case otherwise
DB string // the database added under that name, orm.On's; the default otherwise
Read string // the database its reads go to, over DB (a replica's own name, a reporting copy)
Write string // the database its writes go to, over DB
Mirror string // a database its writes are repeated on (see orm.Mirror)
Unmanaged bool // the database's own table: never created or migrated, orm.Unmanaged's
Indexes []Index // its indexes, as Indexes() returns them
Ordering []string // the order of a query that sets none, as OrderBy takes it
}
Meta is what a model declares about itself, Django's class Meta: a model attribute, given to s.Model in the model's Schema method.
func (u *User) Schema(s *orm.Schema) {
s.Model(orm.Meta{Table: "accounts", Ordering: []string{"-created_at"}})
}
A Meta method, func (User) Meta() orm.Meta, still declares it and wins over the Schema's; it is deprecated, for the Schema method.
It wins over the model's TableName and Indexes methods; For's options (orm.Table, orm.On, orm.Unmanaged) win over it, and under a names set the set's <Names>TableName (LegacyTableName) does.
func (Meta) ApplyModel ¶
func (Meta) ApplyModel(*ModelConfig)
ApplyModel makes Meta a model attribute: s.Model(orm.Meta{…}) is the model's Meta, read whole (a Meta method wins over it), so it folds nothing into a ModelConfig.
type Metric ¶
type Metric int
Metric is how vectors are compared: their Euclidean distance (L2), the cosine distance, or the inner product.
type MigrateOption ¶
type MigrateOption func(*migrateConfig)
MigrateOption tunes Migrate.
func MigrateLogger ¶
func MigrateLogger(l *slog.Logger) MigrateOption
MigrateLogger has Migrate say what it applies on l; slog.Default() otherwise.
func MigrateOn ¶
func MigrateOn(name string) MigrateOption
MigrateOn applies the migrations of the database added as name ("" the default) only; repeat it for several. Every database with migrations otherwise.
type MirrorError ¶
type MirrorError struct {
Table string
Op string // create, update, delete
Mirror string // the mirror's database name ("" for one WithMirror set)
Err error
}
MirrorError is a mirrored write that failed: the primary has the change, the mirror doesn't.
func (MirrorError) Error ¶
func (e MirrorError) Error() string
type Model ¶
type Model[T any] struct { // contains filtered or unexported fields }
Model is a model's base, Django's models.Model: embedded by value in the model it is of, it gives each row the writes of its own and the model its manager.
type User struct {
orm.Model[User]
ID int64
Email string
Roles []Role `gorm:"many2many:user_roles"`
}
u := User{Email: e}
err := u.Save(ctx) // INSERT: u.ID set
u.Email = e2
err = u.Save(ctx) // UPDATE
err = u.Add(ctx, "roles", admin) // a user_roles row
users, err := orm.Objects[User]().Filter(orm.Q{"roles__name": "admin"}).All(ctx)
A row remembers whether it was read from (or written to) the database, Django's _state.adding, and the schema it was: rows read through a QuerySet, Raw, Get or Create come back loaded, related rows SelectRelated and PrefetchRelated load too. Its state is unexported, so GORM and JSON ignore it. Its methods find the row from the embedded field, so embed it exactly once, by value, in the type it names (directly or through an embedded struct); Register and boot fail on anything else.
func (*Model[T]) Add ¶
Add links the row to related rows through a many-to-many relation, Django's related manager add(): a row of the table between for each not linked yet. The relation is named by typed field (UserColumns.Roles), reference or name; related is rows of the relation's model (values or pointers) or their keys.
err := u.Add(ctx, "roles", admin, editor)
func (*Model[T]) DeclaredFieldAttrs ¶
DeclaredFieldAttrs makes the attributes of a model's Schema method what vuka.FieldAttrsOf reads: T's fields' registered attributes, then its Schema's; its model attributes are on the embedded Model field, as a Vuka model writes them on orm.Base.
func (*Model[T]) Delete ¶
Delete deletes the row by its primary key. The row is new again after: Save inserts it.
func (*Model[T]) Load ¶
Load loads relations into the row, as PrefetchRelated loads them into a query's rows: typed fields (UserColumns.Roles), references, names, paths (posts__comments) or orm.Prefetch.
err := u.Load(ctx, "roles", "profile")
func (*Model[T]) Refresh ¶
Refresh reads the row again by its primary key, Django's refresh_from_db: every field, and relations emptied.
func (*Model[T]) Remove ¶
Remove unlinks the row from related rows through a many-to-many relation, Django's remove(): their rows of the table between go.
func (*Model[T]) Save ¶
Save writes the row: an INSERT when it is new (its key set, and the row loaded, after), else an UPDATE of every field by its primary key.
func (*Model[T]) SaveFields ¶
SaveFields updates only the fields named, and the auto_now ones, of a loaded row: Django's save(update_fields=…). A field is a typed field (PostColumns.Title), a Go name or a column.
type ModelAnnotation ¶ added in v2.2.0
type ModelAnnotation[T any] interface { // contains filtered or unexported methods }
ModelAnnotation is a named term of T: what Query.Annotate adds.
type ModelAttr ¶
type ModelAttr interface{ ApplyModel(*ModelConfig) }
ModelAttr is a model attribute: a value given to s.Model in the model's Schema method (or written on the embedded orm.Base in Vuka) that configures the whole model's routing and mirror the way orm.Meta and For's options do. The ORM calls ApplyModel on every model attribute but orm.Meta (read whole as the model's Meta), and folds the result into the model.
func (p *Placement) Schema(s *orm.Schema) {
s.Model(orm.Meta{Table: "placements"}, mirror.Legacy{Table: "tbl_placements"})
s.Field(&p.ID, orm.PK{})
}
where an app's mirror.Legacy implements ModelAttr:
func (l Legacy) ApplyModel(c *orm.ModelConfig) {
c.Mirror = cmp.Or(c.Mirror, "legacy")
c.MirrorNames = cmp.Or(c.MirrorNames, "legacy")
c.MirrorTable = cmp.Or(c.MirrorTable, l.Table)
}
A ModelConfig.Names rebinds the PRIMARY: orm.For[T]() with no Names option, and the model's own read/write path, build the model under that names set, so the live columns use the Schemas[Names] overrides and codecs — a model whose primary is a legacy schema and whose mirror is the clean one (a migration's live source), the inverse of MirrorNames.
The ORM never names any specific attribute: it folds whatever implements ModelAttr. Precedence, highest first: a For option, an orm.Meta field, a ModelAttr; an empty value from a lower layer never clobbers a set one.
Table names the model's table under Names, as MirrorTable names the mirror's under MirrorNames: wherever the model is built under that names set (For[T](), Of, Names(set), relations into it) it wins over <Names>TableName, @orm.Meta's Table and TableName; with Names empty it is the default-naming table, where @orm.Meta's Table wins over it. For's orm.Table wins over both. A ModelAttr that names a mirror but leaves MirrorTable empty mirrors into the model's table under MirrorNames (the same-named table on the mirror's database when the sets share it).
type ModelConfig ¶
type ModelConfig struct {
DB string // the model's primary database (On / Meta.DB); the default otherwise
Names string // the names set the model's OWN (primary) manager binds under
Table string // the model's table under Names (see ModelAttr)
Read string // the database its reads go to, over DB (Meta.Read; a replica)
Write string // the database its writes go to, over DB (Meta.Write)
Mirror string // a database its writes are repeated on (Mirror / Meta.Mirror)
MirrorNames string // the names set the mirror binds under (MirrorUnder)
MirrorTable string // the mirror's table, over the model's (MirrorTable)
Unmanaged bool // the database's own table: never created or migrated (Unmanaged)
// Fields gives the model's fields options as the ORM maps the model,
// over their attributes: for what only the running program knows,
// such as the columns a legacy table it read at start lacks. It is
// asked once per field (owner is the struct declaring it, an embedded
// one for its fields) each time the model is mapped, under each names
// set, so it decides before the model's first query. A later
// attribute's Fields replaces an earlier one's; to keep it, call it.
Fields FieldOptionsFunc
}
ModelConfig is the model-level configuration a ModelAttr sets: the same routing and mirror an @orm.Meta and For's options set, in one value. A zero member leaves the model's setting; a set one is folded in. Later attributes' set members win over earlier ones, and an empty member never undoes one already set (cmp.Or-style), as field attributes merge.
type ModelInfo ¶
type ModelInfo struct {
Name string // the Go type's name
Table string
Type reflect.Type
Meta Meta
}
ModelInfo is a model as a Router sees it: its Go type, its table and the databases it declares (Meta's DB, Read, Write and Mirror, with For's On and Mirror over them).
type Null ¶
type Null struct{}
Null lets the column hold NULL, for a field whose Go type has no nil (an orm.FK that may be unset).
func (Null) Apply ¶
func (Null) Apply(o *FieldOptions)
type NumExpr ¶
type NumExpr[V Number] struct{ OrderedExpr[V] }
NumExpr is an OrderedExpr of numbers, which arithmetic takes further: f.Views.Add(1).Mul(2) is (views + 1) * 2.
type Number ¶
type Number interface {
~int | ~int8 | ~int16 | ~int32 | ~int64 |
~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~float32 | ~float64
}
Number is a type a NumberField holds: an integer or a float.
type NumberField ¶
NumberField is a number field, which arithmetic takes: an Update's new value computed from the row's own,
Posts.Filter(f.Slug.Eq(slug)).Update(ctx, orm.Set{"views": f.Views.Add(1)})
func NumberFieldAt ¶
func NumberFieldAt[V Number](path string) NumberField[V]
NumberFieldAt is the number field at a lookup path. Generated typed fields call it.
func NumberFieldIn ¶ added in v2.16.0
func NumberFieldIn[V Number](src *Source, path string) NumberField[V]
NumberFieldIn is the number field at a lookup path from src's table.
func (NumberField[V]) Add ¶
func (f NumberField[V]) Add(n V) NumExpr[V]
Add, Sub, Mul and Div are the field and n combined, as an expression: f.Views.Add(1) is views + 1. Div divides as the database does, an integer column by an integer in whole numbers on SQLite and Postgres.
func (NumberField[V]) Div ¶
func (f NumberField[V]) Div(n V) NumExpr[V]
func (NumberField[V]) Mul ¶
func (f NumberField[V]) Mul(n V) NumExpr[V]
func (NumberField[V]) Sub ¶
func (f NumberField[V]) Sub(n V) NumExpr[V]
type Observer ¶
Observer sees each statement a context's queries run: for logging, tracing, counting in tests, or catching repeated queries. It runs on the goroutine of the query, after the statement returns.
type OpenOption ¶
type OpenOption interface {
// contains filtered or unexported methods
}
OpenOption shapes a Databases: the databases Declare declares, Routers, ReadYourWrites, Logger, OnOpen.
func Dual ¶
func Dual[T any](primary, mirror string, opts ...DualOption) OpenOption
Dual routes T for a dual write without a code change on the model: its models read and write primary, and every write is repeated on mirror after the primary commits (see Mirror). MirrorUnder and MirrorTable bind the mirror through a names set and table of its own — a legacy schema, whose columns, types and value codecs the model declares for that set — so the clean model stays clean and the mirror's shape rides the route. The table comes from T's Meta. Reads never use the mirror.
orm.Default.Apply(orm.Dual[Placement]("main", "legacy",
orm.MirrorUnder("legacy"), orm.MirrorTable("tbl_placements")))
It is sugar for a Route; the raw Route (DB, Mirror, Names, MirrorNames, MirrorTable) expresses the same from configuration, and a cutover swaps primary and mirror with their schemas. Keep one of Dual or a Route per table.
func FromEnv ¶
func FromEnv() []OpenOption
FromEnv is the databases DATABASE_URL and DATABASE_URL_<NAME> name.
func Logger ¶
func Logger(l *slog.Logger) OpenOption
Logger is where the supervisors log state changes and slow queries; slog.Default() otherwise.
func OnOpen ¶
func OnOpen(fn func(ctx context.Context, s *Databases) error) OpenOption
OnOpen runs fn once Start opened the databases: migrations, a cache warm-up. Its error fails Start.
func ReadYourWrites ¶
func ReadYourWrites(on bool) OpenOption
ReadYourWrites turns Scope's read-your-writes on (the default) or off.
func Routers ¶
func Routers(rs ...Router) OpenOption
Routers adds routers to the Databases (see Router).
type OptCell ¶
OptCell is a scan destination for a nullable field of type vuka.Option[V]: None for NULL, else Some of a V read as Cell reads it.
type OrderTerm ¶
type OrderTerm interface {
// contains filtered or unexported methods
}
OrderTerm is a term of Order: an Ordering (a field path) or an expression's Asc or Desc.
type OrderedExpr ¶
OrderedExpr is a TypedExpr whose values are ordered.
func CosineDistance ¶
func CosineDistance(field string, v Vector) OrderedExpr[float64]
CosineDistance is the cosine distance from a vector field to v.
func InnerProduct ¶
func InnerProduct(field string, v Vector) OrderedExpr[float64]
InnerProduct is the inner product of a vector field and v, negated as pgvector's <#> is: smaller is nearer, as with the distances.
func L2Distance ¶
func L2Distance(field string, v Vector) OrderedExpr[float64]
L2Distance is the Euclidean distance from a vector field to v.
func Ordered ¶
func Ordered[R Orderable](e Expr) OrderedExpr[R]
Ordered is e as an expression of ordered R values.
orm.Ordered[int](orm.F("age")).Between(18, 30)
func SearchRank ¶
func SearchRank(d Document, q TextQuery) OrderedExpr[float64]
SearchRank is how well the document matches the query, higher better: Postgres's ts_rank, MySQL's relevance, SQLite's FTS5 bm25 negated (a model declaring the document), and elsewhere the weights of the fields each word is found in. The weights of a document's fields are A 1, B 0.4, C 0.2, D and none 0.1, as ts_rank's; bm25 weighs a field the document doesn't hold 0, and, unlike ts_rank, ranks a match in a short text above one in a long.
func Similarity ¶
func Similarity(field, term string) OrderedExpr[float64]
Similarity is the trigram similarity of a field and term, from 0 to 1: pg_trgm's on Postgres, the same computed in Go on SQLite.
func (OrderedExpr[R]) Between ¶
func (t OrderedExpr[R]) Between(lo, hi R) Cond
Between holds where the expression is from lo to hi, both included.
func (OrderedExpr[R]) Ge ¶
func (t OrderedExpr[R]) Ge(v R) Cond
Ge holds where the expression is at least v.
func (OrderedExpr[R]) Gt ¶
func (t OrderedExpr[R]) Gt(v R) Cond
Gt holds where the expression is more than v.
func (OrderedExpr[R]) Le ¶
func (t OrderedExpr[R]) Le(v R) Cond
Le holds where the expression is at most v.
func (OrderedExpr[R]) Lt ¶
func (t OrderedExpr[R]) Lt(v R) Cond
Lt holds where the expression is less than v.
func (OrderedExpr[R]) Over ¶
func (t OrderedExpr[R]) Over(w Window) OrderedExpr[R]
Over is TypedExpr's Over, keeping the expression ordered.
type OrderedFuncOf ¶
type OrderedFuncOf[R Orderable] = Fn[OrderedExpr[R]]
OrderedFuncOf is a function of ordered R values, made by OrderedFunc.
func OrderedFunc ¶
func OrderedFunc[R Orderable](name string, opts ...FuncOption) OrderedFuncOf[R]
OrderedFunc is Func of ordered values: numbers, strings, times.
var Similarity = orm.OrderedFunc[float64]("similarity")
Users.Filter(Similarity(orm.F("name"), "amna").Gt(0.3)).Order(Similarity(orm.F("name"), "amna").Desc())
type OrderedTerm ¶
OrderedTerm is a Term of a number (or any cmp.Ordered type).
func OrderedTermOf ¶
func OrderedTermOf[T any, V cmp.Ordered](e any) OrderedTerm[T, V]
func (OrderedTerm[T, V]) Add ¶
func (t OrderedTerm[T, V]) Add(x any) OrderedTerm[T, V]
Add, Sub, Mul and Div are arithmetic with a value, a field or a term.
func (OrderedTerm[T, V]) As ¶
func (t OrderedTerm[T, V]) As(name string) OrderedTerm[T, V]
func (OrderedTerm[T, V]) Div ¶
func (t OrderedTerm[T, V]) Div(x any) OrderedTerm[T, V]
func (OrderedTerm[T, V]) Ge ¶
func (t OrderedTerm[T, V]) Ge(v V) vuka.Pred[T]
func (OrderedTerm[T, V]) Gt ¶
func (t OrderedTerm[T, V]) Gt(v V) vuka.Pred[T]
func (OrderedTerm[T, V]) Le ¶
func (t OrderedTerm[T, V]) Le(v V) vuka.Pred[T]
func (OrderedTerm[T, V]) Lt ¶
func (t OrderedTerm[T, V]) Lt(v V) vuka.Pred[T]
func (OrderedTerm[T, V]) Mul ¶
func (t OrderedTerm[T, V]) Mul(x any) OrderedTerm[T, V]
func (OrderedTerm[T, V]) Range ¶
func (t OrderedTerm[T, V]) Range(lo, hi V) vuka.Pred[T]
Range holds from lo to hi, both included.
func (OrderedTerm[T, V]) Sub ¶
func (t OrderedTerm[T, V]) Sub(x any) OrderedTerm[T, V]
type Ordering ¶
Ordering is an ORDER BY term as plain data, Pred's companion: a field path, descending or not.
type PK ¶
PK makes the field the primary key. An integer key is counted by the database unless Manual says the program sets it; UUID makes a string key a random UUID the ORM sets on create when it is empty (uuid on Postgres, CHAR(36) elsewhere). A key is never NULL, and is unique and indexed already.
func (PK) Apply ¶
func (x PK) Apply(o *FieldOptions)
type PageOption ¶
type PageOption func(*pageConfig)
PageOption shapes Paginate: the fields a client may sort and search by, the default order, the largest page.
func DefaultSize ¶
func DefaultSize(n int) PageOption
func DefaultSort ¶
func DefaultSort(fields ...string) PageOption
DefaultSort is the order when the client asks for none (or none it may have).
func DefaultSortBy ¶
func DefaultSortBy[T any](sorts ...vuka.Order[T]) PageOption
func MaxSize ¶
func MaxSize(n int) PageOption
MaxSize caps the page size (100 by default); DefaultSize is the size asked for none (20).
func Searchable ¶
func Searchable(fields ...string) PageOption
Searchable is the fields Search matches, case-insensitively, any of them.
func SearchableBy ¶
func SearchableBy[T any](fields ...Path[T]) PageOption
func Sortable ¶
func Sortable(fields ...string) PageOption
Sortable is the fields a client may sort by; others are ignored. Paths through foreign keys (author__name) are fields too.
func SortableBy ¶
func SortableBy[T any](fields ...Path[T]) PageOption
SortableBy, SearchableBy and DefaultSortBy are Sortable, Searchable and DefaultSort by field reference.
type PageRequest ¶
PageRequest is a page of a list as a client asks for it: Page from 1, Size, Sort (fields, a leading - for descending, comma-separated) and Search.
func PageFrom ¶
func PageFrom(v url.Values) PageRequest
PageFrom reads a PageRequest from query parameters page, size, sort and q.
type PageResult ¶
PageResult is a page of rows and where it sits in the list.
func Paginate ¶
func Paginate[T any](ctx context.Context, qs QuerySet[T], r PageRequest, opts ...PageOption) (PageResult[T], error)
Paginate is one page of qs as r asks for it, sorted and searched only by the fields opts allow — what a REST list or a view's DataTable shows.
page, err := orm.Paginate(ctx, Users.Filter(orm.Q{"active": true}), orm.PageFrom(c.Request.URL.Query()),
orm.Sortable("name", "created_at"), orm.Searchable("name", "email"), orm.DefaultSort("-created_at"))
type Plan ¶ added in v2.16.0
Plan is a database's plan for a statement: Text as the database writes it, JSON with Format(PlanJSON), and the database's dialect name.
type PlanFormat ¶ added in v2.16.0
type PlanFormat string
PlanFormat is how Explain asks for the plan: PlanText or PlanJSON.
const ( PlanText PlanFormat = "text" PlanJSON PlanFormat = "json" )
type PlanResult ¶
type PlanResult struct {
File string `json:"file,omitempty"`
Source []byte `json:"source,omitempty"`
Ops []string `json:"ops"`
Notes []string `json:"notes,omitempty"`
}
PlanResult is the migration plan wrote: its file's name and source, what each operation does, and the notes beside them. No operations is no changes.
type Pool ¶
type Pool struct {
MaxOpen int // connections open at most (20; negative: no limit)
// MaxIdle is the idle connections kept (MaxOpen when it's set, else 20;
// negative: none). A quiet process can hold that many open until
// MaxLifetime, so replicas × MaxOpen must fit the server's connections.
MaxIdle int
// MinIdle is the idle connections opened at start and kept open
// while the database is up.
MinIdle int
// MaxLifetime retires a connection after it (1h; negative: never),
// less up to a fifth at random so they don't all reconnect at once.
MaxLifetime time.Duration
MaxIdleTime time.Duration // closes a connection idle this long (negative or 0: never)
// Acquire bounds the wait for a connection when MaxOpen are in use
// (database/sql waits as long as the context lets it): past it the
// statement fails Unavailable. 0 waits.
Acquire time.Duration
// Health is how often the supervisor pings the database and its
// replicas (10s).
Health time.Duration
Breaker Breaker
// StartupWait is how long Start waits for the database to answer
// (5s); past it the program starts with it Down and the supervisor
// keeps reconnecting. Negative doesn't wait.
StartupWait time.Duration
}
Pool tunes a declared database's connections and the supervisor keeping them. A zero field takes its default; a negative MaxOpen, MaxIdle, MaxLifetime or MaxIdleTime is no limit (no idle connections kept, for MaxIdle). Give it as a Declare option, or as URL parameters (pool_max, pool_max_idle, pool_min_idle, pool_max_lifetime, pool_max_idle_time, pool_acquire, pool_health, breaker_failures, breaker_cooldown, startup_wait), which are taken off the URL before the driver sees it.
type Pred ¶
type Pred struct {
Op PredOp
// Path is the field, after the relations leading to it:
// {"author", "name"} is author__name. Each part is a Go field name or
// a column, as a Q's key names them.
Path []string
Value any
Args []Pred // OpAnd / OpOr: the operands; OpNot: the one it negates
}
Pred is a condition as plain data: a field path, an operator and a value, or And / Or / Not of predicates. It is the adapter point for a layer above the ORM — a language runtime's typed predicates, a filter decoded from a request — that builds conditions without knowing the ORM's lookups: it hands over a Pred (or anything with a Pred method, through PredCond), and the ORM writes it as it writes a Q.
orm.Pred{Op: orm.OpAnd, Args: []orm.Pred{
{Path: []string{"author", "name"}, Op: orm.OpEq, Value: "Ali"},
{Op: orm.OpNot, Args: []orm.Pred{{Path: []string{"draft"}, Op: orm.OpEq, Value: true}}},
}}
is orm.And(orm.Q{"author__name": "Ali"}, orm.Not(orm.Q{"draft": true})).
type PredOp ¶
type PredOp string
PredOp is a Pred's operator: a comparison of the field with the value, or a combination of predicates.
const ( OpEq PredOp = "eq" // a nil value: IS NULL OpNe PredOp = "ne" // a nil value: IS NOT NULL OpLt PredOp = "lt" OpLte PredOp = "lte" OpGt PredOp = "gt" OpGte PredOp = "gte" OpIn PredOp = "in" // the value is a slice OpRange PredOp = "range" // the value is a two-element slice or array OpIsNull PredOp = "isnull" OpContains PredOp = "contains" OpIContains PredOp = "icontains" OpIExact PredOp = "iexact" OpStartsWith PredOp = "startswith" OpIStartsWith PredOp = "istartswith" OpEndsWith PredOp = "endswith" OpIEndsWith PredOp = "iendswith" OpSearch PredOp = "search" OpAnd PredOp = "and" OpOr PredOp = "or" OpNot PredOp = "not" )
type Predicate ¶
type Predicate interface{ Pred() Pred }
Predicate is a condition a layer above the ORM represents its own way and converts to a Pred.
type PrefetchSpec ¶
type PrefetchSpec struct {
// contains filtered or unexported fields
}
PrefetchSpec is a relation PrefetchRelated loads; see Prefetch.
func Prefetch ¶
func Prefetch(path string, qs prefetcher) PrefetchSpec
Prefetch loads a relation's rows with a query of your own (filtered, ordered, selecting or prefetching further), as Django's Prefetch does:
Users.PrefetchRelated(orm.Prefetch("posts", Posts.Filter(orm.Q{"draft": false}).OrderBy("-id")))
PrefetchRelated("posts") is Prefetch("posts", nil): every related row.
func PrefetchBy ¶
func PrefetchBy[T, R any](rel Path[T], rows Query[R]) PrefetchSpec
PrefetchBy is a relation's rows read by a query: a filtered or ordered prefetch.
Post.Objects.PrefetchRelated(orm.PrefetchBy(Post.Tags, Tag.Objects.Filter(Tag.Name.StartsWith("g"))))
type PtrCell ¶
type PtrCell[V any] struct{ P **V }
PtrCell is a scan destination for a nullable field of type *V: nil for NULL, else a new V read as Cell reads it.
type Q ¶
Q is conditions joined by AND, keyed Django's way: a field, then optionally __ and a lookup.
orm.Q{"age__gte": 18, "name__icontains": "a", "email": e}
Lookups: exact (the default), iexact, contains, icontains, startswith, istartswith, endswith, iendswith, in, gt, gte, lt, lte, range, isnull, search (full text, in web search syntax; see SearchQuery) and trigram_similar. A nil value with exact means IS NULL.
type Query
deprecated
type Query[T any] struct { // contains filtered or unexported fields }
Query is a model's QuerySet as Vuka code reads it: conditions are predicates of field references (Post.Title.Contains("go"), typed by the model, so a User's are refused at compile time), orderings their Asc and Desc, relations and fields named by reference, and the terminals return vuka.Result — First a Result of an Option. Post.Objects is the Query of every Post; each method returns a new Query, and nothing runs until a terminal.
posts := Post.Objects.Filter(Post.Title.Contains("go"), Post.Author.Name.Eq("ada")).
OrderBy(Post.Views.Desc()).All(ctx)?
match Post.Objects.Get(ctx, Post.Slug.Eq(slug)) {
case Ok(p): …
case Err(orm.NotFound): …
case Err(e): …
}
QuerySet and With reach the engine's string forms.
Deprecated: Vuka now writes Post.Objects as the model's Manager and Post.Title as its typed field, PostColumns.Title, so a query is the engine's QuerySet. Query goes in the next minor release.
func (Query[T]) Aggregate ¶
Aggregate is Values of aggregates over every row: one R.
totals := Post.Objects.Aggregate[Totals](ctx, orm.Into(Totals.Views, fn.Sum(Post.Views)))?
func (Query[T]) AggregateSQL ¶ added in v2.16.0
func (q Query[T]) AggregateSQL[R any](ctx context.Context, cols ...Col[T, R]) vuka.Result[Statement]
AggregateSQL is the statement Aggregate runs.
func (Query[T]) Annotate ¶
func (q Query[T]) Annotate(as ...ModelAnnotation[T]) Query[T]
Annotate adds named terms (t.As("name")) as computed columns.
func (Query[T]) AnnotateAs ¶
AnnotateAs adds typed expressions named with their As (orm.Func's results).
func (Query[T]) CountSQL ¶ added in v2.16.0
CountSQL, ExistsSQL, DeleteSQL and UpdateSQL are the statements Count, Exists, Delete and Update run; each Statement's Explain is its plan.
func (Query[T]) Create ¶
Create inserts row (its key set after); BulkCreate inserts rows in batches.
func (Query[T]) Explain ¶ added in v2.16.0
Explain is the database's plan for the query: Analyze, Format.
func (Query[T]) Get ¶
Get is the one row the predicates hold for. It fails with the Kind itself — orm.NotFound, orm.MultipleFound — so match compares it: case Err(orm.NotFound).
func (Query[T]) GetOrCreate ¶
GetOrCreate is the row whose match fields equal row's, else row created.
tag := Tag.Objects.GetOrCreate(ctx, Tag{Name: "go"}, Tag.Name)?.Row
func (Query[T]) Hybrid ¶
func (q Query[T]) Hybrid(doc SearchDoc[T], text string, field Path[T], v Vector, opts ...SearchOption) Query[T]
Hybrid ranks by a text match of doc and the distance of field to v, fused by reciprocal rank, as QuerySet.Hybrid.
Post.Objects.Hybrid(orm.Search(Post.Title, Post.Body), "go web", Post.Embedding, v, orm.K(10))
func (Query[T]) Nearest ¶
func (q Query[T]) Nearest(field Path[T], v Vector, opts ...SearchOption) Query[T]
Nearest orders by the distance of a vector field to v: K(n), MaxDistance(d), DistanceAs(alias), a Metric, EfSearch(n) and Probes(n) as for QuerySet.Nearest.
func (Query[T]) On ¶
On is the model's rows on schema s (a tenant's schema, another database): call it first, the query starts over.
func (Query[T]) Order ¶
Order orders by the engine's order terms: a typed expression's Asc or Desc (orm.Func's results), orm.Ordering.
func (Query[T]) Paginate ¶
func (q Query[T]) Paginate(ctx context.Context, r PageRequest, opts ...PageOption) vuka.Result[PageResult[T]]
Paginate is a page of the rows: PageRequest's page, size, sort and search over the fields SortableBy and SearchableBy allow.
func (Query[T]) PrefetchRelated ¶
PrefetchRelated reads relations' rows in a query each: references, or Prefetch for a filtered one.
func (Query[T]) SQL ¶ added in v2.16.0
SQL is the statement All runs, built for ctx's database and not run.
st := Post.Objects.Filter(Post.Views.Gte(100)).SQL(ctx)? fmt.Println(st) // the text, then -- args: 100
func (Query[T]) SelectRelated ¶
SelectRelated reads foreign keys' rows in the same query (a join).
func (Query[T]) Unfiltered ¶
Unfiltered marks the query as meant for every row (Delete, Update).
func (Query[T]) Update ¶
Update sets fields of every row: Assign(Post.Views, 0), AssignF(Post.Views, fn.Num(Post.Views).Add(1)).
func (Query[T]) UpdateOrCreate ¶
func (q Query[T]) UpdateOrCreate(ctx context.Context, row T, match ...Path[T]) vuka.Result[Outcome[T]]
UpdateOrCreate updates the row whose match fields equal row's with row's other fields, else creates row.
func (Query[T]) Values ¶
Values reads the columns into Rs, Django's values: a source that is a field of the same name is read as is, others are annotated; with an aggregate among them the rows are grouped by the rest.
type QueryInfo ¶
type QueryInfo struct {
SQL string
Args []any
Start time.Time
Duration time.Duration
// Rows is the rows an exec affected; -1 for a query, whose rows are
// read after it returns, and when the driver doesn't say.
Rows int64
Err error
// Refused is a query the ORM refused before sending it (an argument
// it can't write for the database, a field the schema lacks): SQL is
// a comment naming the model, Err why. It never reached the database.
Refused bool
Model string // a refused query's model
// DB is the name of the database the statement ran on ("" for one
// WithDB gave without a name), and Replica whether a replica of it.
DB string
Replica bool
}
QueryInfo is a statement the ORM ran, or refused to, as an Observer sees it.
type QuerySet ¶
type QuerySet[T any] struct { // contains filtered or unexported fields }
QuerySet is a lazy, immutable query of a model: each method returns a new QuerySet, and nothing runs until a terminal (All, First, Get, Count, Exists, Iter, Delete, Update, Aggregate). Keep one in a package variable and share it freely.
func Related ¶
Related is the rows of R related to inst (a model row, or a pointer to one) by its relation named: a foreign key's row, the rows holding its key, or those linked to it many-to-many; queried on inst's schema.
posts, err := orm.Related[Post](&u, "posts").Filter(orm.Q{"draft": false}).All(ctx)
func (QuerySet[T]) AggregateSQL ¶ added in v2.16.0
AggregateSQL is the statement Aggregate runs.
func (QuerySet[T]) Annotate ¶
Annotate adds a computed column, named: Filter, OrderBy and Values use it by name, and a field of the model tagged orm:"computed" with the same name receives it.
Users.Annotate("joined", orm.Year.Of(orm.F("created_at"))).Filter(orm.Q{"joined__gte": 2025})
func (QuerySet[T]) AnnotateAs ¶
AnnotateAs is Annotate of expressions named by their As.
Users.AnnotateAs(orm.Length(orm.F("name")).As("name_len")).Filter(orm.Q{"name_len__gt": 3})
func (QuerySet[T]) CursorPage ¶ added in v2.1.0
func (qs QuerySet[T]) CursorPage(ctx context.Context, after, before string, first, last int) (rows []T, cursors []string, more bool, err error)
CursorPage reads one page of the query's rows by cursor, as a GraphQL connection pages (graphql.Paginate takes a QuerySet): the first rows after the row of cursor after, or (last > 0) the last rows before the row of cursor before. Either cursor may be "", and both bound the page. It returns the rows in the query's order, each row's cursor, and whether rows go on past the page: after it reading forwards, before it reading backwards.
Cursors are opaque strings, keyset cursors when the query's ordering allows: its order (Meta's Ordering when it sets none) is the model's own non-nullable columns — the primary key added last when no column of the ordering is unique, the primary key alone without an ordering — and a page is the rows past the cursor's values in that order, unmoved by rows written before it. Any other ordering (an expression, an annotation, a related model's field, a nullable column) gets offset cursors: a row's position in the result. A cursor made for another ordering is refused (ErrCursor).
func (QuerySet) Delete ¶
Delete removes the matching rows and says how many. With no condition it fails with ErrUnfiltered unless the query is Unfiltered.
func (QuerySet) DeleteSQL ¶ added in v2.16.0
DeleteSQL is the statement Delete runs, refused as Delete refuses it.
func (QuerySet) Explain ¶ added in v2.16.0
func (qs QuerySet) Explain(ctx context.Context, opts ...ExplainOption) (Plan, error)
Explain is the database's plan for the query, as SQL builds it.
func (QuerySet[T]) Filter ¶
Filter keeps the rows matching every condition. Keys may follow relations: author__name (a join), posts__title__icontains (a related row exists).
func (QuerySet[T]) First ¶
First is the first row, by the order given (or Meta's) or else by primary key; ErrNotFound when there is none.
func (QuerySet[T]) Get ¶
Get is the one row matching conds: ErrNotFound when there is none, ErrMultipleFound when there are several.
func (QuerySet[T]) GroupBy ¶
GroupBy groups the rows by names (fields, paths through relations, annotations): the GROUP BY of a Values listing aggregates, over the implicit rule (every other name Values lists). Grouping by a primary key lets Values read the columns depending on it without grouping by them, as Postgres and MySQL allow:
Letters.Annotate("n", orm.Count("placements__id")).GroupBy("id").
Values[[]any]("id", "reference_number", "status", "n")
Typed fields name them too: GroupBy(CategoryColumns.ID).
func (QuerySet[T]) Having ¶
Having keeps the groups matching every condition: HAVING, run after grouping, where the aggregates exist. A grouped query only (Values listing an aggregate, or GroupBy); Filter on an aggregate annotation routes to HAVING too, as Django's does.
Letters.Annotate("n", orm.Count("placements__id")).Having(orm.Q{"n__gt": 0}).Values[…]
func (QuerySet[T]) Hybrid ¶
func (qs QuerySet[T]) Hybrid(doc Document, text TextQuery, field string, v Vector, opts ...SearchOption) QuerySet[T]
Hybrid is hybrid search: the rows ranked twice, by the document's match of the text query (SearchRank, annotated "rank") and by the distance of a vector field from v (as Nearest, "distance"), the ranks fused by reciprocal rank (Fuse, "score": a row scores w/(k + r) for each ranking, from the text's only where the text matches) and ordered by score, best first. Every row is ranked by distance unless Candidates or MaxDistance narrow them; K keeps the best k. It runs where both searches do: Postgres, and SQLite (FTS5 and distances in Go).
Docs.Hybrid(orm.SearchVector("title", "body"), orm.SearchQuery("web server"), "embedding", v,
orm.K(10), orm.Candidates(100), orm.HybridWeights(1, 0.5)).All(ctx)
func (QuerySet[T]) Iter ¶
Iter runs the query and yields its rows one at a time, without holding them all; relations PrefetchRelated names are not loaded.
func (QuerySet[T]) Join ¶ added in v2.16.0
Join combines the rows with another table's: Join(<model>.On(conds…)) where conds hold, or a relation of the queried model by its foreign key (Join(CategoryColumns.Links(), orm.Left)). Inner unless orm.Left; the joined model's typed fields then name its columns in conditions, orders, Values and aggregates. A table joined twice takes an alias (As).
Category.Objects.
Join(ProductCategoryColumns.On(ProductCategoryColumns.Category().Eq(CategoryColumns.ID)), orm.Left).
Join(ProductColumns.On(ProductCategoryColumns.Product().Eq(ProductColumns.ID), ProductColumns.Status.In("active")), orm.Left).
Values[CategoryProducts](CategoryColumns.ID, CategoryColumns.Name, orm.Count(ProductColumns.ID))
func (QuerySet[T]) Nearest ¶
func (qs QuerySet[T]) Nearest(field string, v Vector, opts ...SearchOption) QuerySet[T]
Nearest orders the query by the distance of a vector field from v, nearest first, annotated as "distance" (DistanceAs): K keeps the k nearest, MaxDistance those near enough. The metric is the field's vector index's (Ops), L2 without one, or the option's. On Postgres the ORDER BY is pgvector's operator, so an HNSW or IVFFlat index of that metric serves it (EfSearch, Probes tune it); on SQLite the distance is computed in Go for every row; MySQL has no vector search.
Docs.Nearest("embedding", q, orm.K(10), orm.MaxDistance(0.4)).All(ctx)
Docs.Nearest("embedding", q, orm.Cosine, orm.DistanceAs("d")).Values[Hit]("id", "title", "d")
func (QuerySet[T]) Order ¶
Order sorts by terms, as OrderBy: an expression's Asc or Desc, or an Ordering (a field path) — mixed as needed.
Users.Order(Levenshtein(orm.F("name"), "jon").Asc(), orm.Ordering{Path: []string{"age"}, Desc: true})
func (QuerySet[T]) OrderBy ¶
OrderBy sorts by fields, a leading - for descending: OrderBy("-age", "author__name"); typed fields, ascending unless Desc (OrderBy( CategoryColumns.Name, ProductColumns.Price.Desc())); or expressions and their Asc and Desc. A query that sets no order reads rows in the model's Meta Ordering; OrderBy() sets none, that one included.
func (QuerySet[T]) PrefetchRelated ¶
PrefetchRelated loads relations of any kind after the rows, one query each (per thousand keys): names, paths (posts__comments) or Prefetch with a query of your own. Only All, First and Get load them; Iter streams rows without.
func (QuerySet) SQL ¶ added in v2.2.0
SQL builds this query and its bound arguments for the context's database. It does not execute the query.
func (QuerySet[T]) SelectRelated ¶
SelectRelated reads foreign keys in the same query, one LEFT JOIN each: SelectRelated("author", "author__profile"). A missing related row leaves the field nil (or zero).
func (QuerySet[T]) Unfiltered ¶
Unfiltered lets Update and Delete reach every row the query has: without it, an Update or Delete whose conditions are empty (no Filter, or one of nothing, such as an empty Q) fails with ErrUnfiltered and runs nothing.
Sessions.Unfiltered().Delete(ctx) // every row, on purpose
func (QuerySet[T]) Update ¶
Update writes values to the matching rows and says how many; fields marked auto_now are set to now too. With no condition it fails with ErrUnfiltered unless the query is Unfiltered.
func (QuerySet[T]) UpdateSQL ¶ added in v2.16.0
UpdateSQL is the statement Update runs, refused as Update refuses it; fields marked auto_now are set to the time it is built.
func (QuerySet[T]) Values ¶
Values is the query reading some fields into R, Django's values and values_list. A name is a field, an annotation, or a path through relations (team__name), joined in the same query; through rows held by many, a row per related row. R is a scalar for one name (Values[string]("email")); a struct, its fields matched by orm path tag (orm:"team__name"), name or column, and with no names its own fields say what is read; map[string]any keyed by the names as written; or []any in their order. An aggregate annotation among the names groups the rows by the others:
Users.Annotate("n", orm.Count("id")).Values[map[string]any]("team__name", "n")
Typed columns fill R by position: its fields in order, a list's items, a scalar for one; a typed field (of the model or one it joins), an aggregate (orm.Count(ProductColumns.ID)) or any expression each:
Category.Objects.Join(…).Values[CategoryProducts](CategoryColumns.ID, CategoryColumns.Name, orm.Count(ProductColumns.ID))
type RawOption ¶
type RawOption interface {
// contains filtered or unexported methods
}
RawOption tunes Raw and Exec, given among their arguments: Loose (and On, Timeout, a connection handle).
type RawQuerySet ¶
type RawQuerySet[T any] struct { // contains filtered or unexported fields }
RawQuerySet is a model's rows read by SQL of your own, Django's RawQuerySet: see Manager.Raw.
func (RawQuerySet[T]) All ¶
func (r RawQuerySet[T]) All(ctx context.Context) ([]T, error)
All runs the SQL and returns its rows, relations loaded.
func (RawQuerySet[T]) First ¶
func (r RawQuerySet[T]) First(ctx context.Context) (T, error)
First is the first row the SQL reads, relations loaded; ErrNotFound when there is none.
func (RawQuerySet[T]) Iter ¶
Iter runs the SQL and yields its rows one at a time; relations PrefetchRelated names are not loaded.
func (RawQuerySet[T]) PrefetchRelated ¶
func (r RawQuerySet[T]) PrefetchRelated(specs ...any) RawQuerySet[T]
PrefetchRelated loads relations of the rows after them, as a QuerySet's does.
type Rel ¶
type Rel struct {
// OnDelete controls rows holding the foreign key when the related
// row is deleted: Cascade deletes them, SetNull clears the key,
// and Restrict prevents deletion while references remain.
// For example, Rel{OnDelete: SetNull, Null: true} keeps a shelf
// when its category is deleted and clears the category key.
OnDelete string
// Related names the inverse relation on the target model, used by
// lookups, prefetching and generated typed paths. For example,
// Shelf.Category with Rel{Related: "shelves"} gives Category's
// "shelves" lookup and CategoryColumns.Shelves(). The name must
// not clash with a column or another inverse on Category.
Related string
// Column overrides the foreign key's database column. For example,
// Category FK[Category] with Rel{Column: "category_ref"} stores
// the key in category_ref instead of the default category_id.
Column string
// Through names an M2M relation's join table. For example,
// Product.Tags M2M[Tag] with Rel{Through: "product_tags"} uses
// product_tags instead of <owner table>_<field name>.
Through string
// Null allows the foreign key column to hold SQL NULL, so an FK
// may be unset. For example, Rel{Null: true, OnDelete: SetNull}
// permits clearing the key when its related row is deleted.
Null bool
// CrossDB marks a relation whose target is on another database
// (see ModelInfo). For example, Rel{CrossDB: true} on a warehouse
// FK omits its database foreign key constraint. Load its rows with
// PrefetchRelated; joins, SelectRelated and filters or orderings
// through that relation are unavailable. Filtering its local key
// still works.
CrossDB bool
}
Rel describes a relation field (orm.FK, orm.M2M): what deleting the related row does (Cascade, SetNull, Restrict), the inverse's name on the related model, the foreign key's column, a many-to-many's table between, and whether the key may be NULL.
func (Rel) Apply ¶
func (x Rel) Apply(o *FieldOptions)
type RelationPath ¶ added in v2.2.0
type RelationPath struct {
// contains filtered or unexported fields
}
RelationPath is a model's fields rooted at a relation. Generated paths embed it, so conditions and aggregates use the same lookup prefix.
func RelationAt ¶ added in v2.2.0
func RelationAt(path string) RelationPath
RelationAt constructs a relation path of the queried model.
func RelationIn ¶ added in v2.16.0
func RelationIn(src *Source, path string) RelationPath
RelationIn constructs a relation path from src's table, for generated fields.
func (RelationPath) Avg ¶ added in v2.2.0
func (r RelationPath) Avg(field any) Expr
func (RelationPath) Count ¶ added in v2.2.0
func (r RelationPath) Count() Expr
Count counts distinct related primary keys.
func (RelationPath) CountRows ¶ added in v2.2.0
func (r RelationPath) CountRows() Expr
CountRows counts raw joined rows, including their duplicates.
func (RelationPath) Eq ¶ added in v2.16.0
func (r RelationPath) Eq(v any) Cond
Eq holds where the relation's key equals v: a value, a typed field or an expression. ProductCategoryColumns.Product().Eq(ProductColumns.ID) compares the foreign key column with the product's id.
func (RelationPath) Exists ¶ added in v2.2.0
func (r RelationPath) Exists() Expr
Exists reports whether the relation has a matching row.
func (RelationPath) Max ¶ added in v2.2.0
func (r RelationPath) Max(field any) Expr
func (RelationPath) Min ¶ added in v2.2.0
func (r RelationPath) Min(field any) Expr
func (RelationPath) On ¶ added in v2.16.0
func (r RelationPath) On(conds ...Cond) JoinOn
On is the table of the model these fields are of, joined where conds hold; on a relation (CategoryColumns.Links()), the relation's table joined by its foreign key and conds.
Category.Objects.Join(ProductCategoryColumns.On(ProductCategoryColumns.Category().Eq(CategoryColumns.ID)), orm.Left)
func (RelationPath) Source ¶ added in v2.16.0
func (r RelationPath) Source() *Source
Source is the table the fields read. Generated fields pass it on to the relations they reach.
func (RelationPath) Sum ¶ added in v2.2.0
func (r RelationPath) Sum(field any) Expr
Sum, Avg, Min and Max aggregate each related row once, even when a join chain reaches the same primary key more than once.
func (RelationPath) Where ¶ added in v2.2.0
func (r RelationPath) Where(conditions ...Cond) RelationPath
Where narrows the rows used by an aggregate, preserving the parent rows.
type ReplicaStats ¶
type ReplicaStats struct {
URL string `json:"url"`
Healthy bool `json:"healthy"`
Pool sql.DBStats `json:"pool"`
}
ReplicaStats is a replica's health and pool.
type Result ¶
Result is aggregates by Key: COUNT an int64, AVG a float64, the others what the database gives (nil over no rows).
type Retry ¶
type Retry int
Retry runs a transaction again, up to n more times, when the database aborts it for a deadlock or a serialization failure (Postgres 40001 and 40P01, MySQL 1213 and 1205, SQLite's busy), after a short backoff. Only the outermost transaction retries: fn must be safe to run again.
type Route ¶
type Route struct {
DB string `toml:"db" json:"db"`
Mirror string `toml:"mirror" json:"mirror"`
// Names is the names set the primary (DB) binds through, and MirrorNames
// the one the mirror binds through (orm.MirrorUnder); MirrorTable the
// mirror's table, over the model's (orm.MirrorTable). They let a dual
// write to a legacy schema — a renamed, reformatted table — be
// expressed from configuration, and a cutover swap primary and mirror
// with their schemas.
Names string `toml:"names" json:"names"`
MirrorNames string `toml:"mirror_names" json:"mirror_names"`
MirrorTable string `toml:"mirror_table" json:"mirror_table"`
}
Route is a table's databases, for models that name none themselves (Using, the routers and a model's Meta or On win over it): routing a table moves it without a code change.
type Router ¶
type Router interface {
ReadDB(ctx context.Context, m ModelInfo) string
WriteDB(ctx context.Context, m ModelInfo) string
AllowRelation(a, b ModelInfo) bool
AllowMigrate(db string, m ModelInfo) bool
}
Router picks the databases of models' queries at run time, Django's database routers: a tenant's database from the context, an analytics model on its own server. Register routers on a Databases (Routers, or AddRouter); the first giving an opinion wins.
ReadDB and WriteDB name the database a model's reads and writes go to, "" for no opinion. AllowRelation says whether a relation between two models may be declared, AllowMigrate whether a model's table is migrated on a database: being bools, they can't abstain, so every router must allow (embed BaseRouter to allow by default).
A router's choice yields to orm.Using; it wins over a model's Meta and a table's Route. Migrations run before main: a router that should move a model's migrations is registered on Default at init.
type RowScanner ¶
type RowScanner[T any] interface { // Dest is the scan destinations, one per column; the same slice for // every row. Dest() []any // Bind points the destinations at row's fields. Bind(row *T) }
RowScanner reads a model's rows without reflection: generated per model by orm generate (or ormgen, from go:generate), never written by hand.
type RowWriter ¶
type RowWriter[T any] interface { // Values appends row's column values to dst[:0]. Values(row *T, dst []any) []any }
RowWriter is a generated scanner's other half: a row's column values for an INSERT, in the scanner's column order, without reflection. ormgen writes it beside the scanner of a model with no pointer embeds.
type SQLExpr ¶ added in v2.16.0
type SQLExpr[T any] struct { // contains filtered or unexported fields }
SQLExpr is a SQL fragment of T values, written in a query where the built-ins say nothing: SQLOf's or SQLFor's. It is an expression (Values, OrderBy, Update's Set, a comparison's value), compared by its own methods, and a SQLExpr[bool] is a condition (On, Filter, Exclude, Having).
func SQLFor ¶ added in v2.16.0
SQLFor is SQLOf of a fragment written per database; a query on a database it has none for fails, naming it.
orm.SQLFor[time.Time](orm.Dialects{
orm.MySQL: "DATE_SUB(CURDATE(), INTERVAL ? DAY)",
orm.Postgres: "CURRENT_DATE - ?::int",
orm.SQLite: "date('now', '-' || ? || ' days')",
}, 3)
func SQLOf ¶ added in v2.16.0
SQLOf is a SQL fragment of T values: ? binds the next argument as a parameter, {0}, {1}, … write the arguments they number as SQL — a typed field as its column (of the queried model or a model it joins), an aggregate or another expression as itself; '…' literals are left as written, and ?? is a literal ?. The template must be a constant: values only reach the database bound.
threeDaysAgo := orm.SQLOf[time.Time]("DATE_SUB(CURDATE(), INTERVAL ? DAY)", 3).For(orm.MySQL)
ProductColumns.UpdatedAt.Gte(threeDaysAgo)
orm.SQLOf[bool]("{0} >= DATE_SUB(CURDATE(), INTERVAL ? DAY)", ProductColumns.UpdatedAt, 3) // a condition
func (SQLExpr[T]) Eq ¶ added in v2.16.0
Eq, Ne, Gt, Gte, Lt and Lte compare the fragment with v: a T, a typed field or another expression.
func (SQLExpr[T]) For ¶ added in v2.16.0
func (e SQLExpr[T]) For(d DialectName) SQLExpr[T]
For marks the fragment as d's SQL: a query on another database fails, naming both, instead of with a syntax error.
type Schema ¶
type Schema struct {
// contains filtered or unexported fields
}
Schema is what a model declares beyond its Go types: attributes of the model and of its fields, as values. A model declares them in a Schema method, which the ORM calls once, on a zero value, the first time it maps the model:
type Post struct {
orm.Model[Post]
ID int64
Title string
Slug string
Author orm.FK[User]
Published time.Time
}
func (p *Post) Schema(s *orm.Schema) {
s.Model(orm.Meta{Table: "posts", Ordering: []string{"-published"}})
s.Field(&p.Title, orm.Char{Max: 200})
s.Field(&p.Slug, orm.Slug{Unique: true})
s.Field(&p.Author, orm.Rel{OnDelete: orm.Cascade, Related: "posts"})
s.Field(&p.Published, orm.Datetime{DefaultNow: true})
}
A field is named by its address, so a rename is checked by the compiler; a field with nothing to say isn't listed, its column, NULL-ness and type coming from its name and Go type. Fields of embedded structs are named the same way (&p.Timestamps.Created, or the promoted &p.Created).
The attributes are the ones the ORM declares (PK, Char, Int, Datetime, Rel, Column, Unique, …) and any value of another package implementing FieldAttr or ModelAttr: the ORM treats them alike. Attributes apply in order, a later one's set members over an earlier one's. A Vuka model's field attributes (Title string @orm.Char{Max: 200}) are the same values, and come before its Schema's.
func SchemaOf ¶
SchemaOf is what the struct t declares: its Vuka attributes, then its Schema method's. A model declaring nothing has an empty Schema; one whose Schema method is wrong has a *SchemaError.
func (*Schema) Field ¶
Field adds attributes to the field ptr points to, a field of the value Schema is called on.
func (*Schema) FieldAttrs ¶
FieldAttrs is the attributes of the model's field name (its Go name, as the model's own or promoted from a struct it embeds), in order.
func (*Schema) ModelAttrs ¶
ModelAttrs is the model's attributes, in order.
type SchemaCodec ¶
type SchemaCodec interface {
// contains filtered or unexported methods
}
SchemaCodec converts a single field's value to and from its database form under a names set, at the field level. orm.Codec is the only implementation: build one with orm.Codec[G, DB]{To, From} and attach it to a field for a names set (SchemaField.Codec, from a FieldAttr's Apply or SetFieldOptions). The methods are unexported so the ORM owns the conversion; a type that converts itself per schema uses SchemaValuer.
type SchemaError ¶
SchemaError is a mistake in a model's Schema method, reported by every query of the model and by Check. Code is E0501 for an argument of s.Field that isn't the address of one of the model's fields, E0502 for a nil attribute, E0503 for a Schema method that panicked.
func (*SchemaError) Error ¶
func (e *SchemaError) Error() string
type SchemaField ¶
type SchemaField struct {
Column string
Type string
Skip bool
Codec SchemaCodec
}
SchemaField is a field's column under one names set: its name and SQL type there (as a legacy:"column:…;type:…" tag gives them), and a Codec adapting its value's format for that set. A zero member leaves the default; Skip drops the column there (legacy:"-"). The SQL type is the column's documented type and what migrations would make; a legacy (Unmanaged) table is never migrated, so there it only documents the write format.
type SchemaScanner ¶
SchemaScanner is SchemaValuer's reading side: ScanFor is given the names set the value was read under ("" the default), so a type never guesses which form it got. The ORM calls it for model rows, Values (into the type, a map or a list) and Raw on a schema; a type without it reads through its Scan.
func (s *LetterStatus) ScanFor(names string, src any) error {
if names == "legacy" {
*s = LetterStatus(EmployerLetterStatusFromCode[int(src.(int64))])
return nil
}
*s = LetterStatus(fmt.Sprint(src))
return nil
}
type SchemaValuer ¶
SchemaValuer is a column's Go type whose database value depends on the schema it is written under: a status kept as a code on a legacy table and as its name on the new one. The ORM calls ValueFor with the names set of the query ("" the default) for every value it sends of the type — conditions, Update and Save, Create — so one query serves both. Reading is the type's own Scan, which takes either form.
func (s LetterStatus) ValueFor(names string) (driver.Value, error) {
if names == "legacy" {
return int64(codeOf[s]), nil
}
return string(s), nil
}
A value of another type sent to such a column (an int where the field is a LetterStatus) is refused: it would be right on one schema only.
type SearchDoc ¶
type SearchDoc[T any] struct { // contains filtered or unexported fields }
SearchDoc is fields of T searched as one document: Matches is the condition, Rank how well a row matches.
doc := orm.Search(Post.Title, Post.Body)
Post.Objects.Filter(doc.Matches("go web")).OrderBy(doc.Rank("go web").Desc())
func (SearchDoc[T]) Matches ¶
Matches holds for the rows whose document matches q, a web search ("go web", "go -rust", `"exact phrase"`); MatchesQuery for a TextQuery.
func (SearchDoc[T]) Rank ¶
func (s SearchDoc[T]) Rank(q string) OrderedTerm[T, float64]
Rank is how well the document matches q: order by it descending.
type SearchOf ¶
SearchOf makes an orm.TSVector field a generated column holding the fields' document: each "field" or "field:weight" (A–D).
func (SearchOf) Apply ¶
func (SearchOf) Apply(*FieldOptions)
type SearchOption ¶
type SearchOption interface {
// contains filtered or unexported methods
}
SearchOption shapes Nearest and Hybrid: a Metric, K, MaxDistance, DistanceAs, EfSearch, Probes; and Hybrid's HybridWeights, RRF, Candidates, RankAs and ScoreAs.
func Candidates ¶
func Candidates(n int) SearchOption
Candidates is the n nearest rows Hybrid ranks by distance (all of them otherwise), beside those the text matches: a vector index finds them, where ranking every row by distance reads the table.
func DistanceAs ¶
func DistanceAs(alias string) SearchOption
DistanceAs names the distance's annotation: "distance" otherwise.
func EfSearch ¶
func EfSearch(n int) SearchOption
EfSearch is pgvector's hnsw.ef_search for the query, the candidates an HNSW scan keeps (40 by default: more finds more of the true nearest, slower); Probes is ivfflat.probes, the lists an IVFFlat scan reads (1 by default). Set with SET LOCAL in a transaction of the query's own (a savepoint inside the context's), on Postgres only.
func HybridWeights ¶
func HybridWeights(text, vector float64) SearchOption
HybridWeights weighs Hybrid's text rank and vector distance in their fusion: 1 and 1 otherwise.
func MaxDistance ¶
func MaxDistance(d float64) SearchOption
MaxDistance keeps the rows at most d from the vector: Nearest's filter, and the rows Hybrid ranks by distance as well as those the text matches.
func Probes ¶
func Probes(n int) SearchOption
func RRF ¶
func RRF(k int) SearchOption
RRF is reciprocal-rank fusion's constant k: a row ranked r scores 1/(k + r); 60 otherwise. A smaller k favours the top ranks more.
func RankAs ¶
func RankAs(alias string) SearchOption
RankAs and ScoreAs name Hybrid's text rank and fused score annotations: "rank" and "score" otherwise.
func ScoreAs ¶
func ScoreAs(alias string) SearchOption
type Session ¶
Session is settings each new connection takes: MySQL session variables (SET SESSION k = v), Postgres run-time parameters (SET k = v), SQLite pragmas (PRAGMA k = v). Values are plain: numbers and words as they are, anything else quoted.
orm.Session{"statement_timeout": "5s", "search_path": "app"}
type Skip ¶
type Skip struct{}
Skip leaves the field out of the table (orm:"-").
func (Skip) Apply ¶
func (Skip) Apply(o *FieldOptions)
type SlowQuery ¶
SlowQuery logs (warn, through the Databases' Logger) each statement of the database taking d or longer: a Declare option.
type Slug ¶
Slug is an indexed VARCHAR (Max, 50 by default) for URL parts.
func (Slug) Apply ¶
func (x Slug) Apply(o *FieldOptions)
type Sort ¶
Sort is an ordering of Ts: a field reference's Asc or Desc (vuka.Order[T]), or an expression's.
type Source ¶ added in v2.16.0
type Source struct {
// contains filtered or unexported fields
}
Source is the table a typed field reads: a model, under a name of its own when a query joins it more than once. Generated typed fields carry theirs (ProductColumns's is Product's), so a query tells a joined model's columns from its own; As names another.
type State ¶
type State int32
State is a supervised database's health.
const ( // Connecting: it hasn't answered yet. Connecting State = iota // Up: it answers, and so do its replicas. Up // Degraded: it answers, but a replica doesn't, or the breaker is // probing it. Degraded // Down: it doesn't answer — the breaker is open, or it never answered // within StartupWait. The supervisor keeps reconnecting. Down )
func (State) MarshalText ¶
func (*State) UnmarshalText ¶
type StateEvent ¶
type StateEvent struct {
DB string
Replica string // the replica's URL, its password hidden
From, To State
Err error // what failed, for a change for the worse
}
StateEvent is a change of a database's state, or of one of its replicas' health (Replica set, State Up or Down), as ObserveState sees it.
type Statement ¶ added in v2.16.0
Statement is a query's SQL for one database and the arguments bound to its placeholders, built and not run: CountSQL, ExistsSQL, AggregateSQL, UpdateSQL and DeleteSQL give the statement Count, Exists, Aggregate, Update and Delete would run. Its Explain asks the database for its plan.
type StringTerm ¶
type StringTerm[T any, V ~string] struct{ OrderedTerm[T, V] }
StringTerm is a Term of a string.
func StringTermOf ¶
func StringTermOf[T any, V ~string](e any) StringTerm[T, V]
func (StringTerm[T, V]) As ¶
func (t StringTerm[T, V]) As(name string) StringTerm[T, V]
func (StringTerm[T, V]) Contains ¶
func (t StringTerm[T, V]) Contains(s V) vuka.Pred[T]
func (StringTerm[T, V]) EndsWith ¶
func (t StringTerm[T, V]) EndsWith(s V) vuka.Pred[T]
func (StringTerm[T, V]) IContains ¶
func (t StringTerm[T, V]) IContains(s V) vuka.Pred[T]
func (StringTerm[T, V]) IEndsWith ¶
func (t StringTerm[T, V]) IEndsWith(s V) vuka.Pred[T]
func (StringTerm[T, V]) IExact ¶
func (t StringTerm[T, V]) IExact(s V) vuka.Pred[T]
func (StringTerm[T, V]) IStartsWith ¶
func (t StringTerm[T, V]) IStartsWith(s V) vuka.Pred[T]
func (StringTerm[T, V]) StartsWith ¶
func (t StringTerm[T, V]) StartsWith(s V) vuka.Pred[T]
type SwitchExpr ¶
type SwitchExpr struct {
// contains filtered or unexported fields
}
SwitchExpr is a Switch.
func Switch ¶
func Switch(e Expr) *SwitchExpr
Switch is a Case comparing one expression with values: the result of the first Case value it equals, else Else's, else NULL.
orm.Switch(orm.F("status")).Case("paid", 1).Case("refunded", -1).Else(0)
func (*SwitchExpr) Case ¶
func (s *SwitchExpr) Case(value, then any) *SwitchExpr
Case adds a branch: then where the expression equals value. Each is an Expr or a value.
func (*SwitchExpr) Else ¶
func (s *SwitchExpr) Else(v any) *SwitchExpr
Else is the result when the expression equals no value.
type TSVector ¶
type TSVector string
TSVector is a Postgres tsvector column: a generated column holding a SearchVector (orm:"generated"), searched by its __search lookup. Elsewhere the column holds the document's text.
type Term ¶
type Term[T, V any] struct { // contains filtered or unexported fields }
Term is a typed SQL expression over the model T, of Go type V: what the functions of package orm/fn build from field references (fn.Lower(Post.Title), fn.Count(Post.ID)). Its methods are predicates (vuka.Pred[T], so they go in Filter beside field references' own) and orderings; As names it, for Annotate and Values. It is an Expr, so the engine's string-free APIs take it too. OrderedTerm (numbers), StringTerm (strings) and CompareTerm (times) add what their type has, as vuka's references do.
func TermOf ¶
TermOf, OrderedTermOf, StringTermOf and CompareTermOf type an expression: the way to give a function of your own a result type.
func (Term[T, V]) As ¶
As names the term: Annotate(t) adds it to the query under that name, and the named term then reads it (in Filter, OrderBy, Values).
func (Term[T, V]) Eq ¶
Eq, Ne and In compare the term with values; EqF and NeF with another field or term (Django's F).
func (Term[T, V]) Get ¶
func (t Term[T, V]) Get(T) V
Get makes a Term an Arg; an expression is computed by the database, so it panics.
type TermOrder ¶
type TermOrder[T any] struct { // contains filtered or unexported fields }
TermOrder is an ordering by a term: OrderBy takes it beside field references' orderings.
type TextExpr ¶
type TextExpr struct{ OrderedExpr[string] }
TextExpr is an OrderedExpr of text, matched by patterns too.
func Headline ¶
func Headline(field string, q TextQuery, opts ...HeadlineOption) TextExpr
Headline is a field's text about the query's words, marked <b>…</b>: Postgres's ts_headline; on SQLite, where the model declares a document holding the field, FTS5's snippet (highlight with HighlightAll); and elsewhere, or where none of the words is found, the 160 characters about the first word, unmarked. MySQL's is that substring always.
Posts.Annotate("head", orm.Headline("body", q, orm.Marks("<mark>", "</mark>"), orm.MaxWords(20)))
func (TextExpr) Like ¶
Like holds where the text matches a LIKE pattern of your own: % any run of characters, _ any one (case-sensitive or not as the database's LIKE is). The pattern is a bound argument.
func (TextExpr) StartsWith ¶
StartsWith holds where the text starts with s.
type TextField ¶
TextField is a string field: a Field with the text lookups.
func TextFieldAt ¶
TextFieldAt is the text field at a lookup path.
func TextFieldIn ¶ added in v2.16.0
TextFieldIn is the text field at a lookup path from src's table.
func (TextField[V]) IStartsWith ¶
func (TextField[V]) StartsWith ¶
type TextFuncOf ¶
TextFuncOf is a function of text, made by TextFunc.
func TextFunc ¶
func TextFunc(name string, opts ...FuncOption) TextFuncOf
TextFunc is Func of text.
var Unaccent = orm.TextFunc("unaccent", orm.Arity(1)).Transform()
Users.Filter(Unaccent(orm.F("name")).IContains("jose")) // or Q{"name__unaccent__icontains": "jose"}
type TextQuery ¶
type TextQuery struct {
// contains filtered or unexported fields
}
TextQuery is a SearchQuery.
func SearchQuery ¶
SearchQuery is text to search for in web search syntax, Postgres's websearch_to_tsquery: every word must match, "a phrase" in order, or between alternatives, and -word must not; and, beyond Postgres's syntax, word* matches the words starting with word.
type TimeField ¶ added in v2.2.0
TimeField is a timestamp column. Comparisons accept time.Time values and date expressions; generated paths keep the field's lookup prefix.
func TimeFieldAt ¶ added in v2.2.0
func TimeFieldIn ¶ added in v2.16.0
type Timeout ¶
Timeout bounds a statement: a Declare option (each statement of the database), an argument of Raw, RawRow and Exec (that one), or WithTimeout's (each statement of a context).
type Trigram ¶
type Trigram struct{}
Trigram is a pg_trgm index of a text field, for Similarity and LIKE.
func (Trigram) Apply ¶
func (Trigram) Apply(*FieldOptions)
type TxOn ¶
type TxOn string
TxOn runs a transaction on the database added as name, from its start, instead of the database its first write picks.
type TxOption ¶
type TxOption interface {
// contains filtered or unexported methods
}
TxOption tunes Atomic: TxOn, Retry.
type TypedExpr ¶
type TypedExpr[R any] struct { // contains filtered or unexported fields }
TypedExpr is an expression whose value is an R: a typed function's call, or any Expr given its type with Typed. Its comparisons take R, so a condition on it type-checks; it is an Expr, so it goes in Annotate, Values (through an annotation), Update's Set, a Case, and Where with any lookup.
Go can't give a generic type's methods to some of its type arguments only, so the comparisons a type has come with the constructor: TypedExpr (Func) has those of every type, OrderedExpr (OrderedFunc) adds Lt, Le, Gt, Ge and Between, and TextExpr (TextFunc) adds the pattern matches. Contains on a number doesn't compile.
func (TypedExpr[R]) Ne ¶
Ne holds where the expression doesn't equal v: NOT (… = v), unknown where the expression is NULL, as SQL has it.
func (TypedExpr[R]) Over ¶
Over makes the expression a window function's: computed per row over the rows of its partition, in its order — an aggregate over a window no longer groups.
RowNumber := orm.OrderedFunc[int64]("row_number", orm.Arity(0))
Users.AnnotateAs(RowNumber().Over(orm.Window{PartitionBy: []string{"team_id"}, OrderBy: []string{"-age"}}).As("rank"))
type Unique ¶
type Unique struct{}
Unique makes the column unique.
func (Unique) Apply ¶
func (Unique) Apply(o *FieldOptions)
type UniqueTogether ¶
type UniqueTogether string
UniqueTogether names a unique index: the fields sharing a name are unique together.
func (UniqueTogether) Apply ¶
func (x UniqueTogether) Apply(o *FieldOptions)
type Validator ¶
type Validator interface {
Validate() error
}
Validator checks a value before it is written: a non-nil error refuses the write with an Invalid error naming the column.
type Values ¶
type Values[T, R any] struct { // contains filtered or unexported fields }
Values is a query of some fields of T, read into R.
func (Values[T, R]) Annotate ¶
Annotate adds a computed field (QuerySet.Annotate), e.g. an aggregate the projection groups by.
func (Values[T, R]) Explain ¶ added in v2.16.0
Explain is the database's plan for the query, as SQL builds it.
func (Values[T, R]) GroupBy ¶ added in v2.16.0
GroupBy groups the rows by names or typed fields (QuerySet.GroupBy).
func (Values[T, R]) Having ¶
Having filters the grouped rows (QuerySet.Having) — a condition on an aggregate annotation.
type Vector ¶
type Vector []float32
Vector is an embedding: a pgvector column on Postgres, its dimensions tagged on the field (orm:"vector:1536"); on MySQL a VECTOR column where the server has the type (MySQL 9, MariaDB 11.7), else a VARBINARY of the same bytes, so the column becomes a VECTOR in place once it does (ALTER TABLE … MODIFY); its text, [1,2,3], on SQLite. MySQL stores and reads vectors but can't search them: distances, Nearest and Hybrid are refused there when the query is written.
type WhenClause ¶
type WhenClause struct {
// contains filtered or unexported fields
}
WhenClause is a branch of a Case.
func When ¶
func When(cond Cond, then any) WhenClause
When is a branch of a Case: then where cond, any Cond, holds. then is an Expr (a field, arithmetic, another Case) or a value sent as an argument.
Source Files
¶
- annotation_ref.go
- cast.go
- change.go
- codec.go
- csv.go
- cursor.go
- databases.go
- date_expr.go
- db.go
- declare.go
- dialect.go
- errors.go
- explain.go
- expr.go
- field.go
- fieldspec.go
- fts.go
- func.go
- join.go
- json.go
- loadrelated.go
- lookup.go
- manager.go
- meta.go
- migrate.go
- mirror.go
- model.go
- modelattr.go
- observe.go
- options.go
- paginate.go
- pool.go
- pred.go
- prefetch.go
- q.go
- query.go
- query_sql.go
- queryset.go
- raw.go
- readas.go
- relation.go
- relation_expr.go
- route.go
- scan.go
- scanner.go
- schema.go
- schemavalue.go
- search.go
- sqlfrag.go
- subquery.go
- tables.go
- vuka_attrs.go
- vuka_base.go
- vuka_option.go
- vuka_path.go
- vuka_query.go
- vuka_rel.go
- vuka_search.go
- vuka_term.go
- write.go
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
orm
command
Command orm is the ORM's tool: it writes the generated code of a module's models and drives its migrations, Django's manage.py commands.
|
Command orm is the ORM's tool: it writes the generated code of a module's models and drives its migrations, Django's manage.py commands. |
|
ormgen
command
Command ormgen writes the ORM's row scanners and model registrations into the tree, for go:generate (orm generate does the same):
|
Command ormgen writes the ORM's row scanners and model registrations into the tree, for go:generate (orm generate does the same): |
|
Package fn is the ORM's expressions over Vuka field references, typed: each takes field references (Post.Title, Post.Author.Name) or other terms and gives an orm.Term of the Go type the database computes, so only the comparisons that make sense type-check.
|
Package fn is the ORM's expressions over Vuka field references, typed: each takes field references (Post.Title, Post.Author.Name) or other terms and gives an orm.Term of the Go type the database computes, so only the comparisons that make sense type-check. |
|
internal
|
|
|
schema
Package schema is the ORM's tables as the database needs them, and the SQL that creates and changes them on each dialect.
|
Package schema is the ORM's tables as the database needs them, and the SQL that creates and changes them on each dialect. |
|
Package migration is the ORM's schema migrations, Django's: Go files orm makemigrations writes into the program (migrations/NNNN_name.go, a package of their own), each registering a Migration of operations from its init.
|
Package migration is the ORM's schema migrations, Django's: Go files orm makemigrations writes into the program (migrations/NNNN_name.go, a package of their own), each registering a Migration of operations from its init. |
|
Package mysql links the MySQL driver (go-sql-driver/mysql) for the ORM: blank-import it to Connect to "mysql".
|
Package mysql links the MySQL driver (go-sql-driver/mysql) for the ORM: blank-import it to Connect to "mysql". |
|
Package ormgen writes the row scanners the ORM uses instead of reflection, registers the models embedding orm.Model, and writes each model's typed fields.
|
Package ormgen writes the row scanners the ORM uses instead of reflection, registers the models embedding orm.Model, and writes each model's typed fields. |
|
Package ormtest opens a database for a test with the models' tables made: in-memory SQLite by default, or, with ORMTEST_DRIVER and ORMTEST_DSN set, a schema (Postgres) or database (MySQL) of its own on a real server, dropped when the test ends.
|
Package ormtest opens a database for a test with the models' tables made: in-memory SQLite by default, or, with ORMTEST_DRIVER and ORMTEST_DSN set, a schema (Postgres) or database (MySQL) of its own on a real server, dropped when the test ends. |
|
Package ormweb serves an orm.Databases in a github.com/vuka-lang/web/v2 app: the databases open when the app starts (migrated in development) and close gracefully when it stops; *orm.Databases and the connection handles (@orm.Database) are dependencies; each request's context carries the databases and a read-your-writes Scope; GET /healthz reports every database's state (and, in development, its pool and errors); a model or handle naming a database the app doesn't declare fails the app's Build.
|
Package ormweb serves an orm.Databases in a github.com/vuka-lang/web/v2 app: the databases open when the app starts (migrated in development) and close gracefully when it stops; *orm.Databases and the connection handles (@orm.Database) are dependencies; each request's context carries the databases and a read-your-writes Scope; GET /healthz reports every database's state (and, in development, its pool and errors); a model or handle naming a database the app doesn't declare fails the app's Build. |
|
Package postgres links the Postgres driver (pgx, through database/sql) for the ORM: blank-import it to Connect to "postgres".
|
Package postgres links the Postgres driver (pgx, through database/sql) for the ORM: blank-import it to Connect to "postgres". |
|
Package sqlite links the pure-Go SQLite engine (glebarez/go-sqlite, on modernc's) for the ORM: blank-import it to Connect to "sqlite".
|
Package sqlite links the pure-Go SQLite engine (glebarez/go-sqlite, on modernc's) for the ORM: blank-import it to Connect to "sqlite". |