orm

package
v0.48.0 Latest Latest
Warning

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

Go to latest
Published: Nov 20, 2026 License: MIT Imports: 38 Imported by: 0

README

Declare and query a table

Handwritten declarations bind concrete models and keys to the shared SQL runtime. Use this package for model reads, writes, lifecycle callbacks and relations; orm/expr and orm/rows provide expressions, joins and typed result selections.

Keep the model and its table declaration together. The table's second type parameter is the primary key type, including named natural keys.

type Product struct {
	Code  string
	Price int64
}

type ProductTable struct {
	orm.Table[Product, string]
	Code  orm.TextPrimary[Product, string]
	Price orm.Number[Product, int64]
}

var Products = orm.Define("products", func(b orm.Builder[Product], p *Product) ProductTable {
	table := orm.TableOf(b, &p.Code)
	return ProductTable{
		Table: table,
		Code:  orm.TextKey(orm.PrimaryOf(b, table.Key())),
		Price: orm.NumberOf(b, &p.Price),
	}
})

Call orm.Check(Products) during startup to report declaration errors together. Each query or write also rejects an invalid table.

Column handles are methodless. One function per operation, such as orm.Eq and orm.Set, takes the handle and keeps its concrete model, value and role types. Use them with the query and table package functions:

products, err := orm.All(ctx, db, Products.Query().
	Where(orm.Between(Products.Price, 100, 500)).
	OrderBy(orm.Asc(Products.Code)))

product, err := orm.Find(ctx, db, Products.Table, "SKU-1")
created, err := orm.Insert(ctx, tx, Products.Table, orm.Set(Products.Code, "SKU-1"), orm.Set(Products.Price, 100))
updated, err := orm.Update(ctx, tx, Products.Query(), Products.Key(), "SKU-1", orm.Set(Products.Price, 0))
page, err := orm.Paginate(ctx, db, Products.Query(), orm.Page(2, 20))

Omit an assignment to leave the field unwritten. orm.Set(column, 0) writes zero. Nullable families provide explicit NULL operations, such as orm.SetNull(column). Use NullableTextOf, NullableNumberOf, NullableTimeOf, NullableIDOf, or NullableColumnOf for value.Nullable fields.

Declare every persisted field. Tag transient fields with foundry:"-". Relation fields are slots and do not become columns in this prototype. foundry:"column=email_address" overrides the SQL name, and foundry:"default=database" permits omission on insert.

Use EnumOf for a generated enum descriptor and BytesOf for owned byte buffers. Use ColumnOf(b, &p.Field, orm.Codec(custom)) for a custom codec.

Built-in codecs carry a private framework capability and avoid per-value callback isolation. Custom codecs, validators, scanners and JSON methods remain contained: panic or runtime.Goexit fails the read, preserves safe classification and closes the result stream after the callback exits. Applications cannot grant that capability with WithParameterType or by embedding a framework scanner. A failed collection returns no partial model slice; successful rows retain independent values.

A persisted CreatedAt and UpdatedAt pair uses the existing timestamp convention. Both fields must be time.Time or temporal.DateTime. orm.NoTimestamps() disables that convention. A nullable instant named DeletedAt enables soft deletion. Explicit timestamp constructors support other field names.

Use orm.AllLocked(ctx, tx, orm.Lock(q)) or orm.AllLocked(ctx, tx, orm.ForShare(q)) for row locks. The locked terminal functions require *database.Tx. Ordinary reads accept database.Executor; writes accept database.Transactor and retain nested transaction behavior. A *orm.WriteError[M] preserves a hydrated candidate when transaction confirmation is uncertain. The candidate does not prove persistence.

Declare lifecycle hooks with orm.WithHooks and field mutators on the model. Direct relations, joins and projections are described below.

The key field is bound only by TableOf. Derive ordered numeric capabilities with orm.NumberKey(table.Key()) or text capabilities with orm.TextKey(table.Key()); a second field binding is an error. Primary keys are comparable, cannot use sensitive codecs, and a model.ID[M] key must belong to its model. Text and NullableText retain named string types.

Numeric adjustments require a strictly positive, finite amount:

product, err := orm.Update(ctx, tx, Products.Query(), Products.Key(), "SKU-1", orm.Decrement(Products.Price, 10, orm.AtLeast(int64(0))))
n, err := orm.UpdateAll(ctx, tx, Products.Query().Where(orm.Lt(Products.Price, 500)), orm.Increment(Products.Price, 10, orm.AtMost(int64(500))))

The bound is checked by the same SQL UPDATE. Per-key adjustments return orm.ErrBoundExceeded wrapped in fault.Conflict for a bound-rejected visible row, and database.NotFound for a missing or hidden key, with or without hooks/observers. An empty guarded write or lifecycle locking read adds one key-only locking read in the same transaction, retaining all visibility predicates except the bound. Successful writes keep their statement count; see the batch-write guide. Set-based writes return the number of rows satisfying the bound. Adjustments preserve SQL NULL and accept one numeric adjustment plus ordinary assignments. validation.Positive[N]() applies the same strictly positive, finite rule to scalar numeric input; validation.DecimalPositive() checks exact decimal input. Both rules currently run only on the server.

Construct bounds with AtLeast or AtMost; a zero-value Bound is rejected. PostgreSQL evaluates column +/- amount before comparing the bound. An int64 or float64 overflow returns a database out-of-range error rather than silently passing the guard.

orm.InsertMany(ctx, tx, table, [][]orm.Assignment[M]{...}) inserts an atomic bounded batch. NoSoftDeletes() disables the deletion convention and conflicts with explicit SoftDeleteOf. orm.ForceDelete(ctx, db, table.Query(), soft, table.Key(), key) physically deletes active records by default; use package ForceDelete with a WithTrashed or OnlyTrashed query for deleted records. orm.ForceDeleteAll respects query visibility. Explicit timestamp roles win over names; explicit timestamp constructors conflict with NoTimestamps(). CreatedAt, UpdatedAt, and SoftDelete retain the instant type as their second type parameter. Upserts use orm.OnConflict with typed targets and assignments.

orm.Chunk(ctx, ex, query, size, func([]M) error) reads bounded batches with stable ordering and preserves Limit/Offset. Later batches advance from the last ordered values captured before the callback. Nullable ordering uses the same keyset predicate as the existing query API; explicit NULL placement falls back to OFFSET. Rows close before callbacks run. EachChunked uses the same batches and yields one model at a time. Callback errors and cancellation stop traversal.

Relations and projected rows (Stage 1b)

Bind slots during Define, then declare relationships after both tables exist:

var OrderRelations = struct { Buyer orm.BelongsTo[Order, User] }{
    Buyer: orm.BelongsToOf(Orders.Buyer, Orders.BuyerID, Users.ID),
}
orders, err := orm.All(ctx, db, Orders.Query().With(OrderRelations.Buyer))
loaded, err := orm.LoadFrom(ctx, db, Orders.Query().With(OrderRelations.Buyer), orders)

OneOf and ManyOf bind relation.One and relation.Many fields. Nullable foreign IDs retain their non-null key type. The loader uses the shared engine's 500-key batches and 10,000-row fetched/attachment budgets. orm.LoadFrom returns copies; errors publish no partial result. Target soft deletes and context scopes remain active. orm.Each closes each parent batch before loading relations.

For joins, rows.As[Tag] creates a distinct scope, expr.At binds an explicitly adapted model column to that scope, and rows.LeftScope/RightScope move fields into the joined scope. rows.Define returns a schema embedding rows.Row[R] from b.Row(); rows.IDOf, TextOf, NumberOf, EnumOf, TimeOf, BytesOf and their Nullable...Of counterparts take field pointers and choose their typed codecs. Custom values use rows.FieldOf(b, &r.Field, orm.Codec(custom)) or rows.NullableFieldOf with the underlying value codec. rows.Map unifies that field's value type with its scoped expression. rows.Select requires every field once. rows.SelectValue(Orders.Query(), Orders.TotalCents) selects a scalar. The complete example is the reporting fixture.

Enum descriptors resolve lazily on Check and first use, after package initialization. Model files can sort before generated enum files; no manual initialization references are needed. Call orm.Check and rows.Check during application startup to collect typed fault.Invalid declaration errors.

Scoped expr.Expression[S,V,P] keeps comparison value V separate from projected value P. Nullable fields compare against V and project value.Nullable[V]; use IsNull/IsNotNull for nullness. rows.On unifies comparable unwrapped keys, and rows.InnerJoin accepts only an aliased table on its right side.

Column handles have no methods. Each operator, such as orm.Eq and orm.Gt, is one generic function. It accepts the concrete handle first and preserves its model, value, input and declaration-role types. A type constraint on the column's kind decides which columns it accepts: orm.Gt rejects an enum, orm.Like rejects a number and orm.SetNull rejects a required column, all at compile time. Query chains remain methods; read terminals, lock transitions and table operations are package functions.

Expression and source APIs take the column directly, for example expr.Value(Users.Email). Passing a column allocates no wrapper and adds no capabilities: input columns remain ineligible for source mappings, primary roles retain their restrictions, and encrypted columns accept assignments and NULL checks without expression or equality access.

The surface test pins methodless columns and the retained query/table method sets. Fixture budgets cover individual kinds and model-count growth. There are no compatibility methods or promoted .Column fields, per-kind operator names or column adapters.

Stage 3.1a adds JSONOf/NullableJSONOf for value.JSON[T] and IntervalOf/NullableIntervalOf for temporal.Interval. JSON handles keep the payload type through equality, membership, containment and assignment. They support orm.Asc/orm.Desc and orm.IsJSONNull, but no range comparisons or text patterns. expr.JSONType and expr.JSONLength inspect JSON expressions. Interval handles add ordered comparisons and sorting, without numeric adjustments or text patterns. Nullable handles distinguish SQL NULL from values; JSON null is represented by value.JSON[value.Nullable[T]].

Use TableOf(b, &m.Period, orm.Codec(codec.Interval())) for an interval natural key. PostgreSQL compares intervals using 30-day months and 24-hour days: an orm.Eq(Users.Period, temporal.Months(1)) predicate also matches stored 30 days. Interval natural keys therefore collide for 1 mon and 30 days; hydration preserves their distinct calendar and elapsed components. Use expr.SumInterval and expr.AvgInterval for interval aggregates. BytesOf/NullableBytesOf retain buffer ownership and distinguish empty bytes from NULL. orm.IContains and orm.IContains treat %, _ and \ as literal substring characters and match case-insensitively. For example, orm.IContains(Users.Email, "@EXAMPLE.com") binds a value; it never interpolates SQL. Stage 3.1b adds PasswordOf/NullablePasswordOf, which preserve typed hash scalar comparisons, sorting and assignment while rejecting plaintext and text patterns. The password codec retains its sensitivity and redaction.

EncryptedTextOf/EncryptedJSONOf and their nullable constructors expose typed Set; nullable handles also expose SetNull, IsNull and IsNotNull. They do not support ordering, value comparisons or row projections. Single-model writes seal after UUID generation, inside the transaction using its keyring. Every set-based encrypted assignment is rejected, even with a primary-key equality. Hydration opens using each row's table, column and key through the same shared owner as the generated API. Failures publish no partial model. Table/column/key renames require re-encryption; see encryption. Unknown or committed callback failures retain reconciliation candidates through WriteError; a candidate never proves successful commit.

Encrypted Go values (including value.Nullable wrappers) must use the EncryptedTextOf/EncryptedJSONOf constructors or their nullable forms. ColumnOf with an explicit encrypted codec is rejected at startup. Row projections reject encrypted values because they cannot open them yet.

Hydration publishes only complete, successfully opened models. Buffered reads, page reads, eager loads, and each chunk discard the failing batch. Streaming orm.Each retains rows already delivered before an error; it never delivers the failing row or any later row. This matches the old API's streaming behavior.

Stage 3.1c adds cursor pagination and primary-key chunking as package functions:

page, err := orm.CursorPaginate(ctx, db,
    models.Users.Query().OrderBy(orm.Asc(models.Users.Nickname)), request.Page)
// request is pagination.CursorRequest[Path, Filters, models.User].
// Map the returned orm.CursorPage with pagination.MapCursorPage.
err = orm.ChunkByKey(ctx, db, models.Orders.Query(), models.Orders.ID, 500,
    func(batch []models.Order) error { return process(batch) })
err = orm.EachByKey(ctx, db, models.Orders.Query(), models.Orders.ID, 500, processOrder)

Cursor requests/results reuse the existing HTTP pagination adapters and data/meta/links JSON shape. Tokens retain the old unsigned v1 format and concrete model, filter and ordering scope. They are positions, not credentials: a client may move its own position, but query predicates (tenant, soft-delete and scopes) always still apply. Nullable and mixed orders use the same keyset predicate, with the primary key appended as a unique tiebreaker. Existing Limit/Offset windows are rejected.

Key chunks accept only primary-key ordering and zero Offset; Limit bounds total delivery. Rows close before callbacks and the next key is captured before callback edits. Deleting rows behind the boundary does not shift later batches. Keep keys stable; iteration does not provide a snapshot across callbacks.

Locked keyed reads compose orm.RequireLocked(ctx, tx, orm.Lock(Orders.Query().Where(orm.Eq(Orders.ID, id)))). The executor remains *database.Tx; unlocked reads retain read-pool routing.

Typed raw hydration

orm.Raw and rows.Raw apply no automatic scopes: callers must write tenant, soft-delete and other scope predicates themselves. Both use the supplied executor exactly; raw SQL may write, so they do not choose a read replica. For explicit read routing, the existing level-1 db.QueryRead or database.ReadQuery API is available; an executor wrapper can deliberately forward Query to QueryRead when its SQL is known to be read-only. There is no implicit SQL classification.

orders, err := orm.Raw(ctx, tx, Orders.Table, "SELECT * FROM orders WHERE id=$1", id)
report, err := rows.Raw(ctx, db, OrderRows,
    "SELECT id, label FROM orders WHERE id=$1", id)

Results must contain exactly the declaration's column names, in any order. Use SQL aliases for declared names. Missing, duplicate or extra names fail even when there are zero rows. Arguments go unchanged to the executor. Existing codecs and model encryption opening are reused; row schemas still reject encrypted types. Any decoding/opening failure discards the whole result and closes the stream. For UPDATE … RETURNING, a hydration error does not prove rollback: use an owning transaction and preserve the executor's outcome classification.

Direct eager trees and existence

Declare BelongsToOf, HasOneOf or HasManyOf once, then derive immutable target constraints and finite trees:

orders, err := orm.All(ctx, db, Orders.Query().With(
    OrderRelations.Buyer.Where(orm.Gt(Users.Age, 18)).With(UserRelations.Orders),
))

q := Users.Query().Where(orm.Has(UserRelations.Orders, orm.Gt(Orders.TotalCents, 100)))
q = orm.WithRelationLimits(q, orm.RelationLimits{
    BatchSize: 100, MaxRows: 5000, MaxDepth: 4,
})
missing, err := orm.LoadMissingFrom(ctx, db, q.With(UserRelations.Orders), users)

Each query load executes one parent statement plus, for each tree branch, ceil(distinct eligible non-null keys / batch size) statements. Nested branches batch the complete fetched target collection. orm.LoadFrom and orm.LoadMissingFrom issue no parent statement; the latter preserves already-loaded slots, including empty ones. LoadFrom and LoadMissingFrom accept a query with With relations and WithRelationLimits overrides. They validate that query without fetching or filtering the supplied parents; parent predicates, order and window do not change the input collection. Both functions share the same copy-and-load engine. Supplied parent provenance/authorization belongs to the caller. Related soft-delete and declared scopes still apply. orm.Has/orm.Not(orm.Has(...)) are correlated EXISTS predicates, compose recursively, and add zero statements or eager loads.

Defaults come from the shared relation-limits owner: batches of 500, depth 8, and a shared maximum of 10,000 fetched rows and 10,000 attached values across the whole tree. Query overrides apply to every branch, pagination and each chunk window. Invalid graphs fail before parent SQL; budget/cardinality/decoding errors publish no partial collected parents. Singular relations reject multiple matches. Relation Limit/Offset is unavailable: a global batch limit would truncate collections across parents. Target ordering appends the primary key as a tie-breaker.

For a statement-count regression, install one detector on the pool and begin a scope around the read. Set a threshold appropriate to the expected batch count:

detector, err := database.NewStatementDetector(database.StatementDetectorConfig{
    Threshold: 4, MaxShapes: 32,
})
// Handle err; supply database.WithStatementDetector(detector) when opening db.
ctx, scope := detector.Begin(t.Context())
_, err = orm.All(ctx, db, Users.Query().With(UserRelations.Orders))
// Handle err, then check both the operation's exact statement count and shapes.
dbassert.AssertStatementShapes(t, scope)

Close rows before checking. Only compiler-produced shapes appear as SQL text; raw statements use keyed fingerprints and violations include bounded call sites. See statement instrumentation.

Joined relation families

ThroughOf(b, &m.Groups) binds a relation.Through[Group, Membership] slot. ManyToManyOf unifies the source/pivot and pivot/target key pairs without retaining public generic queries in the descriptor:

links := orm.ManyToManyOf(Users.Groups, orm.JoinKeys(Users.ID, Memberships.UserID), orm.JoinKeys(Memberships.GroupID, Groups.ID))
users, err := orm.All(ctx, db, Users.Query().With(
    links.Where(orm.Eq(Groups.Active, true)).WherePivot(orm.Eq(Memberships.Role, "admin")).
        With(GroupRelations.Owner).WithPivot(MembershipRelations.Inviter),
))
for _, user := range users {
    for _, link := range user.Groups.All() {
        use(link.Model, link.Pivot)
    }
}

Targets and pivots remain separate typed values in each relation.Link. Distinct pivot rows remain distinct links. A pivot matching multiple targets fails with database.TooManyRows; NULL keys, missing targets and filtered targets create no link. Target and pivot soft-delete scopes apply independently. Use WithTrashedPivot, OnlyTrashedPivot or WithoutTrashedPivot to change the latter. OrderBy and OrderByPivot retain their combined call order, with target and pivot primary keys appended as tie-breakers.

HasManyThroughOf and HasOneThroughOf accept a slot followed by four columns: source local key, intermediate first key, intermediate second key, target foreign key. Both key pairs and the intermediate owner must match. Intermediates retain their scopes. A singular descriptor's OfMany(orders...), LatestOfMany() and OldestOfMany() select one target per parent through DISTINCT ON, with a primary key tie-breaker. OfMany requires an order; latest and oldest use the primary key.

model.MorphName and model.Morphable reuse the old API's persisted discriminator contract. MorphOneOf and MorphManyOf filter targets by the source's declared name. MorphToOf declares one concrete slot per possible target and loads only matching source rows. MorphToManyOf and MorphedByManyOf constrain the pivot discriminator. Names must follow the identifier grammar. Discriminator values are bound parameters.

Each joined family uses one SELECT per key batch. Nested target and pivot branches batch their complete collections under the same depth and fetched/attached-value budgets. Each attached link consumes two values. Polymorphic inverses batch each concrete discriminator group; an empty eligible key set sends no statement. orm.Has and orm.Not(orm.Has(...)) also accept these descriptors without extra round trips. Relation writes use orm.Attach, orm.Detach, orm.Sync and their batch variants; pivot lifecycle callbacks retain the declared model ownership.

Field mutators and explicit accessors

orm.Check reports invalid declarations before application resources start. Mutate<Field>(Input) (Stored, error) and Access<Field>() (Result, error) use value receivers and exact concrete types. Their suffix must name a persisted Go field, including after a rename. Binding happens once during Define; writes invoke typed functions without reflective dispatch. Mutators use a zero receiver, so use the input argument rather than receiver state. Accessors are ordinary explicit calls and never replace stored hydration or DTO mappings.

For a same-type transformation, use an input column with a typed transform:

Email: orm.InputTextOf(b, &m.Email, normalizeEmail),

Use the same input-column family for distinct input and storage types:

Email: orm.InputTextOf(b, &m.Email, normalizeEmailInput),
Note:  orm.NullableInputTextOf[Member, LabelInput](b, &m.Note, nil),

A nil constructor transform selects the matching Mutate<Field> method. An explicit transform and a named mutator for the same field are a declaration error. InputColumn, InputText, InputNumber, InputTime, InputEnum, InputJSON and InputInterval retain their stored comparison, ordering and expression capabilities. Each also has a nullable form. InputBytesOf uses an owned binary codec with the InputColumn kind. Set takes only the concrete input type; predicates take only the stored type. Nullable SetNull keeps SQL NULL distinct from an omitted assignment or an assigned zero value.

Mutators run in declaration order inside the write transaction, after automatic timestamps and before encryption and binding. They run once per assigned value, including values in a batch or a set update. Omitted fields and explicit SQL NULL skip scalar callbacks. Reusing assignments starts from the original input; direct binary inputs own their buffers. Other custom inputs retain ordinary Go copy semantics. Return an error to abort the transaction or savepoint. Panic and Goexit use the existing transaction isolation boundary. Keep transforms pure and free of I/O. Encrypted fields reject mutators; transform plaintext before creating the encrypted value. SQL adjustments cannot bypass a field's Go mutator.

The independent mutator consumer and its PostgreSQL source exercise distinct inputs, explicit getters, omission, NULL and rollback.

Primary keys with distinct mutation inputs reuse the one primary declaration:

table := orm.TableOf(b, &user.ID)
id := orm.InputKeyOf[User, FreshID](b, table.Key(), nil)

orm.Set(id, FreshID{Value: storedID}) takes fresh input. orm.Eq(id, storedID) and orm.Find(ctx, db, table, storedID) retain the stored key type. Declare this input key inside Define. Its nil transform selects the matching named method. A distinct input disables automatic UUID creation, so an omitted required key fails before SQL. Ordinary same-type UUID key mutators retain automatic UUID preparation.

Mutator callback errors expose only a fixed field diagnostic through ordinary formatting. Their original cause remains available through errors.Is and errors.As. Required and nullable password constructors bind named mutators; encrypted fields continue to reject them.

Write lifecycle

Declare a per-write factory with WithHooks(func() Hooks[Order] { ... }) as a Define option. The factory runs inside the owning transaction, after a locked original has been hydrated and its rows closed. It runs once per normal write. Saving precedes Creating or Updating. Mutators and conventions follow these callbacks. The effective draft is validated before mutators and encryption; omitted required fields can be supplied with WriteSet(write, orm.Set(Orders.TotalCents, 0)).

Draft getters accept typed setter functions. Declare callbacks with the concrete model and input types:

setTotal := func(v int64) orm.Assignment[Order] { return orm.Set(Orders.TotalCents, v) }
setNote := func(v LabelInput) orm.Assignment[Member] { return orm.Set(Members.Note, v) }

orm.WriteGet(write, setTotal) returns Optional[int64]; orm.WriteNullableGet(write, setNote) returns Optional[Nullable[LabelInput]]. orm.WriteIsSet(write, setNote) also reports an explicit NULL as assigned. These functions preserve input values without running mutators. Use the nullable getter for nullable fields. Getter/assignment errors abort the draft even if a callback ignores them. Draft pointers are valid only during before hooks.

orm.WriteUnset(write, setNote) removes the pending assignment in Saving/Creating/Updating. Getters then report omission, including after an explicit zero or SQL NULL. It does not assign a zero or NULL, invoke mutators, or undo a previously persisted value. Unsetting an omitted field is harmless. Later hooks can set it again; automatic defaults/timestamps still follow their ordinary conventions. The setter keeps the model and input types; foreign declarations and expired drafts fail validation. Caller-owned assignment slices remain reusable.

After RETURNING has hydrated and closed its rows, Created or Updated precedes Saved. Deletion runs Deleting then Deleted; force deletion adds ForceDeleting before Deleting and ForceDeleted after Deleted. Restore runs Restoring then Restored. A callback error, panic, Goexit or cancellation aborts the owning transaction/savepoint. Hook and comparison errors expose fixed framework text while retaining the original cause for errors.Is/errors.As. The supplied context shares the generated API's 32-level lifecycle nesting bound; propagate it to nested operations.

Changes[Order] contains only persisted fields, with locked originals and actual RETURNING results (including defaults, triggers and managed timestamps). ChangeOf(changes, Orders.TotalCents) returns the existing lifecycle.FieldChange[int64]; NullableChangeOf(changes, Members.Note) retains Nullable[StoredLabel]. Assigned reflects effective assignments, even if the canonical stored value did not change. Before is absent on create; After is absent after physical deletion. Snapshot getters return owned binary buffers and exclude ignored fields and relation slots. Compare(Orders.Table, before, after, assignments...) provides the same comparison without a write or operation tag.

Observers use NewObserver[Order]("orders.audit") and RegisterObserver through the existing database Module/provider registration at application.New. Dependency constructors return func() Hooks[Order]. Each application's pool owns an immutable observer set. At every stage local hooks run first, followed by observers in declaration order, including models without a local factory. NewDeletionObserver limits dispatch to deletion operations.

AfterCommit callbacks merge through successful savepoints, are discarded on rollback, and run after the outer commit releases its connection. All callbacks run even if one fails; failures preserve the committed outcome and reconciliation candidate. Use the transaction supplied to after hooks for durable outbox/audit writes: in-memory after-commit work is not crash durable.

Set writes skip per-model hooks, observers and change capture. A declaration with hooks or observers requires WithoutModelHooks(Orders.Query()).UpdateAll(...) (and likewise delete/force-delete); unknown executor wrappers require this explicit acknowledgement too. Per-model writes reject the acknowledgement. InsertMany retains its existing bulk semantics: no per-model hooks/observers. Observer discovery shares the generated API's concrete framework-owner lookup; it never invokes a wrapper's observer method or gives it an internal capability. Per-model writes through wrappers dispatch observers from the supplied transaction.

orm.ForceDelete(ctx, db, Orders.Query(), Orders.Soft, Orders.Key(), id) preserves default active visibility. For deleted rows use ForceDelete(ctx, db, Orders.Query().WithTrashed(), Orders.Soft, Orders.Key(), id); OnlyTrashed and other predicates are retained through locking and deletion.

Typed relation aggregate slots

Declare a non-persisted relation.Value[V] field on the model and an orm.Value[Model,V] handle on its table. Bind the handle inside Define with orm.ValueOf(b, &model.Count). Like relation slots, aggregate slots cannot carry persistence tags and do not enter write drafts or ordinary row hydration.

Bind computations after tables and relations have initialized:

var UserAggregates = struct {
    OrdersCount orm.AggregateRelation[User, int64]
    OrdersTotal orm.AggregateRelation[User, value.Nullable[decimal.Decimal]]
}{
    OrdersCount: Users.OrdersCount.Using(
        expr.Related(UserRelations.Orders, expr.Count[Order]())),
    OrdersTotal: Users.OrdersTotal.Using(
        expr.Related(UserRelations.Orders, expr.Sum(Orders.TotalCents))),
}

