nodes

package
v0.3.0 Latest Latest
Warning

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

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

Documentation

Overview

Package nodes defines the AST node types used to represent SQL query elements.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func RelationName

func RelationName(n Node) string

RelationName returns the name associated with a relation node. For a Table it returns the table name; for a TableAlias it returns the alias name.

func TableSourceName

func TableSourceName(n Node) string

TableSourceName returns the underlying table name from a relation node. For a TableAlias it looks through to the underlying Table if one exists, falling back to the alias name.

Types

type AggregateFunc

type AggregateFunc int

AggregateFunc identifies the aggregate function.

const (
	AggCount AggregateFunc = iota
	AggSum
	AggAvg
	AggMin
	AggMax
)

type AggregateNode

type AggregateNode struct {
	Predications
	Arithmetics
	Combinable
	Func     AggregateFunc
	Expr     Node // argument (nil for COUNT(*))
	Distinct bool // COUNT(DISTINCT ...)
	Filter   Node // FILTER (WHERE ...) clause, nil if not used
}

AggregateNode represents an aggregate function call (COUNT, SUM, AVG, MIN, MAX).

func Avg

func Avg(expr Node) *AggregateNode

Avg creates an AVG aggregate.

func Count

func Count(expr Node) *AggregateNode

Count creates a COUNT aggregate. Pass nil for COUNT(*).

func CountDistinct

func CountDistinct(expr Node) *AggregateNode

CountDistinct creates a COUNT(DISTINCT expr) aggregate.

func Max

func Max(expr Node) *AggregateNode

Max creates a MAX aggregate.

func Min

func Min(expr Node) *AggregateNode

Min creates a MIN aggregate.

func NewAggregateNode

func NewAggregateNode(fn AggregateFunc, expr Node) *AggregateNode

NewAggregateNode creates an AggregateNode with properly initialised embedded structs.

func Sum

func Sum(expr Node) *AggregateNode

Sum creates a SUM aggregate.

func (*AggregateNode) Accept

func (n *AggregateNode) Accept(v Visitor) string

func (*AggregateNode) Over

func (n *AggregateNode) Over(def *WindowDefinition) *OverNode

Over wraps the aggregate with an inline window definition.

func (*AggregateNode) OverName

func (n *AggregateNode) OverName(name string) *OverNode

OverName wraps the aggregate with a named window reference.

func (*AggregateNode) WithFilter

func (n *AggregateNode) WithFilter(condition Node) *AggregateNode

WithFilter returns a copy of the aggregate with a FILTER (WHERE ...) clause.

type AliasNode

type AliasNode struct {
	Predications
	Arithmetics
	Combinable
	Expr Node
	Name string
}

AliasNode represents a column or expression alias: expr AS "name".

func NewAliasNode

func NewAliasNode(expr Node, name string) *AliasNode

NewAliasNode creates an AliasNode with properly initialised embedded structs.

func (*AliasNode) Accept

func (n *AliasNode) Accept(v Visitor) string

type AndNode

type AndNode struct {
	Combinable
	Left  Node
	Right Node
}

AndNode represents a logical AND between two expressions.

func NewAndNode added in v0.2.0

func NewAndNode(left, right Node) *AndNode

NewAndNode creates an AndNode with properly initialised embedded structs.

func (*AndNode) Accept

func (n *AndNode) Accept(v Visitor) string

type Arithmetics

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

Arithmetics provides math and bitwise methods to types that embed it. The self field must be set to the embedding node.

func (Arithmetics) BitwiseAnd

func (a Arithmetics) BitwiseAnd(val any) *InfixNode

func (Arithmetics) BitwiseNot

func (a Arithmetics) BitwiseNot() *UnaryMathNode

func (Arithmetics) BitwiseOr

func (a Arithmetics) BitwiseOr(val any) *InfixNode

func (Arithmetics) BitwiseXor

func (a Arithmetics) BitwiseXor(val any) *InfixNode

func (Arithmetics) Concat

func (a Arithmetics) Concat(val any) *InfixNode

func (Arithmetics) Divide

func (a Arithmetics) Divide(val any) *InfixNode

func (Arithmetics) Minus

func (a Arithmetics) Minus(val any) *InfixNode

func (Arithmetics) Multiply

func (a Arithmetics) Multiply(val any) *InfixNode

func (Arithmetics) Plus

func (a Arithmetics) Plus(val any) *InfixNode

func (Arithmetics) ShiftLeft

func (a Arithmetics) ShiftLeft(val any) *InfixNode

func (Arithmetics) ShiftRight

func (a Arithmetics) ShiftRight(val any) *InfixNode

type AssignmentNode

type AssignmentNode struct {
	Left  Node // column (Attribute)
	Right Node // value
}

AssignmentNode represents a column = value pair in SET clauses.

func (*AssignmentNode) Accept

func (n *AssignmentNode) Accept(v Visitor) string

type Attribute

type Attribute struct {
	Predications
	Arithmetics
	Combinable
	Name     string
	Relation Node   // *Table or *TableAlias
	TypeName string // SQL type for coercion (e.g. "integer", "text")
}

