Help us shape the future of Go! Take the 2026 Go Developer Survey

querycore

package
v0.5.3 Latest Latest
Warning

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

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

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

View Source
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.

View Source
const (
	MaxCursorBytes  = 64 * 1024
	MaxCursorFields = 16
)

Cursor limits bound token decoding and lexicographic predicate construction.

View Source
const AnnotatedValueAlias = "foundry_value"

AnnotatedValueAlias is the computed column paired with a complete model.

View Source
const ConflictProposedTable = "excluded"
View Source
const ConflictStoredTable = "foundry_conflict_stored"
View Source
const DefaultChunkSize = 100

DefaultChunkSize bounds closed batches used by eager and observed iteration.

View Source
const MaxChunkSize = MaxPageSize

MaxChunkSize shares the collection bound across both model read APIs.

View Source
const MaxIdentityBatch = 1000

MaxIdentityBatch bounds primary-key-only identity observations and extension scopes.

View Source
const MaxInsertRows = 1000

MaxInsertRows bounds atomic inserts and upserts before parameter validation.

View Source
const MaxPageSize = 1000

MaxPageSize bounds complete collections returned by a pagination request.

View Source
const MaxPerModelWriteRows = MaxInsertRows

MaxPerModelWriteRows bounds an atomic batch of ordinary model lifecycles.

View Source
const MaxPlanBytes = 4 << 20
View Source
const MaxPlanDepth = 24
View Source
const MaxPlanNodes = 4096
View Source
const PostgresStandardTime uint8 = 1
View Source
const RelationHopAlias = "foundry_through"
View Source
const RelationPivotAlias = "foundry_pivot"
View Source
const RelationTargetAlias = "foundry_target"
View Source
const SetAlias = "foundry_set"

SetAlias is the output scope shared by record and scalar set adapters.

Variables

View Source
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

func ArrayLiteral(kind codec.ParameterType, values []driver.Value) (string, bool)

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

func BinaryOperator(op Operator) (string, bool)

binaryOperator shares SQL tokens with literal comparisons. Contains belongs only to literal binding, where wildcard escaping is explicit.

func BindAssignment

func BindAssignment(column Column, bind func() (driver.Value, error)) (driver.Value, error)

func BuildCursor

func BuildCursor(scope string, count int, get func(int) (driver.Value, error)) (string, error)

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 ComparisonOperator(op Operator) (string, bool)

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

func ConsumeRelationBudget(remaining *int, count int, attached bool) error

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 CursorInputFailure(cause error) error

func CursorStatementScopeFor

func CursorStatementScopeFor(modelIdentity string, statement Statement, identity []string) (string, error)

func DatabaseFailure

func DatabaseFailure(operation string, code database.Code) error

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

func EncodeModelKey(raw driver.Value) (sqlvalue.Value, error)

EncodeModelKey normalizes signed zero while retaining driver representations.

func EscapedPattern

func EscapedPattern(op Operator) bool

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

func IntervalComparisonKey(v temporal.Interval) string

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 LikePattern(op Operator, text string) string

func LiteralValue

func LiteralValue(s *LiteralState) driver.Value

func LoadTimeZone

func LoadTimeZone(name string) (string, error)

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 LockReference(table string) string

func LookupValuesEqual

func LookupValuesEqual(a, b driver.Value) bool

LookupValuesEqual compares stored equality defaults with canonical model-key semantics.

func MakeCursor

func MakeCursor(scope string, values []driver.Value) (string, error)

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 OpenEncryptedValue[V encrypted.Value[V]](row database.Row, table, column string, key func() (driver.Value, error), field *V) error

func OpenNullableEncryptedValue

func OpenNullableEncryptedValue[V encrypted.Value[V]](row database.Row, table, column string, key func() (driver.Value, error), field *value.Nullable[V]) error

func OpenScope

func OpenScope(row database.Row, table, column string, key func() (driver.Value, error)) (context.Context, *encryption.Keyring, encryption.Context, error)