users, err := orm.All(ctx, db, Users.Query().With(UserAggregates.OrdersCount))
count := UserAggregates.OrdersCount.Using(expr.Related(
    UserRelations.Orders.Where(orm.Gt(Orders.TotalCents, minimum)),
    expr.Count[Order](),
))
users, err = orm.LoadMissingFrom(ctx, db, Users.Query().With(count), users)

Keep dependencies flowing from tables to relation namespaces to aggregate namespaces. Table initializers must not reference relation or aggregate namespaces; relation initializers must not reference aggregates. Compose nested eager loads at use sites, for example OrderRelations.Buyer.With(UserAggregates.OrdersCount). Wrapping a reference in a closure does not remove a Go initialization cycle.

expr.Related preserves the source model, measured model and exact aggregate result. Using retains the destination slot when replacing its computation. Computations without slot binding fail validation before execution. Different declarations of the same model remain distinct owners and cannot be mixed.

The expression aggregate rules apply unchanged: counts return int64, existence returns bool, exact sums/averages return nullable decimal, float summaries return nullable float64, interval summaries return nullable interval, and extrema retain the present field type with one nullable layer. Use the existing SumFloat/AvgFloat and SumInterval/AvgInterval constructors for those families. expr.Filter takes expression row predicates, for example expr.Filter(expr.Sum(Orders.TotalCents), expr.Gt(expr.OrderRow(expr.Value(Orders.TotalCents)), 0)). It filters the measure without hiding cardinality errors in the input relation. Relation Where restricts that input before aggregation.

A joined relation measures targets. orm.Pivot(UserRelations.Groups) measures its concrete pivot, retaining target and pivot filters and soft-delete visibility. Counts include duplicate edges; use expr.CountDistinctField(Groups.ID) for distinct targets. Missing targets and NULL join keys contribute no edges. Singular relations still reject multiple matching rows; many-to-many relations reject a pivot matching multiple targets. Direct, through and concrete morph families are supported. Aggregate sources must be framework descriptors: zero, nil and application wrappers (including embedded AggregateSource interfaces) fail validation before SQL. One-of-many and MorphTo inputs are rejected at plan validation. Inputs requesting eager target or pivot children are also rejected; load those as separate branches.

Loading uses existing With, orm.LoadFrom and orm.LoadMissingFrom, including nested target and pivot branches, transactions, locked reads and chunk windows. Each selected slot executes one grouped statement per batch of distinct eligible non-null source keys. Slots are not fused. A query adds its parent statement; explicit loads add none. Empty key sets execute no aggregate SQL. Relation ordering is omitted from grouped SQL. Shared row and attachment limits apply: each returned group consumes one row, and each computed parent slot consumes one attachment, including empty results. These limits bound returned data, not the rows examined by the database.

Get() returns the typed value and a loaded flag. A loaded zero/false/SQL NULL is preserved by orm.LoadMissingFrom; orm.LoadFrom refreshes it. No related models are hydrated to compute a summary. Errors or cancellation discard the collected result and leave caller-owned parents untouched. All statements use the supplied executor; choose transaction isolation when separate slots require one consistent snapshot.

Complete-model retrieval and global scopes

WithRetrievalHooks(func() RetrievalHooks[Order] { ... }) declares a separate read factory. Retrieved(ctx, executor, order) runs after complete stored hydration and successful row closure. Each nonempty fetch/batch constructs the local factory first, then retrieval observer factories in registration order; each model invokes local callbacks before observers. Register instance-owned read observers with NewRetrievalObserver[Order]("orders.read") and RegisterRetrievalObserver, using the existing database Module at application.New. Write and retrieval observer kinds remain distinct.

Reads use the actual rows' frozen observer owner. Unknown executor wrappers cannot prove absence and receive no internal capability. orm.Each keeps streaming when callbacks cannot run; otherwise it reads bounded, stable, closed batches before callbacks and delivery. All, pagination, chunks and loaded relation roles dispatch retrieval. A failed batch publishes no pending models. Earlier delivered batches remain delivered. Write hydration, DTO projections and scalars skip retrieval, even when their source has read callbacks. orm.Raw dispatches retrieval for its complete models while bypassing all scopes and read routing. A callback failure does not roll back SQL supplied to Raw.

Attach tenant defaults through a lazy source receiving the completed typed declaration. This avoids Go initialization cycles and snapshots declaration handles before consumers can replace their public fields:

var Orders = orm.Define("orders", declareOrders,
    orm.WithGlobalScopes(func(t OrderTable) []orm.GlobalScope[Order] {
        return []orm.GlobalScope[Order]{
            orm.Scope(t.Table, "tenant", func(ctx context.Context) (orm.Predicate[Order], error) {
                id, err := tenantID(ctx)
                return orm.Eq(t.TenantID, id), err
            }),
        }
    }),
)

The source runs once when first needed. It may construct relation predicates but must not compile or execute queries. Each scope returns an additive predicate and an error; a zero predicate, foreign declaration, missing context/tenant, invalid name, duplicate name or callback failure fails closed before SQL. Source failures, including panic and Goexit, are retained by the declaration; every later scoped operation returns the failure without executing SQL. Context values are explicit typed request metadata. There is no service registry in the context. Every terminal uses its executing context; WithScopeContext(q, ctx) only supplies context for Compile and inspection.

Scopes apply through the shared effective-predicate owner to reads, keyed and set writes, relation targets/pivots, aggregates, joins and subqueries. Inserts are unfiltered. Remove defaults for one query with WithoutGlobalScope(q, scope) or WithoutGlobalScopes(q); explicit predicates and soft-delete visibility remain. Apply these before taking a row lock. Relation package functions preserve the concrete descriptor and its other side's defaults: WithoutRelationGlobalScope, WithoutRelationGlobalScopes, WithoutPivotGlobalScope and WithoutPivotGlobalScopes. Bypasses do not mutate the source query, descriptor or declaration. Treat them as explicit authorization choices, especially for tenant scopes.

Audit capture and history

Declare model-owned policy with orm.AuditPolicyOf(Orders.Table, orm.AuditField(Orders.Note, record.Exclude)). Unspecified fields use record.Automatic; record.Redact retains change flags and hides values. A zero orm.AuditPolicy[Order] applies Automatic everywhere. Policies cannot exclude, ignore or redact the primary key while retaining it as the subject identity. Foreign columns, duplicate rules and invalid disclosures fail registration or capture. Encrypted fields use orm.AuditField for explicit Exclude, Ignore or Redact; Automatic redacts them.

Register orm.Auditing(Orders.Table, policy) through audit.Register(r, pool, recorderKey, config, declaration) in an application module. The recorder and write observer belong to that application instance. Created, Updated, Deleted and Restored capture inside the business transaction, after local callbacks. Force deletion uses Deleted once. An audit failure or a later write failure rolls back both business and audit rows. Set writes still require explicit WithoutModelHooks acknowledgement and produce no automatic audit entries. Install audit storage through the existing audit migrations.

record.Exclude omits values but preserves the update row as evidence of who changed the model and when. record.Ignore opts out of that evidence: only an update touching at least one ignored field and no other fields except ignored fields and the managed updated_at skips its audit row. An update touching only updated_at still records. created_at has no special exemption. An assigned but unchanged non-ignored field keeps the row. Creates, deletes and restores always record, omitting ignored fields; other hooks and observers still run. Use Exclude or Redact for changes that need evidence, such as secret rotation. See audit policy.

All hooked or observed models read update before-images with FOR NO KEY UPDATE, including soft deletes and restores; physical deletes use FOR UPDATE. The ORM cannot infer UNIQUE columns: changing one can upgrade the lock and cause a 40P01 deadlock with a child inserter that then updates the parent. Take explicit FOR UPDATE first using orm.Lock in the same transaction; see row locks and unique columns.

orm.Audit(Orders.Table, changes, policy) also captures a lifecycle callback's stored changes without SQL. Standalone Compare results cannot be audited. Updates, soft deletes and restores retain assigned or changed fields plus the key; creates and physical deletes retain complete snapshots subject to policy. Values come from locked originals and RETURNING, after mutators and database changes; accessors never replace them. Sensitive codecs, encrypted fields and sensitive names are redacted before their capture binder runs. Nested JSON keys are redacted by the shared record owner before binding the audit row. Fields that are neither assigned nor changed, excluded fields and ignored fields do not invoke their capture codec.

History remains record.Model[M,K]; use orm.AuditRead(history, Orders.Total) or orm.AuditReadNullable(history, Orders.Note) with stored column handles. Both also accept encrypted columns to expose redaction state. An omitted field, an absent model snapshot and SQL NULL remain distinct. Redacted fields and partially redacted JSON cannot hydrate fabricated values; inspect Snapshot() for deliberate export. The same declared codecs restore persisted keys and historical field values. Audit helpers are package functions and add no methods or per-column closures to ordinary reads.

Pivot relation writes

Relation writes are package functions. Relation descriptors retain their own chain methods; model queries and tables use the package terminals. Inputs and results retain the concrete source, target and pivot types:

pivot, err := orm.Attach(ctx, db, UserRelations.Groups, user, group,
    orm.Set(Memberships.Role, "member"))
changes, err := orm.Sync(ctx, db, UserRelations.Groups, user, groups,
    []orm.Assignment[Membership]{orm.Set(Memberships.Role, "member")}, nil)
removed, err := orm.Detach(ctx, db, UserRelations.Groups, user, group)

AttachMany, SyncWithoutDetaching, Toggle, DetachMany, DetachAll and UpdatePivot cover bounded bulk operations. Sync accepts separate create and update assignment slices; a nil update leaves retained links unchanged. Endpoint keys and morph discriminators fill omitted assignments. Explicit assignments and hooks may change them, but inserted pivots must satisfy the relation's endpoint and filter postconditions. Attach permits duplicate existing links; constraints remain the migration's responsibility. Target inputs are deduplicated by refreshed relation keys in input order. Nullable keys use their stored value type even when assignment inputs differ. If a pivot key or morph discriminator has a distinct mutator input, supply that typed assignment explicitly: its stored key cannot synthesize an input. Missing distinct inputs fail before pivot hooks and mutation SQL, matching the old API. Explicit assignments and hook replacements run the mutator once; typed draft getters retain the original input type. Single Attach rechecks both original endpoint identities and their scopes after pivot hooks, inside the same transaction.

Writes refresh and share-lock endpoint identities, skip retrieval callbacks and retain global scopes, target filters, pivot filters and soft-delete visibility. Bulk operations that read current links take FOR NO KEY UPDATE on the source to serialize competing changes. Existing links are locked in primary-key order. Like the old API, bulk sync/detachment selects existing links by pivot filters; target filters constrain requested endpoints and inserted-link checks. Detach soft-deletes when declared; ForceDetach requires a soft-delete pivot and preserves selected pivot visibility, including WithTrashedPivot().

Pivot hooks or observers select the ordinary per-model B5b lifecycle. Otherwise, create/update/removal uses one set statement per change kind. No per-row savepoints are added: each operation owns one transaction, or one savepoint inside the caller's transaction. With primary endpoint keys, attachment uses four statements for any hook-free batch (source, targets, INSERT, postcondition). Sync adds a current-links read and one statement for each nonempty update/removal; inserts also add their postcondition. Hooked inserts cost one statement per pivot; hooked updates/removals also select candidates and lock each original. Internal reads do not call Retrieved.

WithRelationWriteLimit(links, n) lowers the existing atomic row bound. Oversized inputs and current/candidate sets fail; set RETURNING rows are bounded and an excess rolls back the operation with fault.Invalid. Endpoint cardinality violations remain database.TooManyRows. Ordering and eager-child options are rejected on write relations. Empty target batches still refresh the source, as the old API does.

Errors never return successful partial results. Unknown commit and committed callback failures preserve WriteError[P], WriteError[[]P] or WriteError[PivotChanges[P]] according to the function's result. Candidate() is reconciliation data, not proof of persistence or permission to retry. After-commit callbacks remain owned by the outer transaction.

Conflicts and upserts

Upserts use package functions and an explicit immutable conflict policy:

policy := orm.OnConflict(orm.ConflictKey(Users.Email)).DoUpdate(
    orm.ConflictIncoming(Users.Name), // EXCLUDED, already transformed
    orm.ConflictNull(Users.Nickname),
)
item, err := orm.Upsert(ctx, db, Users.Query(), policy,
    orm.Set(Users.Email, "ada@example.test"), orm.Set(Users.Name, "Ada"))

Conflict captures are framework-owned. ConflictSet accepts declared column handles directly; application embedding wrappers cannot replace their setters. ConflictNull uses sealed nullable metadata and never calls an application SetNull override.

orm.ConflictSet(column, input) accepts the column's ordinary write input, including its distinct mutator input. Literal updates transform once per policy execution; ConflictIncoming copies the destination's own proposed value without transforming it twice. Omitted proposed fields use database defaults or NULL. Encrypted fields cannot be conflict update targets. OnConflictConstraint[User]("users_email_key") selects a named constraint. PostgreSQL owns constraint/index existence.

UpsertMany accepts a bounded batch of assignment slices. Both APIs skip local hooks, observers, retrieval callbacks and automatic audit, matching the generated upsert API; WithoutModelHooks is unnecessary. Mutators, encryption of proposed insert fields, timestamps and complete RETURNING hydration still apply. Managed update timestamps copy the normalized proposed instant. A skipped conflict has no returned model; batch result order does not map results to input positions.

policy.Where(...) conditions the update using the stored row. Destination global scopes also constrain DO UPDATE. An unconditional update suppressed by those scopes returns a conflict error and rolls back the whole batch. Inserts remain unfiltered. Conflicting repeated update targets are PostgreSQL errors. Caller transactions use the existing savepoint behavior; reconciliation failures retain typed candidates in WriteError. Column/constraint targets ship in slice 6e1; calculated index targets and stored/proposed row calculations belong to the next slice.

Advanced conflict expressions use orm/rows and the existing orm/expr functions:

records := rows.ConflictRowsOf(Products.Query())
stored := expr.At(records.Stored(), Products.Price)
proposed := expr.At(records.Proposed(), Products.Price)
policy := rows.OnConflictKeys(expr.Group(expr.Value(Products.Code))).
    TargetWhere(orm.Gt(Products.Price, 0)).
    DoUpdate(rows.SetConflictValue(Products.Price, expr.Add(stored, proposed)))
policy = rows.ConflictWhereRows(policy, expr.Greater(proposed, stored))

OnConflictKeys accepts row-phase index expressions. TargetWhere (or rows.ConflictTargetWhere for computed predicates) describes a partial index; its fixed migration values are rendered as schema constants. Ordinary insert inputs, update calculations and conditions remain bound parameters. PostgreSQL owns physical index compatibility. Subqueries and selected-phase expressions cannot be index targets.

ConflictRowsOf exposes complete stored and proposed records in a distinct rows.ConflictRow[M] scope. Query filters do not become conflict conditions. The proposed record includes database defaults and trigger changes. Conflict rows cannot execute or serve as standalone SELECT sources. Use rows.Correlate with them for correlated scalar calculations and existence conditions; rows.ConflictScalarRowQuery and rows.ConflictScalarNullableRowQuery handle independent scalar selections. Source declarations and global scopes remain validated, and missing tenant context fails closed before SQL.

SetConflictValue requires a declared destination and its exact stored type, including nullability. Use expr.NullableRow to widen a required result. Encrypted destinations remain excluded. A field with a Go mutator accepts only its own proposed value as a calculation; other SQL calculations cannot bypass that mutator. Upsert lifecycle, transaction and bounded RETURNING behavior are unchanged from the literal conflict API.

Insert-select and source writes

Source writes use orm/rows package functions and immutable builders. Source expressions keep their scope and exact stored type, including nullability. Mapping, match-key and operation types cannot be converted into one another:

source := rows.From(Products.Query().Where(orm.Gt(Products.Price, 0)).Limit(100))
insert := rows.InsertFrom(source, Products.Query(),
    rows.MapInsert(Products.Code, expr.Value(Products.Code)),
    rows.MapInsert(Products.Price, expr.Value(Products.Price)))
inserted, err := insert.Returning(ctx, db, 100)

matched := rows.MatchSource(Products.Key(), expr.Value(Products.Code))
update := rows.UpdateFrom(Products.Query(), source).Match(matched).
    Select(rows.MapUpdate(Products.Price, expr.Value(Products.Price)))
count, err := update.Exec(ctx, db)
count, err = rows.DeleteUsing(Products.Query(), source).Match(matched).Exec(ctx, db)

Values(assignments...) replaces fixed inputs and normalizes them once inside the owning transaction. SQL mappings cannot bypass Go mutators, copy encrypted envelopes, or replace a managed update timestamp. Updates cannot assign primary keys. Literal encrypted inputs are rejected for these set-based writes.

Omitted insert fields keep database defaults or NULL. Required fields must be mapped or supplied; UUID keys require a source/literal value or database default. No single Go-generated UUID is shared across selected rows. Managed creation time is supplied only when omitted; update time always comes from the owning clock.

Source filters, windows and tenant scopes remain intact. Destination scopes apply to updates and deletes; inserts are unfiltered. Missing tenant context fails closed. MatchNullableSource allows nullable keys; NULL matches no destination. Mapped updates require at most one source match per affected model and roll back on ambiguity. Literal-only updates and deletes tolerate repeated source keys.

Exec returns an affected count. Returning accepts a limit from 1 through orm.MaxInsertRows (1000), hydrates complete models, and rolls back on overflow, decode failure or row-close failure. The limit bounds retained models, not SQL work or field sizes; it neither truncates the source nor promises result order.

These explicit set-based APIs skip local hooks, observers, automatic audit and retrieval callbacks, matching the old source-write API. No WithoutModelHooks acknowledgement is required. They retain the existing transaction/savepoint and write-outcome reconciliation behavior. DeleteUsing applies soft deletion when configured; ForceDeleteUsing requires a soft-delete declaration and preserves the supplied destination visibility (WithTrashed includes deleted rows).

Scoped keyed writes

Use package functions when a primary-key write must also retain an existing selection, such as a tenant boundary:

visible := Users.Query().Where(orm.Eq(Users.TenantID, tenantID))
user, err := orm.Update(ctx, tx, visible, Users.Key(), id, orm.Set(Users.Name, "Ada"))
removed, err := orm.Delete(ctx, tx, visible, Users.Key(), id)

Both predicates constrain the write. The key must come from that exact table declaration. Ordinary lifecycle hooks, observers, complete returning hydration, savepoints and single-row cardinality checks remain active. A scope mismatch returns database.NotFound. Delete uses soft deletion when declared; otherwise it physically removes the row. Unknown commit outcomes retain WriteError reconciliation candidates and must not be retried automatically.

UUID seeks and bounded lifecycle writes

Use UUIDLess, UUIDLessOrEqual, UUIDGreater and UUIDGreaterOrEqual for PostgreSQL bytewise UUID comparisons. Both the query model and model.ID[T] owner remain checked by Go. Nullable UUID columns compare present values; SQL NULL does not match. The corresponding expr functions accept scoped row expressions; use their Nullable variants for nullable row values. They add no column methods.

page := Files.Query().Where(orm.UUIDGreater(Files.Key(), after)).
    OrderBy(orm.Asc(Files.Key())).Limit(100)

UpdateEach(ctx, writer, query, limit, draft) accepts a callback of type func(context.Context, *database.Tx, M) ([]orm.Assignment[M], error). DeleteEach(ctx, writer, query, limit) performs normal physical or soft deletion. RestoreEach(ctx, writer, query, soft, limit) restores only trashed candidates. ForceDeleteEach(ctx, writer, query, soft, limit) physically deletes candidates, preserving the query’s active/trashed visibility. Both require the declaration’s SoftDeletable[M] token, such as Users.Soft; foreign or zero tokens fail before I/O.

All four operations lock the complete candidate set in primary-key order, require a positive limit no greater than MaxPerModelWriteRows, and reject overflow and duplicate identities before any draft or lifecycle callback. Incoming lock policies are rejected; candidate selection waits with FOR NO KEY UPDATE for SQL updates (including soft deletes and restores) and FOR UPDATE for physical and force deletes. The UNIQUE-column caveat also applies to batches. Ordering, pagination, eager-loading options and WithoutModelHooks are rejected.

Each row uses the normal hooks, observers, mutators, encryption, timestamps and change tracking. Internal candidate hydration skips retrieval hooks. Rows are closed before callbacks; propagate the supplied callback context and transaction to nested work. One atomic transaction (or one enclosing savepoint on a supplied transaction) covers all candidates, with no savepoint per model. Cancellation, callback failures and later write failures roll back the operation and discard its after-commit work. Successful results follow primary-key order.

An uncertain commit or committed after-commit failure returns no successful rows. *orm.WriteError[[]M] retains reconciliation candidates; Candidate() is not proof of persistence. There is no automatic retry. These bounded lifecycle operations differ from set-based UpdateAll/DeleteAll, which explicitly skip per-model behavior.

Declaration roles

Declare managed timestamp pairs with orm.CreatedAt/orm.CreatedAtOf and orm.UpdatedAt/orm.UpdatedAtOf. These columns retain ordinary time predicates, ordering, projections and aggregates. A managed field declared through TimeOf fails startup validation with the field name and the required constructor. A lone, unmanaged creation timestamp keeps TimeOf and its existing database-default behavior; NoTimestamps continues to disable conventional timestamp management.

Mutated fields use Input* declarations even when input and stored types match: orm.InputTextOf[User, string](b, &m.Name, nil) discovers MutateName; passing a transform function declares it explicitly. Ordinary columns with mutators fail startup. Each Input capability family has a distinct private layout: converting a column or enum into an ordered input field is rejected by the compiler.

Table.Key() is for lookup and ordinary key assignments. NumberKey and TextKey preserve that role. Applications need PrimaryOf only when mapping a primary key in insert-select: declare ID orm.Primary[User, int64] and bind it with orm.PrimaryOf(b, table.Key()). orm.NumberKey and orm.TextKey retain the key's role. PrimaryOf cannot coexist with InputKeyOf; neither lookup keys nor mutated input keys can be used as insert-select targets. All primary roles are excluded from source-update targets.

Expose soft-delete authority as an ordinary declaration field:

type UserFields struct {
    orm.Table[User, int64]
    DeletedAt orm.SoftDelete[User, time.Time]
    Soft orm.SoftDeletable[User]
}
// Inside Define:
deleted := orm.SoftDeleteOf(b, &m.DeletedAt)
fields := UserFields{table, deleted, orm.SoftDeletes(deleted)}
// After declaration:
_, err := orm.ForceDelete(ctx, db, Users.Query().WithTrashed(), Users.Soft, Users.Key(), id)

Every force-delete entry point requires this token, including ForceDeleteAll, rows.ForceDeleteUsing and pivot ForceDetach. Tokens are bound to the exact model declaration; zero and foreign-declaration tokens fail before SQL. Query visibility remains unchanged. Normal soft deletion does not require the token.

rows.MapInsert and rows.MapUpdate take the column directly and accept only columns whose role allows the mapping. Both reject Input fields and managed update timestamps; creation timestamps remain eligible. Embedding a column in an application wrapper does not grant mapping eligibility. Runtime declaration, ownership and SQL-mapping checks remain active.

Framework adapters

Extension fields remain ordinary translations.Text, attachments.One[M], attachments.Many[M] and metadata.Value[V] values on the model. Bind each with orm.SlotOf(b, &m.Title) inside Define; it adds no persisted column. Declare policies separately with translations.TextOf, attachments.OneOf / ManyOf and metadata.ValueOf, passing extensions.BindSlot(Articles.Key(), Articles.Title). The owner comes from extensions.DefineORMOwner("articles", orm.IdentityOf(Articles.Table, Articles.Key()), extensions.OwnerOptions{StorageModel: "articles"}). Keep that storage identity pinned across table renames.

Bind each descriptor to its concrete manager once, then pass bound.Title.Relation(Articles.Title) to a query with With, then use orm.LoadFrom or orm.LoadMissingFrom. This uses the existing extension fetcher and shared relation row budgets, including loaded-empty values and batch splitting. Register slots.DeclareORM(owner, parts) through the existing model-extension assembly to retain deletion cleanup. Runtime managers never live in the table.

HTTP binding accepts modelbinding.ByKey(db, orm.Keyed(Users.Query(), Users.Key()), pathKey). Use ByColumn for a unique alternate key, ThroughRelation for a direct parent relationship, and ThroughSelectedRelation to retain earlier nested models. Duplicate matches fail before eager loading; missing or out-of-scope matches keep the existing 404 behavior. Binding does not acquire authorization or locks.

factory.Define(Users.Table, build) accepts a builder returning []orm.Assignment[User]. Existing states, relationship composition and after-create hooks work with that concrete draft type. Batch creation uses orm.InsertEach, which invokes every row's lifecycle in one bounded transaction, with one enclosing savepoint for a caller-owned transaction. Unknown outcomes remain failures with reconciliation candidates; no automatic retry occurs. Factories and binding adapters use handwritten declarations.

Pagination adapters consume orm.PageResult, orm.SimplePage, orm.CursorRequest and orm.CursorPage. These expose the shared SQL pagination contracts in internal/querycore. Validation, field shapes, cursor bytes and redacted formatting are unchanged; the reflected defining package is now the shared owner. Applications continue using the public aliases. HTTP pagination retains the published cursor schema identity, so manifests and generated clients do not inherit the implementation package move.

The extension namespace uses TextHandle, OneHandle, ManyHandle and ValueHandle: direct typed methods over private, non-generic callback state. These handles reuse the existing managers and preserve publication outcomes; they do not expose legacy Field, Collection or Key descriptor families. OneHandle and ManyHandle remain distinct, non-convertible capabilities. Lookup diagnostics (Keyed, Unique, RelatedUnique) redact scoped values under ordinary, detailed and Go-syntax formatting.

Diagnostic redaction

ORM query handles redact retained predicate literals, bound data values, assignment inputs, numeric guard bounds, cursor tokens, plan contents and fixed pivot bindings from fmt formatting and interpolating errors such as fmt.Errorf("query: %+v", q). This includes %v, %+v and %#v through private and nested wrapper fields. Structural query metadata, including LIMIT/OFFSET, identifiers and SQL shape, is outside this guarantee and may remain visible, even when the compiler sends it as a parameter. Compiled statement formatting omits its retained SQL text too, because explicit raw SQL can contain literals.

Explicit accessors such as Statement.SQL(), Statement.Arguments(), Cursor.Token(), mutation input readers and Plan.Root()/Plan.JSON() still return their inspection data. Formatting the returned data is an explicit disclosure; the guarantee does not redact hydrated models or page items.