Attribute represents a column reference bound to a table or table alias.

func NewAttribute

func NewAttribute(relation Node, name string) *Attribute

NewAttribute creates an Attribute with Predications and Combinable properly initialized to reference the new Attribute as self.

func (*Attribute) Accept

func (a *Attribute) Accept(v Visitor) string

func (*Attribute) Coerce

func (a *Attribute) Coerce(val any) Node

Coerce wraps val using the attribute's type. If TypeName is set, returns a CastedNode; otherwise returns a plain Literal.

func (*Attribute) Typed

func (a *Attribute) Typed(typeName string) *Attribute

Typed returns a copy of the Attribute with TypeName set. The copy has its own Predications/Arithmetics/Combinable self pointers.

type BetweenNode

type BetweenNode struct {
	Combinable
	Expr   Node
	Low    Node
	High   Node
	Negate bool
}

BetweenNode represents a BETWEEN or NOT BETWEEN range predicate.

func NewBetweenNode added in v0.2.0

func NewBetweenNode(expr, low, high Node, negate bool) *BetweenNode

NewBetweenNode creates a BetweenNode with properly initialised embedded structs.

func (*BetweenNode) Accept

func (n *BetweenNode) Accept(v Visitor) string

type BindParamNode

type BindParamNode struct {
	Value any
}

BindParamNode represents an explicit bind parameter placeholder. Its Value is always emitted as a bind parameter in parameterized mode, or rendered as a literal value in non-parameterized mode.

func NewBindParam

func NewBindParam(value any) *BindParamNode

NewBindParam creates a BindParamNode.

func (*BindParamNode) Accept

func (n *BindParamNode) Accept(v Visitor) string

type BoundType

type BoundType int

BoundType specifies a window frame boundary.

const (
	BoundUnboundedPreceding BoundType = iota
	BoundPreceding
	BoundCurrentRow
	BoundFollowing
	BoundUnboundedFollowing
)

type CTENode

type CTENode struct {
	Name      string
	Query     Node
	Recursive bool
	Columns   []string // optional column list
}

CTENode represents a Common Table Expression (WITH clause).

func (*CTENode) Accept

func (n *CTENode) Accept(v Visitor) string

type CaseNode

type CaseNode struct {
	Predications
	Arithmetics
	Combinable
	Operand Node       // nil for searched CASE
	Whens   []CaseWhen // WHEN ... THEN ... pairs
	ElseVal Node       // ELSE value (nil if omitted)
}

CaseNode represents a SQL CASE expression:

CASE [operand] WHEN cond THEN result ... [ELSE val] END

If Operand is nil, it is a "searched CASE" (CASE WHEN cond THEN ...).

func NewCase

func NewCase(operand ...Node) *CaseNode

NewCase creates a CaseNode. Pass an operand for simple CASE, or nil/no args for searched CASE.

func (*CaseNode) Accept

func (n *CaseNode) Accept(v Visitor) string

func (*CaseNode) Else

func (n *CaseNode) Else(result Node) *CaseNode

Else sets the ELSE value and returns the CaseNode for chaining.

func (*CaseNode) When

func (n *CaseNode) When(cond, result Node) *CaseNode

When adds a WHEN ... THEN ... pair and returns the CaseNode for chaining.

type CaseWhen

type CaseWhen struct {
	Condition Node
	Result    Node
}

CaseWhen represents a single WHEN ... THEN ... pair in a CASE expression.

type CastedNode

type CastedNode struct {
	Predications
	Arithmetics
	Combinable
	Value    any
	TypeName string
}

CastedNode represents a typed value that knows its SQL type. Used for type-aware rendering (e.g., ensuring correct casting).

func NewCasted

func NewCasted(value any, typeName string) *CastedNode

NewCasted creates a CastedNode with properly initialised embedded structs.

func (*CastedNode) Accept

func (n *CastedNode) Accept(v Visitor) string

type Combinable

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

Combinable provides logical chaining methods to types that embed it. The self field must be set to the embedding node.

func (Combinable) And

func (c Combinable) And(other Node) *AndNode

And creates an AndNode combining self with other.

func (Combinable) Not

func (c Combinable) Not() *NotNode

Not creates a NotNode negating self.

func (Combinable) Or

func (c Combinable) Or(other Node) *GroupingNode

Or creates an OrNode wrapped in a GroupingNode for correct precedence.

type ComparisonNode

type ComparisonNode struct {
	Combinable
	Left  Node
	Right Node
	Op    ComparisonOp
}

ComparisonNode represents a binary comparison: Left Op Right.

func NewComparisonNode

func NewComparisonNode(left, right Node, op ComparisonOp) *ComparisonNode

NewComparisonNode creates a ComparisonNode with properly initialised embedded structs.

func (*ComparisonNode) Accept

func (n *ComparisonNode) Accept(v Visitor) string

type ComparisonOp

type ComparisonOp int