func OrderDirection

func OrderDirection(order OrderNode) string

orderDirection renders direction and any explicit NULL placement.

func PageCount

func PageCount(total int64, size int) int64

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 PrimaryEqualities(predicates []Expression, primary string, visit func(driver.Value) error) error

func Qualified

func Qualified(field FieldRef) string

func QuoteArrayElement

func QuoteArrayElement(literal *strings.Builder, text string)

quoteArrayElement always quotes, so NULL, empty strings, braces, commas and whitespace remain ordinary element text. Backslash and quote are escaped.

func QuoteSchemaText

func QuoteSchemaText(value string, remaining int) (string, error)

func Quoted

func Quoted(name string) string

func QuotedTable

func QuotedTable(table string) string

func ReadEnvelope

func ReadEnvelope(kind ReadKind) (string, string)

ReadEnvelope owns scalar result wrappers and their internal output alias.

func ReadMutationAssignments

func ReadMutationAssignments(assignments []MutationAssignment) (map[FieldRef]AssignmentValue, error)

func RecordEqualityKey

func RecordEqualityKey(kind codec.ParameterType, raw driver.Value) (sqlvalue.Value, error)

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 ResolutionArgument

func ResolutionArgument(zone string, policy uint8) (string, error)

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 SameKey

func SameKey(left, right driver.Value) bool

SameKey compares bound primary keys; a []byte key is not comparable with ==.

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 SelectedColumns(table string, columns []Column) string

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

func ValidCursorRequest(size int, after, before bool) bool

ValidCursorRequest checks the request shape before decoding its boundary.

func ValidPageSize

func ValidPageSize(size int) bool

func ValidateAggregateFilterCount

func ValidateAggregateFilterCount(count int) error

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 ValidateExpressionFields

func ValidateExpressionFields(e Expression, field func(FieldRef) error, depth int, nodes *int) error

func ValidateExpressionValues

func ValidateExpressionValues(e Expression, operand func(ValueExpression) error, depth int, nodes *int) error

func ValidateGeographicPoint

func ValidateGeographicPoint(latitude, longitude float64) error

func ValidateJSONKind

func ValidateJSONKind(kind string) error

func ValidateJSONProperty

func ValidateJSONProperty(name string) error

func ValidateLockSources

func ValidateLockSources(node SelectNode, targets []string, explicit bool, depth int) (int, error)

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

func ValidateMorphName(name string) error

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 ValidateRowValue(v ValueExpression, field func(FieldRef) error, depth int, nodes *int) error

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 ValidateSubstringCount(count int32) error

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

func ZoneArgument(zone string) (string, error)

Types

type Adjustment

type Adjustment struct {
	Field    FieldRef
	Bind     func() (driver.Value, error)
	Subtract bool
}

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) Validate

func (a AggregateNode) Validate(field func(FieldRef) error) error

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
}

func (CaseNode) ValueNode

func (CaseNode) ValueNode()

type Column

type Column struct {
	Name            string
	Nullable        bool
	DatabaseDefault bool
	Encrypted       bool
}

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 NewCompiler(columns []Column) Compiler

func (*Compiler) Aggregate

func (c *Compiler) Aggregate(a AggregateNode) (string, error)

func (*Compiler) AggregateAt

func (c *Compiler) AggregateAt(a AggregateNode, field func(FieldRef) error, grouped map[FieldRef]bool, grouping, window bool) (string, error)

func (*Compiler) AggregateField

func (c *Compiler) AggregateField(f FieldRef) error

func (*Compiler) AggregateFilterSQL

func (c *Compiler) AggregateFilterSQL(a AggregateNode, grouped map[FieldRef]bool, grouping, window bool) (string, error)

func (*Compiler) AssignmentParameter

func (c *Compiler) AssignmentParameter(column string, bind func() (driver.Value, error)) (string, error)

func (*Compiler) BeginStatement