Lifecycle terminals and query plans

CreateEach(ctx, db, query, drafts) runs one normal creation lifecycle per input, atomically, in input order. A valid empty batch does not acquire a transaction. CreateOrFirst(ctx, db, query, assignments...) tries insertion first in a savepoint. Only a unique violation from that INSERT on the model's own table allows recovery: after rollback, it reads the first matching competitor. Recovery requires server-reported schema, table and constraint metadata matching the resolved destination; missing metadata preserves the violation. Hooks, observers, hydration errors and uncertain outcomes never trigger recovery or retry. The query must select the conflicting row; snapshot isolation can hide a competitor, in which case the violation is returned. Internal reads skip Retrieved. FirstOrCreate locks the first primary-ordered match, while UpdateOrCreate accepts separate creation assignments and a typed update callback. Only the chosen branch prepares assignments. Omitted creation fields inherit unambiguous top-level equality predicates, including global scopes; mutated fields require explicit input. A created row must satisfy the original query. Concurrent absent rows rely on physical unique constraints; these functions do not retry. Internal model reads skip retrieval callbacks. Read ordering, windows and eager loads are rejected.

PruneBatch(ctx, db, query, size, mass) physically removes a bounded batch of ordinary models. Soft-delete models use ForcePruneBatch(ctx, db, query, soft, size, mass) with their declaration token. Selection locks rows in primary-key order and preserves filters and visibility. With mass=false, every model runs its deletion lifecycle. mass=true explicitly acknowledges one DELETE without per-model hooks, observers or audit. Each batch is atomic. prune.ORMModel and prune.ORMSoftModel register these operations with the bounded prune registry. The registry uses orm.MaxPerModelWriteRows.

Explain returns a bounded typed PostgreSQL Plan without running the SELECT; ExplainAnalyze explicitly executes it. Neither hydrates models, dispatches retrieval callbacks nor runs eager loads. Locked models use orm.ExplainLocked or orm.ExplainAnalyzeLocked, requiring *database.Tx. The corresponding rows functions accept ordinary Result, locked results or transaction-owned records and scalars. Adapt projections, scalars and sets through the existing rows.Read* functions. rows.ExplainCursor/ExplainValueCursor and their Analyze variants plan canonical cursor ordering without adding a page boundary. Plan formatting is redacted; explicit Root and JSON accessors return owned snapshots and may expose server predicates and bound values.

Numeric adjustments use orm.Increment, orm.Decrement and their nullable equivalents. Amounts are positive and finite; AtMost guards increments and AtLeast guards decrements. Numeric primary and lookup keys (orm.NumberKey) expose comparisons, ordering and identity assignment, but no numeric adjustment functions. Managed timestamps and input columns also have no numeric adjustment capability. A guarded per-key update returning no row distinguishes visible bound rejection (ErrBoundExceeded) from a missing or hidden key (database.NotFound).

Projection callbacks use rows.EachRead(ctx, db, rows.Read(report), consume). They receive one fully decoded value at a time while rows remain open. Callback errors stop further decoding and close the result; values already consumed remain consumed if a later decode or close fails. Use report.All when the caller needs an all-or-error slice.

Advisory validation lookups

validation/database accepts an ORM model query and one typed stored column:

available := databasevalidation.Unique(db, Users.Query(), Users.Email)
active := databasevalidation.Exists(db, Users.Query().Where(orm.Eq(Users.Status, StatusActive)), Users.Key())

orm.Lookup(Users.Query(), Users.Email) is the underlying observation handle. It preserves filters, global scopes, soft-delete visibility and stored codecs, without hydrating models, retrieval hooks or implicit transactions. Nullable and mutated columns accept their non-null stored value type. Batch observations use SQL equality in groups of 64; empty lists perform no I/O. Ordered, paginated, eager-loaded and locked sources cannot be used as complete lookup scopes.

databasevalidation.Scoped derives a scope at check time; databasevalidation.UniqueIgnoring derives a typed key exclusion from a supplied validation.Slot. Keep tenant predicates and derive exclusions from trusted route or actor data. Errors never prove availability. These reads are advisory: database constraints still govern writes. See validation for composition and safe metadata exports.

Shared extension loading

Declaration-based attachment, translation and metadata handles use the shared external-slot loader in internal/extensionslot. Public handles retain concrete owner, key and value types through direct method shells over private callback state. Loading keeps per-slot parent batches, loaded-empty values, separate fetched and attached budgets, and the caller's executor. Failed fetches do not attach an incomplete batch tree.

FoundryExtension requires a validated query-family capability and accepts concrete framework slot state. Capabilities never reach slot accessors or application callbacks. Owners retain concrete ORM identity and scope declarations.

Bounded Explain execution and plan decoding also share querycore. The public orm.Plan/PlanNode retain their methods and data contract; their defining Go package is now the internal shared owner.

Consumer resource limits

Use the public constants in orm when bounding application requests or batches. They refer to the compiler's shared limits; expr and rows use the same limits and do not publish alternate spellings.

Constants What applications can bound
MaxInsertRows, MaxParameters Rows in an insert/upsert and parameters in the entire statement; wide rows can require smaller batches.
MaxPerModelWriteRows, MaxRelationWriteRows One atomic lifecycle batch or relation write.
MaxIdentityBatch Keys supplied to an identity observation or extension scope.
MaxChunkSize, DefaultChunkSize Explicit model chunks and the default closed batches for eager/observed iteration.
MaxPageSize Requested page size.
MaxCursorBytes, MaxCursorFields Encoded cursor size and ordered cursor-key fields.
MaxMembershipValues Values in a membership predicate.
MaxExpressionDepth, MaxExpressionNodes, MaxScalarSQLBytes Dynamic expression construction and computed scalar SQL size.

These are upper bounds, not a promise that every combination is valid. Query compilation still validates ownership, phases, ordering and the combined statement. Independent CTE scopes share statement-wide compilation budgets. Ordinary bind values count toward MaxParameters; they are not interpolated into SQL.

Plan-decoder budgets and lifecycle callback recursion guards remain internal implementation bounds.

Documentation

Overview

Package orm declares typed tables without generated model adapters. For example: orders := Define("orders", func(b Builder[Order], o *Order) OrderTable { ... }).

Index

Constants

View Source
const DefaultChunkSize = querycore.DefaultChunkSize

DefaultChunkSize is the closed-batch size used by model iteration with eager relations or retrieval callbacks.

View Source
const MaxChunkSize = querycore.MaxChunkSize

MaxChunkSize is the existing bound on one model batch.

View Source
const MaxCursorBytes = querycore.MaxCursorBytes

MaxCursorBytes bounds the encoded cursor token accepted by ParseCursor.

View Source
const MaxCursorFields = querycore.MaxCursorFields

MaxCursorFields bounds the ordered fields in one cursor key.

View Source
const MaxExpressionDepth = querycore.MaxExpressionDepth

MaxExpressionDepth bounds nested expression and SELECT compilation.

View Source
const MaxExpressionNodes = querycore.MaxExpressionNodes

MaxExpressionNodes bounds expression and SELECT compilation work.

View Source
const MaxIdentityBatch = querycore.MaxIdentityBatch

MaxIdentityBatch bounds keys in one identity observation or extension scope.

View Source
const MaxInsertRows = querycore.MaxInsertRows

MaxInsertRows bounds rows in one atomic insert or upsert statement. The statement-wide MaxParameters limit can require smaller batches.

View Source
const MaxMembershipValues = querycore.MaxMembershipValues

MaxMembershipValues bounds the values in one membership predicate.

View Source
const MaxPageSize = querycore.MaxPageSize

MaxPageSize is the shared pagination bound. Example: size <= orm.MaxPageSize.

View Source
const MaxParameters = querycore.MaxParameters

MaxParameters bounds bound parameters across the whole SQL statement.

View Source
const MaxPerModelWriteRows = querycore.MaxPerModelWriteRows

MaxPerModelWriteRows bounds one atomic lifecycle batch. Example: limit <= orm.MaxPerModelWriteRows.

View Source
const MaxRelationWriteRows = querycore.MaxPerModelWriteRows

MaxRelationWriteRows bounds one atomic relation write. Example: len(targets) <= orm.MaxRelationWriteRows.

View Source
const MaxScalarSQLBytes = querycore.MaxScalarSQLBytes

MaxScalarSQLBytes bounds SQL emitted by computed scalar operations.

Variables

View Source
var ErrBoundExceeded = safeerror.New("numeric adjustment bound exceeded")

ErrBoundExceeded means a guarded per-key adjustment rejected a visible row. A missing or hidden key returns database.NotFound instead.

Functions

func All added in v0.2.0

func All[M any](ctx context.Context, ex database.Executor, q Query[M]) ([]M, error)

All hydrates complete models, discarding partial results on failure. Example: orm.All(ctx, db, Orders.Query()).

func AllLocked added in v0.2.0

func AllLocked[M any](ctx context.Context, tx *database.Tx, q LockedQuery[M]) ([]M, error)

AllLocked reads locked rows within a transaction. Example: orm.AllLocked(ctx, tx, orm.Lock(Orders.Query())).

func Attach

func Attach[M, N, P any](ctx context.Context, writer database.Transactor, r ThroughRelation[M, N, P], source M, target N, create ...Assignment[P]) (P, error)

Attach creates one pivot with omitted endpoint keys supplied from locked models. Example: orm.Attach(ctx,db,UserRelations.Groups,user,group,orm.Set(Memberships.Role, "member")).

func AttachMany

func AttachMany[M, N, P any](ctx context.Context, writer database.Transactor, r ThroughRelation[M, N, P], source M, targets []N, create ...Assignment[P]) ([]P, error)

AttachMany creates one pivot per distinct refreshed target key, retaining duplicate existing links. Example: orm.AttachMany(ctx,db,UserRelations.Groups,user,groups,orm.Set(Memberships.Role, "member")).

func Audit

func Audit[M any, K comparable](table Table[M, K], changes Changes[M], policy AuditPolicy[M]) (auditrecord.Model[M, K], error)

Audit captures an automatic operation's stored changes without getters, mutators or SQL. Example: history, err := Audit(Orders.Table, changes, AuditPolicy[Order]{}).

func AuditRead

func AuditRead[M, K, V, I, P any, Kind RequiredAnyColumnKind, R ColumnRole](history auditrecord.Model[M, K], field ColumnHandle[M, V, I, P, Kind, R]) (value.Optional[auditrecord.FieldChange[V]], error)

AuditRead reads a required historical field through its stored codec (including encrypted redaction state); omitted fields remain absent. Example: field, err := orm.AuditRead(history, Orders.TotalCents).

func AuditReadNullable

func AuditReadNullable[M, K, V, I, P any, Kind NullableColumnKind, R ColumnRole](history auditrecord.Model[M, K], field ColumnHandle[M, V, I, P, Kind, R]) (value.Optional[auditrecord.FieldChange[value.Nullable[V]]], error)

AuditReadNullable keeps SQL NULL separate from an omitted field or absent model (including nullable encrypted redaction state). Example: field, err := orm.AuditReadNullable(history, Orders.Note).

func Auditing

func Auditing[M any, K comparable](table Table[M, K], policy AuditPolicy[M]) auditrecord.Declaration

Auditing registers an instance-owned observer through audit.Register, inside the business transaction. Example: audit.Register(r, pool, recorderKey, config, Auditing(Orders.Table, policy)).

func ChangeOf

func ChangeOf[M, V, I, P any, K RequiredAnyColumnKind, R ColumnRole](changes Changes[M], field ColumnHandle[M, V, I, P, K, R]) (lifecycle.FieldChange[V], error)

ChangeOf selects a required persisted field with its stored type (including encrypted fields using decoded equality). Example: orm.ChangeOf(changes, Orders.TotalCents).

func Check

func Check(tables ...CheckedTable) error

Check reports every declaration error. Example: if err := Check(Orders); err != nil { return err }.

func Chunk added in v0.2.0

func Chunk[M any](ctx context.Context, ex database.Executor, q Query[M], size int, yield func([]M) error) error

Chunk reads stable, bounded batches, closing rows before each callback. It preserves the query window and advances by keyset when ordering permits; explicit NULL placement falls back to offsets. It does not create a snapshot.

func ChunkByKey

func ChunkByKey[M any, K comparable, I, P any, Kind ColumnKind, R ColumnRole](ctx context.Context, ex database.Executor, q Query[M], key ColumnHandle[M, K, I, P, Kind, R], size int, yield func([]M) error) error

ChunkByKey advances by the declared primary key, with rows closed before each callback. Only key ordering and zero Offset are accepted; Limit bounds total delivery. Keys are captured before callbacks. Keep keys stable: batches do not share a snapshot. Example: orm.ChunkByKey(ctx, db, Orders.Query(), Orders.ID, 500, visit).

func Count added in v0.2.0

func Count[M any](ctx context.Context, ex database.Executor, q Query[M]) (int64, error)

Count counts the selected window. Example: orm.Count(ctx, db, Orders.Query()).

func CreateEach

func CreateEach[M any](ctx context.Context, writer database.Transactor, q Query[M], drafts [][]Assignment[M]) ([]M, error)

CreateEach runs each creation lifecycle in one bounded atomic transaction. Unlike InsertMany, callbacks run per model; a valid empty batch performs no SQL. Example: orm.CreateEach(ctx, db, Users.Query(), [][]orm.Assignment[User]{{orm.Set(Users.Name, "Ada")}}).

func CreateOrFirst

func CreateOrFirst[M any](ctx context.Context, writer database.Transactor, q Query[M], create ...Assignment[M]) (M, error)

CreateOrFirst creates through the model lifecycle in a savepoint, then reads the first primary-ordered match only if its own INSERT violates a unique index on this table. Failed hooks and uncertain outcomes never trigger recovery or retries. At snapshot isolation a competitor may be invisible; the original violation is then returned. Internal hydration skips Retrieved callbacks. Example: orm.CreateOrFirst(ctx, db, Users.Query().Where(orm.Eq(Users.Email, email)), orm.Set(Users.Name, name)).

func Define

func Define[M any, T CheckedTable](name string, declare func(Builder[M], *M) T, opts ...Option) (result T)

Define binds and seals one table, collecting errors for Check. Example: Define("orders", declare).

func Delete

func Delete[M any, K comparable](ctx context.Context, writer database.Transactor, q Query[M], key Key[M, K], id K) (M, error)

Delete removes one primary key within the query's current visibility and returns its complete model. Declared soft deletion retains the physical row; otherwise deletion is physical. Example: orm.Delete(ctx, db, visible, Users.Key(), id).

func DeleteAll added in v0.2.0

func DeleteAll[M any](ctx context.Context, tx database.Transactor, q Query[M]) (int64, error)

DeleteAll removes matching rows, respecting soft deletion. Example: orm.DeleteAll(ctx, tx, Orders.Query().Where(orm.Eq(Orders.ID, id))).

func DeleteEach

func DeleteEach[M any](ctx context.Context, writer database.Transactor, q Query[M], limit int) ([]M, error)

DeleteEach removes each active candidate through ordinary delete/soft-delete lifecycle callbacks. Overflow fails before callbacks, and later failures roll back the complete batch and its after-commit work. Results follow primary keys. Example: orm.DeleteEach(ctx,db,Notifications.Query().Where(orm.Eq(Notifications.Read, true)),100).

func Detach

func Detach[M, N, P any](ctx context.Context, writer database.Transactor, r ThroughRelation[M, N, P], source M, target N) ([]P, error)

Detach removes matching active pivots, retaining soft-delete behavior and lifecycle. Example: orm.Detach(ctx,db,UserRelations.Groups,user,group).

func DetachAll

func DetachAll[M, N, P any](ctx context.Context, writer database.Transactor, r ThroughRelation[M, N, P], source M) ([]P, error)

DetachAll removes the source's links selected by pivot filters. Example: orm.DetachAll(ctx,db,UserRelations.Groups,user).

func DetachMany

func DetachMany[M, N, P any](ctx context.Context, writer database.Transactor, r ThroughRelation[M, N, P], source M, targets []N) ([]P, error)

DetachMany removes all links to the requested targets within pivot filters. Example: orm.DetachMany(ctx,db,UserRelations.Groups,user,groups).

func Each added in v0.2.0

func Each[M any](ctx context.Context, ex database.Executor, q Query[M], yield func(M) error) error

Each streams models while rows remain open when retrieval cannot run. Otherwise it uses closed complete batches, dispatching Retrieved before yielding models. Rows yielded before a later failed batch remain yielded.

func EachByKey

func EachByKey[M any, K comparable, I, P any, Kind ColumnKind, R ColumnRole](ctx context.Context, ex database.Executor, q Query[M], key ColumnHandle[M, K, I, P, Kind, R], size int, yield func(M) error) error

EachByKey yields individual models from complete primary-key batches. Example: orm.EachByKey(ctx, db, Orders.Query(), Orders.ID, 500, visit).

func EachChunked added in v0.2.0

func EachChunked[M any](ctx context.Context, ex database.Executor, q Query[M], size int, yield func(M) error) error

EachChunked yields individual models from fully read and closed batches.

func EachLocked added in v0.2.0

func EachLocked[M any](ctx context.Context, tx *database.Tx, q LockedQuery[M], yield func(M) error) error

EachLocked streams locked models in the transaction.

func Exists added in v0.2.0

func Exists[M any](ctx context.Context, ex database.Executor, q Query[M]) (bool, error)

Exists checks the selected window. Example: orm.Exists(ctx, db, Orders.Query()).

func Find added in v0.2.0

func Find[M any, K comparable](ctx context.Context, ex database.Executor, t Table[M, K], key K) (value.Optional[M], error)

Find selects by a typed primary key. Example: orm.Find(ctx, db, Orders.Table, id).

func First added in v0.2.0

func First[M any](ctx context.Context, ex database.Executor, q Query[M]) (value.Optional[M], error)

First returns an omitted Optional on no match. Example: orm.First(ctx, db, Orders.Query()).

func FirstLocked added in v0.2.0

func FirstLocked[M any](ctx context.Context, tx *database.Tx, q LockedQuery[M]) (value.Optional[M], error)

FirstLocked reads at most one locked row. Example: orm.FirstLocked(ctx, tx, orm.ForShare(Orders.Query())).

func FirstOrCreate

func FirstOrCreate[M any](ctx context.Context, writer database.Transactor, q Query[M], create ...Assignment[M]) (M, error)

FirstOrCreate locks the first primary-ordered match or creates through its lifecycle. Equality filters and scopes default omitted stored fields; mutator inputs need explicit assignments. Concurrent absence relies on unique constraints, without retries. Internal reads skip Retrieved. Example: orm.FirstOrCreate(ctx, db, Users.Query().Where(orm.Eq(Users.Email, email)), orm.Set(Users.Name, name)).

func ForceDelete

func ForceDelete[M any, K comparable](ctx context.Context, writer database.Transactor, q Query[M], soft SoftDeletable[M], key Key[M, K], id K) (M, error)

ForceDelete physically deletes one key within the query's current visibility. Example: ForceDelete(ctx,db,Orders.Query().WithTrashed(),Orders.Soft,Orders.Key(),id).

func ForceDeleteAll added in v0.2.0

func ForceDeleteAll[M any](ctx context.Context, tx database.Transactor, q Query[M], soft SoftDeletable[M]) (int64, error)

ForceDeleteAll physically deletes matching rows within the selected scope.

func ForceDeleteEach

func ForceDeleteEach[M any](ctx context.Context, writer database.Transactor, q Query[M], soft SoftDeletable[M], limit int) ([]M, error)

ForceDeleteEach physically deletes selected soft-delete models in one bounded transaction, preserving the query's visibility and running each force-delete lifecycle. Returned models describe their persisted state before deletion. Example: orm.ForceDeleteEach(ctx, db, Users.Query().OnlyTrashed(), Users.Soft, 100).

func ForceDetach

func ForceDetach[M, N, P any](ctx context.Context, writer database.Transactor, r ThroughRelation[M, N, P], soft SoftDeletable[P], source M, target N) ([]P, error)

ForceDetach physically removes matching soft-delete pivots in the selected visibility. Example: orm.ForceDetach(ctx,db,UserRelations.Groups.WithTrashedPivot(),Memberships.Soft,user,group).

func ForcePruneBatch

func ForcePruneBatch[M any](ctx context.Context, writer database.Transactor, q Query[M], soft SoftDeletable[M], size int, mass bool) (int64, error)

ForcePruneBatch physically removes a bounded soft-model batch within its visibility. Mass acknowledges skipping hooks, observers and change capture; selection still locks rows. Example: orm.ForcePruneBatch(ctx, db, Users.Query().OnlyTrashed(), Users.Soft, 100, false).

func FoundryCodec

func FoundryCodec[V any](option ColumnOption[V], seal sqlowner.MetadataSeal) codec.Codec[V]

FoundryCodec supplies an explicit codec option to the row declaration package. Example: FoundryCodec(option, sqlowner.Metadata()).

func FoundryComparisonHandle added in v0.48.0

func FoundryComparisonHandle[M, V, I, P any, K ColumnKind, R ColumnRole](c ColumnHandle[M, V, I, P, K, R], seal sqlowner.MetadataSeal) ormcore.Column[V]

FoundryComparisonHandle supplies the comparison codec for a queryable ColumnHandle to expr/rows.

func FoundryConflictData

func FoundryConflictData[M any](policy Conflict[M], seal sqlowner.ExpressionSeal) ormcore.ConflictPolicy

FoundryConflictData supplies policy data to the expression owner. Example: FoundryConflictData(policy,sqlowner.Expressions()).

func FoundryHandle added in v0.48.0

func FoundryHandle[M, V, I, P any, K ColumnKind, R ColumnRole](c ColumnHandle[M, V, I, P, K, R], seal sqlowner.MetadataSeal) (ormcore.Column[V], ormcore.Column[P])

FoundryHandle supplies comparison and projection codecs for a queryable ColumnHandle to expr/rows.

func FoundryLockedRecord

func FoundryLockedRecord[M any](q LockedQuery[M], seal sqlowner.MetadataSeal) ormcore.RecordSource

FoundryLockedRecord retains the model's lock inside a transaction-only record. Example: FoundryLockedRecord(orm.Lock(Orders.Query()),sqlowner.Metadata()).

func FoundryModel

func FoundryModel[M any](q Query[M], seal sqlowner.MetadataSeal) (ormcore.Source, func(database.Row) (M, error))

FoundryModel supplies a validated model source and its existing hydration codec. Example: FoundryModel(q,sqlowner.Metadata()).

func FoundryModelRead

func FoundryModelRead[M any](q Query[M], seal sqlowner.MetadataSeal) ormcore.RecordSource

FoundryModelRead retains complete hydration, retrieval and eager-load ownership. Example: FoundryModelRead(Users.Query().With(UserRelations.Orders),sqlowner.Metadata()).

func FoundryNullableHandle added in v0.48.0

func FoundryNullableHandle[M, V, I, P any, K NullableComparableKind, R ColumnRole](c ColumnHandle[M, V, I, P, K, R], seal sqlowner.MetadataSeal) (ormcore.Column[V], ormcore.Column[value.Nullable[V]])

FoundryNullableHandle supplies comparison and nullable-projection codecs for a nullable queryable ColumnHandle.

func FoundryPredicate

func FoundryPredicate[M any](p Predicate[M], seal sqlowner.MetadataSeal) ormcore.Predicate

FoundryPredicate retains model declaration ownership in a projection. Example: FoundryPredicate(p,sqlowner.Metadata()).

func FoundryRecord

func FoundryRecord[M any](scope ormcore.Scope, seal sqlowner.MetadataSeal) ormcore.Record

FoundryRecord supplies complete model metadata through the validated metadata family. Example: FoundryRecord[Order](scope,sqlowner.Metadata()).

func FoundryRelatedValue

func FoundryRelatedValue[M, N, V any](source AggregateSource[M, N], expression ormcore.Expression, column ormcore.Column[V], seal sqlowner.ExpressionSeal) ormcore.Expression

FoundryRelatedValue retains validated relation ownership in a row expression. Example: FoundryRelatedValue(source,expression,column,sqlowner.Expressions()).

func FoundrySlot

func FoundrySlot[M any, K comparable, S any](key Key[M, K], slot Slot[M, S], seal sqlowner.MetadataSeal) (string, func(M) model.Reference[M, K], func(M) S, func(M, S) M, error)

FoundrySlot provides typed accessors only to framework metadata adapters. Example: orm.FoundrySlot(Articles.Key(),Articles.Title,sqlowner.Metadata()).

func FoundrySource

func FoundrySource[M any](q Query[M], seal sqlowner.MetadataSeal) ormcore.Source

FoundrySource supplies sealed model AST metadata to rows. Example: FoundrySource(Orders.Query(),sqlowner.Metadata()).

func Insert added in v0.2.0

func Insert[M any, K comparable](ctx context.Context, tx database.Transactor, t Table[M, K], as ...Assignment[M]) (M, error)

Insert creates and hydrates one model. Example: orm.Insert(ctx, tx, Orders.Table, orm.Set(Orders.TotalCents, 10), orm.Set(Orders.BuyerID, buyer)).

func InsertEach

func InsertEach[M any, K comparable](ctx context.Context, writer database.Transactor, table Table[M, K], rows [][]Assignment[M]) ([]M, error)

InsertEach runs each row's ordinary lifecycle in one bounded transaction. A nested caller gets one savepoint for the batch, never one per row. Example: orm.InsertEach(ctx,db,Users.Table,[][]orm.Assignment[User]{{orm.Set(Users.Name, "Ada")}}).

func InsertMany added in v0.2.0

func InsertMany[M any, K comparable](ctx context.Context, tx database.Transactor, t Table[M, K], rows [][]Assignment[M]) ([]M, error)

InsertMany inserts one bounded atomic batch and hydrates RETURNING rows.

func LoadFrom

func LoadFrom[M any](ctx context.Context, ex database.Executor, q Query[M], parents []M) ([]M, error)

LoadFrom loads the query's relations onto copies of existing parents using its relation limits. Parent filters and windows are validated but do not re-fetch or filter supplied models. Errors publish no partial result. Example: loaded, err := orm.LoadFrom(ctx, db, q.With(OrderRelations.Buyer), orders).

func LoadMissingFrom

func LoadMissingFrom[M any](ctx context.Context, ex database.Executor, q Query[M], parents []M) ([]M, error)

LoadMissingFrom uses the query's relation limits while preserving loaded slots, including loaded-empty slots. It performs no parent statement. Example: loaded, err := orm.LoadMissingFrom(ctx, db, q.With(OrderRelations.Buyer), orders).

func NullableChangeOf

