ormcore

package
v0.3.3 Latest Latest
Warning

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

Go to latest
Published: Nov 1, 2026 License: MIT Imports: 35 Imported by: 0

Documentation

Overview

Package ormcore shares sealed metadata between orm, expr and rows.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AmbiguousSourceMatch

func AmbiguousSourceMatch() error

AmbiguousSourceMatch rejects nondeterministic UPDATE FROM results.

func AppendChecks

func AppendChecks(first []func() error, next ...func() error) []func() error

AppendChecks snapshots deferred declaration checks without specializing slice helpers in every generic join/projection consumer.

func CheckReferenceSet

func CheckReferenceSet(s Source, refs []Reference, referenceFree bool) error

CheckReferenceSet distinguishes constructed constants from missing ownership.

func CheckReferences

func CheckReferences(s Source, refs []Reference) error

func Collect

func Collect(ctx context.Context, rows *database.Rows, scan func(database.Row) error, callbacks *ReadCallbacks) (err error)

Collect closes a complete batch before dispatch, retaining the originating owner's callback lease across closure. Both model APIs use this lifetime owner. Empty, incomplete, canceled or unsuccessfully closed batches skip dispatch.

func CompatibleRecordSources

func CompatibleRecordSources(a, b RecordSource) error

func CompileRecord

func CompileRecord(ctx context.Context, r RecordSource) (querycore.Statement, error)

CompileRecord validates the executor kind and all retained declarations.

func CompileResultCursor

func CompileResultCursor(ctx context.Context, q ResultCursor) (querycore.Statement, error)

CompileResultCursor plans canonical ordering without a page boundary or lookahead.

func Consume

func Consume(ctx context.Context, rows RowSource, scan func(database.Row) error) (err error)

Consume owns close/error handling for model and projected reads.

func CorrelationQuery

func CorrelationQuery(c Correlation) querycore.Subquery

func DirectRecord

func DirectRecord(source Source) bool

func EncryptedType

func EncryptedType(typ reflect.Type) bool

EncryptedType recognizes the encrypted.Value contract without invoking user methods. Nullable wrappers retain the restriction of their underlying value.

func EnumCodec

func EnumCodec[E interface {
	enum.Scalar
	EnumDescriptor() enum.Descriptor[E]
}]() (codec.Codec[E], func() error)

EnumCodec resolves generated descriptors after package initialization.

func InputClone

func InputClone[I any]() func(I) I

InputClone selects direct binary-input ownership once, without reflective writes. Other custom values retain ordinary Go copy semantics, as in generated drafts. Example: clone := InputClone[Payload]().

func Invalid

func Invalid(message string) error

func Iteration

func Iteration(ctx context.Context, yield func() error) error

Iteration owns cancellation and panic/Goexit isolation for result delivery.

func JSONArrayAt

func JSONArrayAt(root reflect.Value, ptr unsafe.Pointer, element reflect.Type) error

func JSONCollection

func JSONCollection(t reflect.Type) error

JSONCollection rejects custom encodings and base64 byte slices, whose JSON representation is not the Go map/slice structure. Fixed byte arrays are arrays.

func JSONContainment

func JSONContainment(field querycore.FieldRef, op querycore.ScalarOperation, document driver.Value, err error) querycore.Expression

JSONContainment uses the existing JSON operation compiler for a bound document. Example: JSONContainment(field, querycore.JsonContainsOperation, document, nil).

func JSONIsNull

func JSONIsNull(field querycore.FieldRef) querycore.Expression

JSONIsNull tests a document's JSON kind; SQL NULL remains unknown and does not match. Example: JSONIsNull(field).

func KeyScalarCodec

func KeyScalarCodec[V any]() codec.Codec[V]

KeyScalarCodec accepts only the primitive kinds allowed for natural keys/enums.

func NilDescriptor

func NilDescriptor(v any) bool

NilDescriptor handles typed nils at public declaration boundaries.

func NullableScan

func NullableScan[V any](scan func(*V) any, destination *value.Nullable[V]) sql.Scanner

NullableScan widens a stored codec's scanner without erasing its concrete type.

func NumberCodec

func NumberCodec[V any]() codec.Codec[V]

NumberCodec selects only numeric representations. Decimal has its exact codec.