ComparisonOp represents a binary comparison operator.

const (
	OpEq ComparisonOp = iota
	OpNotEq
	OpGt
	OpGtEq
	OpLt
	OpLtEq
	OpLike
	OpNotLike
	OpRegexp
	OpNotRegexp
	OpDistinctFrom
	OpNotDistinctFrom
	OpCaseSensitiveEq
	OpCaseInsensitiveEq
	OpContains
	OpOverlaps
)

type DeleteStatement

type DeleteStatement struct {
	From      Node
	Wheres    []Node
	Returning []Node
}

DeleteStatement represents DELETE FROM ... WHERE.

func (*DeleteStatement) Accept

func (n *DeleteStatement) Accept(v Visitor) string

type ExistsNode

type ExistsNode struct {
	Subquery Node
	Negated  bool
	Combinable
}

ExistsNode represents an EXISTS or NOT EXISTS subquery expression.

func Exists

func Exists(subquery Node) *ExistsNode

Exists creates an EXISTS(subquery) node.

func NotExists

func NotExists(subquery Node) *ExistsNode

NotExists creates a NOT EXISTS(subquery) node.

func (*ExistsNode) Accept

func (n *ExistsNode) Accept(v Visitor) string

type ExtractField

type ExtractField int

ExtractField identifies the date/time field for EXTRACT.

const (
	ExtractYear ExtractField = iota
	ExtractMonth
	ExtractDay
	ExtractHour
	ExtractMinute
	ExtractSecond
	ExtractDow // day of week
	ExtractDoy // day of year
	ExtractEpoch
	ExtractQuarter
	ExtractWeek
)

type ExtractNode

type ExtractNode struct {
	Predications
	Arithmetics
	Combinable
	Field ExtractField
	Expr  Node
}

ExtractNode represents EXTRACT(field FROM expr).

func Extract

func Extract(field ExtractField, expr Node) *ExtractNode

Extract creates an EXTRACT(field FROM expr) node.

func NewExtractNode

func NewExtractNode(field ExtractField, expr Node) *ExtractNode

NewExtractNode creates an ExtractNode with properly initialised embedded structs.

func (*ExtractNode) Accept

func (n *ExtractNode) Accept(v Visitor) string

type FrameBound

type FrameBound struct {
	Type   BoundType
	Offset Node // only for BoundPreceding / BoundFollowing
}

FrameBound describes a single frame boundary.

func CurrentRow

func CurrentRow() FrameBound

CurrentRow returns a CURRENT ROW frame bound.

func Following

func Following(n Node) FrameBound

Following returns a N FOLLOWING frame bound.

func Preceding

func Preceding(n Node) FrameBound

Preceding returns a N PRECEDING frame bound.

func UnboundedFollowing

func UnboundedFollowing() FrameBound

UnboundedFollowing returns an UNBOUNDED FOLLOWING frame bound.

func UnboundedPreceding

func UnboundedPreceding() FrameBound

UnboundedPreceding returns an UNBOUNDED PRECEDING frame bound.

type FrameType

type FrameType int

FrameType specifies ROWS or RANGE for a window frame.

const (
	FrameRows FrameType = iota
	FrameRange
)

type GroupingNode

type GroupingNode struct {
	Combinable
	Expr Node
}

GroupingNode wraps an expression in parentheses for precedence control.

func NewGroupingNode added in v0.2.0

func NewGroupingNode(expr Node) *GroupingNode

NewGroupingNode creates a GroupingNode with properly initialised embedded structs.

func (*GroupingNode) Accept

func (n *GroupingNode) Accept(v Visitor) string

type GroupingSetNode

type GroupingSetNode struct {
	Type    GroupingSetType
	Columns []Node   // used by CUBE/ROLLUP (flat column list)
	Sets    [][]Node // used by GROUPING SETS (list of column groups)
}

GroupingSetNode represents CUBE(...), ROLLUP(...), or GROUPING SETS((...), ...).

func NewCube

func NewCube(cols ...Node) *GroupingSetNode

NewCube creates a CUBE(cols...) grouping set.

func NewGroupingSets

func NewGroupingSets(sets ...[]Node) *GroupingSetNode

NewGroupingSets creates a GROUPING SETS(sets...) grouping set.

func NewRollup

func NewRollup(cols ...Node) *GroupingSetNode

NewRollup creates a ROLLUP(cols...) grouping set.

func (*GroupingSetNode) Accept

func (n *GroupingSetNode) Accept(v Visitor) string

type GroupingSetType

type GroupingSetType int

GroupingSetType identifies the type of advanced grouping.

const (
	Cube GroupingSetType = iota
	Rollup
	GroupingSets
)

type InNode

type InNode struct {
	Combinable
	Expr   Node
	Vals   []Node
	Negate bool
}

InNode represents an IN or NOT IN set predicate.

func NewInNode added in v0.2.0

func NewInNode(expr Node, vals []Node, negate bool) *InNode

NewInNode creates an InNode with properly initialised embedded structs. Vals are used as given, without Literal wrapping.