func NullableChangeOf[M, V, I, P any, K NullableColumnKind, R ColumnRole](changes Changes[M], field ColumnHandle[M, V, I, P, K, R]) (lifecycle.FieldChange[value.Nullable[V]], error)

NullableChangeOf retains SQL NULL independently of model existence (including nullable encrypted fields). Example: orm.NullableChangeOf(changes, Members.Note).

func PruneBatch

func PruneBatch[M any](ctx context.Context, writer database.Transactor, q Query[M], size int, mass bool) (int64, error)

PruneBatch physically removes at most size ordinary models in primary-key order. Mass explicitly skips per-model callbacks; otherwise ordinary deletion lifecycle runs. Soft-delete declarations require ForcePruneBatch and their declaration token. Example: orm.PruneBatch(ctx, db, Logs.Query().Where(orm.Eq(Logs.Expired, true)), 100, false).

func Raw added in v0.2.0

func Raw[M any, K comparable](ctx context.Context, ex database.Executor, t Table[M, K], sql string, args ...any) ([]M, error)

Raw hydrates the exact declared column set, matched by name in any order. It applies NO scopes, including soft-delete and tenant/global scopes, and uses ex directly without read routing: raw SQL may write. Supply bound arguments. Example: orm.Raw(ctx, tx, Orders.Table, "UPDATE orders SET total_cents=$1 RETURNING *", cents). Retrieved hooks and observers run after complete hydration and row closure. Decode/open/hook failure discards results; this does not imply a raw write rolled back.

func RegisterObserver

func RegisterObserver[M any](r *foundation.Registrar, pool foundation.Key[*database.DB], observer Observer[M], construct func(foundation.Resolver) (func() Hooks[M], error)) error

RegisterObserver installs instance-owned dependencies through a database Module. Example: RegisterObserver(r, pool, NewObserver[Order]("orders.audit"), constructOrderAudit).

func RegisterRetrievalObserver

func RegisterRetrievalObserver[M any](r *foundation.Registrar, pool foundation.Key[*database.DB], observer RetrievalObserver[M], construct func(foundation.Resolver) (func() RetrievalHooks[M], error)) error

RegisterRetrievalObserver constructs dependencies once during application assembly. Example: RegisterRetrievalObserver(r, pool, NewRetrievalObserver[Order]("orders.read"), constructOrderReads).

func Require added in v0.2.0

func Require[M any](ctx context.Context, ex database.Executor, q Query[M]) (M, error)

Require returns database.NotFound on no match. Example: orm.Require(ctx, db, Orders.Query()).

func RequireKey added in v0.2.0

func RequireKey[M any, K comparable](ctx context.Context, ex database.Executor, t Table[M, K], key K) (M, error)

RequireKey selects a key or returns database.NotFound. Example: orm.RequireKey(ctx, db, Orders.Table, id).

func RequireLocked added in v0.2.0

func RequireLocked[M any](ctx context.Context, tx *database.Tx, q LockedQuery[M]) (M, error)

RequireLocked reads one locked row or fails. Example: orm.RequireLocked(ctx, tx, orm.Lock(Orders.Query())).

func Restore added in v0.2.0

func Restore[M any, K comparable](ctx context.Context, tx database.Transactor, t Table[M, K], key K) (M, error)

Restore clears the deletion instant of one deleted key.

func RestoreEach

func RestoreEach[M any](ctx context.Context, writer database.Transactor, q Query[M], soft SoftDeletable[M], limit int) ([]M, error)

RestoreEach restores the selected deleted models in one bounded transaction. It retains predicates, selects only trashed rows, and runs each restore lifecycle. Example: orm.RestoreEach(ctx, db, Users.Query(), Users.Soft, 100).

func Update

func Update[M any, K comparable](ctx context.Context, writer database.Transactor, q Query[M], key Key[M, K], id K, assignments ...Assignment[M]) (M, error)

Update patches one primary key within the query's current visibility and hydrates its complete returned model. Scope predicates, lifecycle and cardinality checks remain active. Example: orm.Update(ctx, db, visible, Users.Key(), id, orm.Set(Users.Name, "Ada")).

func UpdateAll added in v0.2.0

func UpdateAll[M any](ctx context.Context, tx database.Transactor, q Query[M], as ...Assignment[M]) (int64, error)

UpdateAll patches every matching row. Example: orm.UpdateAll(ctx, tx, Orders.Query().Where(orm.Eq(Orders.TotalCents, 0)), orm.Set(Orders.TotalCents, 1)).

func UpdateEach

func UpdateEach[M any](ctx context.Context, writer database.Transactor, q Query[M], limit int, draft func(context.Context, *database.Tx, M) ([]Assignment[M], error)) ([]M, error)

UpdateEach locks the complete candidate set in primary-key order, then derives typed assignments and runs each ordinary model lifecycle in one transaction. Read ordering, pagination, eager loading and WithoutModelHooks are rejected. The callback gets the actual transaction; propagate its context to nested work. Example: orm.UpdateEach(ctx,db,Users.Query(),100,func(ctx context.Context,tx *database.Tx,u User)([]orm.Assignment[User],error){return []orm.Assignment[User]{orm.Set(Users.Name, u.Name)},nil}).

func UpdateOrCreate

func UpdateOrCreate[M any](ctx context.Context, writer database.Transactor, q Query[M], create []Assignment[M], update func(context.Context, *database.Tx, M) ([]Assignment[M], error)) (M, error)

UpdateOrCreate patches the first locked match or creates from separate inputs. Only the chosen branch prepares its assignments. Read windows and eager loads are rejected. Example: orm.UpdateOrCreate(ctx,db,Users.Query(),create,func(ctx context.Context,tx *database.Tx,u User)([]orm.Assignment[User],error){return []orm.Assignment[User]{orm.Set(Users.Name, "Ada")},nil}).

func UpdatePivot

func UpdatePivot[M, N, P any](ctx context.Context, writer database.Transactor, r ThroughRelation[M, N, P], source M, target N, update ...Assignment[P]) ([]P, error)

UpdatePivot patches every matching pivot to one target, including duplicate links. Example: orm.UpdatePivot(ctx,db,links,user,group,orm.Set(Memberships.Role, "admin")).

func Upsert

func Upsert[M any](ctx context.Context, writer database.Transactor, q Query[M], policy Conflict[M], assignments ...Assignment[M]) (value.Optional[M], error)

Upsert inserts or applies a conflict policy. Skipped rows return an omitted value. Like the old upsert API, it transforms inputs but skips per-model hooks and observers. Example: orm.Upsert(ctx,db,Users.Query(),policy,orm.Set(Users.Email, "ada@example.test")).

func UpsertMany

func UpsertMany[M any](ctx context.Context, writer database.Transactor, q Query[M], policy Conflict[M], rows [][]Assignment[M]) ([]M, error)

UpsertMany applies one reusable policy to a bounded atomic batch. Skipped rows are absent; RETURNING order is not an input-row mapping. Per-model callbacks are skipped. Example: orm.UpsertMany(ctx,db,Users.Query(),policy,[][]orm.Assignment[User]{{orm.Set(Users.Email, "ada@example.test")}}).

func WithoutRelationGlobalScope

func WithoutRelationGlobalScope[M, N any, R scopeRelation[M, N, R]](r R, scopes ...GlobalScope[N]) R

WithoutRelationGlobalScope removes named target defaults without changing the relation kind or its pivot defaults. Example: WithoutRelationGlobalScope(UserRelations.Orders, orderTenantScope).Where(orm.Eq(Orders.Active, true)).

func WithoutRelationGlobalScopes

func WithoutRelationGlobalScopes[M, N any, R scopeRelation[M, N, R]](r R) R

WithoutRelationGlobalScopes removes all target defaults from this descriptor. Example: WithoutRelationGlobalScopes(UserRelations.Orders).

func WriteGet

func WriteGet[M, I any](write *Write[M], setter func(I) Assignment[M]) value.Optional[I]

WriteGet reads a required field's input without running its mutator. Example: input, supplied := WriteGet(write, func(v EmailInput) Assignment[Member] { return Set(Members.Email, v) }).Get().

func WriteIsSet

func WriteIsSet[M, I any](write *Write[M], setter func(I) Assignment[M]) bool

WriteIsSet reports assignment independently of input value or NULL. Example: WriteIsSet(write, func(v LabelInput) Assignment[Member] { return Set(Members.Note, v) }).

func WriteNullableGet

func WriteNullableGet[M, I any](write *Write[M], setter func(I) Assignment[M]) value.Optional[value.Nullable[I]]

WriteNullableGet preserves omission, SQL NULL and the distinct mutation input. Example: input := WriteNullableGet(write, func(v LabelInput) Assignment[Member] { return Set(Members.Note, v) }).

func WriteSet

func WriteSet[M any](write *Write[M], assignments ...Assignment[M]) error

WriteSet replaces assigned fields; omission remains distinct from zero and NULL. Example: WriteSet(write, Set(Members.Name, ""), SetNull(Members.Note)).

func WriteUnset

func WriteUnset[M, I any](write *Write[M], setter func(I) Assignment[M]) error

WriteUnset removes a pending assignment; the field becomes omitted, not NULL or zero. Unsetting an omitted field is a no-op. Later hooks may assign it again, and conventions may supply an automatic value. Use only during a before-write callback. Example: WriteUnset(write, func(v EmailInput) Assignment[Member] { return Set(Members.Email, v) }).

Types

type AdjustableRole added in v0.48.0

type AdjustableRole interface {
	ColumnRole
	// contains filtered or unexported methods
}

AdjustableRole admits ordinary mutable columns for Increment/Decrement; numeric keys, Input columns, and managed timestamps are excluded.

type AggregateRelation

type AggregateRelation[M, V any] struct {
	// contains filtered or unexported fields
}

AggregateRelation loads a typed computation into a model slot. Example: Users.Query().With(UserAggregates.OrdersCount).

func FoundryRelated

func FoundryRelated[M, N, V any](source AggregateSource[M, N], expression ormcore.Expression, column ormcore.Column[V], seal sqlowner.ExpressionSeal) AggregateRelation[M, V]

FoundryRelated binds validated expression metadata to a sealed relation source. Example: orm.FoundryRelated(source,expression,column,sqlowner.Expressions()).

func (AggregateRelation[M, V]) Using

func (r AggregateRelation[M, V]) Using(computation AggregateRelation[M, V]) AggregateRelation[M, V]

Using replaces the computation while retaining this descriptor's slot. Example: UserAggregates.OrdersCount.Using(expr.Related(filtered,expr.Count[Order]())).

type AggregateSource

type AggregateSource[M, N any] interface {
	// contains filtered or unexported methods
}

AggregateSource seals the parent and measured model of a relation computation. Example: func count[M,N any](r orm.AggregateSource[M,N]).

func Pivot

func Pivot[M, N, P any](r ThroughRelation[M, N, P]) AggregateSource[M, P]

Pivot measures a relation's pivot while preserving both sides' scopes. Example: expr.Related(orm.Pivot(UserRelations.Groups),expr.Count[Membership]()).

type AnyColumnKind added in v0.48.0

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

AnyColumnKind admits every column kind including encrypted (used by Set, SetIfPresent, and AuditField).

type Assignment

type Assignment[M any] struct {
	// contains filtered or unexported fields
}

Assignment preserves omitted/null/value semantics. Example: orm.Set(Orders.TotalCents, 0).

func Decrement added in v0.48.0

func Decrement[M any, V NumberValue, I, P any, K NumberColumnKind, R AdjustableRole](c ColumnHandle[M, V, I, P, K, R], amount V, bound ...Bound[V]) Assignment[M]

Decrement subtracts a strictly positive amount from an adjustable numeric column in the UPDATE statement. Example: orm.Decrement(Orders.TotalCents, 50, orm.AtLeast[int64](0)).

func Increment added in v0.48.0

func Increment[M any, V NumberValue, I, P any, K NumberColumnKind, R AdjustableRole](c ColumnHandle[M, V, I, P, K, R], amount V, bound ...Bound[V]) Assignment[M]

Increment adds a strictly positive amount to an adjustable numeric column in the UPDATE statement. Example: orm.Increment(Orders.TotalCents, 100, orm.AtMost[int64](1000)).

func Set added in v0.48.0

func Set[M, V, I, P any, K AnyColumnKind, R ColumnRole](c ColumnHandle[M, V, I, P, K, R], v I) Assignment[M]

Set assigns a value (including zero, false, or empty string) to any column, taking the column's input type I. Example: orm.Set(Orders.TotalCents, 0).

func SetIfPresent added in v0.48.0

func SetIfPresent[M, V, I, P any, K AnyColumnKind, R ColumnRole](dst []Assignment[M], c ColumnHandle[M, V, I, P, K, R], v value.Optional[I]) []Assignment[M]

SetIfPresent appends an assignment only when v is set, preserving omitted-field semantics on partial updates. Example: sets = orm.SetIfPresent(sets, Users.Name, input.Name).

func SetNull added in v0.48.0

func SetNull[M, V, I, P any, K NullableColumnKind, R ColumnRole](c ColumnHandle[M, V, I, P, K, R]) Assignment[M]

SetNull explicitly clears a nullable column to SQL NULL (including NullableEncrypted). Example: orm.SetNull(Users.Nickname).

func (Assignment[M]) GoString

func (Assignment[M]) GoString() string

GoString redacts pending values in diagnostics. Example: fmt.Sprintf("%#v", assignment).

func (Assignment[M]) String

func (Assignment[M]) String() string

String redacts pending values. Example: fmt.Sprint(orm.Set(Orders.TotalCents, 10)).

type AuditPolicy

type AuditPolicy[M any] struct {
	// contains filtered or unexported fields
}

AuditPolicy is an immutable model-owned disclosure policy; zero means Automatic for every field. Example: orm.AuditPolicyOf(Orders.Table, orm.AuditField(Orders.Note, record.Exclude)).

func AuditPolicyOf

func AuditPolicyOf[M any, K comparable](table Table[M, K], rules ...AuditRule[M]) AuditPolicy[M]

AuditPolicyOf snapshots field policies; duplicates, foreign fields and hidden primary keys fail registration or capture. Example: orm.AuditPolicyOf(Orders.Table, orm.AuditField(Orders.Note, record.Exclude)).

type AuditRule

type AuditRule[M any] struct {
	// contains filtered or unexported fields
}

AuditRule retains the model owner of a field disclosure. Example: orm.AuditField(Orders.Note, record.Exclude).

func AuditField

func AuditField[M, V, I, P any, K AnyColumnKind, R ColumnRole](field ColumnHandle[M, V, I, P, K, R], disclosure auditrecord.Disclosure) AuditRule[M]

AuditField selects disclosure for any declared stored column, including nullable, encrypted, and distinct-input columns. For encrypted columns, Automatic always redacts. Example: orm.AuditField(Orders.Note, record.Redact).

type BelongsTo

type BelongsTo[M, N any] struct {
	// contains filtered or unexported fields
}

BelongsTo loads a singular target using a local FK. Example: OrderRelations.Buyer.

func BelongsToOf

func BelongsToOf[M, N any, K comparable, I1, P1 any, K1 ColumnKind, R1 ColumnRole, I2, P2 any, K2 ColumnKind, R2 ColumnRole](slot One[M, N], local ColumnHandle[M, K, I1, P1, K1, R1], foreign ColumnHandle[N, K, I2, P2, K2, R2]) BelongsTo[M, N]

BelongsToOf unifies local and target key types. Example: orm.BelongsToOf(Orders.Buyer, Orders.BuyerID, Users.ID).

func MorphToOf

func MorphToOf[M any, N model.Morphable, K comparable, I, P any, Kind ColumnKind, R ColumnRole](slot One[M, N], link KeyLink[M, N, K], kind ColumnHandle[M, model.MorphName, I, P, Kind, R]) BelongsTo[M, N]

MorphToOf loads one concrete target only for matching source rows. Declare one slot per target type. Example: orm.MorphToOf(Notes.Office, orm.JoinKeys(Notes.SubjectID, Offices.Code), Notes.SubjectType).

func (BelongsTo[M, N]) LatestOfMany

func (r BelongsTo[M, N]) LatestOfMany() BelongsTo[M, N]

LatestOfMany chooses the highest target primary key. Example: OrderRelations.Buyer.LatestOfMany().

func (BelongsTo[M, N]) OfMany

func (r BelongsTo[M, N]) OfMany(orders ...Order[N]) BelongsTo[M, N]

OfMany chooses one target per local key using these orders and the primary key. Example: OrderRelations.Buyer.OfMany(orm.Asc(Users.ID)).

func (BelongsTo[M, N]) OldestOfMany

func (r BelongsTo[M, N]) OldestOfMany() BelongsTo[M, N]

OldestOfMany chooses the lowest target primary key. Example: OrderRelations.Buyer.OldestOfMany().

func (BelongsTo[M, N]) OnlyTrashed

func (r BelongsTo[M, N]) OnlyTrashed() BelongsTo[M, N]

OnlyTrashed sets target soft-delete visibility. Example: UserRelations.Orders.OnlyTrashed().

func (BelongsTo[M, N]) OrderBy

func (r BelongsTo[M, N]) OrderBy(os ...Order[N]) BelongsTo[M, N]

OrderBy orders related rows with a primary-key tie-breaker. Example: OrderRelations.Buyer.OrderBy(orm.Asc(Users.Email)).

func (BelongsTo[M, N]) Where

func (r BelongsTo[M, N]) Where(ps ...Predicate[N]) BelongsTo[M, N]

Where constrains related rows. Example: OrderRelations.Buyer.Where(orm.Gt(Users.Age, 18)).

func (BelongsTo[M, N]) With

func (r BelongsTo[M, N]) With(children ...Relation[N]) BelongsTo[M, N]

With batches nested branches over all fetched targets. Example: OrderRelations.Buyer.With(UserRelations.Orders).

func (BelongsTo[M, N]) WithTrashed

func (r BelongsTo[M, N]) WithTrashed() BelongsTo[M, N]

WithTrashed sets target soft-delete visibility. Example: UserRelations.Orders.WithTrashed().

func (BelongsTo[M, N]) WithoutTrashed

func (r BelongsTo[M, N]) WithoutTrashed() BelongsTo[M, N]

WithoutTrashed sets target soft-delete visibility. Example: UserRelations.Orders.WithoutTrashed().

type Bound

type Bound[V NumberValue] struct {
	// contains filtered or unexported fields
}

Bound constrains the result of an atomic numeric adjustment. Construct bounds with AtLeast or AtMost; the zero value is invalid. The database evaluates column +/- amount before comparing the bound. int64/float64 overflow returns a database out-of-range error; it never silently passes the guard.

func AtLeast

func AtLeast[V NumberValue](floor V) Bound[V]

AtLeast requires the decremented value to remain at or above floor.

func AtMost

func AtMost[V NumberValue](ceiling V) Bound[V]

AtMost requires the incremented value to remain at or below ceiling.

type Builder

type Builder[M any] struct {
	// contains filtered or unexported fields
}

Builder binds fields during Define. Example: TextOf(b, &o.Email).

type Changes

type Changes[M any] struct {
	// contains filtered or unexported fields
}

Changes contains persisted snapshots, excluding relations and ignored fields. Example: original, exists := changes.Before().Get().

func Compare

func Compare[M any, K comparable](table Table[M, K], before, after value.Optional[M], assigned ...Assignment[M]) (Changes[M], error)

Compare compares stored snapshots without running hooks, accessors or mutators. Example: Compare(Orders.Table, value.Set(before), value.Set(after), orm.Set(Orders.TotalCents, 0)).

func (Changes[M]) After

func (c Changes[M]) After() value.Optional[M]

After returns an owned stored result, absent for physical deletion. Example: changes.After().Get().

func (Changes[M]) Assigned

func (c Changes[M]) Assigned() bool

Assigned reports effective assignments, including managed fields. Example: changes.Assigned().

func (Changes[M]) Before

func (c Changes[M]) Before() value.Optional[M]

Before returns an owned persisted original, absent for creation. Example: changes.Before().Get().

func (Changes[M]) Changed

func (c Changes[M]) Changed() bool

Changed reports canonical stored differences. Example: changes.Changed().

func (Changes[M]) GoString

func (Changes[M]) GoString() string

GoString redacts snapshots. Example: fmt.Sprintf("%#v",changes).

func (Changes[M]) Operation

func (c Changes[M]) Operation() value.Optional[lifecycle.Operation]

Operation identifies an automatic write; standalone comparisons have none. Example: changes.Operation().Get().

func (Changes[M]) String

func (Changes[M]) String() string

String redacts snapshots. Example: fmt.Sprint(changes).

type CheckedTable

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

CheckedTable is implemented by embedded tables. Example: Check(Orders, Users).

type Column

type Column[M, V any] = ColumnHandle[M, V, V, V, RequiredScalarKind, OrdinaryRole]

Column exposes equality, ordering and assignments. Example: orm.Eq(Orders.BuyerID, id).

func BoolOf

func BoolOf[M any, V ~bool](b Builder[M], ptr *V, opts ...ColumnOption[V]) Column[M, V]

BoolOf binds a Boolean field, including defined Boolean types. Example: BoolOf(b, &u.Enabled).

func BytesOf

func BytesOf[M any, V ~[]byte](b Builder[M], ptr *V, opts ...ColumnOption[V]) Column[M, V]

BytesOf binds owned byte buffers. Example: BytesOf(b,&o.Payload).

func ColumnOf

func ColumnOf[M, V any](b Builder[M], ptr *V, opts ...ColumnOption[V]) Column[M, V]

ColumnOf binds an ordinary field or explicit custom codec. Example: ColumnOf(b,&o.BuyerID).

func IDOf

func IDOf[M, T any](b Builder[M], ptr *model.ID[T]) Column[M, model.ID[T]]

IDOf declares a model-owned foreign ID column. Example: IDOf(b, &o.BuyerID).

func PasswordOf

func PasswordOf[M any](b Builder[M], ptr *password.Hash) Column[M, password.Hash]

PasswordOf binds a stored hash with scalar comparisons, sorting and assignment. Plaintext verification belongs to password.Hasher. Example: orm.Eq(Accounts.Digest, hash).

type ColumnHandle added in v0.48.0

type ColumnHandle[M, V, I, P any, K AnyColumnKind, R ColumnRole] struct {
	// contains filtered or unexported fields
}

ColumnHandle is the 6-parameter, methodless concrete carrier for every model column (including encrypted and input columns). Zero methods avoids eager per-instantiation method emission in model packages; holding only *columnData[V] and the assignment input func keeps the carrier 16 bytes so every operator forwards stored and input branchlessly.

Immutability invariant: once orm.Define seals a table declaration, the pointed-to *columnData[V] and *columnCore are strictly read-only and may be shared across derived handles (PrimaryOf, NumberKey, TextKey, InputKeyOf). No code outside declaration construction inside orm.Define may mutate *columnData[V] or *columnCore.

func NumberKey

func NumberKey[M any, K interface {
	NumberValue
	comparable
}, R KeyRole](key ColumnHandle[M, K, K, K, KeyKind, R]) ColumnHandle[M, K, K, K, NumberKeyKind, R]

NumberKey derives numeric capabilities without binding the field again.

func TextKey

func TextKey[M any, K ~string, R KeyRole](key ColumnHandle[M, K, K, K, KeyKind, R]) ColumnHandle[M, K, K, K, RequiredTextKind, R]

TextKey derives text capabilities without binding the field again.

type ColumnKind added in v0.48.0

type ColumnKind interface {
	AnyColumnKind
	// contains filtered or unexported methods
}

ColumnKind admits every queryable (non-encrypted) column; encrypted ciphertext columns cannot be compared, sorted, projected, joined, or validated in SQL.

type ColumnOption

type ColumnOption[V any] struct {
	// contains filtered or unexported fields
}

ColumnOption supplies a typed custom codec. Example: ColumnOf(b, &o.Code, Codec(custom)).

func Codec

func Codec[V any](c codec.Codec[V]) ColumnOption[V]

Codec selects an explicit codec for a custom value. Example: Codec(codec.String[Code]()).

type ColumnRole added in v0.48.0

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

ColumnRole constrains the declaration role of a ColumnHandle (Ordinary, Created, Updated, Deleted, LookupKey, Primary, Input, InputKey).

type Conflict

type Conflict[M any] struct {
	// contains filtered or unexported fields
}

Conflict is an immutable model-owned upsert policy; its zero value is invalid. Example: orm.OnConflict(orm.ConflictKey(Users.Email)).DoUpdate(orm.ConflictIncoming(Users.Name)).

func FoundryConflict

func FoundryConflict[M any](metadata ormcore.ConflictPolicy, seal sqlowner.ExpressionSeal) Conflict[M]

FoundryConflict binds a framework-built policy to its declaration. Example: FoundryConflict[User](metadata,sqlowner.Expressions()).

func OnConflict

func OnConflict[M any](fields ...ConflictColumn[M]) Conflict[M]

OnConflict infers a unique index from typed columns. Empty targets support DO NOTHING. Example: orm.OnConflict(orm.ConflictKey(Users.Email)).DoNothing().

func OnConflictConstraint

func OnConflictConstraint[M any](name string) Conflict[M]

OnConflictConstraint selects a named database constraint; PostgreSQL owns its existence. Example: orm.OnConflictConstraint[User]("users_email_key").DoNothing().

func (Conflict[M]) DoNothing

func (p Conflict[M]) DoNothing() Conflict[M]

DoNothing skips conflicting rows; skipped rows have no result. Example: orm.OnConflict[User]().DoNothing().

func (Conflict[M]) DoUpdate

func (p Conflict[M]) DoUpdate(updates ...ConflictUpdate[M]) Conflict[M]

DoUpdate replaces the policy's update assignments. Primary-key updates are rejected. Example: policy.DoUpdate(orm.ConflictIncoming(Users.Name)).

func (Conflict[M]) GoString

func (Conflict[M]) GoString() string

GoString omits captured conflict values. Example: fmt.Sprintf("%#v",policy).

func (Conflict[M]) String

func (Conflict[M]) String() string

String omits captured conflict values. Example: fmt.Sprint(policy).

func (Conflict[M]) TargetWhere

func (p Conflict[M]) TargetWhere(predicates ...Predicate[M]) Conflict[M]

TargetWhere declares a partial unique index predicate, separate from update conditions. Fixed target values are rendered as schema constants. Example: policy.TargetWhere(orm.Eq(Users.Active, true)).

func (Conflict[M]) Where

func (p Conflict[M]) Where(predicates ...Predicate[M]) Conflict[M]

Where adds stored-row conditions; false conditions skip RETURNING but keep row locks. Example: policy.Where(orm.Eq(Users.Active, true)).

type ConflictColumn

type ConflictColumn[M any] struct {
	// contains filtered or unexported fields
}