func OwnInsertConflict

func OwnInsertConflict(ctx context.Context, tx *database.Tx, table string, failure InsertFailure, insertErr error) (bool, error)

OwnInsertConflict resolves only a known statement rejection on this table. Incomplete error inspection and uncertain transaction outcomes never authorize competitor retrieval. The concrete child must confirm savepoint rollback.

func Raw

func Raw(ctx context.Context, ex database.Executor, columns []string, statement string, args []any, scan func(database.Row) error) error

Raw validates the complete result shape before iteration, then reuses the caller's decoder. It deliberately neither routes reads nor applies scopes.

func RawComplete

func RawComplete(ctx context.Context, ex database.Executor, columns []string, statement string, args []any, scan func(database.Row) error, callbacks *ReadCallbacks) error

RawComplete adds retrieval dispatch for complete model decoders only.

func Read

func Read(ctx context.Context, ex database.Executor, node querycore.SelectNode, planError error, checks []func() error, scan func(database.Row) error) (err error)

Read centralizes projection/scalar execution and discards unfinished rows.

func ReadComplete

func ReadComplete(ctx context.Context, ex database.Executor, node querycore.SelectNode, planError error, checks []func() error, scan func(database.Row) error, callbacks *ReadCallbacks) (err error)

ReadComplete retains complete-model callback ownership through row closure.

func ReadRecord

func ReadRecord(ctx context.Context, ex database.Executor, r RecordSource, typ reflect.Type, transaction bool, scan func(database.Row) error, batch func() (unsafe.Pointer, int)) error

func RecordBatches

func RecordBatches(ctx context.Context, node querycore.SelectNode, primaryIndex int,
	compile func(querycore.SelectNode) error, read func(querycore.SelectNode) (int, error),
	key func() (driver.Value, error), yield func(int) error) error

RecordBatches shares complete-model iteration between both typed APIs. The reader closes and dispatches a whole batch before delivery. Key capture happens before delivery; non-keyable orders retain the original offset progression.

func RecordCount

func RecordCount(ctx context.Context, ex database.Executor, r RecordSource) (int64, error)

RecordCount retains input windows and nested locks in the shared SELECT compiler.

func RecordExecution

func RecordExecution(ctx context.Context, ex database.Executor, transaction bool) error

func RecordExists

func RecordExists(ctx context.Context, ex database.Executor, r RecordSource) (bool, error)

func RecordMayRetrieve

func RecordMayRetrieve(r Record, ex database.Executor) bool

RecordMayRetrieve consults only validated framework owners. A wrapper cannot claim that retrieval callbacks are absent from the rows it will return.

func ResultCodec

func ResultCodec[V any]() codec.Codec[V]

ResultCodec reuses scalar codecs and supplies concrete nullable built-ins. Named nullable/custom values use the explicit-codec fragment constructor.

func ScalarCodec

func ScalarCodec[V any]() codec.Codec[V]

ScalarCodec is the unrestricted ColumnOf fallback. Concrete framework codecs are selected non-generically; no V-by-underlying-type adaptations are emitted.

func SelectSubquery

func SelectSubquery(source Source) querycore.Subquery

SelectSubquery retains lazy declaration checks at the shared SELECT boundary. It uses the same Subquery/RelationCheck owner as relation EXISTS.

func TimeCodec

func TimeCodec[V any]() codec.Codec[V]

TimeCodec retains the exact framework codec, with no representation adapter.

func ValidateRecord

func ValidateRecord(r Record, typ reflect.Type) error

func ValidateRecordSource

func ValidateRecordSource(r RecordSource, typ reflect.Type, transaction bool) error

Types

type CaseBuilder

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

CaseBuilder retains immutable branches and their complete ownership metadata. Its zero value acquires its first branch through Append.

func (CaseBuilder) Append

func (c CaseBuilder) Append(condition Predicate, result Expression) CaseBuilder

Append returns an independent CASE derivation with bounded branch/reference work.

func (CaseBuilder) Empty

func (c CaseBuilder) Empty() bool

Empty reports whether the first branch still needs to supply the result codec.

func (CaseBuilder) Finish

func (c CaseBuilder) Finish(otherwise Expression) Expression