func (*InNode) Accept

func (n *InNode) Accept(v Visitor) string

type InfixNode

type InfixNode struct {
	Predications
	Arithmetics
	Combinable
	Left  Node
	Right Node
	Op    InfixOp
}

InfixNode represents a binary math, bitwise, or concat expression.

func NewInfixNode

func NewInfixNode(left, right Node, op InfixOp) *InfixNode

NewInfixNode creates an InfixNode with properly initialised embedded structs.

func (*InfixNode) Accept

func (n *InfixNode) Accept(v Visitor) string

type InfixOp

type InfixOp int

InfixOp identifies the binary math/bitwise/concat operator.

const (
	OpPlus InfixOp = iota
	OpMinus
	OpMultiply
	OpDivide
	OpBitwiseAnd
	OpBitwiseOr
	OpBitwiseXor
	OpShiftLeft
	OpShiftRight
	OpConcat
)

type InsertStatement

type InsertStatement struct {
	Into       Node            // *Table
	Columns    []Node          // column list
	Values     [][]Node        // rows of values (multi-row)
	Select     Node            // for INSERT FROM SELECT (mutually exclusive with Values)
	Returning  []Node          // RETURNING columns
	OnConflict *OnConflictNode // ON CONFLICT clause
}

InsertStatement represents INSERT INTO ... VALUES / SELECT.

func (*InsertStatement) Accept

func (n *InsertStatement) Accept(v Visitor) string

type JoinNode

type JoinNode struct {
	Left    Node     // source table
	Right   Node     // target table or subquery
	Type    JoinType // join type
	On      Node     // join condition (nil for CROSS JOIN)
	Lateral bool     // LATERAL modifier (PostgreSQL)
}

JoinNode represents a SQL JOIN clause.

func (*JoinNode) Accept

func (n *JoinNode) Accept(v Visitor) string

type JoinType

type JoinType int

JoinType represents the type of SQL JOIN.

const (
	InnerJoin JoinType = iota
	LeftOuterJoin
	RightOuterJoin
	FullOuterJoin
	CrossJoin
	StringJoin // raw SQL join fragment
)

func (JoinType) String

func (t JoinType) String() string

String returns the display name for this join type.

type LiteralNode

type LiteralNode struct {
	Predications
	Combinable
	Value any
}

LiteralNode wraps a raw Go value (string, int, float, bool, etc.) as an AST node.

func (*LiteralNode) Accept

func (n *LiteralNode) Accept(v Visitor) string

type LockMode

type LockMode int

LockMode represents row-level locking for SELECT queries.

const (
	NoLock         LockMode = iota
	ForUpdate               // FOR UPDATE
	ForShare                // FOR SHARE
	ForNoKeyUpdate          // FOR NO KEY UPDATE
	ForKeyShare             // FOR KEY SHARE
)

func (LockMode) String

func (m LockMode) String() string

String returns the SQL keyword for this lock mode.

type NamedFunctionNode

type NamedFunctionNode struct {
	Predications
	Arithmetics
	Combinable
	Name     string
	Args     []Node
	Distinct bool
}

NamedFunctionNode represents a named SQL function call like COALESCE, LOWER, CAST, etc.

func Cast

func Cast(expr Node, typeName string) *NamedFunctionNode

Cast creates a CAST(expr AS typeName) expression. The type name is stored as a SqlLiteral and validated by the visitor when rendered, so it must look like a SQL type (e.g. "VARCHAR(255)"); anything else panics rather than reaching the SQL output.

func Coalesce

func Coalesce(args ...Node) *NamedFunctionNode

Coalesce creates a COALESCE(args...) function call.

func Lower

func Lower(expr Node) *NamedFunctionNode

Lower creates a LOWER(expr) function call.

func NewNamedFunction

func NewNamedFunction(name string, args ...Node) *NamedFunctionNode

NewNamedFunction creates a NamedFunctionNode with properly initialised embedded structs.

func Substring

func Substring(expr, start, length Node) *NamedFunctionNode

Substring creates a SUBSTRING(expr, start, len) function call.

func Upper

func Upper(expr Node) *NamedFunctionNode

Upper creates an UPPER(expr) function call.

func (*NamedFunctionNode) Accept

func (n *NamedFunctionNode) Accept(v Visitor) string

func (*NamedFunctionNode) Over

Over wraps the named function with an inline window definition.

func (*NamedFunctionNode) OverName

func (n *NamedFunctionNode) OverName(name string) *OverNode

OverName wraps the named function with a named window reference.

type Node

type Node interface {
	Accept(visitor Visitor) string
}

Node is the interface that all AST nodes implement.

func Literal

func Literal(val any) Node

Literal wraps a raw Go value into a LiteralNode. If val already implements Node, it is returned as-is.

type NotNode

type NotNode struct {
	Combinable
	Expr Node
}

NotNode represents a logical NOT of an expression.

func NewNotNode added in v0.2.0

func NewNotNode(expr Node) *NotNode