func (c *Compiler) BeginStatement(ctx context.Context)

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 (c *Compiler) Comparison(e Comparison, grouped map[FieldRef]bool, grouping bool) (string, error)

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 (c *Compiler) ComputedSQL(v ValueExpression, grouped map[FieldRef]bool, grouping bool) (string, error)

func (*Compiler) ConditionClause

func (c *Compiler) ConditionClause(sql *strings.Builder, clause string, predicates []Expression) error

func (*Compiler) ConditionClauseAt

func (c *Compiler) ConditionClauseAt(sql *strings.Builder, clause string, predicates []Expression, grouped map[FieldRef]bool, grouping bool) error

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) CteBody

func (c *Compiler) CteBody(d *CteNode) (string, error)

func (*Compiler) DeclaredField

func (c *Compiler) DeclaredField(f FieldRef) error

func (*Compiler) DiscardArguments

func (c *Compiler) DiscardArguments(start int)

func (*Compiler) DistinctSQL

func (c *Compiler) DistinctSQL(s SelectNode, grouped map[FieldRef]bool, grouping bool) (string, error)

func (*Compiler) Expression

func (c *Compiler) Expression(e Expression) (string, error)

func (*Compiler) ExpressionAt

func (c *Compiler) ExpressionAt(e Expression, grouped map[FieldRef]bool, grouping bool) (string, error)

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

func (c *Compiler) JoinSourceSQL(join JoinNode) (string, error)

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) KeySQL

func (c *Compiler) KeySQL(key *CompiledKey, grouped map[FieldRef]bool, grouping bool) (string, error)

func (*Compiler) MatchingKey

func (c *Compiler) MatchingKey(v ValueExpression, groupedOnly bool) (*CompiledKey, error)

func (*Compiler) NamedWindowsSQL

func (c *Compiler) NamedWindowsSQL(definitions []*NamedWindow, grouped map[FieldRef]bool, grouping bool) (string, error)

func (*Compiler) ObserveField

func (c *Compiler) ObserveField(level int, f FieldRef)

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 (c *Compiler) OperationSQL(n OperationNode, grouped map[FieldRef]bool, grouping bool) (sql string, err error)

func (*Compiler) Parameter

func (c *Compiler) Parameter(value any) (string, error)

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) RawSQL

func (c *Compiler) RawSQL(r RawFragment) (string, error)

func (*Compiler) RegisterKey

func (c *Compiler) RegisterKey(v ValueExpression, grouped bool) (*CompiledKey, error)

func (*Compiler) RenderSelectedExpression

func (c *Compiler) RenderSelectedExpression(e ValueExpression, grouped map[FieldRef]bool, grouping bool) (string, error)

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

func (c *Compiler) SchemaLiteral(value any) (string, error)

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) SelectSQL

func (c *Compiler) SelectSQL(s SelectNode) (string, error)

func (*Compiler) SelectSQLWithOuter

func (c *Compiler) SelectSQLWithOuter(s SelectNode, outer *OuterScope) (string, error)

func (*Compiler) SelectedExpression

func (c *Compiler) SelectedExpression(e ValueExpression, grouped map[FieldRef]bool, grouping bool) (string, error)

func (*Compiler) SetSQL

func (c *Compiler) SetSQL(s SetNode, columns []Column) (string, error)

func (*Compiler) SourceSQL

func (c *Compiler) SourceSQL(s TableSource) (string, error)

func (*Compiler) Statement

func (c *Compiler) Statement(template string) Statement

func (*Compiler) SubqueryPredicate

func (c *Compiler) SubqueryPredicate(p SubqueryPredicate, grouped map[FieldRef]bool, grouping bool) (string, error)

func (*Compiler) SubquerySQL

func (c *Compiler) SubquerySQL(q Subquery, single bool, grouped map[FieldRef]bool, grouping bool) (string, error)

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 (c *Compiler) ValidateWindow(n WindowNode, grouped map[FieldRef]bool, grouping bool) error

func (*Compiler) Where

func (c *Compiler) Where(sql *strings.Builder, predicates []Expression) error