Finish requires a branch and an explicit ELSE, preserving fallback provenance.

type Column

type Column[V any] struct {
	// AggregateInput is issued by a declared ordered result field, never a promoted marker.
	AggregateInput bool
	Text           bool
	Sensitive      bool
	Reference
	Field    querycore.FieldRef
	Kind     codec.ParameterType
	Nullable bool
	Bind     func(V) (driver.Value, error)
	Clone    func(V) V
	Scan     func(*V) any
	Err      error
}

Column retains typed closures without a heavy codec field.

type CommonTable

type CommonTable struct {
	Definition *querycore.CteNode
	Record     RecordSource
}

CommonTable keeps the declaration identity and deferred checks with its definition.

func NewCommonTable

func NewCommonTable(name string, r RecordSource) CommonTable

type ConflictAssignment

type ConflictAssignment struct {
	Update querycore.ConflictUpdate
	Owner  any
	Err    error
}

ConflictAssignment retains the declared destination beside its calculation.

func ConflictCalculation

func ConflictCalculation(destination Reference, field querycore.FieldRef, err error, scope reflect.Type, value Expression) ConflictAssignment

type ConflictPolicy

type ConflictPolicy struct {
	Policy querycore.Conflict
	Owner  any
	Err    error
}

ConflictPolicy carries immutable SQL policy data and concrete declaration ownership.

func ConflictKeys

func ConflictKeys(scope reflect.Type, keys []Expression) ConflictPolicy

func ConflictPredicates

func ConflictPredicates(p ConflictPolicy, scope reflect.Type, predicates []Predicate, rows bool) ConflictPolicy

type CorrelatedRecord

type CorrelatedRecord struct {
	Correlation Correlation
	Columns     []querycore.Column
	Owner       any
}

CorrelatedRecord contains complete result metadata without an executable query.

func SelectCorrelationRecord

func SelectCorrelationRecord(c Correlation, scope Scope) CorrelatedRecord

type Correlation

type Correlation struct {
	Source       Source
	Outer, Inner VisibleScope
}

Correlation retains the inner SELECT and its enclosing visibility separately.

func BindCorrelation

func BindCorrelation(outer VisibleScope, inner Source, outerType, scope reflect.Type) Correlation

type CursorPlan

type CursorPlan struct {
	Record RecordSource
	Fields []RecordField
	Scope  string
}

CursorPlan owns codecs and query identity for one validated navigation request.

func PlanResultCursor

func PlanResultCursor(ctx context.Context, q ResultCursor, size int, token string, present, backward bool) (CursorPlan, error)

func (CursorPlan) Token

func (p CursorPlan) Token(base unsafe.Pointer) (string, error)

type Expression

type Expression struct {
	Sensitive bool
	Node      querycore.ValueExpression
	Refs      []Reference
	// ReferenceFree marks a constructed expression with no SQL column dependencies.
	ReferenceFree bool
	Err           error
}

Expression carries SQL and the referenced declarations for ownership checks.

func Aggregate

Aggregate constructs a stored-field aggregate retaining declaration provenance.

func AnchorExpression

func AnchorExpression(source Source) Expression

AnchorExpression makes an independent value retain the concrete outer source.

func Conditional

func Conditional(kind querycore.ConditionalKind, arguments ...Expression) Expression

Conditional composes values without erasing any operand's errors or ownership.

func CorrelatedScalarExpression

func CorrelatedScalarExpression(c Correlation) Expression

func FilterAggregate

func FilterAggregate(input Expression, predicates []Predicate) Expression

FilterAggregate appends immutable row filters while preserving all ownership.

func Operation

func Operation(kind querycore.ScalarOperation, result codec.ParameterType, arguments ...OperationArgument) Expression

Operation combines immutable typed operands in the shared scalar AST.

func ScalarExpression

func ScalarExpression(outer Source, inner Source) Expression

ScalarExpression is a SELECT boundary, independent of its outer aggregate phase.

func WindowExpression

func WindowExpression(w Window, n querycore.WindowNode, input *Expression) Expression

WindowExpression merges window and operand provenance without traversing or compiling SQL. Querycore owns frame, nesting, grouping and aggregate validation.

type InsertFailure

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