NewNotNode creates a NotNode with properly initialised embedded structs.

func (*NotNode) Accept

func (n *NotNode) Accept(v Visitor) string

type NullsDirection

type NullsDirection int

NullsDirection controls NULLS FIRST/LAST positioning.

const (
	NullsDefault NullsDirection = iota
	NullsFirst
	NullsLast
)

type OnConflictAction

type OnConflictAction int

OnConflictAction specifies the action for ON CONFLICT clauses.

const (
	DoNothing OnConflictAction = iota
	DoUpdate
)

type OnConflictNode

type OnConflictNode struct {
	Columns     []Node            // conflict target columns
	Action      OnConflictAction  // DoNothing or DoUpdate
	Assignments []*AssignmentNode // SET for DO UPDATE
	Wheres      []Node            // WHERE for DO UPDATE
}

OnConflictNode represents ON CONFLICT (...) DO NOTHING / DO UPDATE SET ...

func (*OnConflictNode) Accept

func (n *OnConflictNode) Accept(v Visitor) string

type OrNode

type OrNode struct {
	Combinable
	Left  Node
	Right Node
}

OrNode represents a logical OR between two expressions.

func NewOrNode added in v0.2.0

func NewOrNode(left, right Node) *OrNode

NewOrNode creates an OrNode with properly initialised embedded structs. Unlike Combinable.Or it does not wrap the result in a GroupingNode.

func (*OrNode) Accept

func (n *OrNode) Accept(v Visitor) string

type OrderDirection

type OrderDirection int

OrderDirection represents ASC or DESC ordering.

const (
	Asc OrderDirection = iota
	Desc
)

type OrderingNode

type OrderingNode struct {
	Expr      Node
	Direction OrderDirection
	Nulls     NullsDirection
	Combinable
}

OrderingNode represents an ORDER BY expression with a direction.

func NewOrderingNode added in v0.2.0

func NewOrderingNode(expr Node, dir OrderDirection, nulls NullsDirection) *OrderingNode

NewOrderingNode creates an OrderingNode with properly initialised embedded structs.

func (*OrderingNode) Accept

func (n *OrderingNode) Accept(v Visitor) string

type OverNode

type OverNode struct {
	Predications
	Arithmetics
	Combinable
	Expr       Node              // WindowFuncNode or AggregateNode
	Window     *WindowDefinition // inline window definition (nil if using WindowName)
	WindowName string            // named window reference (empty if using Window)
}

OverNode wraps an expression (window function or aggregate) with an OVER clause.

func NewOverNode

func NewOverNode(expr Node) *OverNode

NewOverNode creates an OverNode with properly initialised embedded structs.

func (*OverNode) Accept

func (n *OverNode) Accept(v Visitor) string

type Parameterizer

type Parameterizer interface {
	Params() []any
	Reset()
}

Parameterizer is implemented by visitors that support parameterized queries. Callers use type assertion to extract collected parameters after SQL generation.

type Predications

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

Predications provides comparison methods to types that embed it. The self field must be set to the embedding node so that comparisons reference the correct left-hand side.

func (Predications) As

func (p Predications) As(name string) *AliasNode

As creates an AliasNode wrapping self with the given alias name.

func (Predications) Asc

func (p Predications) Asc() *OrderingNode

Asc creates an ascending ordering node.

func (Predications) Between

func (p Predications) Between(low, high any) *BetweenNode

Between creates a BETWEEN predicate: self BETWEEN low AND high.

func (Predications) CaseInsensitiveEq

func (p Predications) CaseInsensitiveEq(val any) *ComparisonNode

CaseInsensitiveEq creates a case-insensitive equality comparison.

func (Predications) CaseSensitiveEq

func (p Predications) CaseSensitiveEq(val any) *ComparisonNode

CaseSensitiveEq creates a case-sensitive equality comparison.

func (Predications) Contains

func (p Predications) Contains(val any) *ComparisonNode

Contains creates an array/JSONB containment operator: self @> val.

func (Predications) Desc

func (p Predications) Desc() *OrderingNode

Desc creates a descending ordering node.

func (Predications) DoesNotMatchRegexp

func (p Predications) DoesNotMatchRegexp(val any) *ComparisonNode

DoesNotMatchRegexp creates a negated regexp match: self !~ val.

func (Predications) Eq

func (p Predications) Eq(val any) *ComparisonNode

Eq creates an equality comparison: self = val.

func (Predications) EqAll

func (p Predications) EqAll(vals ...any) Node

EqAll returns col = v1 AND col = v2 AND ...

func (Predications) EqAny

func (p Predications) EqAny(vals ...any) *GroupingNode

EqAny returns col = v1 OR col = v2 OR ... wrapped in a GroupingNode.

func (Predications) Gt

func (p Predications) Gt(val any) *ComparisonNode

Gt creates a greater-than comparison: self > val.

func (Predications) GtEq

func (p Predications) GtEq(val any) *ComparisonNode

GtEq creates a greater-than-or-equal comparison: self >= val.

func (Predications) In

