Documentation
¶
Overview ¶
Package querycore owns the model-independent SQL planning and compiler implementation. Public ORM declarations enforce concrete model, field and result ownership before lowering through validated framework capabilities. Keep this package independent of public ORM facades and application assembly.
Index ¶
- Constants
- Variables
- func ArrayLiteral(kind codec.ParameterType, values []driver.Value) (string, bool)
- func AssignedKey(primary string, assignments []MutationAssignment) func() (driver.Value, error)
- func BinaryOperator(op Operator) (string, bool)
- func BindAssignment(column Column, bind func() (driver.Value, error)) (driver.Value, error)
- func BuildCursor(scope string, count int, get func(int) (driver.Value, error)) (string, error)
- func CheckRemovals(scopes []ScopeDefinition, removed []GlobalScopeName) error
- func ComparisonOperator(op Operator) (string, bool)
- func ComparisonValues(s *ComparisonValuesState) []any
- func CompatibleRecords(left, right RecordLayout) error
- func CompileLock(node SelectNode, spec LockSpec) (string, error)
- func ConsumeRelationBudget(remaining *int, count int, attached bool) error
- func ContextScopeResolver(scope ScopeDefinition, table string) func(context.Context) (Expression, error)
- func CursorInputFailure(cause error) error
- func CursorStatementScopeFor(modelIdentity string, statement Statement, identity []string) (string, error)
- func DatabaseFailure(operation string, code database.Code) error
- func DecodeCursorValue(v CursorValue) (driver.Value, error)
- func EncodeModelKey(raw driver.Value) (sqlvalue.Value, error)
- func EscapedPattern(op Operator) bool
- func FetchRelationBatches(count, batchSize int, remaining *int, ...) error
- func GroupRelationRows[N any](rows []N, seen map[sqlvalue.Value]bool, ...) (map[sqlvalue.Value][]N, error)
- func GroupsCondition(p Expression, depth int) bool
- func GroupsSelect(v ValueExpression) bool
- func GroupsValue(v ValueExpression, depth int) bool
- func HasEncryptedAssignments(assignments []MutationAssignment) bool
- func HasPrimaryEquality(predicates []Expression, primary string) bool
- func IntervalComparisonKey(v temporal.Interval) string
- func IntervalOperationSQL(n OperationNode, args []string) (string, error)
- func InvalidCursor() error
- func JSONMapKey[K comparable](key K) (string, error)
- func JsonOperationSQL(n OperationNode, args []string) (string, error)
- func LikePattern(op Operator, text string) string
- func LiteralValue(s *LiteralState) driver.Value
- func LoadTimeZone(name string) (string, error)
- func LockReference(table string) string
- func LookupValuesEqual(a, b driver.Value) bool
- func MakeCursor(scope string, values []driver.Value) (string, error)
- func NumericRepresentation(kind codec.ParameterType) bool
- func OffsetValue(s *OffsetState) int64
- func OpenEncryptedValue[V encrypted.Value[V]](row database.Row, table, column string, key func() (driver.Value, error), ...) error
- func OpenNullableEncryptedValue[V encrypted.Value[V]](row database.Row, table, column string, key func() (driver.Value, error), ...) error
- func OpenScope(row database.Row, table, column string, key func() (driver.Value, error)) (context.Context, *encryption.Keyring, encryption.Context, error)
- func OrderDirection(order OrderNode) string
- func PageCount(total int64, size int) int64
- func PageOffset(r PageRequest) (int, error)
- func ParameterSQLType(kind codec.ParameterType) (string, error)
- func PredicateKey(predicates []Expression, primary string) func() (driver.Value, error)
- func PrimaryEqualities(predicates []Expression, primary string, visit func(driver.Value) error) error
- func Qualified(field FieldRef) string
- func QuoteArrayElement(literal *strings.Builder, text string)
- func QuoteSchemaText(value string, remaining int) (string, error)
- func Quoted(name string) string
- func QuotedTable(table string) string
- func ReadEnvelope(kind ReadKind) (string, string)
- func ReadMutationAssignments(assignments []MutationAssignment) (map[FieldRef]AssignmentValue, error)
- func RecordEqualityKey(kind codec.ParameterType, raw driver.Value) (sqlvalue.Value, error)
- func RelationKeys[K any](ctx context.Context, count, batchSize int, ...) ([]value.Optional[sqlvalue.Value], []K, map[sqlvalue.Value]bool, error)
- func ResolutionArgument(zone string, policy uint8) (string, error)
- func ResultCursorFields(node SelectNode, columns []Column, orders []QueryOrder, ...) ([]int, []bool, error)
- func RowValues(s *RowValuesState) []driver.Value
- func SameKey(left, right driver.Value) bool
- func SelectSensitivity(node SelectNode) ([]bool, error)
- func SelectedColumns(table string, columns []Column) string
- func SetEncryptedError() error
- func StoredInput(state *InputState) any
- func TemporalOperationSQL(n OperationNode, args []string) (string, error)
- func TransactionKeys(tx *database.Tx) *encryption.Keyring
- func TruncationUnitName(unit, minimum TemporalUnit) (string, error)
- func ValidCursorRequest(size int, after, before bool) bool
- func ValidPageSize(size int) bool
- func ValidateAggregateFilterCount(count int) error
- func ValidateConditionalArguments(kind ConditionalKind, count int) error
- func ValidateConflictMutator(u ConflictUpdate, field FieldMutator) error
- func ValidateExpression(e Expression, table string, depth int, nodes *int) error
- func ValidateExpressionFields(e Expression, field func(FieldRef) error, depth int, nodes *int) error
- func ValidateExpressionValues(e Expression, operand func(ValueExpression) error, depth int, nodes *int) error
- func ValidateGeographicPoint(latitude, longitude float64) error
- func ValidateJSONKind(kind string) error
- func ValidateJSONProperty(name string) error
- func ValidateLockSources(node SelectNode, targets []string, explicit bool, depth int) (int, error)
- func ValidateLockValue(v ValueExpression) error
- func ValidateMorphName(name string) error
- func ValidateProjectionColumns(columns []ProjectionColumn, hasDecoder bool) error
- func ValidateRangeOrder(kind codec.ParameterType, temporal bool) error
- func ValidateRowValue(v ValueExpression, field func(FieldRef) error, depth int, nodes *int) error
- func ValidateSQLMapping(model *ModelDefinition, column string, mutated bool) error
- func ValidateScopes(scopes []ScopeDefinition, table string) error
- func ValidateSubstringCount(count int32) error
- func VisitComputedValue(v ValueExpression, item func(ValueExpression) error, ...) (bool, error)
- func VisitWindowSpec(w WindowSpec, item func(ValueExpression) error, ...) error
- func ZoneArgument(zone string) (string, error)
- type Adjustment
- type AggregateCast
- type AggregateFilter
- type AggregateKind
- type AggregateNode
- type AssignmentValue
- type BinaryComparison
- type CaseBranch
- type CaseNode
- type Column
- type Comparison
- type ComparisonValuesState
- type CompiledKey
- type Compiler
- func (c *Compiler) Aggregate(a AggregateNode) (string, error)
- func (c *Compiler) AggregateAt(a AggregateNode, field func(FieldRef) error, grouped map[FieldRef]bool, ...) (string, error)
- func (c *Compiler) AggregateField(f FieldRef) error
- func (c *Compiler) AggregateFilterSQL(a AggregateNode, grouped map[FieldRef]bool, grouping, window bool) (string, error)
- func (c *Compiler) AssignmentParameter(column string, bind func() (driver.Value, error)) (string, error)
- func (c *Compiler) BeginStatement(ctx context.Context)
- func (c *Compiler) Comparison(e Comparison, grouped map[FieldRef]bool, grouping bool) (string, error)
- func (c *Compiler) CompileCTEs(node SelectNode) (string, error)
- func (c *Compiler) CompileLocks(node SelectNode, specs []LockSpec) (string, error)
- func (c *Compiler) CompileSelect(node SelectNode) (string, error)
- func (c *Compiler) ComputedSQL(v ValueExpression, grouped map[FieldRef]bool, grouping bool) (string, error)
- func (c *Compiler) ConditionClause(sql *strings.Builder, clause string, predicates []Expression) error
- func (c *Compiler) ConditionClauseAt(sql *strings.Builder, clause string, predicates []Expression, ...) error
- func (c *Compiler) CorrelationScope(required *ScopeRequirement, grouped map[FieldRef]bool, grouping bool) (*OuterScope, error)
- func (c *Compiler) CteBody(d *CteNode) (string, error)
- func (c *Compiler) DeclaredField(f FieldRef) error
- func (c *Compiler) DiscardArguments(start int)
- func (c *Compiler) DistinctSQL(s SelectNode, grouped map[FieldRef]bool, grouping bool) (string, error)
- func (c *Compiler) Expression(e Expression) (string, error)
- func (c *Compiler) ExpressionAt(e Expression, grouped map[FieldRef]bool, grouping bool) (string, error)
- func (c *Compiler) FrameBoundSQL(b FrameBound) (string, error)
- func (c *Compiler) GroupKeys(values []ValueExpression) (map[FieldRef]bool, error)
- func (c *Compiler) JoinSourceSQL(join JoinNode) (string, error)
- func (c *Compiler) JsonTextScalarSQL(n OperationNode, grouped map[FieldRef]bool, grouping bool) (string, bool, error)
- func (c *Compiler) KeySQL(key *CompiledKey, grouped map[FieldRef]bool, grouping bool) (string, error)
- func (c *Compiler) MatchingKey(v ValueExpression, groupedOnly bool) (*CompiledKey, error)
- func (c *Compiler) NamedWindowsSQL(definitions []*NamedWindow, grouped map[FieldRef]bool, grouping bool) (string, error)
- func (c *Compiler) ObserveField(level int, f FieldRef)
- func (c *Compiler) OperationArguments(n OperationNode, grouped map[FieldRef]bool, grouping bool) ([]string, error)
- func (c *Compiler) OperationSQL(n OperationNode, grouped map[FieldRef]bool, grouping bool) (sql string, err error)
- func (c *Compiler) Parameter(value any) (string, error)
- func (c *Compiler) ParameterSQL(p ParameterNode) (string, error)
- func (c *Compiler) PlanValue(v ValueExpression) (PlannedValue, error)
- func (c *Compiler) RangeDistanceSQL(d RangeDistance) (string, error)
- func (c *Compiler) RawSQL(r RawFragment) (string, error)
- func (c *Compiler) RegisterKey(v ValueExpression, grouped bool) (*CompiledKey, error)
- func (c *Compiler) RenderSelectedExpression(e ValueExpression, grouped map[FieldRef]bool, grouping bool) (string, error)
- func (c *Compiler) RowComparison(e RowComparison, grouped map[FieldRef]bool, grouping bool) (string, error)
- func (c *Compiler) SchemaLiteral(value any) (string, error)
- func (c *Compiler) SelectSQL(s SelectNode) (string, error)
- func (c *Compiler) SelectSQLWithOuter(s SelectNode, outer *OuterScope) (string, error)
- func (c *Compiler) SelectedExpression(e ValueExpression, grouped map[FieldRef]bool, grouping bool) (string, error)
- func (c *Compiler) SetSQL(s SetNode, columns []Column) (string, error)
- func (c *Compiler) SourceSQL(s TableSource) (string, error)
- func (c *Compiler) Statement(template string) Statement
- func (c *Compiler) SubqueryPredicate(p SubqueryPredicate, grouped map[FieldRef]bool, grouping bool) (string, error)
- func (c *Compiler) SubquerySQL(q Subquery, single bool, grouped map[FieldRef]bool, grouping bool) (string, error)
- func (c *Compiler) TrackShape()
- func (c *Compiler) ValidateHavingValue(v ValueExpression, grouped map[FieldRef]bool) error
- func (c *Compiler) ValidateSelectedExpression(e ValueExpression, grouped map[FieldRef]bool, grouping bool) error
- func (c *Compiler) ValidateWindow(n WindowNode, grouped map[FieldRef]bool, grouping bool) error
- func (c *Compiler) Where(sql *strings.Builder, predicates []Expression) error
- func (c *Compiler) WindowDefinitionSQL(w WindowSpec, grouped map[FieldRef]bool, grouping bool) (string, error)
- func (c *Compiler) WindowSQL(n WindowNode, grouped map[FieldRef]bool, grouping bool) (string, error)
- func (c *Compiler) WindowSpecSQL(w WindowSpec, grouped map[FieldRef]bool, grouping bool) (string, error)
- type ComputedOrder
- type ConditionalKind
- type ConditionalNode
- type Conflict
- func (p Conflict) CheckReturned(q QueryCore, requested, returned int) error
- func (p Conflict) Compile(c *Compiler, table, alias string, columns []Column, scopes []Expression) (string, error)
- func (p Conflict) Dependencies(node SelectNode) SelectNode
- func (p Conflict) ValidateRows(c *Compiler) error
- func (p Conflict) ValidateShape(q QueryCore, c *Compiler, validateMutator func(ConflictUpdate) error) error
- func (p Conflict) WithUpdatedTimestamp(table, name string) Conflict
- type ConflictAction
- type ConflictUpdate
- type CteMaterialization
- type CteNode
- type Cursor
- type CursorBoundary
- type CursorEnvelope
- type CursorField
- type CursorInputError
- type CursorPage
- type CursorRequest
- type CursorValue
- type DistinctKind
- type DistinctOrder
- type DistinctSpec
- type Expression
- type FieldMutator
- func NewCapturedFieldMutator[I, V any](column string, capture func(V) AssignmentValue, mutate func(I) (V, error)) FieldMutator
- func NewFieldMutator[I, V any](column string, c codec.Codec[V], mutate func(I) (V, error)) FieldMutator
- func NewNullableFieldMutator[I, V any](column string, c codec.Codec[V], mutate func(I) (V, error)) FieldMutator
- type FieldRef
- type FrameBound
- type FrameBoundKind
- type FrameExclusion
- type FrameKind
- type GlobalScopeName
- type InputState
- type JoinKind
- type JoinNode
- type JoinedNode
- type Junction
- type LazyScopes
- type LiteralState
- type LockBehavior
- type LockSpec
- type LockStrength
- type LookupDefault
- type ModelDefinition
- type MutationAssignment
- type MutationKind
- type NamedWindow
- type Negation
- type NullPlacement
- type OffsetState
- type OperationArgument
- type OperationNode
- type OperationSpec
- type Operator
- type OrderNode
- type OuterScope
- type Page
- type PageRequest
- type ParameterNode
- type Plan
- type PlanBytes
- type PlanEnvelope
- type PlanNode
- type PlannedValue
- type PredicateState
- type ProjectionColumn
- type ProjectionMapping
- type QueryCore
- func (q QueryCore) ActiveScopePredicates(scopes []ScopeDefinition) []Expression
- func (q QueryCore) CompileInsert(c Compiler, rows []map[string]MutationAssignment, union map[string]bool, ...) (Statement, error)
- func (q QueryCore) CompileInsertSelect(c Compiler, node SelectNode, mapped map[string]ValueExpression, ...) (Statement, error)
- func (q QueryCore) CompileModel(kind ReadKind, selections []SelectItem) (Statement, error)
- func (q QueryCore) CompileMutation(c Compiler, node SelectNode, kind MutationKind, ...) (Statement, error)
- func (q QueryCore) CompileSourceWrite(c Compiler, destination, source SelectNode, key SourceWriteKey, ...) (Statement, error)
- func (q QueryCore) DeferredScopes(lazy *LazyScopes) ScopeNode
- func (q QueryCore) DeletionPredicate(op Operator) Expression
- func (q QueryCore) EffectivePredicates() []Expression
- func (q QueryCore) HasSoftDeletes() bool
- func (q QueryCore) ModelSelect(selections []SelectItem) SelectNode
- func (q QueryCore) RequireInsertFields(present func(string) bool) error
- func (q QueryCore) ScopePredicates() []Expression
- func (q QueryCore) StableOrder() (QueryCore, error)
- func (q QueryCore) Validate() error
- func (q QueryCore) ValidateAdjustment(a *Adjustment, c *Compiler, assigned map[string]MutationAssignment) error
- func (q QueryCore) ValidateMutation(kind MutationKind, assignments []MutationAssignment, c *Compiler) (map[string]MutationAssignment, error)
- func (q QueryCore) ValidateMutationShape(kind MutationKind, assignments []MutationAssignment, c *Compiler) (map[string]MutationAssignment, error)
- func (q QueryCore) ValidateScopeOptions() error
- func (q QueryCore) ValidateSoftDeleteScope() error
- func (q QueryCore) WriteCompiler(kind MutationKind, requirePrimary, hasRelations bool) (Compiler, error)
- type QueryOrder
- type RangeDistance
- type RawFragment
- type ReadKind
- type RecordLayout
- type RecursiveCTE
- type RecursiveReference
- type RelationLimits
- type RelationOrder
- type ResultCursorField
- type RowComparison
- type RowValuesState
- type ScalarOperation
- type ScalarSubquery
- type ScopeDefinition
- type ScopeNode
- type ScopeRequirement
- type Sealer
- type SelectItem
- type SelectKeys
- type SelectNames
- type SelectNode
- func CountNode(node SelectNode) SelectNode
- func RelatedValueSelect(node SelectNode, inputTable, inputAlias string, group, local FieldRef, ...) (SelectNode, error)
- func RelationAggregateSelect(node SelectNode, inputTable, inputAlias string, group FieldRef, ...) (SelectNode, error)
- func RelationExistsSelect(node SelectNode, source string) (SelectNode, string, error)
- func RelationHopJoin(node SelectNode, targetAlias string, foreign FieldRef, source TableSource, ...) SelectNode
- func RelationThroughSelect(target, pivot QueryCore, foreign, pivotForeign FieldRef, ...) SelectNode
- func ReorderUnwindowed(node SelectNode, orders int) (SelectNode, error)
- func ResultCursorNode(source SelectNode, columns []Column, hasDecoder bool) (SelectNode, error)
- func ResultPageWindow(node SelectNode, offset, size int, lookahead bool) (SelectNode, error)
- func SelectProjection(source SelectNode, columns []ProjectionColumn, mappings []ProjectionMapping) (SelectNode, error)
- func SelectRecordNode(node SelectNode, table string, columns []Column, hasDecoder bool) (SelectNode, error)
- type SelectWalk
- func (w *SelectWalk) Expression(e Expression, depth int)
- func (w *SelectWalk) RestrictRecursion(reason string, visit func())
- func (w *SelectWalk) SelectNode(s SelectNode, depth int)
- func (w *SelectWalk) Subquery(q Subquery, depth int)
- func (w *SelectWalk) Value(v ValueExpression, depth int)
- func (w *SelectWalk) Visit(depth int) bool
- func (w *SelectWalk) VisitCorrelation(required *ScopeRequirement)
- func (w *SelectWalk) VisitField(f FieldRef)
- func (w *SelectWalk) VisitSource(s TableSource, depth int)
- func (w *SelectWalk) WindowSpec(spec WindowSpec, depth int)
- type SensitiveValue
- type SetNode
- type SetOperator
- type SimplePage
- type SoftDeleteColumn
- type SoftDeleteScope
- type SourceWriteKey
- type Statement
- type StatementState
- type Subquery
- type SubqueryPredicate
- type TableSource
- type TemporalUnit
- type TimestampColumns
- type ValueExpression
- func MapComputedValue(v ValueExpression, item func(ValueExpression) ValueExpression, ...) (ValueExpression, bool)
- func RequalifyValue(v ValueExpression, alias string) ValueExpression
- func UnwrapSensitivity(v ValueExpression) ValueExpression
- func WithSensitivity(v ValueExpression, sensitive bool) ValueExpression
- type ValueIndex
- type WindowFrame
- type WindowFunction
- type WindowNode
- type WindowSpec
Constants ¶
const ( MaxExpressionDepth = 128 MaxExpressionNodes = 10000 MaxParameters = 65535 // MaxMembershipValues bounds one In/NotIn list. Supported scalar codecs bind // the whole list as one array parameter, so it is not limited by // MaxParameters; other codecs still bind one parameter per value. MaxMembershipValues = 1 << 20 // MaxScalarSQLBytes bounds expanded scalar SQL during one compilation. // Encoded parameter contents are separate from this SQL-text work budget. MaxScalarSQLBytes = 1 << 20 )
These limits bound SQL compilation work and PostgreSQL's parameter protocol.
const ( MaxCursorBytes = 64 * 1024 MaxCursorFields = 16 )
Cursor limits bound token decoding and lexicographic predicate construction.
const AnnotatedValueAlias = "foundry_value"
AnnotatedValueAlias is the computed column paired with a complete model.
const ConflictProposedTable = "excluded"
const ConflictStoredTable = "foundry_conflict_stored"
const DefaultChunkSize = 100
DefaultChunkSize bounds closed batches used by eager and observed iteration.
const MaxChunkSize = MaxPageSize
MaxChunkSize shares the collection bound across both model read APIs.
const MaxIdentityBatch = 1000
MaxIdentityBatch bounds primary-key-only identity observations and extension scopes.
const MaxInsertRows = 1000
MaxInsertRows bounds atomic inserts and upserts before parameter validation.
const MaxPageSize = 1000
MaxPageSize bounds complete collections returned by a pagination request.
const MaxPerModelWriteRows = MaxInsertRows
MaxPerModelWriteRows bounds an atomic batch of ordinary model lifecycles.
const MaxPlanBytes = 4 << 20
const MaxPlanDepth = 24
const MaxPlanNodes = 4096
const PostgresStandardTime uint8 = 1
const RelationHopAlias = "foundry_through"
const RelationPivotAlias = "foundry_pivot"
const RelationTargetAlias = "foundry_target"
const SetAlias = "foundry_set"
SetAlias is the output scope shared by record and scalar set adapters.
Variables ¶
var LikeEscaper = strings.NewReplacer("!", "!!", "%", "!%", "_", "!_")
likePattern escapes literal text for LIKE/ILIKE with '!' as the escape. Fixed SQL escaping grammar, safe for concurrent use across applications.
Functions ¶
func ArrayLiteral ¶
arrayLiteral renders bound scalar values as one PostgreSQL array literal for = ANY($n) / <> ALL($n). It is a bound parameter, never SQL text: the server parses it using the element type inferred from the compared operand. Only scalar kinds whose driver values have one unambiguous text form qualify; anything else keeps one parameter per value.
func AssignedKey ¶
func AssignedKey(primary string, assignments []MutationAssignment) func() (driver.Value, error)
assignedKey is an insert's primary key: its own explicit assignment.
func BinaryOperator ¶
binaryOperator shares SQL tokens with literal comparisons. Contains belongs only to literal binding, where wildcard escaping is explicit.
func BindAssignment ¶
func BuildCursor ¶
BuildCursor bounds and encodes each field before evaluating the next getter. This preserves error precedence and bounded expansion for both API adapters.
func CheckRemovals ¶
func CheckRemovals(scopes []ScopeDefinition, removed []GlobalScopeName) error
func ComparisonOperator ¶
func ComparisonValues ¶
func ComparisonValues(s *ComparisonValuesState) []any
func CompatibleRecords ¶
func CompatibleRecords(left, right RecordLayout) error
CompatibleRecords validates ordered output layouts for sets and recursive steps.
func CompileLock ¶
func CompileLock(node SelectNode, spec LockSpec) (string, error)
Lock clauses belong to their SELECT node. The compiler permits them only through a transaction-required read boundary, including nested definitions.
func ConsumeRelationBudget ¶
ConsumeRelationBudget charges fetched rows or attached values independently.
func ContextScopeResolver ¶
func ContextScopeResolver(scope ScopeDefinition, table string) func(context.Context) (Expression, error)
contextScopeResolver contains application panics and validates the resolved predicate against the model table before any requalification wraps it.
func CursorInputFailure ¶
func CursorStatementScopeFor ¶
func DatabaseFailure ¶
DatabaseFailure snapshots known framework operation and code text. Public database.NewError remains untrusted; only internal query owners use this helper.
func DecodeCursorValue ¶
func DecodeCursorValue(v CursorValue) (driver.Value, error)
func EncodeModelKey ¶
EncodeModelKey normalizes signed zero while retaining driver representations.
func EscapedPattern ¶
escapedPattern reports operators whose literal text the compiler escapes.
func FetchRelationBatches ¶
func FetchRelationBatches(count, batchSize int, remaining *int, fetch func(start, end, limit int) (int, error)) error
FetchRelationBatches enforces the shared row budget with a one-row sentinel.
func GroupRelationRows ¶
func GroupRelationRows[N any](rows []N, seen map[sqlvalue.Value]bool, read func(N) (sqlvalue.Value, bool, error)) (map[sqlvalue.Value][]N, error)
GroupRelationRows checks every returned key before associating rows to parents.
func GroupsCondition ¶
func GroupsCondition(p Expression, depth int) bool
func GroupsSelect ¶
func GroupsSelect(v ValueExpression) bool
Ordinary aggregates inside window arguments/orderings group the outer SELECT; the aggregate receiving OVER itself does not. Scalar subqueries own their groups.
func GroupsValue ¶
func GroupsValue(v ValueExpression, depth int) bool
func HasEncryptedAssignments ¶
func HasEncryptedAssignments(assignments []MutationAssignment) bool
func HasPrimaryEquality ¶
func HasPrimaryEquality(predicates []Expression, primary string) bool
func IntervalComparisonKey ¶
IntervalComparisonKey uses PostgreSQL's 30-day months and 24-hour days.
func IntervalOperationSQL ¶
func IntervalOperationSQL(n OperationNode, args []string) (string, error)
func InvalidCursor ¶
func InvalidCursor() error
func JSONMapKey ¶
func JSONMapKey[K comparable](key K) (string, error)
JSONMapKey uses the JSON payload boundary's canonical typed map-key codec.
func JsonOperationSQL ¶
func JsonOperationSQL(n OperationNode, args []string) (string, error)
func LikePattern ¶
func LiteralValue ¶
func LiteralValue(s *LiteralState) driver.Value
func LoadTimeZone ¶
LoadTimeZone validates a named zone using Go's timezone database. Local and empty names are rejected to avoid process-specific timezone selection.
func LockReference ¶
func LookupValuesEqual ¶
LookupValuesEqual compares stored equality defaults with canonical model-key semantics.
func MakeCursor ¶
MakeCursor serializes the unchanged v1 envelope after bounding each key.
func NumericRepresentation ¶
func NumericRepresentation(kind codec.ParameterType) bool
func OffsetValue ¶
func OffsetValue(s *OffsetState) int64
func OpenEncryptedValue ¶
func OrderDirection ¶
orderDirection renders direction and any explicit NULL placement.
func PageOffset ¶
func PageOffset(r PageRequest) (int, error)
func ParameterSQLType ¶
func ParameterSQLType(kind codec.ParameterType) (string, error)
func PredicateKey ¶
func PredicateKey(predicates []Expression, primary string) func() (driver.Value, error)
PredicateKey is a single-row write's primary key: its one primary equality.
func PrimaryEqualities ¶
func QuoteArrayElement ¶
quoteArrayElement always quotes, so NULL, empty strings, braces, commas and whitespace remain ordinary element text. Backslash and quote are escaped.
func QuotedTable ¶
func ReadEnvelope ¶
ReadEnvelope owns scalar result wrappers and their internal output alias.
func ReadMutationAssignments ¶
func ReadMutationAssignments(assignments []MutationAssignment) (map[FieldRef]AssignmentValue, error)
func RecordEqualityKey ¶
RecordEqualityKey agrees with SQL equality, including PostgreSQL intervals.
func RelationKeys ¶
func RelationKeys[K any](ctx context.Context, count, batchSize int, read func(int) (K, sqlvalue.Value, bool, error)) ([]value.Optional[sqlvalue.Value], []K, map[sqlvalue.Value]bool, error)
RelationKeys preserves parent positions and first-seen unique key order. Typed adapters retain decoded values at the returned unique indices.
func ResultCursorFields ¶
func ResultCursorFields(node SelectNode, columns []Column, orders []QueryOrder, fields []ResultCursorField) ([]int, []bool, error)
ResultCursorFields shares output codec/identity validation across typed adapters.
func RowValues ¶
func RowValues(s *RowValuesState) []driver.Value
func SelectSensitivity ¶
func SelectSensitivity(node SelectNode) ([]bool, error)
SelectSensitivity follows output provenance rather than decoder metadata: a set may decode with its left codec while values originate from either input. Nothing is written back to declarations or shared query nodes.
func SelectedColumns ¶
func SetEncryptedError ¶
func SetEncryptedError() error
func StoredInput ¶
func StoredInput(state *InputState) any
func TemporalOperationSQL ¶
func TemporalOperationSQL(n OperationNode, args []string) (string, error)
func TransactionKeys ¶
func TransactionKeys(tx *database.Tx) *encryption.Keyring
func TruncationUnitName ¶
func TruncationUnitName(unit, minimum TemporalUnit) (string, error)
func ValidCursorRequest ¶
ValidCursorRequest checks the request shape before decoding its boundary.
func ValidPageSize ¶
func ValidateAggregateFilterCount ¶
ValidateAggregateFilterCount checks the shared constructor/compiler bound.
func ValidateConditionalArguments ¶
func ValidateConditionalArguments(kind ConditionalKind, count int) error
ValidateConditionalArguments checks conditional shape before allocation or traversal.
func ValidateConflictMutator ¶
func ValidateConflictMutator(u ConflictUpdate, field FieldMutator) error
ValidateConflictMutator prevents SQL calculations from bypassing a Go mutator. The field's own EXCLUDED value has already been transformed by the insert. Example: ValidateConflictMutator(update, field).
func ValidateExpression ¶
func ValidateExpression(e Expression, table string, depth int, nodes *int) error
func ValidateExpressionValues ¶
func ValidateExpressionValues(e Expression, operand func(ValueExpression) error, depth int, nodes *int) error
func ValidateGeographicPoint ¶
func ValidateJSONKind ¶
func ValidateJSONProperty ¶
func ValidateLockSources ¶
Called only after the shared SELECT compiler has validated the entire AST and its resource bounds. Predicate/scalar subqueries are independent lock scopes.
func ValidateLockValue ¶
func ValidateLockValue(v ValueExpression) error
Calculations can contain windows below their root node. Reuse the bounded expression visitor, keeping scalar subqueries in their independent SELECT.
func ValidateMorphName ¶
ValidateMorphName uses the persisted identifier grammar for discriminators.
func ValidateProjectionColumns ¶
func ValidateProjectionColumns(columns []ProjectionColumn, hasDecoder bool) error
func ValidateRangeOrder ¶
func ValidateRangeOrder(kind codec.ParameterType, temporal bool) error
ValidateRangeOrder checks the representation required by a typed RANGE family. Both query APIs use this declaration boundary; frame traversal validates the resulting single ordering, bound values and positions separately.
func ValidateRowValue ¶
func ValidateSQLMapping ¶
func ValidateSQLMapping(model *ModelDefinition, column string, mutated bool) error
ValidateSQLMapping owns the declaration rules shared by both model APIs.
func ValidateScopes ¶
func ValidateScopes(scopes []ScopeDefinition, table string) error
func ValidateSubstringCount ¶
func VisitComputedValue ¶
func VisitComputedValue(v ValueExpression, item func(ValueExpression) error, condition func(Expression) error) (bool, error)
One structural boundary is shared by compilation, analysis, validation and qualification. Child callbacks retain the caller's row/group/window context.
func VisitWindowSpec ¶
func VisitWindowSpec(w WindowSpec, item func(ValueExpression) error, reference func(*NamedWindow) error) error
This shared structural boundary lets dependency analysis and local window registration traverse definitions without duplicating expression handling.
func ZoneArgument ¶
Types ¶
type Adjustment ¶
type AggregateCast ¶
type AggregateCast uint8
const ( NativeNumber AggregateCast = iota ExactNumberCast FloatNumberCast IntervalValueCast )
type AggregateFilter ¶
type AggregateFilter struct{ Predicates []Expression }
The immutable pointer keeps aggregateNode comparable for zero-declaration checks while storing ordinary predicates in the shared expression AST.
type AggregateKind ¶
type AggregateKind uint8
const ( CountAll AggregateKind = iota + 1 CountValues CountDistinct SumValues AverageValues MinimumValue MaximumValue ExistsValues )
type AggregateNode ¶
type AggregateNode struct {
Sensitive bool
Kind AggregateKind
Field FieldRef
Cast AggregateCast
Filter *AggregateFilter
}
func RequalifyAggregate ¶
func RequalifyAggregate(a AggregateNode, alias string) AggregateNode
func (AggregateNode) ValidateFilter ¶
func (a AggregateNode) ValidateFilter(field func(FieldRef) error, nodes *int) error
func (AggregateNode) ValueNode ¶
func (AggregateNode) ValueNode()
type AssignmentValue ¶
type AssignmentValue struct {
Bind func() (driver.Value, error)
Value *InputState // Private type erasure; metadata checks the exact V before mutation.
CopyValue func() any
}
assignmentValue is shared by model drafts and conflict literals. Keeping the captured value independent of M avoids re-instantiating its codec closure for every model/query scope while the public Assignment/Conflict retain ownership.
func CaptureAssignment ¶
func CaptureAssignment[V any](c codec.Codec[V], v V) AssignmentValue
CaptureAssignment owns a typed stored value and its codec snapshot. Example: CaptureAssignment(codec.String[string](), "stored").
func CaptureInput ¶
func CaptureInput[I any](input I, clone func(I) I) AssignmentValue
CaptureInput defers binding until transformation, cloning mutable inputs when declared. Example: CaptureInput(input, cloneInput).
func (AssignmentValue) InputValue ¶
func (v AssignmentValue) InputValue() any
type BinaryComparison ¶
type BinaryComparison struct {
Text bool
Left, Right ValueExpression
Operator Operator
}
binaryComparison compares SQL operands without treating either as a literal binding.
func (BinaryComparison) ExpressionNode ¶
func (BinaryComparison) ExpressionNode()
type CaseBranch ¶
type CaseBranch struct {
Condition Expression
Result ValueExpression
}
type CaseNode ¶
type CaseNode struct {
Branches []CaseBranch
Otherwise ValueExpression
Err error
}
type Column ¶
Column describes one persisted column at the generated declaration boundary. DatabaseDefault permits omission of a non-nullable field on insert; the actual SQL default expression remains owned by the migration, never duplicated here. Encrypted marks a database/encrypted field, bound to the row's primary key.
type Comparison ¶
type Comparison struct {
Operand ValueExpression
Values *ComparisonValuesState
Bind func(any) (driver.Value, error)
// Text is supplied by text-capable builders, never inferred from a string codec.
Text bool
Operator Operator
// Kind is the operand codec's scalar representation. Membership tests over
// supported scalar kinds bind one array parameter instead of one per value.
Kind codec.ParameterType
// contains filtered or unexported fields
}
func CodecComparison ¶
func CodecComparison(node Comparison, bind func(any) (driver.Value, error)) Comparison
CodecComparison installs a binding adapter owned by the framework codec path. Application callbacks belong in Codec.New or Comparison.Bind, never here.
func (Comparison) ExpressionNode ¶
func (Comparison) ExpressionNode()
type ComparisonValuesState ¶
type ComparisonValuesState = comparisonValuesState
func RetainComparisonValues ¶
func RetainComparisonValues(v []any) *ComparisonValuesState
type CompiledKey ¶
type CompiledKey struct {
Node ValueExpression
Grouped bool
Sql string
ArgumentEnd int
Rendering bool
}
Keys are local to one SELECT. Reusing their emitted SQL also reuses parameter identities, as required for PostgreSQL grouping and DISTINCT ON matching.
type Compiler ¶
type Compiler struct {
AllowLocks bool
LockWork int
Ctes map[string]*CteNode
Self *RecursiveReference
DirectSelf bool
InWindow bool
IndexTarget bool
Outer *OuterScope
Keys *SelectKeys
FieldObserver func(int, FieldRef)
Arguments []any
Columns map[string]Column
Sources map[string]map[string]Column
// scopeContext is the executing call's context; it resolves context
// global scopes, including those lowered from related queries.
ScopeContext context.Context
ScopeShapeOnly bool
SelectDepth, SelectNodes, ExpressionNodes int
ValueDepth int
ScalarSQLBytes int
// contains filtered or unexported fields
}
func NewCompiler ¶
func (*Compiler) AggregateAt ¶
func (*Compiler) AggregateField ¶
func (*Compiler) AggregateFilterSQL ¶
func (*Compiler) AssignmentParameter ¶
func (*Compiler) BeginStatement ¶
BeginStatement re-evaluates diagnostic scope for every compilation, including reused compilers. An inactive execution follows the ordinary renderer without fragment state or a shape allocation. Inspect-only compiles may have no context.
func (*Compiler) Comparison ¶
func (*Compiler) CompileCTEs ¶
func (c *Compiler) CompileCTEs(node SelectNode) (string, error)
Definitions are statement-local and independent of row correlation. References in nested SELECTs use this registry without inheriting surrounding row fields.
func (*Compiler) CompileLocks ¶
func (c *Compiler) CompileLocks(node SelectNode, specs []LockSpec) (string, error)
func (*Compiler) CompileSelect ¶
func (c *Compiler) CompileSelect(node SelectNode) (string, error)
func (*Compiler) ComputedSQL ¶
func (*Compiler) ConditionClause ¶
func (*Compiler) ConditionClauseAt ¶
func (*Compiler) CorrelationScope ¶
func (c *Compiler) CorrelationScope(required *ScopeRequirement, grouped map[FieldRef]bool, grouping bool) (*OuterScope, error)
Capture enclosing maps and grouping rules by value: recursive compilation changes compiler state. Correlation can access only its declared parent scope.
func (*Compiler) DeclaredField ¶
func (*Compiler) DiscardArguments ¶
func (*Compiler) DistinctSQL ¶
func (*Compiler) Expression ¶
func (c *Compiler) Expression(e Expression) (string, error)
func (*Compiler) ExpressionAt ¶
func (*Compiler) FrameBoundSQL ¶
func (c *Compiler) FrameBoundSQL(b FrameBound) (string, error)
func (*Compiler) GroupKeys ¶
func (c *Compiler) GroupKeys(values []ValueExpression) (map[FieldRef]bool, error)
func (*Compiler) JoinSourceSQL ¶
Lateral FROM inputs observe preceding rows before this SELECT's grouping. Ordinary derived sources continue to compile with no outer visibility.
func (*Compiler) JsonTextScalarSQL ¶
func (c *Compiler) JsonTextScalarSQL(n OperationNode, grouped map[FieldRef]bool, grouping bool) (string, bool, error)
jsonTextScalarSQL extracts a scalar directly below a property or element with ->>, which returns the same text as (document -> key) #>> '{}' (JSON null and missing paths are SQL NULL), so (document ->> 'key') expression indexes match typed predicates on declared properties.
func (*Compiler) MatchingKey ¶
func (c *Compiler) MatchingKey(v ValueExpression, groupedOnly bool) (*CompiledKey, error)
func (*Compiler) NamedWindowsSQL ¶
func (*Compiler) ObserveField ¶
func (*Compiler) OperationArguments ¶
func (c *Compiler) OperationArguments(n OperationNode, grouped map[FieldRef]bool, grouping bool) ([]string, error)
operationArguments compiles each argument with its explicit SQL type.
func (*Compiler) OperationSQL ¶
func (*Compiler) ParameterSQL ¶
func (c *Compiler) ParameterSQL(p ParameterNode) (string, error)
func (*Compiler) PlanValue ¶
func (c *Compiler) PlanValue(v ValueExpression) (PlannedValue, error)
func (*Compiler) RangeDistanceSQL ¶
func (c *Compiler) RangeDistanceSQL(d RangeDistance) (string, error)
func (*Compiler) RegisterKey ¶
func (c *Compiler) RegisterKey(v ValueExpression, grouped bool) (*CompiledKey, error)
func (*Compiler) RenderSelectedExpression ¶
func (*Compiler) RowComparison ¶
func (c *Compiler) RowComparison(e RowComparison, grouped map[FieldRef]bool, grouping bool) (string, error)
rowComparison compiles (a, b) > ($1, $2) for keyset traversal.
func (*Compiler) SchemaLiteral ¶
Only a conflict target compiler enables this path. Values have already passed their declared codec; this final boundary owns PostgreSQL literal escaping and output bounds, independent of standard_conforming_strings.
func (*Compiler) SelectSQLWithOuter ¶
func (c *Compiler) SelectSQLWithOuter(s SelectNode, outer *OuterScope) (string, error)
func (*Compiler) SelectedExpression ¶
func (*Compiler) SubqueryPredicate ¶
func (*Compiler) SubquerySQL ¶
func (*Compiler) TrackShape ¶
func (c *Compiler) TrackShape()
func (*Compiler) ValidateHavingValue ¶
func (c *Compiler) ValidateHavingValue(v ValueExpression, grouped map[FieldRef]bool) error
func (*Compiler) ValidateSelectedExpression ¶
func (c *Compiler) ValidateSelectedExpression(e ValueExpression, grouped map[FieldRef]bool, grouping bool) error
Validation is pure: nested SELECTs bind only at their SQL output position.
func (*Compiler) ValidateWindow ¶
func (*Compiler) Where ¶
func (c *Compiler) Where(sql *strings.Builder, predicates []Expression) error
func (*Compiler) WindowDefinitionSQL ¶
func (*Compiler) WindowSpecSQL ¶
type ComputedOrder ¶
type ComputedOrder struct{ Expression ValueExpression }
type ConditionalKind ¶
type ConditionalKind uint8
const ( CoalesceValues ConditionalKind = iota + 1 NullIfValues )
type ConditionalNode ¶
type ConditionalNode struct {
Kind ConditionalKind
Arguments []ValueExpression
Err error
}
func (ConditionalNode) ValueNode ¶
func (ConditionalNode) ValueNode()
type Conflict ¶
type Conflict struct {
Keys []ValueExpression
Constraint string
Named bool
Action ConflictAction
Updates []ConflictUpdate
Condition, RowCondition, TargetCondition []Expression
}
Conflict contains SQL policy data only; public facades retain model ownership.
func MutateConflictLiterals ¶
func MutateConflictLiterals(ctx context.Context, policy Conflict, fields []FieldMutator) (Conflict, error)
MutateConflictLiterals transforms a reusable policy once, independently of its number of proposed rows. Fields retain each facade's nullable input encoding. Example: MutateConflictLiterals(ctx, policy, fields).
func (Conflict) CheckReturned ¶
CheckReturned rejects an unconditional update suppressed by destination scopes. Example: policy.CheckReturned(query, 2, 1).
func (Conflict) Compile ¶
func (p Conflict) Compile(c *Compiler, table, alias string, columns []Column, scopes []Expression) (string, error)
compile renders the conflict clause. scopes are the destination's active global scope predicates: DO UPDATE never changes a conflicting row outside them, so a tenant cannot overwrite another tenant's row through a globally unique key.
func (Conflict) Dependencies ¶
func (p Conflict) Dependencies(node SelectNode) SelectNode
One dependency node exposes index targets, assignment subqueries and update predicates to the existing bounded alias allocator and statement-wide CTE planner.
func (Conflict) ValidateRows ¶
func (Conflict) ValidateShape ¶
func (Conflict) WithUpdatedTimestamp ¶
WithUpdatedTimestamp copies the normalized proposed instant during DO UPDATE. Example: policy.WithUpdatedTimestamp("users", "updated_at").
type ConflictAction ¶
type ConflictAction uint8
const ( ConflictNothing ConflictAction ConflictDoUpdate )
type ConflictUpdate ¶
type ConflictUpdate struct {
Field FieldRef
Literal *AssignmentValue
MutatedLiteral bool
Incoming, Null bool
Value ValueExpression
}
type CteMaterialization ¶
type CteMaterialization uint8
const ( CteDefault CteMaterialization = iota CteMaterialized CteNotMaterialized )
type CteNode ¶
type CteNode struct {
Name string
Query SelectNode
Columns []Column
Materialization CteMaterialization
Recursion *RecursiveCTE
}
func OrderedCTEs ¶
func OrderedCTEs(root SelectNode) ([]*CteNode, error)
type Cursor ¶
type Cursor[M any] struct { // contains filtered or unexported fields }
Cursor is an opaque model/result-owned position. Tokens are versioned and scoped to the query but are not signed/encrypted credentials. Apply authorization on every request. Token explicitly exports the transport value; formatting omits it.
func ParseCursor ¶
ParseCursor validates bounded transport structure. CursorPaginate additionally verifies the model/query scope and decodes every key through its field codec.
type CursorBoundary ¶
func ReadCursorBoundary ¶
func ReadCursorBoundary(token string, present, backward bool, scope string, fields []CursorField, required []bool) (CursorBoundary, error)
type CursorEnvelope ¶
type CursorEnvelope struct {
Version int `json:"v"`
Scope string `json:"scope"`
Values []CursorValue `json:"values"`
}
func DecodeCursor ¶
func DecodeCursor(token string) (CursorEnvelope, error)
type CursorField ¶
type CursorInputError ¶
type CursorInputError struct {
// contains filtered or unexported fields
}
func (*CursorInputError) Error ¶
func (*CursorInputError) Error() string
func (*CursorInputError) GoString ¶
func (e *CursorInputError) GoString() string
func (*CursorInputError) Is ¶
func (*CursorInputError) Is(target error) bool
func (*CursorInputError) Unwrap ¶
func (e *CursorInputError) Unwrap() error
type CursorPage ¶
CursorPage keeps canonical query order even for backward traversal. Next and Previous are navigation hints, not guarantees against concurrent data changes.
func (CursorPage[R]) Validate ¶
func (p CursorPage[R]) Validate() error
Validate checks bounded output metadata without querying for navigation. Empty pages carry no cursor; a nonempty page's navigation remains a hint.
type CursorRequest ¶
CursorRequest selects a bounded forward or backward page in the query's declared order. After and Before are mutually exclusive; omit both to start.
func (CursorRequest[R]) Validate ¶
func (r CursorRequest[R]) Validate() error
Validate checks size, exclusive directions and supplied token structure. Omit both directions for the first page; a supplied zero cursor is invalid.
type CursorValue ¶
func EncodeCursorValue ¶
func EncodeCursorValue(v driver.Value) (CursorValue, error)
type DistinctKind ¶
type DistinctKind uint8
const ( NoDistinct DistinctKind = iota DistinctRows DistinctOn )
type DistinctOrder ¶
type DistinctOrder struct {
Index ValueIndex
Ordinals []int
}
Match SQL emitted by the single expression compiler, including encoded bindings. Sorting by the matched output ordinal reuses its parameters instead of emitting equivalent expressions with different PostgreSQL parameter IDs.
func (*DistinctOrder) Add ¶
func (d *DistinctOrder) Add(plan PlannedValue, ordinal int)
type DistinctSpec ¶
type DistinctSpec struct {
Kind DistinctKind
Keys []ValueExpression
}
type Expression ¶
type Expression interface{ ExpressionNode() }
func CursorPredicate ¶
func CursorPredicate(orders []QueryOrder, keys []driver.Value, nullable func(QueryOrder) bool) Expression
CursorPredicate expands lexicographic comparison with explicit SQL NULL semantics. DESC defaults NULLS FIRST, ASC NULLS LAST, including reversed pages. nullable reports whether an order key can be NULL; NOT NULL keys never add an IS NULL alternative. When every key is NOT NULL and all keys share one direction, the equivalent row comparison (a, id) > ($1, $2) is emitted so PostgreSQL can use one composite index range.
func PredicateNode ¶
func PredicateNode(state *PredicateState) Expression
PredicateNode preserves the invalid zero predicate without a nil dereference.
func Requalify ¶
func Requalify(e Expression, alias string) Expression
requalify is used only after the original model scope has been validated. It copies expression containers; the caller's predicates remain unchanged.
type FieldMutator ¶
type FieldMutator struct {
Column string
Input, Output reflect.Type
Apply func(AssignmentValue) (AssignmentValue, error)
}
FieldMutator is model-independent transform metadata shared by both APIs. Example: NewFieldMutator("email", codec.String[string](), normalize).
func NewCapturedFieldMutator ¶
func NewCapturedFieldMutator[I, V any](column string, capture func(V) AssignmentValue, mutate func(I) (V, error)) FieldMutator
NewCapturedFieldMutator reuses a declared column's typed stored-value capture. Example: NewCapturedFieldMutator("id", captureID, convertFreshID).
func NewFieldMutator ¶
func NewFieldMutator[I, V any](column string, c codec.Codec[V], mutate func(I) (V, error)) FieldMutator
NewFieldMutator binds typed input and output once, without reflective invocation. Example: NewFieldMutator("email", codec.String[string](), normalize).
func NewNullableFieldMutator ¶
func NewNullableFieldMutator[I, V any](column string, c codec.Codec[V], mutate func(I) (V, error)) FieldMutator
NewNullableFieldMutator retains NULL while transforming assigned non-null inputs. Example: NewNullableFieldMutator("note", codec.String[string](), normalize).
type FrameBound ¶
type FrameBound struct {
Kind FrameBoundKind
Offset *OffsetState
Distance *RangeDistance
}
type FrameBoundKind ¶
type FrameBoundKind uint8
const ( UnboundedPreceding FrameBoundKind = iota + 1 PrecedingBound CurrentRow FollowingBound UnboundedFollowing )
type FrameExclusion ¶
type FrameExclusion uint8
const ( ExcludeNone FrameExclusion = iota ExcludeCurrent ExcludeGroup ExcludeTies )
type GlobalScopeName ¶
type GlobalScopeName string
GlobalScopeName identifies one model-declared default scope. It uses the SQL identifier grammar so diagnostics never echo arbitrary text.
type InputState ¶
type InputState = inputState
InputState retains an unencoded assignment or bound without invoking its codec or clone callback. In particular, type preflight must not clone inputs.
func RetainInput ¶
func RetainInput(value any) *InputState
type JoinNode ¶
type JoinNode struct {
Source TableSource
On Expression
Kind JoinKind
Lateral *ScopeRequirement
}
type JoinedNode ¶
type JoinedNode struct {
Node SelectNode
Aliases map[string]reflect.Type
Err error
}
func AliasNode ¶
func AliasNode(node SelectNode, columns []Column, direct bool, alias string, identity reflect.Type, err error) JoinedNode
AliasNode preserves source windows and filters inside their SELECT boundary.
func JoinNodes ¶
func JoinNodes(leftNode, rightNode SelectNode, leftAliases, rightAliases map[string]reflect.Type, leftError, rightError error, on Expression, kind JoinKind) JoinedNode
type Junction ¶
type Junction struct {
Any bool
Children []Expression
}
func (Junction) ExpressionNode ¶
func (Junction) ExpressionNode()
type LazyScopes ¶
type LazyScopes struct {
Source func() []ScopeDefinition
Once sync.Once
Ready atomic.Bool
Scopes []ScopeDefinition
Err error
}
lazyScopes evaluates a scope source once. Until it has run, queries lower the model's scopes as one deferred node that the compiler expands, so declaring the scopes (which may lower relation predicates of this same model) never re-enters an evaluation in progress.
func (*LazyScopes) Get ¶
func (l *LazyScopes) Get(table string) ([]ScopeDefinition, error)
type LiteralState ¶
type LiteralState = literalState
LiteralState and the slice variants keep SQL literals opaque wherever an AST is retained (including public projection, join, scope and subquery adapters). The private pointee prevents fmt from traversing a nested or private field. These immutable holders add no methods to consumer descriptors.
func RetainLiteral ¶
func RetainLiteral(v driver.Value) *LiteralState
type LockBehavior ¶
type LockBehavior uint8
const ( LockWait LockBehavior = iota LockNoWait LockSkip )
type LockSpec ¶
type LockSpec struct {
Strength LockStrength
Behavior LockBehavior
Targets []string
// nil targets means all eligible sources; an explicitly empty Of is invalid.
Explicit bool
}
type LockStrength ¶
type LockStrength uint8
const ( LockUpdate LockStrength = iota + 1 LockNoKeyUpdate )
type LookupDefault ¶
LookupDefault is a stored equality value eligible as an omitted creation input.
func LookupDefaults ¶
func LookupDefaults(ctx context.Context, q QueryCore, eligible func(string) bool) ([]LookupDefault, error)
LookupDefaults resolves top-level equalities and scopes, excluding conflicts and mutators.
type ModelDefinition ¶
type ModelDefinition struct {
Sensitive map[string]bool
Table, Primary string
Columns []Column
Timestamps *TimestampColumns
SoftDelete *SoftDeleteColumn
GlobalScopes []ScopeDefinition
ScopeSource *LazyScopes
}
modelDefinition contains immutable SQL metadata. Hydration, field getters and lifecycle callbacks remain on Definition[M]; no service or model is boxed.
func (*ModelDefinition) NullableOrder ¶
func (d *ModelDefinition) NullableOrder(order QueryOrder) bool
nullableOrder reports whether a model order key may be NULL. Computed keys and undeclared columns are treated as nullable.
func (ModelDefinition) Source ¶
func (d ModelDefinition) Source(table, alias string) TableSource
Source is the single persisted-model source constructor, including relation inputs that do not select/hydrate the model itself.
func (ModelDefinition) ValidateColumns ¶
func (d ModelDefinition) ValidateColumns(hasDecoder bool) (map[string]bool, error)
func (ModelDefinition) ValidateGlobalScopes ¶
func (d ModelDefinition) ValidateGlobalScopes() error
type MutationAssignment ¶
type MutationAssignment struct {
Field FieldRef
AssignmentValue
// seal encrypts an encrypted field's plaintext for its row before binding.
Seal Sealer
}
mutationAssignment is lowered SQL data. Public Assignment/Mutation keep the owner, while validation and compilation share this value across models.
func MutateAssignments ¶
func MutateAssignments(ctx context.Context, assignments []MutationAssignment, fields []FieldMutator) ([]MutationAssignment, error)
MutateAssignments checks all input types before invoking transforms in field order. It copies assignments so reusing a caller's write starts from the original inputs. Example: MutateAssignments(ctx, assignments, fields).
func SealAssignments ¶
func SealAssignments(ctx context.Context, keys *encryption.Keyring, table string, assignments []MutationAssignment, key func() (driver.Value, error)) ([]MutationAssignment, error)
type MutationKind ¶
type MutationKind uint8
const ( InsertModel MutationKind = iota UpdateModel DeleteModel SoftDeleteModel RestoreModel ForceDeleteModel )
func (MutationKind) Deletes ¶
func (k MutationKind) Deletes() bool
deletes reports the kinds deletion observers observe: delete, soft delete and force delete.
func (MutationKind) Operation ¶
func (kind MutationKind) Operation() lifecycle.Operation
func (MutationKind) SqlKind ¶
func (kind MutationKind) SqlKind() MutationKind
SQL shape and lifecycle intent are distinct: restoration and soft deletion write updates without emitting ordinary saving/updating callbacks.
type NamedWindow ¶
type NamedWindow struct {
Name string
Definition WindowSpec
}
func OrderedWindows ¶
func OrderedWindows(s SelectNode) ([]*NamedWindow, error)
type Negation ¶
type Negation struct{ Child Expression }
func (Negation) ExpressionNode ¶
func (Negation) ExpressionNode()
type NullPlacement ¶
type NullPlacement uint8
const ( NullsDefault NullPlacement = iota NullsFirst NullsLast )
type OffsetState ¶
type OffsetState = offsetState
OffsetState protects literal window offsets just like ordinary SQL parameters.
func RetainOffset ¶
func RetainOffset(v int64) *OffsetState
type OperationArgument ¶
type OperationArgument struct {
Value ValueExpression
Kind codec.ParameterType
}
type OperationNode ¶
type OperationNode struct {
Kind ScalarOperation
Arguments []OperationArgument
Result codec.ParameterType
Err error
}
func (OperationNode) Validate ¶
func (n OperationNode) Validate() error
func (OperationNode) ValidateInterval ¶
func (n OperationNode) ValidateInterval() error
func (OperationNode) ValidateJSON ¶
func (n OperationNode) ValidateJSON() error
func (OperationNode) ValidateTemporal ¶
func (n OperationNode) ValidateTemporal() error
func (OperationNode) ValueNode ¶
func (OperationNode) ValueNode()
type OperationSpec ¶
Operation names and arities are private, closed compiler metadata. Public builders never accept SQL function/operator/type names.
func IntervalOperationSpec ¶
func IntervalOperationSpec(op ScalarOperation) (OperationSpec, bool)
func JsonOperationSpec ¶
func JsonOperationSpec(op ScalarOperation) (OperationSpec, bool)
func TemporalOperationSpec ¶
func TemporalOperationSpec(op ScalarOperation) (OperationSpec, bool)
type OrderNode ¶
type OrderNode struct {
Expression ValueExpression
Descending bool
Nulls NullPlacement
}
func OrderNodes ¶
func OrderNodes(orders []QueryOrder) []OrderNode
type OuterScope ¶
type Page ¶
Page contains complete results and an unpaginated matching count. Count and rows are separate queries; use a repeatable-read transaction for one snapshot.
type PageRequest ¶
type PageRequest struct{ Number, Size int }
PageRequest selects a one-based page. Size must be between 1 and MaxPageSize. Invalid requests fail rather than being silently clamped.
func (PageRequest) Validate ¶
func (r PageRequest) Validate() error
Validate checks number, size and offset representability without database I/O. Transport adapters reuse this contract rather than computing offsets.
type ParameterNode ¶
type ParameterNode struct {
Sensitive bool
Kind codec.ParameterType
Value *LiteralState
Err error
// literal renders a generated declaration constant, such as a JSON
// property name, inline as an escaped schema literal instead of a bind
// parameter, so expression indexes on the same path can match. Values
// supplied at run time always remain bind parameters.
Literal bool
}
func (ParameterNode) Validate ¶
func (p ParameterNode) Validate() error
func (ParameterNode) ValueNode ¶
func (ParameterNode) ValueNode()
type Plan ¶
type Plan struct {
// contains filtered or unexported fields
}
Plan owns a bounded response for one compiled SELECT. Inspection does not hydrate models, run retrieval hooks or execute eager relation queries. JSON may contain predicates and bound values; only explicit accessors expose it.
type PlanEnvelope ¶
type PlanNode ¶
type PlanNode struct {
NodeType string `json:"Node Type"`
ParentRelationship string `json:"Parent Relationship,omitempty"`
RelationName string `json:"Relation Name,omitempty"`
Schema string `json:"Schema,omitempty"`
Alias string `json:"Alias,omitempty"`
IndexName string `json:"Index Name,omitempty"`
JoinType string `json:"Join Type,omitempty"`
Strategy string `json:"Strategy,omitempty"`
ParallelAware bool `json:"Parallel Aware"`
StartupCost float64 `json:"Startup Cost"`
TotalCost float64 `json:"Total Cost"`
PlanRows float64 `json:"Plan Rows"`
PlanWidth int64 `json:"Plan Width"`
ActualStartupTime value.Optional[float64] `json:"Actual Startup Time,omitzero"`
ActualTotalTime value.Optional[float64] `json:"Actual Total Time,omitzero"`
ActualRows value.Optional[float64] `json:"Actual Rows,omitzero"`
ActualLoops value.Optional[float64] `json:"Actual Loops,omitzero"`
Plans []PlanNode `json:"Plans,omitempty"`
}
PlanNode is a typed snapshot of PostgreSQL's common plan fields. Actual measurements are absent for ordinary Explain. Costs are planner units; reported time values are milliseconds. JSON retains additional server fields.
type PlannedValue ¶
A canonical value uses the shared compiler with local parameter numbering. Bound values participate in identity; SQL text alone is insufficient.
type PredicateState ¶
type PredicateState = predicateState
PredicateState names opaque retained expression storage for the typed API packages. Its private concrete type is kept behind a pointer so fmt cannot recursively expose literals, including through unexported wrapper fields.
func RetainComparison ¶
func RetainComparison(node Comparison, count int) (*PredicateState, []any)
RetainComparison co-locates the opaque holders and the common single literal. The caller fills values before publishing the predicate; neither the AST nor the typed predicate exposes them through formatting.
func RetainPredicate ¶
func RetainPredicate(node Expression) *PredicateState
RetainPredicate keeps the immutable AST intact behind the formatting boundary.
type ProjectionColumn ¶
Projection plans erase scope identities only after Map/Project checked the input, output and value types. Decoder/getter values stay concretely typed.
type ProjectionMapping ¶
type ProjectionMapping struct {
Sensitive bool
Column ProjectionColumn
Expression ValueExpression
}
type QueryCore ¶
type QueryCore struct {
Table string
Predicates []Expression
Orders []QueryOrder
Limit value.Optional[int]
Offset int
SoftDeleteScope SoftDeleteScope
// Global scope options: removed scopes, all scopes removed, and the
// context that resolves context scopes (see WithScopeContext).
WithoutScopes []GlobalScopeName
AllScopesOff bool
ScopeContext context.Context
// skipModelHooks acknowledges hook-free set-based writes only.
SkipModelHooks bool
// distinctOnKey is set only by one-of-many relation loading.
DistinctOnKey *FieldRef
Model *ModelDefinition
}
queryCore owns model-independent builder state and planning. Public adapters check concrete owner/value types before lowering into the existing SQL AST. Values are immutable: every operation extending a slice makes an owned copy.
func (QueryCore) ActiveScopePredicates ¶
func (q QueryCore) ActiveScopePredicates(scopes []ScopeDefinition) []Expression
func (QueryCore) CompileInsert ¶
func (q QueryCore) CompileInsert(c Compiler, rows []map[string]MutationAssignment, union map[string]bool, node SelectNode, conflict *Conflict) (Statement, error)
func (QueryCore) CompileInsertSelect ¶
func (q QueryCore) CompileInsertSelect(c Compiler, node SelectNode, mapped map[string]ValueExpression, values map[string]MutationAssignment, kind func(string) codec.ParameterType, returning bool) (Statement, error)
The existing SELECT compiler owns source scopes, CTE dependencies, expression validation and bindings. Destination declaration order owns insertion columns. This private compiler accepts only already-prepared literal values.
func (QueryCore) CompileModel ¶
func (q QueryCore) CompileModel(kind ReadKind, selections []SelectItem) (Statement, error)
func (QueryCore) CompileMutation ¶
func (q QueryCore) CompileMutation(c Compiler, node SelectNode, kind MutationKind, assignments []MutationAssignment, assigned map[string]MutationAssignment, adjust *Adjustment, countOnly bool) (Statement, error)
func (QueryCore) CompileSourceWrite ¶
func (q QueryCore) CompileSourceWrite(c Compiler, destination, source SelectNode, key SourceWriteKey, kind MutationKind, mapped map[string]ValueExpression, values map[string]MutationAssignment, returning bool) (Statement, error)
Source SELECTs, dependencies, predicates and all bindings use the shared AST compiler. Only the native mutation envelope is assembled here.
func (QueryCore) DeferredScopes ¶
func (q QueryCore) DeferredScopes(lazy *LazyScopes) ScopeNode
deferredScopes expands the model's scopes at compilation: it runs the source once, checks removals, and resolves context scopes with the compiler's context (an absent context fails only if a context scope exists).
func (QueryCore) DeletionPredicate ¶
func (q QueryCore) DeletionPredicate(op Operator) Expression
func (QueryCore) EffectivePredicates ¶
func (q QueryCore) EffectivePredicates() []Expression
effectivePredicates is the sole source of automatic model visibility. Keep explicit filters separate so replacing the implicit scope never removes one. Model global scopes join here too, so every read, write, relation and subquery path that honors soft deletion honors them identically.
func (QueryCore) HasSoftDeletes ¶
func (QueryCore) ModelSelect ¶
func (q QueryCore) ModelSelect(selections []SelectItem) SelectNode
func (QueryCore) RequireInsertFields ¶
func (QueryCore) ScopePredicates ¶
func (q QueryCore) ScopePredicates() []Expression
scopePredicates returns the active scopes' predicates. Context scopes become placeholders that the compiler resolves with the bound execution context. A model whose scope source has not run yet contributes one deferred node.
func (QueryCore) StableOrder ¶
func (QueryCore) ValidateAdjustment ¶
func (q QueryCore) ValidateAdjustment(a *Adjustment, c *Compiler, assigned map[string]MutationAssignment) error
ValidateAdjustment checks the target before a write acquires resources or samples time.
func (QueryCore) ValidateMutation ¶
func (q QueryCore) ValidateMutation(kind MutationKind, assignments []MutationAssignment, c *Compiler) (map[string]MutationAssignment, error)
func (QueryCore) ValidateMutationShape ¶
func (q QueryCore) ValidateMutationShape(kind MutationKind, assignments []MutationAssignment, c *Compiler) (map[string]MutationAssignment, error)
func (QueryCore) ValidateScopeOptions ¶
func (QueryCore) ValidateSoftDeleteScope ¶
func (QueryCore) WriteCompiler ¶
func (q QueryCore) WriteCompiler(kind MutationKind, requirePrimary, hasRelations bool) (Compiler, error)
type QueryOrder ¶
type QueryOrder struct {
Field FieldRef
Computed *ComputedOrder
Descending bool
Nulls NullPlacement
}
func CursorOrders ¶
func CursorOrders(orders []QueryOrder, backward bool) []QueryOrder
func ModelOrder ¶
func ModelOrder(node OrderNode) QueryOrder
ModelOrder preserves plain-column identity for keyset and stable ordering.
func ResultCursorOrders ¶
func ResultCursorOrders(node SelectNode, columns []Column, orders []QueryOrder, unique []FieldRef) ([]QueryOrder, error)
ResultCursorOrders validates identity and appends missing identity fields.
func (QueryOrder) Value ¶
func (o QueryOrder) Value() ValueExpression
type RangeDistance ¶
type RangeDistance struct {
Parameter ParameterNode
Interval *temporal.Interval
Err error
}
func (RangeDistance) Validate ¶
func (d RangeDistance) Validate(kind codec.ParameterType) error
type RawFragment ¶
type RawFragment struct {
// contains filtered or unexported fields
}
RawFragment owns lexed SQL and normalized arguments. Private state prevents bypassing construction validation or mutating a fragment through an AST copy.
func NewRawFragment ¶
func NewRawFragment(sql string, arguments []any) RawFragment
func (RawFragment) ExpressionNode ¶
func (RawFragment) ExpressionNode()
func (RawFragment) Validate ¶
func (r RawFragment) Validate() error
func (RawFragment) ValueNode ¶
func (RawFragment) ValueNode()
type RecordLayout ¶
type RecordLayout struct {
Node SelectNode
Columns []Column
HasDecoder bool
Err error
}
RecordLayout describes the complete output expected by a record decoder.
type RecursiveCTE ¶
type RecursiveCTE struct {
Reference *RecursiveReference
Step SelectNode
Operator SetOperator
}
type RecursiveReference ¶
Pointer identity binds the working table to one recursive declaration without making the AST cyclic or giving an escaped self-reference a new definition.
type RelationLimits ¶
type RelationLimits struct{ BatchSize, MaxRows, MaxDepth int }
RelationLimits bounds key batches, fetched/attached rows and nesting.
func DefaultRelationLimits ¶
func DefaultRelationLimits() RelationLimits
func (RelationLimits) Validate ¶
func (l RelationLimits) Validate() error
type RelationOrder ¶
type RelationOrder struct {
Value ValueExpression
Descending, Pivot bool
Nulls NullPlacement
}
RelationOrder preserves the combined target/pivot order without model types.
type ResultCursorField ¶
ResultCursorField describes codec availability without retaining typed getters.
type RowComparison ¶
type RowComparison struct {
Operands []ValueExpression
Operator Operator
Values *RowValuesState
}
rowComparison is a lexicographic row-value comparison such as (a, id) > ($1, $2). Keyset traversal uses it only for NOT NULL keys sorted in one direction, where it matches the expanded predicate and lets PostgreSQL use one composite index range.
func (RowComparison) ExpressionNode ¶
func (RowComparison) ExpressionNode()
type RowValuesState ¶
type RowValuesState = rowValuesState
func RetainRowValues ¶
func RetainRowValues(v []driver.Value) *RowValuesState
type ScalarOperation ¶
type ScalarOperation uint8
const ( AddOperation ScalarOperation = iota + 1 SubtractOperation MultiplyOperation DivideOperation RemainderOperation NegateOperation AbsOperation CastOperation LowerOperation UpperOperation TrimOperation TrimLeftOperation TrimRightOperation LengthOperation OctetLengthOperation ConcatOperation ConcatWSOperation SubstringOperation ReplaceOperation ExtractYearOperation ExtractMonthOperation ExtractDayOperation ExtractDayOfWeekOperation ExtractISODayOfWeekOperation ExtractDayOfYearOperation ExtractISOWeekOperation ExtractISOYearOperation ExtractQuarterOperation ExtractCenturyOperation ExtractDecadeOperation ExtractMillenniumOperation ExtractJulianDayOperation ExtractHourOperation ExtractMinuteOperation ExtractSecondOperation ExtractMillisecondsOperation ExtractMicrosecondsOperation ExtractUnixSecondsOperation ExtractUnixMillisecondsOperation FromUnixMillisOperation TruncateDateOperation TruncateLocalOperation TruncateInstantOperation LocalAtOperation ResolveLocalOperation DateOfOperation TimeOfOperation CombineDateTimeOperation AddDateDaysOperation DateDifferenceOperation AddDateIntervalOperation SubtractDateIntervalOperation AddLocalIntervalOperation SubtractLocalIntervalOperation AddInstantIntervalOperation SubtractInstantIntervalOperation AddClockElapsedOperation SubtractClockElapsedOperation TransactionTimeOperation AddIntervalsOperation SubtractIntervalsOperation NegateIntervalOperation LocalDifferenceOperation InstantDifferenceOperation ClockDifferenceOperation IntervalMonthsOperation IntervalDaysOperation IntervalElapsedOperation JsonContainsOperation JsonContainedByOperation JsonKindOperation JsonPropertyOperation JsonIndexOperation JsonScalarOperation JsonUnquoteOperation JsonArrayLengthOperation SphericalDistanceOperation )
func (ScalarOperation) Spec ¶
func (op ScalarOperation) Spec() (OperationSpec, bool)
type ScalarSubquery ¶
type ScalarSubquery struct{ Query Subquery }
func (ScalarSubquery) ValueNode ¶
func (ScalarSubquery) ValueNode()
type ScopeDefinition ¶
type ScopeDefinition struct {
Name GlobalScopeName
Predicate Expression
Resolve func(context.Context) (Expression, error)
}
scopeDefinition is private SQL data; only its declaration adapter knows M.
type ScopeNode ¶
type ScopeNode struct {
Name GlobalScopeName
Context context.Context
// needsContext marks a context scope; a deferred scope expansion resolves
// its own context scopes and may run without a context.
NeedsContext bool
Resolve func(context.Context) (Expression, error)
}
scopeNode is a context scope resolved when compiled. The executing call's context, supplied to the compiler, always wins, so a query value lowered into another statement never keeps an earlier request's scope; the context captured from WithScopeContext serves only Compile and plan inspection. Rewrites such as alias requalification compose onto resolve.
func (ScopeNode) ExpressionNode ¶
func (ScopeNode) ExpressionNode()
func (ScopeNode) Resolved ¶
func (n ScopeNode) Resolved(executing context.Context) (Expression, error)
func (ScopeNode) Rewrite ¶
func (n ScopeNode) Rewrite(fn func(Expression) (Expression, error)) ScopeNode
rewrite composes an expression rewrite onto the deferred resolution.
type ScopeRequirement ¶
type Sealer ¶
type Sealer func(context.Context, *encryption.Keyring, encryption.Context) (AssignmentValue, error)
Sealer encrypts one captured plaintext for the row it is written to.
func EncryptedSealer ¶
func EncryptedSealer[V encrypted.Value[V]](v V, capture func(V) AssignmentValue) Sealer
EncryptedSealer is keyed only by the encrypted value type, never its model.
func NullableEncryptedSealer ¶
type SelectItem ¶
type SelectItem struct {
Sensitive bool // Explicit result-codec sensitivity, independent of its SQL expression.
Expression ValueExpression
Alias string
}
func ColumnSelections ¶
func ColumnSelections(table string, columns []Column) []SelectItem
type SelectKeys ¶
type SelectKeys struct {
Index ValueIndex
Entries []*CompiledKey
Fields map[FieldRef]*CompiledKey
Kinds map[reflect.Type]bool
GroupCount int
}
type SelectNames ¶
Alias allocation and CTE planning share one bounded AST traversal.
func NamesInSelects ¶
func NamesInSelects(nodes ...SelectNode) (*SelectNames, error)
func (*SelectNames) Allocate ¶
func (n *SelectNames) Allocate(prefix string) string
type SelectNode ¶
type SelectNode struct {
Locks []LockSpec
Source TableSource
Selections []SelectItem // Empty selects the constant 1, used by count/exists.
Distinct DistinctSpec
GroupBy []ValueExpression
Joins []JoinNode
Predicates []Expression
Having []Expression
Orders []OrderNode
Limit value.Optional[int]
Offset int
}
func CountNode ¶
func CountNode(node SelectNode) SelectNode
countNode omits an outer ORDER BY that cannot affect a count. Orders remain when DISTINCT ON chooses rows or when a Limit/Offset window is counted.
func RelatedValueSelect ¶
func RelatedValueSelect(node SelectNode, inputTable, inputAlias string, group, local FieldRef, measure AggregateNode) (SelectNode, error)
RelatedValueSelect lowers an ad-hoc relation aggregate to one correlated row. Both public APIs share alias allocation, filters and correlation keys here.
func RelationAggregateSelect ¶
func RelationAggregateSelect(node SelectNode, inputTable, inputAlias string, group FieldRef, measure AggregateNode, singular bool, unique FieldRef, keys []driver.Value, limit int) (SelectNode, error)
RelationAggregateSelect builds one grouped batch for both relation APIs.
func RelationExistsSelect ¶
func RelationExistsSelect(node SelectNode, source string) (SelectNode, string, error)
RelationExistsSelect is the shared relation alias/scoping owner. Only filters affect existence; ordering and eager loading do not cause extra work.
func RelationHopJoin ¶
func RelationHopJoin(node SelectNode, targetAlias string, foreign FieldRef, source TableSource, predicates []Expression, second FieldRef) SelectNode
RelationHopJoin adds the intermediate model with its own scopes.
func RelationThroughSelect ¶
func RelationThroughSelect(target, pivot QueryCore, foreign, pivotForeign FieldRef, orders []RelationOrder, targetAlias, pivotAlias string) SelectNode
RelationThroughSelect is the shared joined-model SELECT owner for both APIs.
func ReorderUnwindowed ¶
func ReorderUnwindowed(node SelectNode, orders int) (SelectNode, error)
ReorderUnwindowed validates report ordering before removing the outer orders.
func ResultCursorNode ¶
func ResultCursorNode(source SelectNode, columns []Column, hasDecoder bool) (SelectNode, error)
ResultCursorNode preserves the complete input window behind an allocated alias.
func ResultPageWindow ¶
func ResultPageWindow(node SelectNode, offset, size int, lookahead bool) (SelectNode, error)
ResultPageWindow applies a validated page request to an explicitly ordered result.
func SelectProjection ¶
func SelectProjection(source SelectNode, columns []ProjectionColumn, mappings []ProjectionMapping) (SelectNode, error)
func SelectRecordNode ¶
func SelectRecordNode(node SelectNode, table string, columns []Column, hasDecoder bool) (SelectNode, error)
type SelectWalk ¶
type SelectWalk struct {
Parameter func(ParameterNode)
Sensitive func()
SubqueryVisitor func(Subquery, int)
Named func(*NamedWindow, int)
Window func(WindowNode)
LocalSelect bool
Source func(TableSource, int)
Field func(FieldRef)
Correlation func(ScopeRequirement)
Nodes int
Err error
RecursiveRestriction string
}
Visitors may descend into a referenced CTE using the same walker and budget. Nested SELECTs are visited unless localSelect restricts discovery to this level; traversal does not change scopes.
func (*SelectWalk) Expression ¶
func (w *SelectWalk) Expression(e Expression, depth int)
func (*SelectWalk) RestrictRecursion ¶
func (w *SelectWalk) RestrictRecursion(reason string, visit func())
func (*SelectWalk) SelectNode ¶
func (w *SelectWalk) SelectNode(s SelectNode, depth int)
func (*SelectWalk) Subquery ¶
func (w *SelectWalk) Subquery(q Subquery, depth int)
func (*SelectWalk) Value ¶
func (w *SelectWalk) Value(v ValueExpression, depth int)
func (*SelectWalk) Visit ¶
func (w *SelectWalk) Visit(depth int) bool
func (*SelectWalk) VisitCorrelation ¶
func (w *SelectWalk) VisitCorrelation(required *ScopeRequirement)
func (*SelectWalk) VisitField ¶
func (w *SelectWalk) VisitField(f FieldRef)
func (*SelectWalk) VisitSource ¶
func (w *SelectWalk) VisitSource(s TableSource, depth int)
func (*SelectWalk) WindowSpec ¶
func (w *SelectWalk) WindowSpec(spec WindowSpec, depth int)
type SensitiveValue ¶
type SensitiveValue struct{ Value ValueExpression }
SensitiveValue retains a codec's mark when a computation chooses a different result codec. It changes neither SQL, scope, grouping nor the value's type.
func (SensitiveValue) ValueNode ¶
func (SensitiveValue) ValueNode()
type SetNode ¶
type SetNode struct {
Left, Right SelectNode
Operator SetOperator
}
type SetOperator ¶
type SetOperator uint8
const ( UnionSet SetOperator = iota UnionAllSet IntersectSet IntersectAllSet ExceptSet ExceptAllSet )
type SimplePage ¶
SimplePage contains complete results without a total count. HasMore indicates an extra row existed after this page in the read's snapshot. Number > 1 permits backward navigation; neither direction guarantees rows survive a later request.
func (SimplePage[R]) Validate ¶
func (p SimplePage[R]) Validate() error
Validate checks a bounded simple page without fabricating totals. HasMore requires a full page because its hidden lookahead row was removed by the read.
type SoftDeleteColumn ¶
type SoftDeleteColumn struct{ Name string }
type SoftDeleteScope ¶
type SoftDeleteScope uint8
const ( ActiveRecords SoftDeleteScope = iota AllRecords TrashedRecords )
type SourceWriteKey ¶
type SourceWriteKey struct {
Expression ValueExpression
Nullable bool
}
SourceWriteKey is lowered only after exact source/destination identity checks.
type Statement ¶
Statement is a compiled parameterized PostgreSQL statement. SQL and Arguments are explicit inspection/integration boundaries. Formatting omits bindings.
func CompileRead ¶
func StatementValue ¶
func StatementValue(state *StatementState) Statement
type StatementState ¶
type StatementState = statementState
StatementState hides both SQL text and bindings from recursive formatting. SQL inspection remains an explicit operation at the typed frontend.
func RetainStatement ¶
func RetainStatement(value Statement) *StatementState
type Subquery ¶
type Subquery struct {
// RelationCheck defers declaration checks until compilation, preserving lazy
// enum initialization while retaining a static AST for nested alias planning.
RelationCheck func() error
Node SelectNode
Err error
Correlation *ScopeRequirement
}
func DirectRelationExists ¶
func DirectRelationExists(node SelectNode, local, foreign FieldRef, columns []Column) Subquery
DirectRelationExists lowers a validated direct relation without model boxing. Aliasing and correlation are shared by both public query APIs, including self links, nested EXISTS and lazy context/soft-delete scopes.
func RelationExistence ¶
func RelationExistence(node SelectNode, source string, columns []Column) Subquery
RelationExistence declares the exact outer source allowed by the correlated subquery compiler. The ordinary SELECT/EXISTS compiler owns SQL and shapes.
func RequalifyCorrelation ¶
Relation loading qualifies a validated single-model predicate. Only explicit correlated outer references follow that rename; isolated inner queries do not.
type SubqueryPredicate ¶
type SubqueryPredicate struct {
Query Subquery
Operand ValueExpression // nil means EXISTS; otherwise single-column IN.
}
func (SubqueryPredicate) ExpressionNode ¶
func (SubqueryPredicate) ExpressionNode()
type TableSource ¶
type TableSource struct {
// RequiresTransaction follows the source through alias and join lowering,
// including unlocked sources whose public adapters require a transaction.
RequiresTransaction bool
Sensitive map[string]bool // Immutable base-column sensitivity, retained by direct aliases.
Table, Alias string
Columns []Column
Query *SelectNode
Cte *CteNode
Set *SetNode
Self *RecursiveReference
}
All read paths share this relational SELECT node and compiler. Public typed declarations resolve model ownership before entering this private boundary.
func LockSources ¶
func LockSources(s SelectNode) ([]TableSource, []bool)
lockSources tracks null extension introduced by every join, including a later RIGHT/FULL JOIN that makes an earlier preserved side nullable.
func (TableSource) Name ¶
func (s TableSource) Name() string
type TemporalUnit ¶
type TemporalUnit uint8
const ( UnitMicrosecond TemporalUnit = iota + 1 UnitMillisecond UnitSecond UnitMinute UnitHour UnitDay UnitWeek UnitMonth UnitQuarter UnitYear UnitDecade UnitCentury UnitMillennium )
func (TemporalUnit) Name ¶
func (u TemporalUnit) Name() string
type TimestampColumns ¶
type TimestampColumns struct{ Created, Updated string }
type ValueExpression ¶
type ValueExpression interface{ ValueNode() }
func MapComputedValue ¶
func MapComputedValue(v ValueExpression, item func(ValueExpression) ValueExpression, condition func(Expression) Expression) (ValueExpression, bool)
func RequalifyValue ¶
func RequalifyValue(v ValueExpression, alias string) ValueExpression
func UnwrapSensitivity ¶
func UnwrapSensitivity(v ValueExpression) ValueExpression
UnwrapSensitivity is only for SQL shape/identity checks. Stored ASTs retain their annotations; the ordinary expression visitor validates their children.
func WithSensitivity ¶
func WithSensitivity(v ValueExpression, sensitive bool) ValueExpression
type ValueIndex ¶
type ValueIndex struct {
Values []PlannedValue
Slots map[string][]int
Comparisons, Arguments int
}
func (*ValueIndex) Add ¶
func (x *ValueIndex) Add(p PlannedValue) int
func (*ValueIndex) Find ¶
func (x *ValueIndex) Find(p PlannedValue) (int, bool, error)
type WindowFrame ¶
type WindowFrame struct {
Kind FrameKind
Start, End FrameBound
Exclusion FrameExclusion
RangeType codec.ParameterType
}
type WindowFunction ¶
type WindowFunction uint8
const ( RowNumberWindow WindowFunction = iota + 1 RankWindow DenseRankWindow PercentRankWindow CumeDistWindow NtileWindow LagWindow LeadWindow FirstValueWindow LastValueWindow NthValueWindow AggregateWindow )
type WindowNode ¶
type WindowNode struct {
Kind WindowFunction
Window WindowSpec
Input ValueExpression
Aggregate AggregateNode
N *OffsetState
Fallback *LiteralState
HasFallback bool
Err error
}
func (WindowNode) ValueNode ¶
func (WindowNode) ValueNode()
type WindowSpec ¶
type WindowSpec struct {
Reference *NamedWindow
Partitions []ValueExpression
Orders []OrderNode
Frame *WindowFrame
Err error
}
func ResolveWindow ¶
func ResolveWindow(w WindowSpec, copying bool, depth int) (WindowSpec, error)
Resolution validates inheritance once for both window functions and WINDOW definitions. Bare OVER name differs from copying a definition in parentheses.
func (WindowSpec) ReferenceOnly ¶
func (w WindowSpec) ReferenceOnly() bool
func (WindowSpec) ValidateFrame ¶
func (w WindowSpec) ValidateFrame() error
Source Files
¶
- aggregate.go
- aggregate_filter.go
- alias_core.go
- ast.go
- batch_limits.go
- comparison_binding.go
- compile_conflict.go
- compile_conflict_target.go
- compile_insert_select.go
- compile_lock.go
- compile_mutation.go
- compile_source_write.go
- compile_update_set.go
- compiler.go
- computed_expression.go
- computed_mapping.go
- conditional_expression.go
- conflict.go
- conflict_expressions.go
- conflict_mutator.go
- conflict_rows.go
- correlation_compiler.go
- correlation_requalify.go
- correlation_scope.go
- cte.go
- cte_compiler.go
- cursor_boundary.go
- cursor_contract.go
- cursor_error.go
- cursor_pagination.go
- cursor_predicate.go
- cursor_token.go
- definition.go
- diagnostics.go
- distinct.go
- distinct_compiler.go
- doc.go
- encrypted_fields.go
- encrypted_value.go
- explain.go
- explain_decode.go
- field_mutator.go
- geographic_expression.go
- global_scope.go
- identity.go
- interval_operation.go
- join_core.go
- json_operation.go
- json_path.go
- key_compiler.go
- lateral_compiler.go
- literal_state.go
- locking.go
- lookup_defaults.go
- membership_array.go
- model_source.go
- model_timestamps.go
- mutation.go
- mutation_core.go
- mutation_validation.go
- page_contract.go
- parameter_expression.go
- predicate_extensions.go
- predicate_state.go
- projection_core.go
- query_core.go
- raw_fragment.go
- record_core.go
- record_equality.go
- record_layout.go
- recursive_cte.go
- relation_aggregate.go
- relation_exists.go
- relation_join.go
- relation_loading.go
- report.go
- requalify.go
- result_cursor.go
- retained_state.go
- scalar_arguments.go
- scalar_operation.go
- schema_literal.go
- select.go
- select_names.go
- select_sensitivity.go
- select_walk.go
- set.go
- set_write.go
- soft_delete_scope.go
- soft_delete_write.go
- sql_mapping.go
- statement_shape.go
- subquery.go
- temporal_operation.go
- temporal_zone.go
- value_comparison.go
- value_expression.go
- value_index.go
- value_sensitivity.go
- window.go
- window_compiler.go
- window_function.go
- window_named.go
- window_range.go