ConflictColumn is a model-owned unique-index column. Example: orm.ConflictKey(Users.Email).

func ConflictKey

func ConflictKey[M, V, I, P any, K ColumnKind, R ColumnRole](field ColumnHandle[M, V, I, P, K, R]) ConflictColumn[M]

ConflictKey selects a declared column for unique-index inference. Example: orm.OnConflict(orm.ConflictKey(Users.Email)).DoNothing().

type ConflictSetRole added in v0.48.0

type ConflictSetRole interface {
	ColumnRole
	// contains filtered or unexported methods
}

ConflictSetRole admits column roles legal in ConflictSet and ConflictNull updates.

type ConflictUpdate

type ConflictUpdate[M any] struct {
	// contains filtered or unexported fields
}

ConflictUpdate is a model-owned assignment in DO UPDATE. Example: orm.ConflictIncoming(Users.Email).

func ConflictIncoming

func ConflictIncoming[M, V, I, P any, K ColumnKind, R ColumnRole](field ColumnHandle[M, V, I, P, K, R]) ConflictUpdate[M]

ConflictIncoming copies the destination's own EXCLUDED value, already transformed. Omitted insert values copy the database default or NULL. Encrypted fields are excluded. Example: orm.ConflictIncoming(Users.Email).

func ConflictNull

func ConflictNull[M, V, I, P any, K NullableComparableKind, R ConflictSetRole](field ColumnHandle[M, V, I, P, K, R]) ConflictUpdate[M]

ConflictNull clears a nullable field without invoking its mutator. Example: orm.ConflictNull(Users.Nickname).

func ConflictSet

func ConflictSet[M, I, V, P any, K ColumnKind, R ConflictSetRole](field ColumnHandle[M, V, I, P, K, R], input I) ConflictUpdate[M]

ConflictSet captures the column's write input, including distinct mutator inputs. Encrypted fields have no conflict assignment capability. Example: orm.ConflictSet(Members.Email, EmailInput{Address:"ada@example.test"}).

func FoundryConflictUpdate

func FoundryConflictUpdate[M any](metadata ormcore.ConflictAssignment, seal sqlowner.ExpressionSeal) ConflictUpdate[M]

FoundryConflictUpdate binds a framework-built calculation to its destination. Example: FoundryConflictUpdate[User](metadata,sqlowner.Expressions()).

func (ConflictUpdate[M]) GoString

func (ConflictUpdate[M]) GoString() string

GoString redacts literal inputs. Example: fmt.Sprintf("%#v",update).

func (ConflictUpdate[M]) String

func (ConflictUpdate[M]) String() string

String redacts literal inputs. Example: fmt.Sprint(orm.ConflictSet(Users.Email,"ada@example.test")).

type CreatedAt

type CreatedAt[M any, V InstantValue] = ColumnHandle[M, V, V, V, RequiredTimeKind, CreatedRole]

CreatedAt is an explicitly managed creation instant. Example: CreatedAtOf(b,&o.CreatedAt).

func CreatedAtOf

func CreatedAtOf[M any, V InstantValue](b Builder[M], ptr *V) CreatedAt[M, V]

CreatedAtOf explicitly marks a creation timestamp. Example: CreatedAtOf(b,&o.CreatedAt).

type CreatedRole added in v0.48.0

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

CreatedRole marks a framework-managed creation timestamp (CreatedAt); excluded from numeric adjustments and updates.

type Cursor

type Cursor[M any] = querycore.Cursor[M]

Cursor is the existing owner-typed position token, preserving its wire identity. Example: var next orm.Cursor[User].

func ParseCursor

func ParseCursor[M any](token string) (Cursor[M], error)

ParseCursor parses a position without granting access to its source. Example: orm.ParseCursor[User](token).

type CursorInputError

type CursorInputError = querycore.CursorInputError

CursorInputError preserves typed cursor error classification. Example: var invalid *orm.CursorInputError.

type CursorPage

type CursorPage[M any] = querycore.CursorPage[M]

CursorPage preserves the existing keyset response. Example: page.Next.Get().

func CursorPaginate

func CursorPaginate[M any](ctx context.Context, ex database.Executor, q Query[M], request CursorRequest[M]) (CursorPage[M], error)

CursorPaginate reads a bounded keyset page using the existing HTTP pagination request/result adapters. Tokens are scoped positions, not authorization or a snapshot. Example: orm.CursorPaginate(ctx, db, Orders.Query(), request.Page).

type CursorRequest

type CursorRequest[M any] = querycore.CursorRequest[M]

CursorRequest preserves the existing bounded keyset request. Example: orm.CursorRequest[User]{Size:20}.

type DeleteSource

type DeleteSource[S, M any] struct {
	// contains filtered or unexported fields
}

DeleteSource removes matching models using declared soft-delete conventions. Example: rows.DeleteUsing(Users.Query(),rows.From(Archives.Query())).

func FoundryDeleteUsing

func FoundryDeleteUsing[S, M any](q Query[M], source ormcore.Source, force bool, soft SoftDeletable[M], seal sqlowner.QuerySeal) DeleteSource[S, M]

FoundryDeleteUsing creates a source removal plan with explicit visibility. Example: FoundryDeleteUsing[Archive](Users.Query(),source,false,SoftDeletable[User]{},sqlowner.Queries()).

func (DeleteSource[S, M]) Exec

func (p DeleteSource[S, M]) Exec(ctx context.Context, writer database.Transactor) (int64, error)

Exec affects each matching destination once. Example: plan.Exec(ctx,db).

func (DeleteSource[S, M]) Format

func (DeleteSource[S, M]) Format(s fmt.State, _ rune)

Format hides captured source values. Example: fmt.Sprintf("%#v",plan).

func (DeleteSource[S, M]) Match

func (p DeleteSource[S, M]) Match(key SourceKey[S, M]) DeleteSource[S, M]

Match replaces the source-to-primary match. Example: plan.Match(rows.MatchSource(Users.ID,expr.Value(Archives.UserID))).

func (DeleteSource[S, M]) Returning

func (p DeleteSource[S, M]) Returning(ctx context.Context, writer database.Transactor, limit int) ([]M, error)

Returning returns complete affected models; physical deletion returns old values. Example: plan.Returning(ctx,db,100).

type DeletedRole added in v0.48.0

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

DeletedRole marks a soft-delete timestamp (SoftDelete); valid for null checks, row insert/update mappings, and conflict sets.

type DirectRelation

type DirectRelation[P, M any] interface {
	BelongsTo[P, M] | HasOne[P, M] | HasMany[P, M]
	AggregateSource[P, M]
}

DirectRelation restricts scoped binding to direct relationships. Example: func bind[R orm.DirectRelation[Team,Project]](r R).

type Encrypted

type Encrypted[M any, V encrypted.Value[V]] = ColumnHandle[M, V, V, V, RequiredEncryptedKind, OrdinaryRole]

Encrypted exposes only typed assignment; ciphertext has no predicate or ordering capabilities. Example: orm.Set(Vaults.Secret, encrypted.NewText("private")).

func EncryptedJSONOf

func EncryptedJSONOf[M, T any](b Builder[M], ptr *encrypted.JSON[T]) Encrypted[M, encrypted.JSON[T]]

EncryptedJSONOf binds a typed JSON envelope. Example: EncryptedJSONOf(b,&m.Settings).

func EncryptedTextOf

func EncryptedTextOf[M any](b Builder[M], ptr *encrypted.Text) Encrypted[M, encrypted.Text]

EncryptedTextOf binds a text envelope to its table, column and row key. Example: EncryptedTextOf(b,&m.Secret).

type Enum

type Enum[M any, E enum.Scalar] = ColumnHandle[M, E, E, E, RequiredEnumKind, OrdinaryRole]

Enum restricts values to an enum's descriptor. Example: orm.Eq(Users.Status, StatusActive).

func EnumOf

func EnumOf[M any, E interface {
	enum.Scalar
	EnumDescriptor() enum.Descriptor[E]
}](b Builder[M], ptr *E, opts ...ColumnOption[E]) Enum[M, E]

EnumOf uses generated enum metadata. Example: EnumOf(b,&o.Status).

type ExistenceRelation

type ExistenceRelation[M, N any] interface {
	Relation[M]
	// contains filtered or unexported methods
}

ExistenceRelation retains both source and target owners for predicate inference. Example: orm.Has(UserRelations.Orders, orm.Gt(Orders.TotalCents, 100)).

type ExtensionRelation

type ExtensionRelation[M any] struct {
	// contains filtered or unexported fields
}

ExtensionRelation is a model-owned external-store loader. Example: Articles.Query().With(title).

func FoundryExtension

func FoundryExtension[M, S any](slot Slot[M, S], source extensionslot.Slot[M], seal sqlowner.QuerySeal) ExtensionRelation[M]

FoundryExtension binds a shared external loader using a validated framework capability. Example: orm.FoundryExtension(Articles.Title,loader,sqlowner.Queries()).

type GlobalScope

type GlobalScope[M any] struct {
	// contains filtered or unexported fields
}

GlobalScope is a model-owned, additive default predicate. Keep its value for query-local removal. Example: var tenantScope orm.GlobalScope[Order].

func Scope

func Scope[M any, K comparable](table Table[M, K], name string, resolve func(context.Context) (Predicate[M], error)) GlobalScope[M]

Scope resolves a predicate with the executing context on every statement. A missing tenant must return an error. Example: orm.Scope(Orders.Table, "tenant", func(ctx context.Context) (orm.Predicate[Order], error) { id, err := tenantID(ctx); return orm.Eq(Orders.TenantID, id), err }).

func (GlobalScope[M]) Name

func (s GlobalScope[M]) Name() string

Name returns the declared identifier. Example: tenantScope.Name().

type HasMany

type HasMany[M, N any] struct {
	// contains filtered or unexported fields
}

HasMany loads target collections by their FK. Example: UserRelations.Orders.

func HasManyOf

func HasManyOf[M, N any, K comparable, I1, P1 any, K1 ColumnKind, R1 ColumnRole, I2, P2 any, K2 ColumnKind, R2 ColumnRole](slot Many[M, N], local ColumnHandle[M, K, I1, P1, K1, R1], foreign ColumnHandle[N, K, I2, P2, K2, R2]) HasMany[M, N]

HasManyOf unifies parent keys with target FKs. Example: orm.HasManyOf(Users.Orders, Users.ID, Orders.BuyerID).

func HasManyThroughOf

func HasManyThroughOf[M, I, N any, A, B comparable](slot Many[M, N], firstHop KeyLink[M, I, A], secondHop KeyLink[I, N, B]) HasMany[M, N]

HasManyThroughOf unifies both key pairs via an intermediate model. Example: orm.HasManyThroughOf(Countries.Posts, orm.JoinKeys(Countries.ID, Users.CountryID), orm.JoinKeys(Users.ID, Posts.UserID)).

func MorphManyOf

func MorphManyOf[M model.Morphable, N any, K comparable, I, P any, Kind ColumnKind, R ColumnRole](slot Many[M, N], link KeyLink[M, N, K], kind ColumnHandle[N, model.MorphName, I, P, Kind, R]) HasMany[M, N]

MorphManyOf filters targets by the source discriminator. Example: orm.MorphManyOf(Offices.Notes, orm.JoinKeys(Offices.Code, Notes.SubjectID), Notes.SubjectType).

func (HasMany[M, N]) OnlyTrashed

func (r HasMany[M, N]) OnlyTrashed() HasMany[M, N]

OnlyTrashed sets target soft-delete visibility. Example: UserRelations.Orders.OnlyTrashed().

func (HasMany[M, N]) OrderBy

func (r HasMany[M, N]) OrderBy(os ...Order[N]) HasMany[M, N]

OrderBy orders related collections. Example: UserRelations.Orders.OrderBy(orm.Desc(Orders.TotalCents)).

func (HasMany[M, N]) Where

func (r HasMany[M, N]) Where(ps ...Predicate[N]) HasMany[M, N]

Where constrains related rows. Example: UserRelations.Orders.Where(orm.Gt(Orders.TotalCents, 100)).

func (HasMany[M, N]) With

func (r HasMany[M, N]) With(children ...Relation[N]) HasMany[M, N]

With batches nested branches over all fetched targets. Example: UserRelations.Orders.With(OrderRelations.Buyer).

func (HasMany[M, N]) WithTrashed

func (r HasMany[M, N]) WithTrashed() HasMany[M, N]

WithTrashed sets target soft-delete visibility. Example: UserRelations.Orders.WithTrashed().

func (HasMany[M, N]) WithoutTrashed

func (r HasMany[M, N]) WithoutTrashed() HasMany[M, N]

WithoutTrashed sets target soft-delete visibility. Example: UserRelations.Orders.WithoutTrashed().

type HasOne

type HasOne[M, N any] struct {
	// contains filtered or unexported fields
}

HasOne loads at most one target by its FK. Example: UserRelations.Profile.

func HasOneOf

func HasOneOf[M, N any, K comparable, I1, P1 any, K1 ColumnKind, R1 ColumnRole, I2, P2 any, K2 ColumnKind, R2 ColumnRole](slot One[M, N], local ColumnHandle[M, K, I1, P1, K1, R1], foreign ColumnHandle[N, K, I2, P2, K2, R2]) HasOne[M, N]

HasOneOf unifies the parent key and target FK and rejects multiple matches. Example: orm.HasOneOf(Users.Profile, Users.ID, Profiles.UserID).

func HasOneThroughOf

func HasOneThroughOf[M, I, N any, A, B comparable](slot One[M, N], firstHop KeyLink[M, I, A], secondHop KeyLink[I, N, B]) HasOne[M, N]

HasOneThroughOf loads at most one target per source via an intermediate. Example: orm.HasOneThroughOf(Countries.LatestPost, orm.JoinKeys(Countries.ID, Users.CountryID), orm.JoinKeys(Users.ID, Posts.UserID)).

func MorphOneOf

func MorphOneOf[M model.Morphable, N any, K comparable, I, P any, Kind ColumnKind, R ColumnRole](slot One[M, N], link KeyLink[M, N, K], kind ColumnHandle[N, model.MorphName, I, P, Kind, R]) HasOne[M, N]

MorphOneOf loads at most one target of the source discriminator. Example: orm.MorphOneOf(slot, orm.JoinKeys(Offices.Code, Notes.SubjectID), Notes.SubjectType).

func (HasOne[M, N]) LatestOfMany

func (r HasOne[M, N]) LatestOfMany() HasOne[M, N]

LatestOfMany chooses the highest target primary key. Example: UserRelations.LatestOrder.LatestOfMany().

func (HasOne[M, N]) OfMany

func (r HasOne[M, N]) OfMany(orders ...Order[N]) HasOne[M, N]

OfMany chooses the first target per parent in these orders, then primary key. Example: UserRelations.LatestOrder.OfMany(orm.Desc(Orders.TotalCents)).

func (HasOne[M, N]) OldestOfMany

func (r HasOne[M, N]) OldestOfMany() HasOne[M, N]

OldestOfMany chooses the lowest target primary key. Example: UserRelations.LatestOrder.OldestOfMany().

func (HasOne[M, N]) OnlyTrashed

func (r HasOne[M, N]) OnlyTrashed() HasOne[M, N]

OnlyTrashed sets target soft-delete visibility. Example: UserRelations.Orders.OnlyTrashed().

func (HasOne[M, N]) OrderBy

func (r HasOne[M, N]) OrderBy(os ...Order[N]) HasOne[M, N]

OrderBy orders related rows without hiding cardinality errors. Example: UserRelations.Profile.OrderBy(orm.Asc(Profiles.ID)).

func (HasOne[M, N]) Where

func (r HasOne[M, N]) Where(ps ...Predicate[N]) HasOne[M, N]

Where constrains related rows. Example: UserRelations.Profile.Where(orm.Eq(Profiles.Active, true)).

func (HasOne[M, N]) With

func (r HasOne[M, N]) With(children ...Relation[N]) HasOne[M, N]

With batches nested branches over all fetched targets. Example: UserRelations.Profile.With(ProfileRelations.Photo).

func (HasOne[M, N]) WithTrashed

func (r HasOne[M, N]) WithTrashed() HasOne[M, N]

WithTrashed sets target soft-delete visibility. Example: UserRelations.Orders.WithTrashed().

func (HasOne[M, N]) WithoutTrashed

func (r HasOne[M, N]) WithoutTrashed() HasOne[M, N]

WithoutTrashed sets target soft-delete visibility. Example: UserRelations.Orders.WithoutTrashed().

type Hooks

type Hooks[M any] struct {
	// Saving precedes Creating/Updating. Example: Saving: validateOrder.
	Saving func(context.Context, *database.Tx, value.Optional[M], *Write[M]) error
	// Creating can supply omitted required fields. Example: Creating: initializeOrder.
	Creating func(context.Context, *database.Tx, *Write[M]) error
	// Updating receives the locked original. Example: Updating: reviseOrder.
	Updating func(context.Context, *database.Tx, M, *Write[M]) error
	// Deleting precedes soft and physical deletion. Example: Deleting: authorizeRemoval.
	Deleting func(context.Context, *database.Tx, M) error
	// Restoring precedes restoring a deleted row. Example: Restoring: authorizeRestore.
	Restoring func(context.Context, *database.Tx, M) error
	// ForceDeleting precedes Deleting. Example: ForceDeleting: authorizePurge.
	ForceDeleting func(context.Context, *database.Tx, M) error
	// Created runs after RETURNING, inside the transaction. Example: Created: recordCreation.
	Created func(context.Context, *database.Tx, Changes[M]) error
	// Updated runs after RETURNING, inside the transaction. Example: Updated: recordRevision.
	Updated func(context.Context, *database.Tx, Changes[M]) error
	// Deleted runs after soft or physical deletion. Example: Deleted: recordRemoval.
	Deleted func(context.Context, *database.Tx, Changes[M]) error
	// Saved follows Created/Updated. Example: Saved: writeOutbox.
	Saved func(context.Context, *database.Tx, Changes[M]) error
	// Restored runs after restoration. Example: Restored: recordRestore.
	Restored func(context.Context, *database.Tx, Changes[M]) error
	// ForceDeleted follows Deleted. Example: ForceDeleted: recordPurge.
	ForceDeleted func(context.Context, *database.Tx, Changes[M]) error
	// AfterCommit runs after the outer commit; it is not crash durable. Example: AfterCommit: invalidateCache.
	AfterCommit func(context.Context, lifecycle.Operation, Changes[M]) error
}

Hooks declares operation-local write callbacks; nil callbacks are skipped. Example: Hooks[Order]{Creating: func(ctx context.Context, tx *database.Tx, w *Write[Order]) error { return WriteSet(w, orm.Set(Orders.TotalCents, 0)) }}.

type InputColumn

type InputColumn[M, I any, V any] = ColumnHandle[M, V, I, V, RequiredScalarKind, InputRole]

InputColumn accepts I for writes and retains V for stored operations. Example: InputColumn[Member, EmailInput, StoredEmail].

func InputBytesOf

func InputBytesOf[M, I any, V ~[]byte](b Builder[M], ptr *V, transform func(I) (V, error)) InputColumn[M, I, V]

InputBytesOf binds owned stored bytes and a concrete input. Example: InputBytesOf[Document, BodyInput](b, &document.Body, encodeBody).

func InputColumnOf

func InputColumnOf[M, I any, V any](b Builder[M], ptr *V, transform func(I) (V, error), opts ...ColumnOption[V]) InputColumn[M, I, V]

InputColumnOf binds a distinct input. A nil transform selects the model Mutate method. Example: InputColumnOf[Member, EmailInput](b, &member.Email, nil).

type InputEnum

type InputEnum[M, I any, E interface {
	enum.Scalar
	EnumDescriptor() enum.Descriptor[E]
}] = ColumnHandle[M, E, I, E, RequiredEnumKind, InputRole]

InputEnum accepts I for writes and retains E for stored operations. Example: InputEnum[Member, StatusInput, Status].

func InputEnumOf

func InputEnumOf[M, I any, E interface {
	enum.Scalar
	EnumDescriptor() enum.Descriptor[E]
}](b Builder[M], ptr *E, transform func(I) (E, error), opts ...ColumnOption[E]) InputEnum[M, I, E]

InputEnumOf binds a distinct input. A nil transform selects the model Mutate method. Example: InputEnumOf[Member, StatusInput](b, &member.Status, nil).

type InputInterval

InputInterval accepts I for writes and retains temporal.Interval for stored operations. Example: InputInterval[Booking, PeriodInput].

func InputIntervalOf

func InputIntervalOf[M, I any](b Builder[M], ptr *temporal.Interval, transform func(I) (temporal.Interval, error), opts ...ColumnOption[temporal.Interval]) InputInterval[M, I]

InputIntervalOf binds a distinct input. A nil transform selects the model Mutate method. Example: InputIntervalOf[Booking, PeriodInput](b, &booking.Period, nil).

type InputJSON

type InputJSON[M, I any, T any] = ColumnHandle[M, value.JSON[T], I, value.JSON[T], RequiredJSONKind, InputRole]

InputJSON accepts I for writes and retains value.JSON[T] for stored operations. Example: InputJSON[Member, PreferencesInput, Preferences].

func InputJSONOf

func InputJSONOf[M, I any, T any](b Builder[M], ptr *value.JSON[T], transform func(I) (value.JSON[T], error), opts ...ColumnOption[value.JSON[T]]) InputJSON[M, I, T]

InputJSONOf binds a distinct input. A nil transform selects the model Mutate method. Example: InputJSONOf[Member, PreferencesInput](b, &member.Settings, nil).

type InputKey

type InputKey[M, I any, K comparable] = ColumnHandle[M, K, I, K, KeyKind, InputKeyRole]

InputKey retains stored K for lookup and accepts I for primary-key assignment. Example: InputKey[User, FreshID, model.ID[User]].

func InputKeyOf

func InputKeyOf[M, I any, K comparable](b Builder[M], key Key[M, K], transform func(I) (K, error)) InputKey[M, I, K]

InputKeyOf adds a typed input to the primary key already declared by TableOf. A nil transform selects the matching Mutate<Field> method; distinct inputs disable automatic UUID creation. Call inside Define. Example: InputKeyOf[User, FreshID](b, table.Key(), nil).

type InputKeyRole added in v0.48.0

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

InputKeyRole marks a mutator-transformed primary key (orm.InputKey); Set takes input I, predicates compare stored key K, and MapInsert/MapUpdate reject it.

type InputNumber

type InputNumber[M, I any, V NumberValue] = ColumnHandle[M, V, I, V, RequiredNumberKind, InputRole]

InputNumber accepts I for writes and retains V for stored operations. Example: InputNumber[Invoice, AmountInput, int64].

func InputNumberOf

func InputNumberOf[M, I any, V NumberValue](b Builder[M], ptr *V, transform func(I) (V, error), opts ...ColumnOption[V]) InputNumber[M, I, V]

InputNumberOf binds a distinct input. A nil transform selects the model Mutate method. Example: InputNumberOf[Invoice, AmountInput](b, &invoice.Amount, nil).

type InputRole added in v0.48.0

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

InputRole marks a mutator-transformed column (orm.Input*); Set takes input I, predicates compare stored V, and rows.MapInsert/MapUpdate/Increment reject it.

type InputText

type InputText[M, I any, V ~string] = ColumnHandle[M, V, I, V, RequiredTextKind, InputRole]

InputText accepts I for writes and retains V for stored operations. Example: InputText[Member, EmailInput, StoredEmail].

func InputTextOf

func InputTextOf[M, I any, V ~string](b Builder[M], ptr *V, transform func(I) (V, error), opts ...ColumnOption[V]) InputText[M, I, V]

InputTextOf binds a distinct input. A nil transform selects the model Mutate method. Example: InputTextOf[Member, EmailInput](b, &member.Email, nil).

type InputTime

type InputTime[M, I any, V TimeValue] = ColumnHandle[M, V, I, V, RequiredTimeKind, InputRole]

InputTime accepts I for writes and retains V for stored operations. Example: InputTime[Event, TimestampInput, time.Time].

func InputTimeOf

func InputTimeOf[M, I any, V TimeValue](b Builder[M], ptr *V, transform func(I) (V, error), opts ...ColumnOption[V]) InputTime[M, I, V]

InputTimeOf binds a distinct input. A nil transform selects the model Mutate method. Example: InputTimeOf[Event, TimestampInput](b, &event.StartsAt, nil).

type InsertMapping

type InsertMapping[S, M any] struct {
	// contains filtered or unexported fields
}

InsertMapping maps one exact stored source value. Example: rows.MapInsert(Archives.Name, expr.Value(Users.Name)).

func FoundryInsertMapping

func FoundryInsertMapping[S, M any](m ormcore.ModelMapping, seal sqlowner.ExpressionSeal) InsertMapping[S, M]

FoundryInsertMapping binds a framework expression to its destination. Example: FoundryInsertMapping[User,Archive](mapping,sqlowner.Expressions()).

func (InsertMapping[S, M]) Format

func (InsertMapping[S, M]) Format(s fmt.State, _ rune)

Format hides captured source values. Example: fmt.Sprintf("%#v",mapping).

type InsertSelect

type InsertSelect[S, M any] struct {
	// contains filtered or unexported fields
}

InsertSelect inserts a complete source window without per-model callbacks. Example: rows.InsertFrom(rows.From(Users.Query()),Archives.Query()).

func FoundryInsertFrom

func FoundryInsertFrom[S, M any](q Query[M], source ormcore.Source, seal sqlowner.QuerySeal) InsertSelect[S, M]

FoundryInsertFrom creates a source insertion plan. Example: FoundryInsertFrom[User](Archives.Query(),source,sqlowner.Queries()).

func (InsertSelect[S, M]) Exec

func (p InsertSelect[S, M]) Exec(ctx context.Context, writer database.Transactor) (int64, error)

Exec returns the affected count without collecting models. Example: plan.Exec(ctx,db).

func (InsertSelect[S, M]) Format

func (InsertSelect[S, M]) Format(s fmt.State, _ rune)

Format hides captured source values. Example: fmt.Sprintf("%#v",plan).

func (InsertSelect[S, M]) Returning

func (p InsertSelect[S, M]) Returning(ctx context.Context, writer database.Transactor, limit int) ([]M, error)

Returning collects at most limit complete models; overflow rolls back, never truncates. Example: plan.Returning(ctx,db,100).

func (InsertSelect[S, M]) Select

func (p InsertSelect[S, M]) Select(mappings ...InsertMapping[S, M]) InsertSelect[S, M]

Select appends mappings; duplicates and overlap with Values are rejected. Example: plan.Select(rows.MapInsert(Archives.Name, expr.Value(Users.Name))).

func (InsertSelect[S, M]) Values