func (p Predications) In(vals ...any) *InNode

In creates an IN predicate: self IN (vals...).

func (Predications) InAll

func (p Predications) InAll(sets ...[]any) Node

InAll returns col IN (set1) AND col IN (set2) AND ... Each argument is a []any slice representing one IN set.

func (Predications) InAny

func (p Predications) InAny(sets ...[]any) *GroupingNode

InAny returns col IN (set1) OR col IN (set2) OR ... wrapped in a GroupingNode. Each argument is a []any slice representing one IN set.

func (Predications) IsDistinctFrom

func (p Predications) IsDistinctFrom(val any) *ComparisonNode

IsDistinctFrom creates an IS DISTINCT FROM comparison.

func (Predications) IsNotDistinctFrom

func (p Predications) IsNotDistinctFrom(val any) *ComparisonNode

IsNotDistinctFrom creates an IS NOT DISTINCT FROM comparison.

func (Predications) IsNotNull

func (p Predications) IsNotNull() *UnaryNode

IsNotNull creates an IS NOT NULL predicate.

func (Predications) IsNull

func (p Predications) IsNull() *UnaryNode

IsNull creates an IS NULL predicate.

func (Predications) Like

func (p Predications) Like(val any) *ComparisonNode

Like creates a LIKE comparison: self LIKE val.

func (Predications) Lt

func (p Predications) Lt(val any) *ComparisonNode

Lt creates a less-than comparison: self < val.

func (Predications) LtEq

func (p Predications) LtEq(val any) *ComparisonNode

LtEq creates a less-than-or-equal comparison: self <= val.

func (Predications) MatchesAll

func (p Predications) MatchesAll(vals ...any) Node

MatchesAll returns col LIKE p1 AND col LIKE p2 AND ...

func (Predications) MatchesAny

func (p Predications) MatchesAny(vals ...any) *GroupingNode

MatchesAny returns col LIKE p1 OR col LIKE p2 OR ... wrapped in a GroupingNode.

func (Predications) MatchesRegexp

func (p Predications) MatchesRegexp(val any) *ComparisonNode

MatchesRegexp creates a regexp match: self ~ val.

func (Predications) NotBetween

func (p Predications) NotBetween(low, high any) *BetweenNode

NotBetween creates a NOT BETWEEN predicate: self NOT BETWEEN low AND high.

func (Predications) NotEq

func (p Predications) NotEq(val any) *ComparisonNode

NotEq creates an inequality comparison: self != val.

func (Predications) NotIn

func (p Predications) NotIn(vals ...any) *InNode

NotIn creates a NOT IN predicate: self NOT IN (vals...).

func (Predications) NotLike

func (p Predications) NotLike(val any) *ComparisonNode

NotLike creates a NOT LIKE comparison: self NOT LIKE val.

func (Predications) Overlaps

func (p Predications) Overlaps(val any) *ComparisonNode

Overlaps creates an array overlap operator: self && val.

type RawSQL

type RawSQL string

RawSQL is a string type that marks a value as a developer-controlled raw SQL fragment. It is intentionally not interchangeable with a plain string to prevent user-controlled input from reaching raw SQL injection points without an explicit cast. Use nodes.RawSQL("...") for developer-written fragments — the cast is the audit trail.

This follows the html/template.HTML pattern from the Go standard library, which uses the same idiom to prevent XSS.

type SelectCore

type SelectCore struct {
	From        Node
	Projections []Node
	Wheres      []Node
	Joins       []*JoinNode
	Groups      []Node              // GROUP BY expressions
	Havings     []Node              // HAVING conditions
	Windows     []*WindowDefinition // WINDOW definitions
	Orders      []Node              // OrderingNode values
	Limit       Node                // nil or LiteralNode
	Offset      Node                // nil or LiteralNode
	Distinct    bool
	DistinctOn  []Node     // DISTINCT ON columns (PostgreSQL)
	Lock        LockMode   // FOR UPDATE/SHARE
	SkipLocked  bool       // SKIP LOCKED
	Comment     string     // query comment /* ... */
	Hints       []string   // optimizer hints /*+ ... */
	CTEs        []*CTENode // WITH clause
}

SelectCore represents the data container for a SELECT clause. The fluent API for building queries lives in the managers package.

func (*SelectCore) Accept

func (n *SelectCore) Accept(v Visitor) string

type SetOpType

type SetOpType int

SetOpType represents the type of set operation.

const (
	Union SetOpType = iota
	UnionAll
	Intersect
	IntersectAll
	Except
	ExceptAll
)

func (SetOpType) String

func (t SetOpType) String() string

String returns the SQL keyword for this set operation type.

type SetOperationNode

type SetOperationNode struct {
	Left   Node
	Right  Node
	Type   SetOpType
	Orders []Node // ORDER BY for the combined result
	Limit  Node   // LIMIT for the combined result
	Offset Node   // OFFSET for the combined result
}

SetOperationNode represents a set operation between two queries. Orders, Limit, and Offset apply to the entire result of the set operation.