func (*Compiler) WindowDefinitionSQL

func (c *Compiler) WindowDefinitionSQL(w WindowSpec, grouped map[FieldRef]bool, grouping bool) (string, error)

func (*Compiler) WindowSQL

func (c *Compiler) WindowSQL(n WindowNode, grouped map[FieldRef]bool, grouping bool) (string, error)

func (*Compiler) WindowSpecSQL

func (c *Compiler) WindowSpecSQL(w WindowSpec, grouped map[FieldRef]bool, grouping bool) (string, error)

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

func (p Conflict) CheckReturned(q QueryCore, requested, returned int) error

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 (p Conflict) ValidateRows(c *Compiler) error

func (Conflict) ValidateShape

func (p Conflict) ValidateShape(q QueryCore, c *Compiler, validateMutator func(ConflictUpdate) error) error

func (Conflict) WithUpdatedTimestamp

func (p Conflict) WithUpdatedTimestamp(table, name string) Conflict

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

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

ParseCursor validates bounded transport structure. CursorPaginate additionally verifies the model/query scope and decodes every key through its field codec.

func (Cursor[M]) GoString

func (c Cursor[M]) GoString() string

func (Cursor[M]) String

func (c Cursor[M]) String() string

func (Cursor[M]) Token

func (c Cursor[M]) Token() string

func (Cursor[R]) Validate

func (c Cursor[R]) Validate() error

Validate checks the token's bounded structure without database I/O. Query execution still verifies the query fingerprint and every ordered key codec.

type CursorBoundary

type CursorBoundary struct {
	Keys              []driver.Value
	Backward, Present bool
}

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 CursorField struct {
	Sensitive bool
	Decode    func(any) (driver.Value, error)
}

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

type CursorPage[M any] struct {
	Items          []M
	Size           int
	Next, Previous value.Optional[Cursor[M]]
}

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

type CursorRequest[M any] struct {
	Size          int
	After, Before value.Optional[Cursor[M]]
}

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

type CursorValue = sqlvalue.Value

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)

func (*DistinctOrder) Compile

func (d *DistinctOrder) Compile(c *Compiler, order OrderNode, grouped map[FieldRef]bool, grouping bool) (string, error)

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 FieldRef

type FieldRef struct{ Table, Column string }

func (FieldRef) Validate

func (f FieldRef) Validate(table string) error

func (FieldRef) ValueNode

func (FieldRef) ValueNode()

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 FrameKind

type FrameKind uint8
const (
	RowsFrame FrameKind = iota + 1
	GroupsFrame
	RangeFrame
)

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 JoinKind

type JoinKind uint8
const (
	InnerJoin JoinKind = iota
	LeftJoin
	RightJoin
	FullJoin
	CrossJoin
)

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
	LockShare
	LockKeyShare
)

type LookupDefault

type LookupDefault struct {
	Column string
	Value  driver.Value
}

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

type OperationSpec struct {
	Name     string
	Min, Max int
	Infix    bool
}

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 Operator

type Operator uint8
const (
	Equal Operator = iota + 1
	NotEqual
	Less
	LessOrEqual
	Greater
	GreaterOrEqual
	Like
	Contains
	In
	IsNull
	IsNotNull
	IsDistinctFrom
	IsNotDistinctFrom
	InsensitiveContains
	NotIn
	StartsWith
	EndsWith
	InsensitiveStartsWith
	InsensitiveEndsWith
	InsensitiveLike
)

type OrderNode

type OrderNode struct {
	Expression ValueExpression
	Descending bool
	Nulls      NullPlacement
}

func OrderNodes

func OrderNodes(orders []QueryOrder) []OrderNode

type OuterScope

type OuterScope struct {
	Sources map[string]map[string]Column
	Field   func(FieldRef) error
}

type Page

type Page[M any] struct {
	Items        []M
	Number, Size int
	Total, Pages int64
}

Page contains complete results and an unpaginated matching count. Count and rows are separate queries; use a repeatable-read transaction for one snapshot.