func (p InsertSelect[S, M]) Values(values ...Assignment[M]) InsertSelect[S, M]

Values replaces literal inputs, normalized once per statement. Example: plan.Values(orm.Set(Archives.Tag, input)).

type InsertableRole added in v0.48.0

type InsertableRole interface {
	ColumnRole
	// contains filtered or unexported methods
}

InsertableRole admits columns eligible for rows.MapInsert (Ordinary, Created, Deleted, Primary); call orm.PrimaryOf for primary keys, and avoid Input/UpdatedAt columns.

type InstantValue

type InstantValue interface{ time.Time | temporal.DateTime }

InstantValue permits managed timestamp fields. Example: CreatedAtOf(b, &o.CreatedAt).

type Interval

Interval supports ordered interval predicates and assignments, retaining calendar components. PostgreSQL compares using 30-day months and 24-hour days: Eq(temporal.Months(1)) also matches 30 days. Hydration preserves distinct calendar and elapsed components. Example: orm.Gt(Records.Period, temporal.Days(1)).

func IntervalOf

func IntervalOf[M any](b Builder[M], ptr *temporal.Interval, opts ...ColumnOption[temporal.Interval]) Interval[M]

IntervalOf binds an interval without enabling numeric adjustments or text patterns. Example: IntervalOf(b, &m.Period).

type IntervalColumnKind added in v0.48.0

type IntervalColumnKind interface {
	ColumnKind
	// contains filtered or unexported methods
}

IntervalColumnKind admits duration interval columns (Interval, NullableInterval) for SumInterval/AvgInterval aggregates.

type JSON

JSON binds a typed JSON document with sorting but without range comparisons or text patterns. Example: orm.Eq(Records.Settings, settings).

func JSONOf

func JSONOf[M, T any](b Builder[M], ptr *value.JSON[T], opts ...ColumnOption[value.JSON[T]]) JSON[M, T]

JSONOf binds immutable typed JSON through its existing codec. Example: JSONOf(b,&m.Settings).

type JSONColumnKind added in v0.48.0

type JSONColumnKind interface {
	ColumnKind
	// contains filtered or unexported methods
}

JSONColumnKind admits JSON document columns (JSON, NullableJSON, InputJSON) for ContainsDocument, ContainedByDocument, and IsJSONNull.

type Key

type Key[M any, K comparable] = ColumnHandle[M, K, K, K, KeyKind, LookupKeyRole]

Key identifies a table's primary column. Example: orm.Eq(Orders.Key(), id).

type KeyKind added in v0.48.0

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

KeyKind marks a required model primary key column (orm.Key/orm.Primary); use orm.NumberKey/TextKey for ordered or text operations.

type KeyLink[M, N any, K comparable] struct {
	// contains filtered or unexported fields
}

KeyLink represents a typed key-equality join edge between two models.

func JoinKeys added in v0.48.0

func JoinKeys[M, N any, K comparable, I1, P1 any, K1 ColumnKind, R1 ColumnRole, I2, P2 any, K2 ColumnKind, R2 ColumnRole](local ColumnHandle[M, K, I1, P1, K1, R1], foreign ColumnHandle[N, K, I2, P2, K2, R2]) KeyLink[M, N, K]

JoinKeys binds a matching key pair across two models directly from their columns. Example: orm.JoinKeys(Users.ID, Memberships.UserID).

type KeyLookup

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

KeyLookup retains a filtered declaration and a typed lookup key. Example: orm.Keyed(Users.Query(),Users.Key()).Find(ctx,db,id).

func Keyed

func Keyed[M any, K comparable](q Query[M], key Key[M, K]) KeyLookup[M, K]

Keyed retains filters, eager loads, soft-delete scope and retrieval hooks. Example: modelbinding.ByKey(db,orm.Keyed(Users.Query(),Users.Key()),pathKey).

func Unique

func Unique[M any, K comparable, I, P any, Kind ColumnKind, R ColumnRole](q Query[M], field ColumnHandle[M, K, I, P, Kind, R]) KeyLookup[M, K]

Unique binds a stored alternate key, rejecting a second matching row. Example: orm.Unique(Users.Query(), Users.Email).Find(ctx, db, email).

func (KeyLookup[M, K]) Find

func (l KeyLookup[M, K]) Find(ctx context.Context, ex database.Executor, key K) (value.Optional[M], error)

Find performs one parameterized SELECT; only unique results receive eager loads. Example: lookup.Find(ctx,db,key).

func (KeyLookup[M, K]) Format

func (KeyLookup[M, K]) Format(s fmt.State, _ rune)

Format redacts scope literals and model metadata. Example: fmt.Sprintf("%+v", lookup).

func (KeyLookup[M, K]) GoString

func (KeyLookup[M, K]) GoString() string

GoString redacts Go-syntax diagnostics. Example: fmt.Sprintf("%#v", lookup).

func (KeyLookup[M, K]) String

func (KeyLookup[M, K]) String() string

String redacts scope literals. Example: fmt.Sprint(lookup).

func (KeyLookup[M, K]) Validate

func (l KeyLookup[M, K]) Validate() error

Validate checks the declaration without SQL. Example: lookup.Validate().

type KeyRole added in v0.48.0

type KeyRole interface {
	ColumnRole
	// contains filtered or unexported methods
}

KeyRole admits primary-key roles (LookupKeyRole, PrimaryRole) used by orm.NumberKey and orm.TextKey.

type LockedQuery

type LockedQuery[M any] struct {
	// contains filtered or unexported fields
}

LockedQuery requires a transaction for every terminal. Example: orm.AllLocked(ctx, tx, orm.Lock(Orders.Query())).

func ForKeyShare added in v0.2.0

func ForKeyShare[M any](q Query[M]) LockedQuery[M]

ForKeyShare protects selected keys against physical deletion and key changes.

func ForNoKeyUpdate added in v0.2.0

func ForNoKeyUpdate[M any](q Query[M]) LockedQuery[M]

ForNoKeyUpdate requests a lock compatible with key-share locks.

func ForShare added in v0.2.0

func ForShare[M any](q Query[M]) LockedQuery[M]

ForShare requests share locks. Example: orm.AllLocked(ctx, tx, orm.ForShare(Orders.Query())).

func Lock added in v0.2.0

func Lock[M any](q Query[M]) LockedQuery[M]

Lock requests update locks. Example: orm.AllLocked(ctx, tx, orm.Lock(Orders.Query())).

func (LockedQuery[M]) Limit

func (q LockedQuery[M]) Limit(n int) LockedQuery[M]

Limit bounds locked rows.

func (LockedQuery[M]) NoWait

func (q LockedQuery[M]) NoWait() LockedQuery[M]

NoWait fails instead of waiting for conflicting locks.

func (LockedQuery[M]) Offset

func (q LockedQuery[M]) Offset(n int) LockedQuery[M]

Offset skips matching rows before locking.

func (LockedQuery[M]) OnlyTrashed

func (q LockedQuery[M]) OnlyTrashed() LockedQuery[M]

OnlyTrashed selects deleted rows.

func (LockedQuery[M]) OrderBy

func (q LockedQuery[M]) OrderBy(os ...Order[M]) LockedQuery[M]

OrderBy appends locked-row ordering.

func (LockedQuery[M]) SkipLocked

func (q LockedQuery[M]) SkipLocked() LockedQuery[M]

SkipLocked skips rows held by conflicting locks.

func (LockedQuery[M]) Wait

func (q LockedQuery[M]) Wait() LockedQuery[M]

Wait restores the default waiting behavior.

func (LockedQuery[M]) Where

func (q LockedQuery[M]) Where(ps ...Predicate[M]) LockedQuery[M]

Where adds conditions to a locked query.

func (LockedQuery[M]) WithTrashed

func (q LockedQuery[M]) WithTrashed() LockedQuery[M]

WithTrashed includes deleted rows.

func (LockedQuery[M]) WithoutTrashed

func (q LockedQuery[M]) WithoutTrashed() LockedQuery[M]

WithoutTrashed selects active rows.

type LookupKeyRole added in v0.48.0

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

LookupKeyRole marks a primary key lookup handle (Table.Key()); declare orm.PrimaryOf(b, table.Key()) to allow rows.MapInsert.

type Many

type Many[M, N any] struct {
	// contains filtered or unexported fields
}

Many identifies a collection slot. Example: Orders Many[User,Order].

func ManyOf

func ManyOf[M, N any](b Builder[M], ptr *relation.Many[N]) Many[M, N]

ManyOf binds a collection slot during Define. Example: ManyOf(b,&u.Orders).

type ModelIdentity

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

ModelIdentity retains a declaration's concrete primary key without model methods. Identity reads select keys only and do not run retrieval hooks. Example: orm.IdentityOf(Users.Table, Users.Key()).

func IdentityOf

func IdentityOf[M any, K comparable](table Table[M, K], key Key[M, K]) ModelIdentity[M, K]

IdentityOf binds the model's own primary handle. Example: orm.IdentityOf(Users.Table, Users.Key()).

func (ModelIdentity[M, K]) ActiveKeys

func (d ModelIdentity[M, K]) ActiveKeys(ctx context.Context, ex database.Executor, keys []K) ([]K, error)

ActiveKeys selects currently visible keys in one bounded statement. Example: identity.ActiveKeys(ctx,db,ids).

func (ModelIdentity[M, K]) KeyToken

func (d ModelIdentity[M, K]) KeyToken(key K) (string, error)

KeyToken preserves SQL equality canonicalization for extension storage. Example: identity.KeyToken(id).

func (ModelIdentity[M, K]) LockActive

func (d ModelIdentity[M, K]) LockActive(ctx context.Context, tx *database.Tx, key K) (bool, error)

LockActive locks one visible owner in the caller's transaction. Example: identity.LockActive(ctx,tx,id).

func (ModelIdentity[M, K]) ModelName

func (d ModelIdentity[M, K]) ModelName() string

ModelName returns the persisted table name. Example: identity.ModelName().

func (ModelIdentity[M, K]) Parse

func (d ModelIdentity[M, K]) Parse(stored model.Identity) (model.Reference[M, K], error)

Parse restores a reference with the same model and codec. Example: identity.Parse(stored).

func (ModelIdentity[M, K]) Reference

func (d ModelIdentity[M, K]) Reference(key K) model.Reference[M, K]

Reference builds a typed reference using the stored key codec. Example: identity.Reference(id).

func (ModelIdentity[M, K]) ReferenceOf

func (d ModelIdentity[M, K]) ReferenceOf(m M) model.Reference[M, K]

ReferenceOf reads the model's stored primary key without I/O. Example: identity.ReferenceOf(user).

func (ModelIdentity[M, K]) RetainedKeys

func (d ModelIdentity[M, K]) RetainedKeys(ctx context.Context, ex database.Executor, keys []K) ([]K, error)

RetainedKeys includes soft-deleted owners for orphan inspection. Example: identity.RetainedKeys(ctx,db,ids).

func (ModelIdentity[M, K]) Scope

func (d ModelIdentity[M, K]) Scope(keys ...K) Predicate[M]

Scope retains model and key ownership for bounded membership. Example: Users.Query().Where(identity.Scope(ids...)).

func (ModelIdentity[M, K]) Validate

func (d ModelIdentity[M, K]) Validate() error

Validate rejects zero declarations and keys from another declaration. Example: identity.Validate().

type NullableColumn

type NullableColumn[M, V any] = ColumnHandle[M, V, V, value.Nullable[V], NullableScalarKind, OrdinaryRole]

NullableColumn exposes explicit NULL. Example: orm.SetNull(Users.IntroducerID).

func NullableBytesOf

func NullableBytesOf[M any, V ~[]byte](b Builder[M], ptr *value.Nullable[V], opts ...ColumnOption[V]) NullableColumn[M, V]

NullableBytesOf binds nullable binary values. Example: NullableBytesOf(b,&o.Payload).

func NullableColumnOf

func NullableColumnOf[M, V any](b Builder[M], ptr *value.Nullable[V], opts ...ColumnOption[V]) NullableColumn[M, V]

NullableColumnOf binds nullable scalar values. Example: NullableColumnOf(b,&o.IntroducerID).

func NullableIDOf

func NullableIDOf[M, T any](b Builder[M], ptr *value.Nullable[model.ID[T]]) NullableColumn[M, model.ID[T]]

NullableIDOf declares a nullable model-owned ID. Example: NullableIDOf(b, &u.IntroducerID).

func NullablePasswordOf

func NullablePasswordOf[M any](b Builder[M], ptr *value.Nullable[password.Hash]) NullableColumn[M, password.Hash]

NullablePasswordOf adds SQL NULL operations to a sensitive stored hash. Example: orm.SetNull(Accounts.Backup).

type NullableColumnKind added in v0.48.0

type NullableColumnKind interface {
	AnyColumnKind
	// contains filtered or unexported methods
}

NullableColumnKind admits nullable columns including NullableEncrypted (used by IsNull, IsNotNull, SetNull, AuditReadNullable, and NullableChangeOf); required columns must not call null operations.

type NullableComparableKind added in v0.48.0

type NullableComparableKind interface {
	ColumnKind
	NullableColumnKind
}

NullableComparableKind admits nullable queryable (non-encrypted) columns; use required entry points for non-null columns and IsNull/SetNull for encrypted ones.

type NullableEncrypted

type NullableEncrypted[M any, V encrypted.Value[V]] = ColumnHandle[M, V, V, value.Nullable[V], NullableEncryptedKind, OrdinaryRole]

NullableEncrypted adds only SQL NULL predicates and assignments. Example: orm.IsNull(Vaults.Backup).

func NullableEncryptedJSONOf

func NullableEncryptedJSONOf[M, T any](b Builder[M], ptr *value.Nullable[encrypted.JSON[T]]) NullableEncrypted[M, encrypted.JSON[T]]

NullableEncryptedJSONOf adds SQL NULL to encrypted JSON. Example: NullableEncryptedJSONOf(b,&m.BackupSettings).

func NullableEncryptedTextOf

func NullableEncryptedTextOf[M any](b Builder[M], ptr *value.Nullable[encrypted.Text]) NullableEncrypted[M, encrypted.Text]

NullableEncryptedTextOf adds SQL NULL to encrypted text. Example: NullableEncryptedTextOf(b,&m.Backup).

type NullableEncryptedKind added in v0.48.0

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

NullableEncryptedKind marks a nullable encrypted column (orm.NullableEncrypted); only Set, SetIfPresent, SetNull, IsNull, IsNotNull, AuditField, AuditReadNullable, and NullableChangeOf are legal.

type NullableEnum

type NullableEnum[M any, E enum.Scalar] = ColumnHandle[M, E, E, value.Nullable[E], NullableEnumKind, OrdinaryRole]

NullableEnum exposes nullable enums. Example: orm.SetNull(records.Status).

func NullableEnumOf

func NullableEnumOf[M any, E interface {
	enum.Scalar
	EnumDescriptor() enum.Descriptor[E]
}](b Builder[M], ptr *value.Nullable[E], opts ...ColumnOption[E]) NullableEnum[M, E]

NullableEnumOf binds nullable enums. Example: NullableEnumOf(b,&o.Status).

type NullableEnumColumnKind added in v0.48.0

type NullableEnumColumnKind interface {
	ColumnKind
	NullableColumnKind
	// contains filtered or unexported methods
}

NullableEnumColumnKind admits nullable enum columns for datatable.NullableEnum; use Enum* for non-null enums.

type NullableEnumKind added in v0.48.0

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

NullableEnumKind marks a nullable enum column (orm.NullableEnum); supports equality, null checks, and datatable.NullableEnum.

type NullableInputColumn

type NullableInputColumn[M, I any, V any] = ColumnHandle[M, V, I, value.Nullable[V], NullableScalarKind, InputRole]

NullableInputColumn accepts I for writes and retains V for stored operations. Example: NullableInputColumn[Member, LabelInput, StoredLabel].

func NullableInputBytesOf

func NullableInputBytesOf[M, I any, V ~[]byte](b Builder[M], ptr *value.Nullable[V], transform func(I) (V, error)) NullableInputColumn[M, I, V]

NullableInputBytesOf binds owned stored bytes and a concrete input. Example: NullableInputBytesOf[Document, BodyInput](b, &document.Body, encodeBody).

func NullableInputColumnOf

func NullableInputColumnOf[M, I any, V any](b Builder[M], ptr *value.Nullable[V], transform func(I) (V, error), opts ...ColumnOption[V]) NullableInputColumn[M, I, V]

NullableInputColumnOf binds a distinct input. A nil transform selects the model Mutate method. Example: NullableInputColumnOf[Member, LabelInput](b, &member.Note, nil).

type NullableInputEnum

type NullableInputEnum[M, I any, E interface {
	enum.Scalar
	EnumDescriptor() enum.Descriptor[E]
}] = ColumnHandle[M, E, I, value.Nullable[E], NullableEnumKind, InputRole]

NullableInputEnum accepts I for writes and retains E for stored operations. Example: NullableInputEnum[Member, StatusInput, Status].

func NullableInputEnumOf

func NullableInputEnumOf[M, I any, E interface {
	enum.Scalar
	EnumDescriptor() enum.Descriptor[E]
}](b Builder[M], ptr *value.Nullable[E], transform func(I) (E, error), opts ...ColumnOption[E]) NullableInputEnum[M, I, E]

NullableInputEnumOf binds a distinct input. A nil transform selects the model Mutate method. Example: NullableInputEnumOf[Member, StatusInput](b, &member.Status, nil).

type NullableInputInterval

NullableInputInterval accepts I for writes and retains temporal.Interval for stored operations. Example: NullableInputInterval[Booking, PeriodInput].

func NullableInputIntervalOf

func NullableInputIntervalOf[M, I any](b Builder[M], ptr *value.Nullable[temporal.Interval], transform func(I) (temporal.Interval, error), opts ...ColumnOption[temporal.Interval]) NullableInputInterval[M, I]

NullableInputIntervalOf binds a distinct input. A nil transform selects the model Mutate method. Example: NullableInputIntervalOf[Booking, PeriodInput](b, &booking.Period, nil).

type NullableInputJSON

type NullableInputJSON[M, I any, T any] = ColumnHandle[M, value.JSON[T], I, value.Nullable[value.JSON[T]], NullableJSONKind, InputRole]

NullableInputJSON accepts I for writes and retains value.JSON[T] for stored operations. Example: NullableInputJSON[Member, PreferencesInput, Preferences].

func NullableInputJSONOf

func NullableInputJSONOf[M, I any, T any](b Builder[M], ptr *value.Nullable[value.JSON[T]], transform func(I) (value.JSON[T], error), opts ...ColumnOption[value.JSON[T]]) NullableInputJSON[M, I, T]

NullableInputJSONOf binds a distinct input. A nil transform selects the model Mutate method. Example: NullableInputJSONOf[Member, PreferencesInput](b, &member.Settings, nil).

type NullableInputNumber

type NullableInputNumber[M, I any, V NumberValue] = ColumnHandle[M, V, I, value.Nullable[V], NullableNumberKind, InputRole]

NullableInputNumber accepts I for writes and retains V for stored operations. Example: NullableInputNumber[Invoice, AmountInput, int64].

func NullableInputNumberOf

func NullableInputNumberOf[M, I any, V NumberValue](b Builder[M], ptr *value.Nullable[V], transform func(I) (V, error), opts ...ColumnOption[V]) NullableInputNumber[M, I, V]

NullableInputNumberOf binds a distinct input. A nil transform selects the model Mutate method. Example: NullableInputNumberOf[Invoice, AmountInput](b, &invoice.Amount, nil).

type NullableInputText

type NullableInputText[M, I any, V ~string] = ColumnHandle[M, V, I, value.Nullable[V], NullableTextKind, InputRole]

NullableInputText accepts I for writes and retains V for stored operations. Example: NullableInputText[Member, LabelInput, StoredLabel].

func NullableInputTextOf

func NullableInputTextOf[M, I any, V ~string](b Builder[M], ptr *value.Nullable[V], transform func(I) (V, error), opts ...ColumnOption[V]) NullableInputText[M, I, V]

NullableInputTextOf binds a distinct input. A nil transform selects the model Mutate method. Example: NullableInputTextOf[Member, LabelInput](b, &member.Note, nil).

type NullableInputTime

type NullableInputTime[M, I any, V TimeValue] = ColumnHandle[M, V, I, value.Nullable[V], NullableTimeKind, InputRole]

NullableInputTime accepts I for writes and retains V for stored operations. Example: NullableInputTime[Event, TimestampInput, time.Time].

func NullableInputTimeOf

func NullableInputTimeOf[M, I any, V TimeValue](b Builder[M], ptr *value.Nullable[V], transform func(I) (V, error), opts ...ColumnOption[V]) NullableInputTime[M, I, V]

NullableInputTimeOf binds a distinct input. A nil transform selects the model Mutate method. Example: NullableInputTimeOf[Event, TimestampInput](b, &event.StartsAt, nil).

type NullableInterval

NullableInterval adds SQL NULL to interval predicates and assignments. PostgreSQL compares using 30-day months and 24-hour days: Eq(temporal.Months(1)) also matches 30 days. Hydration preserves distinct calendar and elapsed components. Example: orm.IsNull(Records.MaybePeriod).

func NullableIntervalOf

func NullableIntervalOf[M any](b Builder[M], ptr *value.Nullable[temporal.Interval], opts ...ColumnOption[temporal.Interval]) NullableInterval[M]

NullableIntervalOf binds nullable intervals. Example: NullableIntervalOf(b, &m.MaybePeriod).

type NullableIntervalKind added in v0.48.0

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

NullableIntervalKind marks a nullable duration interval column (orm.NullableInterval); supports ordering, null checks, and interval aggregates.

type NullableJSON

type NullableJSON[M, T any] = ColumnHandle[M, value.JSON[T], value.JSON[T], value.Nullable[value.JSON[T]], NullableJSONKind, OrdinaryRole]

NullableJSON distinguishes SQL NULL from a typed JSON document, including JSON null. Example: orm.IsNull(Records.MaybeSettings).

func NullableJSONOf

func NullableJSONOf[M, T any](b Builder[M], ptr *value.Nullable[value.JSON[T]], opts ...ColumnOption[value.JSON[T]]) NullableJSON[M, T]

NullableJSONOf binds nullable typed JSON. Example: NullableJSONOf(b,&m.MaybeSettings).

type NullableJSONKind added in v0.48.0

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

NullableJSONKind marks a nullable JSON document column (orm.NullableJSON); supports JSON document predicates and SQL null checks.

type NullableNumber

type NullableNumber[M any, V NumberValue] = ColumnHandle[M, V, V, value.Nullable[V], NullableNumberKind, OrdinaryRole]

NullableNumber exposes nullable numeric values. Example: orm.IsNull(LedgerEntries.Balance).

func NullableNumberOf

func NullableNumberOf[M any, V NumberValue](b Builder[M], ptr *value.Nullable[V], opts ...ColumnOption[V]) NullableNumber[M, V]

NullableNumberOf binds nullable numeric values. Example: NullableNumberOf(b,&o.Balance).

type NullableNumberKind added in v0.48.0

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

NullableNumberKind marks a nullable numeric column (orm.NullableNumber); supports ordering, aggregates, adjustments, and null checks.

type NullableNumericColumnKind added in v0.48.0

type NullableNumericColumnKind interface {
	NumericColumnKind
	NullableColumnKind
}

NullableNumericColumnKind admits nullable numeric columns for datatable.NullableNumber; use Number* for non-null numbers.

type NullableOrderedKind added in v0.48.0

type NullableOrderedKind interface {
	OrderedKind
	NullableColumnKind
}

NullableOrderedKind admits nullable ordered columns; use required ordered entry points for non-null columns.

type NullableScalarKind added in v0.48.0

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

NullableScalarKind marks a nullable general scalar column (orm.NullableColumn); supports null checks and SetNull.

type NullableText

type NullableText[M any, V ~string] = ColumnHandle[M, V, V, value.Nullable[V], NullableTextKind, OrdinaryRole]

NullableText exposes nullable text. Example: orm.SetNull(Users.Nickname).

func NullableTextOf

func NullableTextOf[M any, V ~string](b Builder[M], ptr *value.Nullable[V], opts ...ColumnOption[V]) NullableText[M, V]

NullableTextOf binds nullable text. Example: NullableTextOf(b,&o.Nickname).

type NullableTextColumnKind added in v0.48.0

type NullableTextColumnKind interface {
	TextColumnKind
	NullableColumnKind
}

NullableTextColumnKind admits nullable text columns (e.g. expr.TextNullableRow, datatable.NullableText); use required Text* for non-null text.

type NullableTextKind added in v0.48.0

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

NullableTextKind marks a nullable text column (orm.NullableText); supports text patterns, null checks, and datatable.NullableText.

type NullableTime

type NullableTime[M any, V TimeValue] = ColumnHandle[M, V, V, value.Nullable[V], NullableTimeKind, OrdinaryRole]

NullableTime exposes nullable temporal values. Example: orm.IsNull(Users.Birthday).

func NullableTimeOf

func NullableTimeOf[M any, V TimeValue](b Builder[M], ptr *value.Nullable[V], opts ...ColumnOption[V]) NullableTime[M, V]

NullableTimeOf binds nullable temporal values. Example: NullableTimeOf(b,&o.Birthday).

type NullableTimeColumnKind added in v0.48.0

type NullableTimeColumnKind interface {
	OrderedKind
	NullableColumnKind
	// contains filtered or unexported methods
}

NullableTimeColumnKind admits nullable date/time columns for datatable.NullableTime; use Time* for non-null timestamps.

type NullableTimeKind added in v0.48.0

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

NullableTimeKind marks a nullable date or timestamp column (orm.NullableTime/SoftDelete); supports ordering, null checks, and datatable.NullableTime.

type Number

type Number[M any, V NumberValue] = ColumnHandle[M, V, V, V, RequiredNumberKind, OrdinaryRole]

Number exposes ordered numeric comparisons. Example: Number[Order,int64].

func NumberOf

func NumberOf[M any, V NumberValue](b Builder[M], ptr *V, opts ...ColumnOption[V]) Number[M, V]

NumberOf selects a numeric codec at startup. Example: NumberOf(b,&o.TotalCents).

type NumberColumnKind added in v0.48.0

type NumberColumnKind interface {
	OrderedKind
	// contains filtered or unexported methods
}

NumberColumnKind admits adjustable numeric columns (Number, NullableNumber) for Increment/Decrement; NumberKey and plain Column[M, int64] are excluded.

type NumberKeyKind added in v0.48.0

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

NumberKeyKind marks a numeric primary key (orm.NumberKey); supports ordering and aggregates but rejects Increment/Decrement.

type NumberLookupKey