func (*SetOperationNode) Accept

func (n *SetOperationNode) Accept(v Visitor) string

type SqlLiteral

type SqlLiteral struct {
	Predications
	Combinable
	Raw   RawSQL
	Binds []any // optional bind parameters for parameterized mode
}

SqlLiteral represents a raw SQL fragment injected verbatim into the query.

SECURITY: The Raw field is rendered directly into SQL output without escaping or parameterization. Never pass user-controlled input to NewSqlLiteral or NewBoundSqlLiteral's raw parameter. Use parameterized queries (BindParam) for user-provided values. The RawSQL type enforces this at compile time: a plain string variable cannot be passed without an explicit RawSQL(...) cast.

func NewBoundSqlLiteral

func NewBoundSqlLiteral(raw RawSQL, binds ...any) *SqlLiteral

NewBoundSqlLiteral creates a SqlLiteral with bind parameters. In parameterized mode, the binds are added to the parameter list.

SECURITY: Only the binds are parameterized. The raw string is injected verbatim into SQL output and must not contain user-controlled input. The RawSQL type enforces this at compile time.

func NewSqlLiteral

func NewSqlLiteral(raw RawSQL) *SqlLiteral

func (*SqlLiteral) Accept

func (n *SqlLiteral) Accept(v Visitor) string

type StarNode

type StarNode struct {
	Table *Table // nil for unqualified *
}

StarNode represents a SQL star (*) or qualified star (table.*).

func Star

func Star() *StarNode

Star returns an unqualified StarNode representing SQL *.

func (*StarNode) Accept

func (n *StarNode) Accept(v Visitor) string

type Table

type Table struct {
	Name string
}

Table represents a SQL table reference.

func NewTable

func NewTable(name string) *Table

func (*Table) Accept

func (t *Table) Accept(v Visitor) string

func (*Table) Alias

func (t *Table) Alias(name string) *TableAlias

Alias creates an aliased reference to this table.

func (*Table) Col

func (t *Table) Col(name string) *Attribute

Col creates an Attribute (column reference) bound to this table.

func (*Table) Star

func (t *Table) Star() *StarNode

Star creates a qualified star (table.*) for this table.

type TableAlias

type TableAlias struct {
	Relation  Node // *Table, *SelectCore, or any Node
	AliasName string
}

TableAlias represents an aliased reference to a table or subquery.

func (*TableAlias) Accept

func (ta *TableAlias) Accept(v Visitor) string

func (*TableAlias) Col

func (ta *TableAlias) Col(name string) *Attribute

Col creates an Attribute (column reference) bound to this table alias.

type UnaryMathNode

type UnaryMathNode struct {
	Predications
	Arithmetics
	Combinable
	Expr Node
	Op   UnaryMathOp
}

UnaryMathNode represents a unary math expression (e.g., bitwise NOT).

func NewUnaryMathNode

func NewUnaryMathNode(expr Node, op UnaryMathOp) *UnaryMathNode

NewUnaryMathNode creates a UnaryMathNode with properly initialised embedded structs.

func (*UnaryMathNode) Accept

func (n *UnaryMathNode) Accept(v Visitor) string

type UnaryMathOp

type UnaryMathOp int

UnaryMathOp identifies the unary math operator.

const (
	OpBitwiseNot UnaryMathOp = iota
)

type UnaryNode

type UnaryNode struct {
	Combinable
	Expr Node
	Op   UnaryOp
}

UnaryNode represents a unary predicate: Expr IS NULL / IS NOT NULL.

func NewUnaryNode added in v0.2.0

func NewUnaryNode(expr Node, op UnaryOp) *UnaryNode

NewUnaryNode creates a UnaryNode with properly initialised embedded structs.

func (*UnaryNode) Accept

func (n *UnaryNode) Accept(v Visitor) string

type UnaryOp

type UnaryOp int

UnaryOp represents a unary postfix operator.

const (
	OpIsNull UnaryOp = iota
	OpIsNotNull
)

type UpdateStatement

type UpdateStatement struct {
	Table       Node
	Assignments []*AssignmentNode
	Wheres      []Node
	Returning   []Node
}

UpdateStatement represents UPDATE ... SET ... WHERE.

func (*UpdateStatement) Accept

func (n *UpdateStatement) Accept(v Visitor) string

type Visitor