InsertFailure binds statement provenance to the child savepoint that executed it. Recovery requires that concrete child to have confirmed rollback.

type JSONFieldBinding

type JSONFieldBinding struct {
	Name   string
	Quoted bool
	Err    error
	Bound  bool
}

JSONFieldBinding is immutable metadata, resolved once at declaration startup. A zero binding is invalid; no selector or application pointer is retained.

func JSONFieldAt

func JSONFieldAt(root reflect.Value, ptr unsafe.Pointer, field reflect.Type) JSONFieldBinding

func (JSONFieldBinding) Validate

func (b JSONFieldBinding) Validate() error

type JoinCondition

type JoinCondition struct {
	Node                querycore.Expression
	Left, Right         []Reference
	LeftFree, RightFree bool
	Err                 error
}

JoinCondition retains independent operand provenance until sources are bound.

func CombineJoinConditions

func CombineJoinConditions(any bool, conditions []JoinCondition) JoinCondition

CombineJoinConditions snapshots a bounded immutable AND/OR condition list.

func FilterJoinCondition

func FilterJoinCondition(on JoinCondition, left bool, predicates []Predicate) JoinCondition

FilterJoinCondition adds predicates owned by just one side of an ON boundary.

func JoinComparison

func JoinComparison(left, right Expression, op querycore.Operator, text ...bool) JoinCondition

JoinComparison shares expression validation with ordinary row comparisons.

func NegateJoinCondition

func NegateJoinCondition(on JoinCondition) JoinCondition

NegateJoinCondition retains both sides while negating SQL three-valued truth.

type ModelMapping

type ModelMapping struct {
	Destination Reference
	Field       querycore.FieldRef
	Stored      reflect.Type
	Value       Expression
	NullableKey bool
	Err         error
}

ModelMapping retains both declaration ownership and the exact stored value type.

type OperationArgument

type OperationArgument struct {
	Value Expression
	Kind  codec.ParameterType
}

OperationArgument retains a scalar operand's representation and provenance.

type Order

type Order struct {
	Node querycore.OrderNode
	Refs []Reference
	// ReferenceFree marks a constructed expression with no SQL column dependencies.
	ReferenceFree bool
	Err           error
}

Order carries a scoped ordering.

func OrderExpression

func OrderExpression(e Expression, descending bool) Order

OrderExpression retains an expression's provenance without specializing by model, result type or row/selected phase. Typed shells supply the phase.

type Predicate

type Predicate struct {
	Node querycore.Expression
	Refs []Reference
	// ReferenceFree marks a constructed expression with no SQL column dependencies.
	ReferenceFree bool
	Err           error
}

Predicate carries a scoped SQL condition.

func CompareExpressions

func CompareExpressions(left, right Expression, op querycore.Operator, text ...bool) Predicate

CompareExpressions preserves both operands' declaration provenance.

func Conjunction

func Conjunction(predicates []Predicate) Predicate

Conjunction joins conditions without duplicating retained ownership references.

func CorrelatedExists

func CorrelatedExists(c Correlation) Predicate

func CorrelatedMembership

func CorrelatedMembership(left Expression, c Correlation) Predicate

func ExistsPredicate

func ExistsPredicate(outer Source, inner Source) Predicate

ExistsPredicate shares SubqueryPredicate/SubquerySQL with relation existence.

func MembershipPredicate

func MembershipPredicate(left Expression, inner Source) Predicate

MembershipPredicate preserves SQL NULL behavior and only the outer row references.

func NegatePredicate

func NegatePredicate(p Predicate) Predicate

NegatePredicate retains ownership and errors under SQL NOT.

type RangeWindow

type RangeWindow struct {
	Window Window
	Order  querycore.OrderNode
	Kind   codec.ParameterType
}

RangeWindow owns one ordering expression and its distance representation.

func WindowRange

func WindowRange(w Window, input Expression, kind codec.ParameterType, temporal bool) RangeWindow

type ReadCallbacks

type ReadCallbacks struct {
	Needed   func(lifecycle.Observers) bool
	Complete func(context.Context, lifecycle.Observers) error
}

ReadCallbacks belongs only to a complete-model decoder. Projection and write decoders pass nil. Needed inspects the actual returned rows' frozen owner.