type NumberLookupKey[M any, K interface {
	NumberValue
	comparable
}] = ColumnHandle[M, K, K, K, NumberKeyKind, LookupKeyRole]

NumberLookupKey retains the primary lookup role. Example: NumberKey(table.Key()).

type NumberPrimary

type NumberPrimary[M any, K interface {
	NumberValue
	comparable
}] = ColumnHandle[M, K, K, K, NumberKeyKind, PrimaryRole]

NumberPrimary preserves numeric primary capabilities. Example: NumberKey(PrimaryOf(b, table.Key())).

type NumberValue

type NumberValue interface {
	~int | ~int8 | ~int16 | ~int32 | ~int64 | ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~float32 | ~float64 | decimal.Decimal
}

NumberValue permits exact and approximate numeric fields. Example: Number[Order, int64].

type NumericColumnKind added in v0.48.0

type NumericColumnKind interface {
	OrderedKind
	// contains filtered or unexported methods
}

NumericColumnKind admits numeric columns (Number, NullableNumber, NumberKey) for Sum/Avg aggregates; declare numeric columns with orm.NumberOf, not orm.ColumnOf.

type Observer

type Observer[M any] struct {
	// contains filtered or unexported fields
}

Observer fixes registration to this model's Hooks type. Example: NewObserver[Order]("orders.audit").

func NewDeletionObserver

func NewDeletionObserver[M any](name string) Observer[M]

NewDeletionObserver observes only delete/soft-delete/force-delete writes. Example: NewDeletionObserver[Order]("orders.removal").

func NewObserver

func NewObserver[M any](name string) Observer[M]

NewObserver declares a write observer without invoking its factory. Example: NewObserver[Order]("orders.audit").

func (Observer[M]) Declare

func (o Observer[M]) Declare(factory func() Hooks[M]) (lifecycle.Declaration, error)

Declare captures a typed per-operation factory. Example: NewObserver[Order]("orders.audit").Declare(orderAuditHooks).

func (Observer[M]) Name

func (o Observer[M]) Name() string

Name returns the registration identifier. Example: observer.Name().

func (Observer[M]) Validate

func (o Observer[M]) Validate() error

Validate checks the immutable identifier without invoking its factory. Example: observer.Validate().

type One

type One[M, N any] struct {
	// contains filtered or unexported fields
}

One identifies a singular model slot. Example: Buyer One[Order,User].

func OneOf

func OneOf[M, N any](b Builder[M], ptr *relation.One[N]) One[M, N]

OneOf binds a singular relation slot during Define. Example: OneOf(b,&o.Buyer).

type Option

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

Option configures a declaration. Example: Define("logs", declare, NoTimestamps()).

func NoSoftDeletes

func NoSoftDeletes() Option

NoSoftDeletes disables the DeletedAt convention. Explicit SoftDeleteOf conflicts with this option.

func NoTimestamps

func NoTimestamps() Option

NoTimestamps disables CreatedAt/UpdatedAt conventions. Example: NoTimestamps().

func WithGlobalScopes

func WithGlobalScopes[M any, T CheckedTable](source func(T) []GlobalScope[M]) Option

WithGlobalScopes attaches a lazy immutable source, evaluated once when needed. The source receives an owned copy of the completed declaration, avoiding Go initialization cycles. It may reference relations; it must not execute or compile queries. Example: WithGlobalScopes(func(t OrderTable) []GlobalScope[Order] { return []GlobalScope[Order]{Scope(t.Table, "tenant", tenantPredicate(t))} }).

func WithHooks

func WithHooks[M any](factory func() Hooks[M]) Option

WithHooks installs a factory invoked once per normal write, after row locking. Example: Define("orders", declareOrders, WithHooks(func() Hooks[Order] { return Hooks[Order]{} })).

func WithRetrievalHooks

func WithRetrievalHooks[M any](factory func() RetrievalHooks[M]) Option

WithRetrievalHooks installs a factory run once per nonempty complete batch. Example: WithRetrievalHooks(func() RetrievalHooks[Order] { return orderReadHooks() }).

type Order

type Order[M any] struct {
	// contains filtered or unexported fields
}

Order is a model-owned sort direction. Example: orm.Asc(Orders.ID).

func Asc added in v0.48.0

func Asc[M, V, I, P any, K ColumnKind, R ColumnRole](c ColumnHandle[M, V, I, P, K, R]) Order[M]

Asc orders a query ascending by a queryable column. Example: orm.Asc(Orders.ID).

func Desc added in v0.48.0

func Desc[M, V, I, P any, K ColumnKind, R ColumnRole](c ColumnHandle[M, V, I, P, K, R]) Order[M]

Desc orders a query descending by a queryable column. Example: orm.Desc(Orders.CreatedAt).

func FoundryRelationOrder

func FoundryRelationOrder[M, N any](r ExistenceRelation[M, N], o ormcore.Order, seal sqlowner.MetadataSeal) Order[N]

FoundryRelationOrder validates a computed order against the actual relation target. Example: FoundryRelationOrder(r,o,sqlowner.Metadata()).

func FoundryRelationPivotOrder

func FoundryRelationPivotOrder[M, N, P any](r ThroughRelation[M, N, P], o ormcore.Order, seal sqlowner.MetadataSeal) Order[P]

FoundryRelationPivotOrder validates both relation owners and the concrete pivot. Example: FoundryRelationPivotOrder(r,o,sqlowner.Metadata()).

func (Order[M]) NullsFirst

func (o Order[M]) NullsFirst() Order[M]

NullsFirst places NULL before concrete values.

func (Order[M]) NullsLast

func (o Order[M]) NullsLast() Order[M]

NullsLast places NULL after concrete values.

type OrderedKind added in v0.48.0

type OrderedKind interface {
	ColumnKind
	// contains filtered or unexported methods
}

OrderedKind admits columns with SQL range ordering (Number, NumberKey, Text, Time, Interval); Enum, JSON, Key, and Encrypted cannot use Gt/Lt/Between/Min/Max.

type OrdinaryRole added in v0.48.0

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

OrdinaryRole marks a standard mutable model column; valid for predicates, writes, adjustments, and row mappings.

type PageRequest

type PageRequest = querycore.PageRequest

PageRequest retains the existing pagination validation contract. Example: Page(2,20).

func Page

func Page(number, size int) PageRequest

Page selects a one-based page. Example: orm.Paginate(ctx, db, Orders.Query(), Page(2,20)).

type PageResult

type PageResult[M any] = querycore.Page[M]

PageResult retains the existing pagination response contract. Example: page.Items.

func Paginate added in v0.2.0

func Paginate[M any](ctx context.Context, ex database.Executor, q Query[M], request PageRequest) (PageResult[M], error)

Paginate reads a matching total and a stable page. Example: orm.Paginate(ctx, db, Orders.Query(), Page(1,20)).

type PivotChanges

type PivotChanges[P any] struct {
	// Attached contains newly inserted pivots. Example: changes.Attached[0].ID
	// identifies the membership created by Sync or Toggle.
	Attached []P
	// Detached contains pivots removed by Sync or Toggle. Soft-delete models
	// remain stored with DeletedAt set; ordinary models are physically deleted.
	// Example: changes.Detached[0].ID identifies the removed membership in either case.
	Detached []P
	// Updated contains retained pivots patched by Sync or SyncWithoutDetaching.
	// Example: changes.Updated[0].Role is the membership role after its update.
	Updated []P
}

PivotChanges contains reconciliation-ready concrete pivot models. Example: changes.Attached[0].ID.

func Sync

func Sync[M, N, P any](ctx context.Context, writer database.Transactor, r ThroughRelation[M, N, P], source M, targets []N, create, update []Assignment[P]) (PivotChanges[P], error)

Sync creates missing links, removes others and optionally updates retained links. A nil update leaves retained links unchanged. Example: orm.Sync(ctx,db,links,user,groups,create,nil).

func SyncWithoutDetaching

func SyncWithoutDetaching[M, N, P any](ctx context.Context, writer database.Transactor, r ThroughRelation[M, N, P], source M, targets []N, create, update []Assignment[P]) (PivotChanges[P], error)

SyncWithoutDetaching creates missing links and optionally updates retained links. Example: orm.SyncWithoutDetaching(ctx,db,links,user,groups,create,nil).

func Toggle

func Toggle[M, N, P any](ctx context.Context, writer database.Transactor, r ThroughRelation[M, N, P], source M, targets []N, create ...Assignment[P]) (PivotChanges[P], error)

Toggle removes linked targets and attaches unlinked targets atomically. Example: orm.Toggle(ctx,db,links,user,groups,orm.Set(Memberships.Role, "member")).

type Plan

type Plan = querycore.Plan

Plan owns bounded PostgreSQL plan data; formatting omits predicates and values. Example: plan.Root().TotalCost.

func Explain

func Explain[M any](ctx context.Context, ex database.Executor, q Query[M]) (Plan, error)

Explain plans a SELECT without hydration, retrieval callbacks or eager loads. Example: orm.Explain(ctx, db, Users.Query()).

func ExplainAnalyze

func ExplainAnalyze[M any](ctx context.Context, ex database.Executor, q Query[M]) (Plan, error)

ExplainAnalyze executes the SELECT and includes actual measurements. Example: orm.ExplainAnalyze(ctx, db, Users.Query().Limit(10)).

func ExplainAnalyzeLocked

func ExplainAnalyzeLocked[M any](ctx context.Context, tx *database.Tx, q LockedQuery[M]) (Plan, error)

ExplainAnalyzeLocked takes the SELECT locks in the caller's transaction. Example: orm.ExplainAnalyzeLocked(ctx, tx, orm.Lock(Users.Query())).

func ExplainLocked

func ExplainLocked[M any](ctx context.Context, tx *database.Tx, q LockedQuery[M]) (Plan, error)

ExplainLocked plans a locked SELECT using its required transaction. Example: orm.ExplainLocked(ctx, tx, orm.Lock(Users.Query())).

type PlanNode

type PlanNode = querycore.PlanNode

PlanNode contains typed planner statistics. Example: plan.Root().NodeType.

type Predicate

type Predicate[M any] struct {
	// contains filtered or unexported fields
}

Predicate is a model-owned SQL condition. Example: orm.Eq(Orders.ID, id).

func And

func And[M any](ps ...Predicate[M]) Predicate[M]

And combines model-owned conditions. Example: orm.And(orm.Eq(Orders.ID, id), orm.Gt(Orders.TotalCents, 0)).

func Between added in v0.48.0

func Between[M, V, I, P any, K OrderedKind, R ColumnRole](c ColumnHandle[M, V, I, P, K, R], a, b V) Predicate[M]

Between includes both endpoints on an ordered column. Example: orm.Between(Orders.TotalCents, 100, 500).

func ContainedByDocument added in v0.48.0

func ContainedByDocument[M, V, I, P any, K JSONColumnKind, R ColumnRole](c ColumnHandle[M, V, I, P, K, R], v V) Predicate[M]

ContainedByDocument tests reverse JSONB containment (<@) on a JSON column. Example: orm.ContainedByDocument(Records.Settings, superset).

func Contains added in v0.48.0

func Contains[M any, V ~string, I, P any, K TextColumnKind, R ColumnRole](c ColumnHandle[M, V, I, P, K, R], v V) Predicate[M]

Contains matches a literal substring on a text column. Example: orm.Contains(Users.Email, "@").

func ContainsDocument added in v0.48.0

func ContainsDocument[M, V, I, P any, K JSONColumnKind, R ColumnRole](c ColumnHandle[M, V, I, P, K, R], v V) Predicate[M]

ContainsDocument tests JSONB containment (@>) on a JSON column. Example: orm.ContainsDocument(Records.Settings, subset).

func EndsWith added in v0.48.0

func EndsWith[M any, V ~string, I, P any, K TextColumnKind, R ColumnRole](c ColumnHandle[M, V, I, P, K, R], v V) Predicate[M]

EndsWith matches a literal suffix on a text column. Example: orm.EndsWith(Users.Email, ".org").

func Eq added in v0.48.0

func Eq[M, V, I, P any, K ColumnKind, R ColumnRole](c ColumnHandle[M, V, I, P, K, R], v V) Predicate[M]

Eq compares a queryable column against a concrete value. Example: orm.Eq(Orders.BuyerID, id).

func FoundryRelationFilter

func FoundryRelationFilter[M, N any](r ExistenceRelation[M, N], p ormcore.Predicate, seal sqlowner.MetadataSeal) Predicate[N]

FoundryRelationFilter validates expression conditions for a relation target. Example: FoundryRelationFilter(r,p,sqlowner.Metadata()).

func FoundryRelationPredicate

func FoundryRelationPredicate[M, N any](r ExistenceRelation[M, N], ps []ormcore.Predicate, seal sqlowner.MetadataSeal) Predicate[M]

FoundryRelationPredicate validates projected child conditions at the relation owner. Example: FoundryRelationPredicate(r,ps,sqlowner.Metadata()).

func Gt added in v0.48.0

func Gt[M, V, I, P any, K OrderedKind, R ColumnRole](c ColumnHandle[M, V, I, P, K, R], v V) Predicate[M]

Gt compares an ordered column against a lower exclusive bound. Example: orm.Gt(Orders.TotalCents, 0).

func Gte added in v0.48.0

func Gte[M, V, I, P any, K OrderedKind, R ColumnRole](c ColumnHandle[M, V, I, P, K, R], v V) Predicate[M]

Gte compares an ordered column against a lower inclusive bound. Example: orm.Gte(Orders.TotalCents, 100).

func Has

func Has[M, N any](r ExistenceRelation[M, N], ps ...Predicate[N]) Predicate[M]

Has matches parents with related rows satisfying the target predicates and related scopes, without eager loading. Example: Users.Query().Where(orm.Has(UserRelations.Orders)).

func IContains added in v0.48.0

func IContains[M any, V ~string, I, P any, K TextColumnKind, R ColumnRole](c ColumnHandle[M, V, I, P, K, R], v V) Predicate[M]

IContains matches a case-insensitive literal substring on a text column. Example: orm.IContains(Users.Name, "ada").

func IEndsWith added in v0.48.0

func IEndsWith[M any, V ~string, I, P any, K TextColumnKind, R ColumnRole](c ColumnHandle[M, V, I, P, K, R], v V) Predicate[M]

IEndsWith matches a case-insensitive literal suffix on a text column. Example: orm.IEndsWith(Users.Email, ".org").

func ILike added in v0.48.0

func ILike[M any, V ~string, I, P any, K TextColumnKind, R ColumnRole](c ColumnHandle[M, V, I, P, K, R], v V) Predicate[M]

ILike matches a case-insensitive SQL ILIKE pattern on a text column. Example: orm.ILike(Users.Email, "%@example.com").

func IStartsWith added in v0.48.0

func IStartsWith[M any, V ~string, I, P any, K TextColumnKind, R ColumnRole](c ColumnHandle[M, V, I, P, K, R], v V) Predicate[M]

IStartsWith matches a case-insensitive literal prefix on a text column. Example: orm.IStartsWith(Users.Email, "admin").

func In added in v0.48.0

func In[M, V, I, P any, K ColumnKind, R ColumnRole](c ColumnHandle[M, V, I, P, K, R], vs ...V) Predicate[M]

In tests membership against concrete values. Example: orm.In(Orders.Status, StatusPending, StatusPaid).

func IsJSONNull added in v0.48.0

func IsJSONNull[M, V, I, P any, K JSONColumnKind, R ColumnRole](c ColumnHandle[M, V, I, P, K, R]) Predicate[M]

IsJSONNull matches a JSON null document, excluding SQL NULL. Example: orm.IsJSONNull(Records.Settings).

func IsNotNull added in v0.48.0

func IsNotNull[M, V, I, P any, K NullableColumnKind, R ColumnRole](c ColumnHandle[M, V, I, P, K, R]) Predicate[M]

IsNotNull excludes SQL NULL on a nullable column (including NullableEncrypted). Example: orm.IsNotNull(Users.Nickname).

func IsNull added in v0.48.0

func IsNull[M, V, I, P any, K NullableColumnKind, R ColumnRole](c ColumnHandle[M, V, I, P, K, R]) Predicate[M]

IsNull matches SQL NULL on a nullable column (including NullableEncrypted). Example: orm.IsNull(Users.DeletedAt).

func Like added in v0.48.0

func Like[M any, V ~string, I, P any, K TextColumnKind, R ColumnRole](c ColumnHandle[M, V, I, P, K, R], v V) Predicate[M]

Like matches a SQL LIKE pattern on a text column. Example: orm.Like(Users.Email, "%@example.com").

func Lt added in v0.48.0

func Lt[M, V, I, P any, K OrderedKind, R ColumnRole](c ColumnHandle[M, V, I, P, K, R], v V) Predicate[M]

Lt compares an ordered column against an upper exclusive bound. Example: orm.Lt(Orders.TotalCents, 1000).

func Lte added in v0.48.0

func Lte[M, V, I, P any, K OrderedKind, R ColumnRole](c ColumnHandle[M, V, I, P, K, R], v V) Predicate[M]

Lte compares an ordered column against an upper inclusive bound. Example: orm.Lte(Orders.TotalCents, 1000).

func Ne added in v0.48.0

func Ne[M, V, I, P any, K ColumnKind, R ColumnRole](c ColumnHandle[M, V, I, P, K, R], v V) Predicate[M]

Ne excludes a concrete value on a queryable column. Example: orm.Ne(Orders.Status, StatusCancelled).

func Not

func Not[M any](p Predicate[M]) Predicate[M]

Not negates a condition. Example: orm.Not(orm.Like(users.Email, "%@example.com")).

func NotIn added in v0.48.0

func NotIn[M, V, I, P any, K ColumnKind, R ColumnRole](c ColumnHandle[M, V, I, P, K, R], vs ...V) Predicate[M]

NotIn excludes membership against concrete values. Example: orm.NotIn(Orders.Status, StatusCancelled).

func Or

func Or[M any](ps ...Predicate[M]) Predicate[M]

Or matches any supplied condition. Example: orm.Or(orm.Lt(users.Age, 18), orm.Gt(users.Age, 65)).

func StartsWith added in v0.48.0

func StartsWith[M any, V ~string, I, P any, K TextColumnKind, R ColumnRole](c ColumnHandle[M, V, I, P, K, R], v V) Predicate[M]

StartsWith matches a literal prefix on a text column. Example: orm.StartsWith(Users.Email, "admin").

func UUIDGreater

func UUIDGreater[M, T, I, P any, K ColumnKind, R ColumnRole](column ColumnHandle[M, model.ID[T], I, P, K, R], v model.ID[T]) Predicate[M]

UUIDGreater compares model-owned UUIDs bytewise. Example: orm.UUIDGreater(Files.Key(), after).

func UUIDGreaterOrEqual

func UUIDGreaterOrEqual[M, T, I, P any, K ColumnKind, R ColumnRole](column ColumnHandle[M, model.ID[T], I, P, K, R], v model.ID[T]) Predicate[M]

UUIDGreaterOrEqual compares model-owned UUIDs bytewise. Example: orm.UUIDGreaterOrEqual(Files.Key(), after).

func UUIDLess

func UUIDLess[M, T, I, P any, K ColumnKind, R ColumnRole](column ColumnHandle[M, model.ID[T], I, P, K, R], v model.ID[T]) Predicate[M]

UUIDLess compares model-owned UUIDs bytewise. Example: orm.UUIDLess(Files.Key(), after).

func UUIDLessOrEqual

func UUIDLessOrEqual[M, T, I, P any, K ColumnKind, R ColumnRole](column ColumnHandle[M, model.ID[T], I, P, K, R], v model.ID[T]) Predicate[M]

UUIDLessOrEqual compares model-owned UUIDs bytewise. Example: orm.UUIDLessOrEqual(Files.Key(), after).

func WhereRaw

func WhereRaw[M any](sql string, args ...any) Predicate[M]

WhereRaw binds a model-owned predicate fragment inside the surrounding query's scopes and transaction. Use ? for arguments and ?? for a literal question mark. Example: Users.Query().Where(orm.WhereRaw[User]("score > ?", 10)).

type Primary

type Primary[M any, K comparable] = ColumnHandle[M, K, K, K, KeyKind, PrimaryRole]

Primary is an unmutated primary column eligible for insert-select mapping. Example: ID Primary[User, model.ID[User]]. Ordinary lookups only need Table.Key.

func PrimaryOf

func PrimaryOf[M any, K comparable](b Builder[M], key Key[M, K]) Primary[M, K]

PrimaryOf declares insert-select eligibility for an existing unmutated key. Call only inside Define, and only when primary-key SQL mapping is needed. Example: PrimaryOf(b, table.Key()).

type PrimaryRole added in v0.48.0

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

PrimaryRole marks an explicitly declared insertable primary key (orm.PrimaryOf); valid for rows.MapInsert, excluded from rows.MapUpdate.

type Query

type Query[M any] struct {
	// contains filtered or unexported fields
}

Query stores only a model-independent AST and table binding. Example: Orders.Query().Where(orm.Eq(Orders.ID, id)).

func FoundryOrderBy

func FoundryOrderBy[M any](q Query[M], o ormcore.Order, seal sqlowner.QuerySeal) Query[M]

FoundryOrderBy appends sealed computed row ordering in a model's original scope. Example: FoundryOrderBy(q,o,sqlowner.Queries()).

func FoundryWhere

func FoundryWhere[M any](q Query[M], p ormcore.Predicate, seal sqlowner.QuerySeal) Query[M]

FoundryWhere appends a sealed computed predicate in a model's original scope. Example: FoundryWhere(q,p,sqlowner.Queries()).

func WithRelationLimits

func WithRelationLimits[M any](q Query[M], limits RelationLimits) Query[M]

WithRelationLimits returns a query with immutable tree-wide limits. Example: q = orm.WithRelationLimits(q, orm.RelationLimits{BatchSize:100,MaxRows:5000,MaxDepth:4}).

func WithScopeContext

func WithScopeContext[M any](q Query[M], ctx context.Context) Query[M]

WithScopeContext supplies context for Compile; execution always uses its own context. Example: Compile(WithScopeContext(Orders.Query(), ctx)).

func WithoutGlobalScope

func WithoutGlobalScope[M any](q Query[M], scopes ...GlobalScope[M]) Query[M]

WithoutGlobalScope removes named defaults from this query only, preserving explicit predicates and soft-delete visibility. Example: WithoutGlobalScope(Orders.Query(), orderTenantScope).

func WithoutGlobalScopes

func WithoutGlobalScopes[M any](q Query[M]) Query[M]

WithoutGlobalScopes removes all model defaults from this query only. Example: WithoutGlobalScopes(Orders.Query()).Where(orm.Eq(Orders.ID, id)).

func WithoutModelHooks

func WithoutModelHooks[M any](q Query[M]) Query[M]

WithoutModelHooks acknowledges set writes skip per-model hooks, observers and changes. Per-model writes reject this flag. Example: orm.UpdateAll(ctx, db, WithoutModelHooks(Orders.Query()), orm.Set(Orders.TotalCents, 0)).

func (Query[M]) Limit

func (q Query[M]) Limit(n int) Query[M]

Limit bounds returned rows. Example: Orders.Query().Limit(10).

func (Query[M]) Offset

func (q Query[M]) Offset(n int) Query[M]

Offset skips rows. Example: Orders.Query().Offset(10).

func (Query[M]) OnlyTrashed

func (q Query[M]) OnlyTrashed() Query[M]

OnlyTrashed selects deleted records. Example: orm.All(ctx, db, records.Query().OnlyTrashed()).

func (Query[M]) OrderBy

func (q Query[M]) OrderBy(os ...Order[M]) Query[M]

OrderBy appends sort directions. Example: Orders.Query().OrderBy(orm.Asc(Orders.ID)).

func (Query[M]) Where

func (q Query[M]) Where(ps ...Predicate[M]) Query[M]

Where appends AND predicates. Example: Orders.Query().Where(orm.Gt(Orders.TotalCents, 0)).

func (Query[M]) With

func (q Query[M]) With(rels ...Relation[M]) Query[M]

With adds batched eager loading. Example: Orders.Query().With(OrderRelations.Buyer).

func (Query[M]) WithTrashed

func (q Query[M]) WithTrashed() Query[M]

WithTrashed includes deleted records. Example: orm.All(ctx, db, records.Query().WithTrashed()).

func (Query[M]) WithoutTrashed

func (q Query[M]) WithoutTrashed() Query[M]

WithoutTrashed restores the default active-record scope.

type RelatedLookup

type RelatedLookup[P, M any, K comparable] struct {
	// contains filtered or unexported fields
}

RelatedLookup retains the parent, target and alternate-key types. Example: orm.RelatedUnique(TeamRelations.Projects,Projects.Slug).

func RelatedUnique

func RelatedUnique[P, M any, K comparable, Rel DirectRelation[P, M], I, Pr any, Kind ColumnKind, R ColumnRole](relation Rel, field ColumnHandle[M, K, I, Pr, Kind, R]) RelatedLookup[P, M, K]

RelatedUnique scopes a unique lookup through a loaded parent without a fallback query. Example: orm.RelatedUnique(TeamRelations.Projects, Projects.Slug).Find(ctx, db, team, slug).

func (RelatedLookup[P, M, K]) Find

func (l RelatedLookup[P, M, K]) Find(ctx context.Context, ex database.Executor, parent P, key K) (value.Optional[M], error)

Find retains the relationship predicate, target filters and ordinary hydration. Example: lookup.Find(ctx,db,team,slug).

func (RelatedLookup[P, M, K]) Format

func (RelatedLookup[P, M, K]) Format(s fmt.State, _ rune)

Format redacts parent and target scopes. Example: fmt.Sprintf("%+v", related).

func (RelatedLookup[P, M, K]) GoString

func (RelatedLookup[P, M, K]) GoString() string

GoString redacts Go-syntax diagnostics. Example: fmt.Sprintf("%#v", related).

func (RelatedLookup[P, M, K]) String

func (RelatedLookup[P, M, K]) String() string

String redacts parent and target scopes. Example: fmt.Sprint(related).

func (RelatedLookup[P, M, K]) Validate

func (l RelatedLookup[P, M, K]) Validate() error

Validate rejects non-direct plans and windowed target scopes. Example: lookup.Validate().

type Relation

type Relation[M any] interface {
	// contains filtered or unexported methods
}

Relation is a model-owned, immutable eager-loading descriptor. Example: q.With(OrderRelations.Buyer).

type RelationLimits

type RelationLimits = querycore.RelationLimits

RelationLimits is the existing shared public limits type. MaxRows separately bounds fetched rows and attached values across the whole tree. Example: limits := orm.DefaultRelationLimits().

func DefaultRelationLimits

func DefaultRelationLimits() RelationLimits