type Visitor interface {
	VisitTable(node *Table) string
	VisitTableAlias(node *TableAlias) string
	VisitAttribute(node *Attribute) string
	VisitLiteral(node *LiteralNode) string
	VisitStar(node *StarNode) string
	VisitSqlLiteral(node *SqlLiteral) string
	VisitComparison(node *ComparisonNode) string
	VisitUnary(node *UnaryNode) string
	VisitAnd(node *AndNode) string
	VisitOr(node *OrNode) string
	VisitNot(node *NotNode) string
	VisitIn(node *InNode) string
	VisitBetween(node *BetweenNode) string
	VisitGrouping(node *GroupingNode) string
	VisitJoin(node *JoinNode) string
	VisitOrdering(node *OrderingNode) string
	VisitSelectCore(node *SelectCore) string
	VisitInsertStatement(node *InsertStatement) string
	VisitUpdateStatement(node *UpdateStatement) string
	VisitDeleteStatement(node *DeleteStatement) string
	VisitAssignment(node *AssignmentNode) string
	VisitOnConflict(node *OnConflictNode) string
	VisitInfix(node *InfixNode) string
	VisitUnaryMath(node *UnaryMathNode) string
	VisitAggregate(node *AggregateNode) string
	VisitExtract(node *ExtractNode) string
	VisitWindowFunction(node *WindowFuncNode) string
	VisitOver(node *OverNode) string
	VisitExists(node *ExistsNode) string
	VisitSetOperation(node *SetOperationNode) string
	VisitCTE(node *CTENode) string
	VisitNamedFunction(node *NamedFunctionNode) string
	VisitCase(node *CaseNode) string
	VisitGroupingSet(node *GroupingSetNode) string
	VisitAlias(node *AliasNode) string
	VisitBindParam(node *BindParamNode) string
	VisitCasted(node *CastedNode) string
}

Visitor defines the interface for walking the AST and producing output. Concrete visitors (e.g., Postgres, MySQL) implement this interface.

type WindowDefinition

type WindowDefinition struct {
	Name        string
	PartitionBy []Node
	OrderBy     []Node
	Frame       *WindowFrame
}

WindowDefinition describes a window specification: name, partitioning, ordering, and frame.

func NewWindowDef

func NewWindowDef(name ...string) *WindowDefinition

NewWindowDef creates a new WindowDefinition with an optional name.

func (*WindowDefinition) Order

func (w *WindowDefinition) Order(orderings ...Node) *WindowDefinition

Order sets the ORDER BY expressions.

func (*WindowDefinition) Partition

func (w *WindowDefinition) Partition(cols ...Node) *WindowDefinition

Partition sets the PARTITION BY columns.

func (*WindowDefinition) Range

func (w *WindowDefinition) Range(start FrameBound, end ...FrameBound) *WindowDefinition

Range sets a RANGE frame with start and optional end bound.

func (*WindowDefinition) Rows

func (w *WindowDefinition) Rows(start FrameBound, end ...FrameBound) *WindowDefinition

Rows sets a ROWS frame with start and optional end bound.

type WindowFrame

type WindowFrame struct {
	Type  FrameType
	Start FrameBound
	End   *FrameBound // nil means no BETWEEN (just the Start bound)
}

WindowFrame describes the frame clause (ROWS/RANGE BETWEEN ... AND ...).

type WindowFunc

type WindowFunc int

WindowFunc identifies the window function.

const (
	WinRowNumber WindowFunc = iota
	WinRank
	WinDenseRank
	WinNtile
	WinLag
	WinLead
	WinFirstValue
	WinLastValue
	WinNthValue
	WinCumeDist
	WinPercentRank
)

type WindowFuncNode

type WindowFuncNode struct {
	Func WindowFunc
	Args []Node
}

WindowFuncNode represents a window function call (e.g. ROW_NUMBER(), RANK()). It is always wrapped by OverNode for the OVER clause.

func CumeDist

func CumeDist() *WindowFuncNode

CumeDist creates a CUME_DIST() window function node.

func DenseRank

func DenseRank() *WindowFuncNode

DenseRank creates a DENSE_RANK() window function node.

func FirstValue

func FirstValue(expr Node) *WindowFuncNode

FirstValue creates a FIRST_VALUE(expr) window function node.

func Lag

func Lag(args ...Node) *WindowFuncNode

Lag creates a LAG(expr [, offset [, default]]) window function node.

func LastValue

func LastValue(expr Node) *WindowFuncNode

LastValue creates a LAST_VALUE(expr) window function node.

func Lead

func Lead(args ...Node) *WindowFuncNode

Lead creates a LEAD(expr [, offset [, default]]) window function node.

func NthValue

func NthValue(args ...Node) *WindowFuncNode

NthValue creates an NTH_VALUE(expr, n) window function node.

func Ntile

func Ntile(n Node) *WindowFuncNode

Ntile creates an NTILE(n) window function node.

func PercentRank

func PercentRank() *WindowFuncNode

PercentRank creates a PERCENT_RANK() window function node.

func Rank

func Rank() *WindowFuncNode

Rank creates a RANK() window function node.

func RowNumber

func RowNumber() *WindowFuncNode

RowNumber creates a ROW_NUMBER() window function node.

func (*WindowFuncNode) Accept

func (n *WindowFuncNode) Accept(v Visitor) string

func (*WindowFuncNode) Over

func (n *WindowFuncNode) Over(def *WindowDefinition) *OverNode

Over wraps the window function with an inline window definition.

func (*WindowFuncNode) OverName

func (n *WindowFuncNode) OverName(name string) *OverNode

OverName wraps the window function with a named window reference.

Jump to

Keyboard shortcuts

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