func (Page[R]) Validate

func (p Page[R]) Validate() error

Validate checks page metadata and the bounded item count. It does not assert that Total and Items came from one snapshot: counting and reading may observe different database states. Empty and beyond-last pages remain valid.

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.

func DecodePlan

func DecodePlan(ctx context.Context, data []byte, analyze bool) (Plan, error)

func Explain

func Explain(ctx context.Context, executor database.Executor, compile func(context.Context) (Statement, error), analyze bool) (Plan, error)

Explain shares bounded plan execution across typed query frontends.

func (Plan) Analyzed

func (p Plan) Analyzed() bool

func (Plan) ExecutionMilliseconds

func (p Plan) ExecutionMilliseconds() value.Optional[float64]

func (Plan) Format

func (p Plan) Format(state fmt.State, _ rune)

func (Plan) JSON

func (p Plan) JSON() []byte

func (Plan) NodeCount

func (p Plan) NodeCount() int

func (Plan) PlanningMilliseconds

func (p Plan) PlanningMilliseconds() value.Optional[float64]

func (Plan) Root

func (p Plan) Root() PlanNode

type PlanBytes

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

func (*PlanBytes) Scan

func (p *PlanBytes) Scan(source any) error

type PlanEnvelope

type PlanEnvelope struct {
	Plan          PlanNode                `json:"Plan"`
	PlanningTime  value.Optional[float64] `json:"Planning Time,omitzero"`
	ExecutionTime value.Optional[float64] `json:"Execution Time,omitzero"`
}

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

type PlannedValue struct {
	Sql       string
	Arguments []any
	Shape     string
}

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

type ProjectionColumn struct {
	Sensitive bool
	Name      string
	Typ       reflect.Type
	Nullable  bool
}

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 (q QueryCore) HasSoftDeletes() bool

func (QueryCore) ModelSelect

func (q QueryCore) ModelSelect(selections []SelectItem) SelectNode

func (QueryCore) RequireInsertFields

func (q QueryCore) RequireInsertFields(present func(string) bool) error

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 (q QueryCore) StableOrder() (QueryCore, error)

func (QueryCore) Validate

func (q QueryCore) Validate() error

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 (q QueryCore) ValidateScopeOptions() error

func (QueryCore) ValidateSoftDeleteScope

func (q QueryCore) ValidateSoftDeleteScope() error

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 ReadKind

type ReadKind uint8
const (
	ReadModels ReadKind = iota
	ReadCount
	ReadExists
)

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

type RecursiveReference struct {
	Name    string
	Columns []Column
}

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

type ResultCursorField struct {
	Name             string
	Sensitive, Valid bool
}

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 ScopeRequirement struct {
	Sources map[string][]Column
	Err     error
}

type Sealer

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

func NullableEncryptedSealer[V encrypted.Value[V]](v value.Nullable[V], capture func(value.Nullable[V]) AssignmentValue) Sealer

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

type SelectNames struct{ Used map[string]bool }

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

type SimplePage[R any] struct {
	Items        []R
	Number, Size int
	HasMore      bool
}

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

type Statement struct {
	SQLText  string
	Bindings []any
	Shape    string
}

Statement is a compiled parameterized PostgreSQL statement. SQL and Arguments are explicit inspection/integration boundaries. Formatting omits bindings.

func CompileRead

func CompileRead(node SelectNode, scopeContext context.Context, transaction bool, err error, hasDecoder bool) (Statement, error)

func StatementValue

func StatementValue(state *StatementState) Statement

func (Statement) Context

func (s Statement) Context(ctx context.Context) context.Context

func (Statement) Envelope

func (s Statement) Envelope(prefix, suffix string) Statement

Envelope preserves the compiler-owned shape when a framework executor adds a fixed count/explain envelope. Callers are internal framework packages only.

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

func RequalifyCorrelation(q Subquery, alias string) Subquery

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

Jump to

Keyboard shortcuts

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