DefaultRelationLimits uses the shared defaults: batches 500, rows 10000, depth 8. Example: limits := orm.DefaultRelationLimits().

type RequiredAnyColumnKind added in v0.48.0

type RequiredAnyColumnKind interface {
	AnyColumnKind
	// contains filtered or unexported methods
}

RequiredAnyColumnKind admits non-null columns including RequiredEncryptedKind (used by AuditRead and ChangeOf).

type RequiredColumnKind added in v0.48.0

type RequiredColumnKind interface {
	ColumnKind
	RequiredAnyColumnKind
	// contains filtered or unexported methods
}

RequiredColumnKind admits non-null queryable columns; pass a nullable-aware entry point (e.g. AuditReadNullable, NullableChangeOf) for nullable columns.

type RequiredEncryptedKind added in v0.48.0

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

RequiredEncryptedKind marks a non-null encrypted column (orm.Encrypted); only Set, SetIfPresent, AuditField, AuditRead, and ChangeOf are legal because ciphertext is non-queryable.

type RequiredEnumColumnKind added in v0.48.0

type RequiredEnumColumnKind interface {
	ColumnKind
	RequiredColumnKind
	// contains filtered or unexported methods
}

RequiredEnumColumnKind admits non-null enum columns for datatable.Enum; use NullableEnum* for nullable enums.

type RequiredEnumKind added in v0.48.0

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

RequiredEnumKind marks a non-null enum column (orm.Enum); supports equality and Asc/Desc, not ordered comparisons or text patterns.

type RequiredIntervalKind added in v0.48.0

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

RequiredIntervalKind marks a non-null duration interval column (orm.Interval); supports ordering, Between, and interval aggregates.

type RequiredJSONKind added in v0.48.0

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

RequiredJSONKind marks a non-null JSON document column (orm.JSON); supports ContainsDocument, ContainedByDocument, and IsJSONNull.

type RequiredNumberKind added in v0.48.0

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

RequiredNumberKind marks a non-null numeric column (orm.Number); supports ordering, aggregates, and Increment/Decrement.

type RequiredNumericColumnKind added in v0.48.0

type RequiredNumericColumnKind interface {
	NumericColumnKind
	RequiredColumnKind
}

RequiredNumericColumnKind admits non-null numeric columns for datatable.Number; use NullableNumber* for nullable numbers.

type RequiredOrderedKind added in v0.48.0

type RequiredOrderedKind interface {
	OrderedKind
	RequiredColumnKind
}

RequiredOrderedKind admits non-null ordered columns; use NullableOrderedColumn or nullable datatable constructors for nullable columns.

type RequiredScalarColumnKind added in v0.48.0

type RequiredScalarColumnKind interface {
	ColumnKind
	RequiredColumnKind
	// contains filtered or unexported methods
}

RequiredScalarColumnKind admits non-null general scalar columns (orm.Column, e.g. bool) for datatable.Bool.

type RequiredScalarKind added in v0.48.0

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

RequiredScalarKind marks a non-null general scalar column (orm.Column); use orm.Number/Text/Time/Enum for kind-specific operations.

type RequiredTextColumnKind added in v0.48.0

type RequiredTextColumnKind interface {
	TextColumnKind
	RequiredColumnKind
}

RequiredTextColumnKind admits non-null text columns (e.g. expr.TextRow, datatable.Text); use NullableText* for nullable text and Enum* for enums.

type RequiredTextKind added in v0.48.0

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

RequiredTextKind marks a non-null text column (orm.Text); supports Like/Contains patterns, ordering, and datatable.Text.

type RequiredTimeColumnKind added in v0.48.0

type RequiredTimeColumnKind interface {
	OrderedKind
	RequiredColumnKind
	// contains filtered or unexported methods
}

RequiredTimeColumnKind admits non-null date/time columns for datatable.Time; use NullableTime* for nullable timestamps.

type RequiredTimeKind added in v0.48.0

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

RequiredTimeKind marks a non-null date or timestamp column (orm.Time/CreatedAt/UpdatedAt); supports ordering and datatable.Time.

type RetrievalHooks

type RetrievalHooks[M any] struct {
	// Retrieved receives the caller's executor; reads create no implicit write transaction.
	// Example: Retrieved: func(ctx context.Context, ex database.Executor, order Order) error { return nil }.
	Retrieved func(context.Context, database.Executor, M) error
}

RetrievalHooks observes complete stored models after hydration and row closure. Example: RetrievalHooks[Order]{Retrieved: inspectOrder}.

type RetrievalObserver

type RetrievalObserver[M any] struct {
	// contains filtered or unexported fields
}

RetrievalObserver retains a retrieval-only model factory at registration. Example: NewRetrievalObserver[Order]("orders.read").

func NewRetrievalObserver

func NewRetrievalObserver[M any](name string) RetrievalObserver[M]

NewRetrievalObserver declares an instance-owned complete-read observer. Example: NewRetrievalObserver[Order]("orders.read").

func (RetrievalObserver[M]) Declare

func (o RetrievalObserver[M]) Declare(factory func() RetrievalHooks[M]) (lifecycle.Declaration, error)

Declare captures the per-batch factory without running it. Example: observer.Declare(orderReadHooks).

func (RetrievalObserver[M]) Name

func (o RetrievalObserver[M]) Name() string

Name returns the registration identifier. Example: observer.Name().

func (RetrievalObserver[M]) Validate

func (o RetrievalObserver[M]) Validate() error

Validate checks the identifier without constructing hooks. Example: observer.Validate().

type SimplePage

type SimplePage[M any] = querycore.SimplePage[M]

SimplePage retains the existing page-without-total response contract.

func SimplePaginate added in v0.2.0

func SimplePaginate[M any](ctx context.Context, ex database.Executor, q Query[M], request PageRequest) (SimplePage[M], error)

SimplePaginate fetches one extra row to determine whether another page exists.

type Slot

type Slot[M, S any] struct {
	// contains filtered or unexported fields
}

Slot binds an extension value without persisting a model column. Example: Title orm.Slot[Article,translations.Text].

func SlotOf

func SlotOf[M, S any](b Builder[M], ptr *S) Slot[M, S]

SlotOf binds a concrete extension field inside Define. Example: orm.SlotOf(b,&article.Title).

type SoftDeletable

type SoftDeletable[M any] struct {
	// contains filtered or unexported fields
}

SoftDeletable authorizes restoring or physically deleting soft-delete models. Example: Soft SoftDeletable[User]. Its zero value is invalid.

func SoftDeletes

func SoftDeletes[M any, V InstantValue](field SoftDelete[M, V]) SoftDeletable[M]

SoftDeletes captures the explicitly declared deletion column. Example: Soft: SoftDeletes(deletedAt).

type SoftDelete

type SoftDelete[M any, V InstantValue] = ColumnHandle[M, V, V, value.Nullable[V], NullableTimeKind, DeletedRole]

SoftDelete is a nullable deletion instant. Example: SoftDeleteOf(b,&o.DeletedAt).

func SoftDeleteOf

func SoftDeleteOf[M any, V InstantValue](b Builder[M], ptr *value.Nullable[V]) SoftDelete[M, V]

SoftDeleteOf explicitly marks a deletion timestamp. Example: SoftDeleteOf(b,&o.DeletedAt).

type SourceKey

type SourceKey[S, M any] struct {
	// contains filtered or unexported fields
}

SourceKey matches a stored primary value without assigning it. Example: rows.MatchSource(Users.ID,expr.Value(Archives.UserID)).

func FoundrySourceKey

func FoundrySourceKey[S, M any](m ormcore.ModelMapping, seal sqlowner.ExpressionSeal) SourceKey[S, M]

FoundrySourceKey binds a framework expression to a stored primary key. Example: FoundrySourceKey[Archive,User](mapping,sqlowner.Expressions()).

func (SourceKey[S, M]) Format

func (SourceKey[S, M]) Format(s fmt.State, _ rune)

Format hides captured source values. Example: fmt.Sprintf("%#v",key).

type Statement

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

Statement is an immutable compiled statement. Example: s,err := Compile(Orders.Query()).

func Compile

func Compile[M any](q Query[M]) (Statement, error)

Compile inspects a read without I/O. Example: Compile(Orders.Query()).

func CompileLocked

func CompileLocked[M any](q LockedQuery[M]) (Statement, error)

CompileLocked inspects a locked read without I/O. Example: CompileLocked(orm.Lock(Orders.Query())).

func FoundryStatement

func FoundryStatement(s querycore.Statement, seal sqlowner.MetadataSeal) (Statement, error)

FoundryStatement retains the shared immutable inspection boundary. Example: FoundryStatement(s,sqlowner.Metadata()).

func (Statement) Arguments

func (s Statement) Arguments() []any

Arguments returns an owned binding snapshot. Example: statement.Arguments().

func (Statement) GoString

func (s Statement) GoString() string

GoString omits SQL and bindings from diagnostics. Example: fmt.Sprintf("%#v",statement).

func (Statement) SQL

func (s Statement) SQL() string

SQL exposes parameterized SQL. Example: statement.SQL().

func (Statement) String

func (s Statement) String() string

String omits SQL and bindings from diagnostics. Example: fmt.Sprint(statement).

type Table

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

Table retains the model and primary-key types. Example: Table[Order,model.ID[Order]].

func TableOf

func TableOf[M any, K comparable](b Builder[M], ptr *K, opts ...ColumnOption[K]) Table[M, K]

TableOf declares the primary key once. Example: tbl := TableOf(b,&o.ID).

func (Table[M, K]) Key

func (t Table[M, K]) Key() Key[M, K]

Key returns the already bound primary column. Example: orm.Set(tbl.Key(), id).

func (Table[M, K]) Query

func (t Table[M, K]) Query() Query[M]

Query starts an immutable model query. Example: Orders.Query().Limit(20).

type Text

type Text[M any, V ~string] = ColumnHandle[M, V, V, V, RequiredTextKind, OrdinaryRole]

Text exposes literal and pattern matching. Example: orm.Contains(Users.Email, "@").

func TextOf

func TextOf[M any, V ~string](b Builder[M], ptr *V, opts ...ColumnOption[V]) Text[M, V]

TextOf binds text. Example: TextOf(b,&o.Email).

type TextColumnKind added in v0.48.0

type TextColumnKind interface {
	ColumnKind
	// contains filtered or unexported methods
}

TextColumnKind admits text columns (Text, NullableText, InputText) for Like/Contains patterns; string-backed Enum and Key columns do not acquire text patterns.

type TextLookupKey

type TextLookupKey[M any, K ~string] = ColumnHandle[M, K, K, K, RequiredTextKind, LookupKeyRole]

TextLookupKey retains the primary lookup role. Example: TextKey(table.Key()).

type TextPrimary

type TextPrimary[M any, K ~string] = ColumnHandle[M, K, K, K, RequiredTextKind, PrimaryRole]

TextPrimary preserves text primary capabilities. Example: TextKey(PrimaryOf(b, table.Key())).

type Through

type Through[M, N, P any] struct {
	// contains filtered or unexported fields
}

Through identifies a typed pivot slot. Example: Groups orm.Through[User,Group,Membership].

func ThroughOf

func ThroughOf[M, N, P any](b Builder[M], ptr *relation.Through[N, P]) Through[M, N, P]

ThroughOf binds a pivot slot during Define. Example: orm.ThroughOf(b,&u.Groups).

type ThroughRelation

type ThroughRelation[M, N, P any] struct {
	// contains filtered or unexported fields
}

ThroughRelation retains source, target and pivot owners in a thin immutable plan. Example: UserRelations.Groups.WherePivot(orm.Eq(Memberships.Role, "admin")).

func ManyToManyOf

func ManyToManyOf[M, N, P any, A, B comparable](slot Through[M, N, P], parentToPivot KeyLink[M, P, A], pivotToTarget KeyLink[P, N, B]) ThroughRelation[M, N, P]

ManyToManyOf unifies both key pairs and binds a concrete pivot slot. Example: orm.ManyToManyOf(Users.Groups, orm.JoinKeys(Users.ID, Memberships.UserID), orm.JoinKeys(Memberships.GroupID, Groups.ID)).

func MorphToManyOf

func MorphToManyOf[M model.Morphable, N, P any, A, B comparable, I, Pr any, Kind ColumnKind, R ColumnRole](slot Through[M, N, P], parentToPivot KeyLink[M, P, A], kind ColumnHandle[P, model.MorphName, I, Pr, Kind, R], pivotToTarget KeyLink[P, N, B]) ThroughRelation[M, N, P]

MorphToManyOf filters the shared pivot by the source discriminator. Example: orm.MorphToManyOf(Offices.Labels, orm.JoinKeys(Offices.Code, Labelings.LabelableID), Labelings.LabelableType, orm.JoinKeys(Labelings.LabelID, Labels.ID)).

func MorphedByManyOf

func MorphedByManyOf[M any, N model.Morphable, P any, A, B comparable, I, Pr any, Kind ColumnKind, R ColumnRole](slot Through[M, N, P], parentToPivot KeyLink[M, P, A], kind ColumnHandle[P, model.MorphName, I, Pr, Kind, R], pivotToTarget KeyLink[P, N, B]) ThroughRelation[M, N, P]

MorphedByManyOf filters the shared pivot by one concrete target discriminator. Example: orm.MorphedByManyOf(Labels.Offices, orm.JoinKeys(Labels.ID, Labelings.LabelID), Labelings.LabelableType, orm.JoinKeys(Labelings.LabelableID, Offices.Code)).

func WithRelationWriteLimit

func WithRelationWriteLimit[M, N, P any](r ThroughRelation[M, N, P], limit int) ThroughRelation[M, N, P]

WithRelationWriteLimit lowers the atomic row bound without changing read limits. Example: links := orm.WithRelationWriteLimit(UserRelations.Groups,100).

func WithoutPivotGlobalScope

func WithoutPivotGlobalScope[M, N, P any](r ThroughRelation[M, N, P], scopes ...GlobalScope[P]) ThroughRelation[M, N, P]

WithoutPivotGlobalScope removes named pivot defaults only. Example: WithoutPivotGlobalScope(UserRelations.Groups, membershipTenantScope).

func WithoutPivotGlobalScopes

func WithoutPivotGlobalScopes[M, N, P any](r ThroughRelation[M, N, P]) ThroughRelation[M, N, P]

WithoutPivotGlobalScopes removes every pivot default only. Example: WithoutPivotGlobalScopes(UserRelations.Groups).

func (ThroughRelation[M, N, P]) OnlyTrashed

func (r ThroughRelation[M, N, P]) OnlyTrashed() ThroughRelation[M, N, P]

OnlyTrashed sets visibility for this side only. Example: links.OnlyTrashed().

func (ThroughRelation[M, N, P]) OnlyTrashedPivot

func (r ThroughRelation[M, N, P]) OnlyTrashedPivot() ThroughRelation[M, N, P]

OnlyTrashedPivot sets visibility for this side only. Example: links.OnlyTrashedPivot().

func (ThroughRelation[M, N, P]) OrderBy

func (r ThroughRelation[M, N, P]) OrderBy(orders ...Order[N]) ThroughRelation[M, N, P]

OrderBy derives an immutable joined descriptor for its typed side. Example: links.OrderBy(orm.Asc(Groups.Name)).

func (ThroughRelation[M, N, P]) OrderByPivot

func (r ThroughRelation[M, N, P]) OrderByPivot(orders ...Order[P]) ThroughRelation[M, N, P]

OrderByPivot derives an immutable joined descriptor for its typed side. Example: links.OrderByPivot(orm.Asc(Memberships.ID)).

func (ThroughRelation[M, N, P]) Where

func (r ThroughRelation[M, N, P]) Where(ps ...Predicate[N]) ThroughRelation[M, N, P]

Where derives an immutable joined descriptor for its typed side. Example: links.Where(orm.Eq(Groups.Name, "maintainers")).

func (ThroughRelation[M, N, P]) WherePivot

func (r ThroughRelation[M, N, P]) WherePivot(ps ...Predicate[P]) ThroughRelation[M, N, P]

WherePivot derives an immutable joined descriptor for its typed side. Example: links.WherePivot(orm.Eq(Memberships.Role, "admin")).

func (ThroughRelation[M, N, P]) With

func (r ThroughRelation[M, N, P]) With(children ...Relation[N]) ThroughRelation[M, N, P]

With derives an immutable joined descriptor for its typed side. Example: links.With(GroupRelations.Owner).

func (ThroughRelation[M, N, P]) WithPivot

func (r ThroughRelation[M, N, P]) WithPivot(children ...Relation[P]) ThroughRelation[M, N, P]

WithPivot derives an immutable joined descriptor for its typed side. Example: links.WithPivot(MembershipRelations.Inviter).

func (ThroughRelation[M, N, P]) WithTrashed

func (r ThroughRelation[M, N, P]) WithTrashed() ThroughRelation[M, N, P]

WithTrashed sets visibility for this side only. Example: links.WithTrashed().

func (ThroughRelation[M, N, P]) WithTrashedPivot

func (r ThroughRelation[M, N, P]) WithTrashedPivot() ThroughRelation[M, N, P]

WithTrashedPivot sets visibility for this side only. Example: links.WithTrashedPivot().

func (ThroughRelation[M, N, P]) WithoutTrashed

func (r ThroughRelation[M, N, P]) WithoutTrashed() ThroughRelation[M, N, P]

WithoutTrashed sets visibility for this side only. Example: links.WithoutTrashed().

func (ThroughRelation[M, N, P]) WithoutTrashedPivot

func (r ThroughRelation[M, N, P]) WithoutTrashedPivot() ThroughRelation[M, N, P]

WithoutTrashedPivot sets visibility for this side only. Example: links.WithoutTrashedPivot().

type Time

type Time[M any, V TimeValue] = ColumnHandle[M, V, V, V, RequiredTimeKind, OrdinaryRole]

Time exposes ordered temporal comparisons. Example: Time[Order,temporal.DateTime].

func TimeOf

func TimeOf[M any, V TimeValue](b Builder[M], ptr *V, opts ...ColumnOption[V]) Time[M, V]

TimeOf binds a temporal field. Example: TimeOf(b,&o.OccurredAt).

type TimeValue

type TimeValue interface {
	time.Time | temporal.DateTime | temporal.Date | temporal.Time | temporal.LocalDateTime
}

TimeValue permits supported temporal fields. Example: Time[Order, temporal.DateTime].

type UpdatableRole added in v0.48.0

type UpdatableRole interface {
	ColumnRole
	// contains filtered or unexported methods
}

UpdatableRole admits columns eligible for rows.MapUpdate (Ordinary, Created, Deleted); keys, UpdatedAt, and Input columns cannot be SQL-mapped in UpdateFrom.

type UpdateMapping

type UpdateMapping[S, M any] struct {
	// contains filtered or unexported fields
}

UpdateMapping maps a non-primary stored value. Example: rows.MapUpdate(Users.Name, expr.Value(Archives.Name)).

func FoundryUpdateMapping

func FoundryUpdateMapping[S, M any](m ormcore.ModelMapping, seal sqlowner.ExpressionSeal) UpdateMapping[S, M]

FoundryUpdateMapping binds a framework expression to its destination. Example: FoundryUpdateMapping[Archive,User](mapping,sqlowner.Expressions()).

func (UpdateMapping[S, M]) Format

func (UpdateMapping[S, M]) Format(s fmt.State, _ rune)

Format hides captured source values. Example: fmt.Sprintf("%#v",mapping).

type UpdateSource

type UpdateSource[S, M any] struct {
	// contains filtered or unexported fields
}

UpdateSource updates matching models; ambiguous mapped values roll back. Example: rows.UpdateFrom(Users.Query(),rows.From(Archives.Query())).

func FoundryUpdateFrom

func FoundryUpdateFrom[S, M any](q Query[M], source ormcore.Source, seal sqlowner.QuerySeal) UpdateSource[S, M]

FoundryUpdateFrom creates a source update plan. Example: FoundryUpdateFrom[Archive](Users.Query(),source,sqlowner.Queries()).

func (UpdateSource[S, M]) Exec

func (p UpdateSource[S, M]) Exec(ctx context.Context, writer database.Transactor) (int64, error)

Exec rolls back ambiguous SQL-mapped updates. Example: plan.Exec(ctx,db).

func (UpdateSource[S, M]) Format

func (UpdateSource[S, M]) Format(s fmt.State, _ rune)

Format hides captured source values. Example: fmt.Sprintf("%#v",plan).

func (UpdateSource[S, M]) Match

func (p UpdateSource[S, M]) Match(key SourceKey[S, M]) UpdateSource[S, M]

Match replaces the source-to-primary match. Example: plan.Match(rows.MatchSource(Users.ID,expr.Value(Archives.UserID))).

func (UpdateSource[S, M]) Returning

func (p UpdateSource[S, M]) Returning(ctx context.Context, writer database.Transactor, limit int) ([]M, error)

Returning preserves complete hydration and rejects ambiguous matches. Example: plan.Returning(ctx,db,100).

func (UpdateSource[S, M]) Select

func (p UpdateSource[S, M]) Select(mappings ...UpdateMapping[S, M]) UpdateSource[S, M]

Select appends stored-value mappings without bypassing mutators. Example: plan.Select(rows.MapUpdate(Users.Name, expr.Value(Archives.Name))).

func (UpdateSource[S, M]) Values

func (p UpdateSource[S, M]) Values(values ...Assignment[M]) UpdateSource[S, M]

Values replaces literal inputs; repeated source keys are allowed without mappings. Example: plan.Values(orm.Set(Users.Name, "archived")).

type UpdatedAt

type UpdatedAt[M any, V InstantValue] = ColumnHandle[M, V, V, V, RequiredTimeKind, UpdatedRole]

UpdatedAt is an explicitly managed update instant. Example: UpdatedAtOf(b,&o.UpdatedAt).

func UpdatedAtOf

func UpdatedAtOf[M any, V InstantValue](b Builder[M], ptr *V) UpdatedAt[M, V]

UpdatedAtOf explicitly marks an update timestamp. Example: UpdatedAtOf(b,&o.UpdatedAt).

type UpdatedRole added in v0.48.0

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

UpdatedRole marks a framework-managed update timestamp (UpdatedAt); excluded from rows.MapInsert, rows.MapUpdate, and adjustments.

type Value

type Value[M, V any] struct {
	// contains filtered or unexported fields
}

Value identifies a typed computed slot. Example: OrdersCount orm.Value[User,int64].

func ValueOf

func ValueOf[M, V any](b Builder[M], ptr *relation.Value[V]) Value[M, V]

ValueOf binds an aggregate slot during Define. Example: orm.ValueOf(b,&u.OrdersCount).

func (Value[M, V]) Using

func (v Value[M, V]) Using(computation AggregateRelation[M, V]) AggregateRelation[M, V]

Using binds a computation with the slot's exact owner and result type. Example: Users.OrdersCount.Using(expr.Related(UserRelations.Orders,expr.Count[Order]())).

type ValueLookup

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

ValueLookup observes a stored field without hydrating models or running retrieval hooks. It is advisory, not a reservation. Example: orm.Lookup(Users.Query(), Users.Email).

func Lookup

func Lookup[M any, V comparable, I, P any, K ColumnKind, R ColumnRole](source Query[M], field ColumnHandle[M, V, I, P, K, R]) ValueLookup[M, V]

Lookup binds a stored column's non-null value type to its complete model scope. Ordering, pagination and eager loading are rejected. Example: orm.Lookup(Users.Query(), Users.Nickname).

func (ValueLookup[M, V]) AllExist

func (l ValueLookup[M, V]) AllExist(ctx context.Context, ex database.Executor, input []V) (bool, error)

AllExist checks SQL equality in batches of 64, including duplicate representations. Empty input performs no I/O. Example: lookup.AllExist(ctx, db, emails).

func (ValueLookup[M, V]) AnyExist

func (l ValueLookup[M, V]) AnyExist(ctx context.Context, ex database.Executor, input []V) (bool, error)

AnyExist checks IN predicates in batches of 64 and stops on the first match. Empty input performs no I/O. Example: lookup.AnyExist(ctx, db, emails).

func (ValueLookup[M, V]) Exists

func (l ValueLookup[M, V]) Exists(ctx context.Context, ex database.Executor, input V) (bool, error)

Exists performs one equality observation without a transaction. Example: lookup.Exists(ctx, db, email).

func (ValueLookup[M, V]) Format

func (l ValueLookup[M, V]) Format(s fmt.State, _ rune)

Format redacts every formatting verb. Example: fmt.Sprintf("%+v", lookup).

func (ValueLookup[M, V]) GoString

func (l ValueLookup[M, V]) GoString() string

GoString redacts Go-syntax diagnostics. Example: fmt.Sprintf("%#v", lookup).

func (ValueLookup[M, V]) String

func (ValueLookup[M, V]) String() string

String redacts retained predicates. Example: fmt.Sprint(lookup).

func (ValueLookup[M, V]) Validate

func (l ValueLookup[M, V]) Validate() error

Validate checks declarations without encoding values or performing I/O. Example: lookup.Validate().

type Write

type Write[M any] struct {
	// contains filtered or unexported fields
}

Write is an operation-local draft. Use it only during Saving/Creating/Updating. Example: WriteSet(write, orm.Set(Orders.TotalCents, 0)).

func (*Write[M]) GoString

func (*Write[M]) GoString() string

GoString redacts pending input. Example: fmt.Sprintf("%#v",write).

func (*Write[M]) String

func (*Write[M]) String() string

String redacts pending input. Example: fmt.Sprint(write).

type WriteError

type WriteError[R any] struct {
	// contains filtered or unexported fields
}

WriteError preserves a candidate when persistence needs reconciliation. Example: errors.As(err,&writeError).

func (*WriteError[R]) Candidate

func (e *WriteError[R]) Candidate() R

Candidate is reconciliation data, not proof of persistence. Example: writeError.Candidate().

func (*WriteError[R]) Error

func (e *WriteError[R]) Error() string

Error omits model values. Example: writeError.Error().

func (*WriteError[R]) GoString

func (e *WriteError[R]) GoString() string

GoString omits model values. Example: fmt.Sprintf("%#v",writeError).

func (*WriteError[R]) Unwrap

func (e *WriteError[R]) Unwrap() error

Unwrap retains the original transaction outcome. Example: errors.As(writeError, &databaseError).

Directories

Path Synopsis
Package expr provides thin, typed SQL expressions in explicit source scopes.
Package expr provides thin, typed SQL expressions in explicit source scopes.
internal
enuminit
Package enuminit deliberately declares models before generated enum variables.
Package enuminit deliberately declares models before generated enum variables.
Package rows provides typed aliases, joins and complete row projections.
Package rows provides typed aliases, joins and complete row projections.

Jump to

Keyboard shortcuts

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