type Record

type Record struct {
	Primary   string // Model-owned primary column; empty for declared projections.
	Fields    func() []RecordField
	Type      reflect.Type
	Owner     any
	Columns   []querycore.Column
	Scan      func(database.Row, unsafe.Pointer) error
	Callbacks func(database.Executor, func() (unsafe.Pointer, int)) *ReadCallbacks
	Checks    []func() error
	Err       error
}

type RecordField

type RecordField struct {
	Name      string
	Sensitive bool
	Get       func(unsafe.Pointer) (driver.Value, error)
	Decode    func(any) (driver.Value, error)
}

Record keeps an ordered complete decoder bound to its declaration and Go type. Scan receives memory only after the typed adapter validates Type.

type RecordSource

type RecordSource struct {
	Source      Source
	Record      Record
	Transaction bool
	Direct      bool
}

RecordSource returns SQL, result metadata and executor kind in one operation.

func CombineRecords

func CombineRecords(a, b RecordSource, operator querycore.SetOperator, scope reflect.Type) RecordSource

func CommonTableRecord

func CommonTableRecord(c CommonTable) RecordSource

func FirstRecord

func FirstRecord(r RecordSource) RecordSource

func LockRecord

func LockRecord(r RecordSource, locks []RowLock) RecordSource

func RecordLockBehavior

func RecordLockBehavior(r RecordSource, behavior querycore.LockBehavior) RecordSource

func RecordLockTargets

func RecordLockTargets(r RecordSource, targets []Scope) RecordSource

func RecursiveRecord

func RecursiveRecord(name string, anchor RecordSource) (RecordSource, *querycore.RecursiveReference)

RecursiveRecord is a non-executable working table; the compiler owns its lifetime.

func SelectRecord

func SelectRecord(source Source, scope Scope, record Record, typ reflect.Type) RecordSource

func SetRecord

func SetRecord(r RecordSource) RecordSource

type Reference

type Reference struct {
	Scope reflect.Type
	Table string
	Owner any
}

Reference retains runtime declaration ownership after static scope checking.

func MergeReferences

func MergeReferences(groups ...[]Reference) ([]Reference, error)

MergeReferences snapshots a bounded set of declaration and scope identities.

type RelationRow

type RelationRow struct {
	Row                 database.Row
	Start, Count, Total int
}

RelationRow partitions an owned joined row, preserving encryption context.

func (RelationRow) FieldEncryption

func (r RelationRow) FieldEncryption() (context.Context, *encryption.Keyring)

FieldEncryption forwards the underlying stream's decryption scope.

func (RelationRow) Scan

func (r RelationRow) Scan(destinations ...any) error

type ResultCursor

type ResultCursor struct {
	Record RecordSource
	Orders []querycore.QueryOrder
	Unique []querycore.FieldRef
}

ResultCursor retains the boundary, output identity and the complete decoder.

func CursorOrder

func CursorOrder(q ResultCursor, orders []Order) ResultCursor

func CursorUnique

func CursorUnique(q ResultCursor, keys []Expression) ResultCursor

func NewResultCursor

func NewResultCursor(r RecordSource, scope reflect.Type) ResultCursor

type RowLock

type RowLock struct {
	Spec    querycore.LockSpec
	Targets []Scope
	Err     error
}

func LockTargets

func LockTargets(lock RowLock, targets []Scope) RowLock

type RowSource

type RowSource interface {
	database.Row
	Next() bool
	Err() error
	Close() error
}

RowSource is the in-memory/testable shape of database.Rows.

func InsertRows

func InsertRows(ctx context.Context, tx *database.Tx, statement querycore.Statement, capture *InsertFailure) (RowSource, error)

InsertRows records only errors from the model's own statement, never hydration or lifecycle errors. A nil capture leaves ordinary writes unchanged.

type ScannerFunc added in v0.3.0

type ScannerFunc func(any) error

ScannerFunc adapts an existing driver-boundary scan callback to sql.Scanner. Domain value types stay in the callback's typed destination closure.

func (ScannerFunc) Scan added in v0.3.0

func (scan ScannerFunc) Scan(source any) error

Scan delegates one raw driver value to the retained callback.

type Scope

type Scope struct {
	Reference
	Err error
}

Scope identifies one preserved model inside a query source.

func ConflictScope

func ConflictScope(source VisibleScope, table string) Scope

func CorrelationScope

func CorrelationScope(c Correlation, scope Scope, outer bool) Scope

func Rescope

func Rescope(scope Scope, owners map[string]any, err error) Scope

Rescope validates the declaration and side before retaining a model reference.

type Source

type Source struct {
	Scope   reflect.Type
	Node    querycore.SelectNode
	Owners  map[string]any
	Aliases map[string]reflect.Type
	Err     error
	Checks  []func() error
}

Source is a validated model/alias/join input without a result decoder.

func AliasLateral

func AliasLateral(record CorrelatedRecord, alias string, scope reflect.Type) Source

func AliasRecord

func AliasRecord(r RecordSource, alias string, typ, scope reflect.Type, transaction bool) Source

func ConflictAnchor

func ConflictAnchor(source VisibleScope) Source

func Distinct

func Distinct(s Source, kind querycore.DistinctKind, keys []Expression) Source

Distinct replaces earlier distinct clauses with independently owned keys.

func GroupBy

func GroupBy(s Source, keys []Expression) Source

GroupBy appends immutable row keys; querycore validates row phase and grouping.

func Having

func Having(s Source, predicates []Predicate) Source

Having appends immutable group predicates with their full ownership checks.

func JoinLateral

func JoinLateral(left, right Source, outer VisibleScope, on []JoinCondition, kind querycore.JoinKind, scope reflect.Type) Source

func JoinSources

func JoinSources(left, right Source, on JoinCondition, kind querycore.JoinKind, scope reflect.Type) Source

JoinSources retains ownership and declaration checks around the shared SQL AST.

func LockSource

func LockSource(source Source, locks []RowLock) Source

LockSource is shared by executable records and non-executable correlations.

func OrderBy

func OrderBy(s Source, orders []Order) Source

OrderBy appends row/selected orders without permitting model writes.

func OrderSource

func OrderSource(source Source, orders []Order) Source

func SelectScalar

func SelectScalar(source Source, value Expression) Source

SelectScalar validates exactly one typed selection before building a subquery.

func SourceLockBehavior

func SourceLockBehavior(s Source, behavior querycore.LockBehavior) Source

func SourceLockTargets

func SourceLockTargets(s Source, targets []Scope) Source

func WhereSource

func WhereSource(source Source, predicates []Predicate) Source

WhereSource owns immutable predicate appends for projected and scalar queries.

type SourceMatchRow

type SourceMatchRow struct{ database.Row }

SourceMatchRow validates the compiler's trailing match count before publication.

func (SourceMatchRow) FieldEncryption

func (r SourceMatchRow) FieldEncryption() (context.Context, *encryption.Keyring)

FieldEncryption preserves the underlying stream's decryption scope.

func (SourceMatchRow) Scan

func (r SourceMatchRow) Scan(destinations ...any) error

type VisibleScope

type VisibleScope struct {
	Scope    reflect.Type
	Required querycore.ScopeRequirement
	Owners   map[string]any
	Checks   []func() error
}

VisibleScope carries the SQL visibility and declaration identities together.

func ConflictVisibility

func ConflictVisibility(source Source, scope reflect.Type) VisibleScope

func CorrelationVisibility

func CorrelationVisibility(c Correlation) VisibleScope

func SourceVisibility

func SourceVisibility(source Source) VisibleScope

type Window

type Window struct {
	Spec          querycore.WindowSpec
	Refs          []Reference
	HasReferences bool
}

Window retains immutable SQL and ownership independently of scope/value types.

func RangeBetween

func RangeBetween(r RangeWindow, declared bool, start, end querycore.FrameBound) Window

func WindowBetween

func WindowBetween(w Window, kind querycore.FrameKind, start, end querycore.FrameBound) Window

func WindowExclude

func WindowExclude(w Window, exclusion querycore.FrameExclusion) Window

func WindowNamed

func WindowNamed(w Window, name string) Window

func WindowOrder

func WindowOrder(w Window, orders []Order) Window

func WindowPartition

func WindowPartition(w Window, keys []Expression) Window

Jump to

Keyboard shortcuts

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