ast

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Aug 28, 2026 License: Apache-2.0 Imports: 4 Imported by: 0

Documentation

Overview

Package ast is the base module's statement layer: standard SQL composed as Go values — an abstract syntax tree rendered through the provider's dialect. The vocabulary is sealed: expressions (Col, Val, Fn, and Raw as the deliberate escape hatch), predicates (the comparison methods on Expression, combined by And, Or, Not), and statements as plain structs — Select and Compound as the Query expressions, Insert, Update, and Delete as the write statements — each rendered by its Render method into an SQL value: the text and bound arguments, placeholders through the dialect. The operation package composes contract-shaped constructors above this layer; the exec package runs what either produces.

Standard core

The vocabulary composes the SQL every engine accepts, and the portability rules are structural rather than documented: table aliases render without AS, compound branches render without parentheses and carry no tail clauses, WITH belongs to the outermost statement, a subquery orders only when it pages, write statements render only at the top and take plain table names, and paging is the SQL:2008 OFFSET/FETCH form with bound arguments, always under an ORDER BY. Request-derived text reaches a statement only as a bound argument; Raw and the pool beneath the package are the declared passthroughs for SQL the vocabulary does not compose.

Dialect capabilities

Where engines diverge, the package defines an optional dialect interface checked at the divergent render site, in one of two directions. A standard feature with divergent renderings keeps standard emission as the default and lets a dialect override it — PagingRenderer. A declared native feature with no standard emission renders only through its capability and otherwise fails with a typed UnsupportedFeatureError — ReturningRenderer, for the write statements' Returning clause. Either way the dialect interface itself grows nothing speculatively, and a statement renders portably or fails typed; it never silently emits one-engine SQL.

Index

Constants

View Source
const FeatureReturning = "returning"

FeatureReturning names the declared native returning clause, carried by UnsupportedFeatureError when a dialect lacks ReturningRenderer.

Variables

View Source
var ErrInvalidStatement = errors.New("invalid query statement")

ErrInvalidStatement classifies a statement that cannot be rendered — an empty select list, a derived table without an alias, paging without ORDER BY. It is wrapped with the specific defect, so errors.Is matches the class while the message names the fix.

Functions

This section is empty.

Types

type Assignment

type Assignment struct {
	Column string
	Value  any
}

Assignment is one SET entry: the target column and its value. The value lifts like any operand — an Expression renders in place, so Raw("version + 1") assigns a computation, and any other Go value binds as a parameter.

type CTE

type CTE struct {
	Name      string
	Columns   []string
	Recursive bool
	Query     Query
}

CTE is one common table expression in a statement's WITH list. Recursive marks it for WITH RECURSIVE — its query is then a Compound whose first branch is the anchor. Columns optionally names the CTE's column list, which a recursive CTE usually needs.

type Column

type Column struct {
	Expr  Expression
	Alias string
}

Column is one select-list entry: an expression and its optional alias.

type Compound

type Compound struct {
	With    []CTE
	Op      SetOp
	All     bool
	Queries []Query
	OrderBy []Order
	Paging  *Paging
}

Compound joins two or more Select branches with one set operator. Branches render without parentheses — the one form every engine accepts — so each compound carries a single operator and deliberate nesting goes through a derived table. ORDER BY and paging attach to the compound; branches carry neither, nor WITH.

func Except

func Except(queries ...Query) Compound

Except composes an EXCEPT of the queries.

func ExceptAll

func ExceptAll(queries ...Query) Compound

ExceptAll composes an EXCEPT ALL of the queries.

func Intersect

func Intersect(queries ...Query) Compound

Intersect composes an INTERSECT of the queries.

func IntersectAll

func IntersectAll(queries ...Query) Compound

IntersectAll composes an INTERSECT ALL of the queries.

func Union

func Union(queries ...Query) Compound

Union composes a UNION of the queries.

func UnionAll

func UnionAll(queries ...Query) Compound

UnionAll composes a UNION ALL of the queries.

func (Compound) Render

func (c Compound) Render(d database.Dialect) (SQL, error)

Render renders the compound through the dialect, with the same contract as Select.Render.

type Delete

type Delete struct {
	Table     string
	Where     Predicate
	Returning []Column
}

Delete is a delete statement as a value: the plain table name — joined or aliased DML targets are engine-divergent and stay out of the vocabulary — and the WHERE predicate. An absent Where deletes every row; guard against that at the operation layer, not here. Returning is the declared-native clause, rendered only through ReturningRenderer.

func (Delete) Render

func (d Delete) Render(dialect database.Dialect) (SQL, error)

Render renders the statement through the dialect, with the same contract as Select.Render; a Returning list on a dialect without ReturningRenderer fails with UnsupportedFeatureError.

type Expression

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

Expression is one standard-SQL expression: a column reference, a bound value, a function call, a raw fragment, or a subquery. The zero value is empty and fails the statement that renders it. The comparison methods produce Predicate values; Expression.As names it as a select-list column.

func Col

func Col(parts ...string) Expression

Col references a column by its identifier parts. Each part may itself be dotted — Col("o.name") and Col("o", "name") are the same reference — so the structure survives for a dialect quoting extension while call sites keep reading like SQL. Parts render verbatim, dot-joined; an identifier containing a literal dot goes through Raw. An empty part fails the statement.

func Fn

func Fn(name string, args ...any) Expression

Fn composes a function call. Arguments lift like comparison operands — expressions render in place, plain values bind — so Fn("COUNT", Raw("*")) and Fn("COALESCE", Col("nickname"), "") both hold.

func Raw

func Raw(sql string) Expression

Raw is the escape hatch: a consumer-authored SQL fragment rendered verbatim. It is the deliberate seam for SQL the vocabulary does not compose; never route request-derived text through it.

func Val

func Val(v any) Expression

Val binds a value explicitly. Comparison operands lift plain Go values on their own; Val is for a bound value standing alone as an expression, such as a constant select-list column.

func (Expression) As

func (e Expression) As(alias string) Column

As names the expression as a select-list column.

func (Expression) Empty

func (e Expression) Empty() bool

Empty reports whether the expression is the zero value. Layers above the package use it to validate their contracts before rendering.

func (Expression) Eq

func (e Expression) Eq(v any) Predicate

Eq compares for equality; the operand lifts like every comparison operand.

func (Expression) Ge

func (e Expression) Ge(v any) Predicate

Ge compares greater-than-or-equal.

func (Expression) Gt

func (e Expression) Gt(v any) Predicate

Gt compares greater-than.

func (Expression) In

func (e Expression) In(vals ...any) Predicate

In tests membership: values lift as bound parameters, expressions render in place, and a single Select or Compound argument becomes IN (subquery). An empty list fails the statement.

func (Expression) IsNotNull

func (e Expression) IsNotNull() Predicate

IsNotNull tests for NOT NULL.

func (Expression) IsNull

func (e Expression) IsNull() Predicate

IsNull tests for NULL.

func (Expression) Le

func (e Expression) Le(v any) Predicate

Le compares less-than-or-equal.

func (Expression) Like

func (e Expression) Like(v any) Predicate

Like matches against a pattern.

func (Expression) Lt

func (e Expression) Lt(v any) Predicate

Lt compares less-than.

func (Expression) Ne

func (e Expression) Ne(v any) Predicate

Ne compares for inequality.

type Insert

type Insert struct {
	Table     string
	Columns   []string
	Rows      [][]any
	Query     Query
	Returning []Column
}

Insert is an insert statement as a value: the plain table name, an optional column list, and either literal Rows or a Query (INSERT ... SELECT), never both. Row values lift like operands — expressions render in place, plain values bind — and each row's width must match the column list when one is given. Returning is the declared-native clause, rendered only through ReturningRenderer.

func (Insert) Render

func (i Insert) Render(d database.Dialect) (SQL, error)

Render renders the statement through the dialect, with the same contract as Select.Render; a Returning list on a dialect without ReturningRenderer fails with UnsupportedFeatureError.

type Order

type Order struct {
	Expr       Expression
	Descending bool
}

Order is one ORDER BY key. Ascending is the default; Descending renders DESC.

type Paging

type Paging struct {
	Offset int
	Fetch  int
}

Paging is the SQL:2008 offset/fetch pair, rendered as bound arguments: OFFSET ? ROWS FETCH NEXT ? ROWS ONLY. Paging always requires ORDER BY. An engine that lacks the standard form renders through PagingRenderer.

type PagingRenderer

type PagingRenderer interface {
	RenderPaging(w Writer, offset, fetch int)
}

PagingRenderer is the render override for an engine that lacks the SQL:2008 OFFSET/FETCH form. A provider's dialect opts in by implementing it and writes its engine's paging clause — no leading space, offset and fetch bound through the writer rather than interpolated. Absent, the standard form renders: this is the capability pattern's override direction, where standard emission stays the default.

type Predicate

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

Predicate is a boolean expression: a comparison, a null test, a membership test, or a combination. The zero value is empty — an absent WHERE or HAVING — and And and Or drop empty operands, so optional conditions compose without special cases.

func And

func And(preds ...Predicate) Predicate

And conjoins predicates, dropping empty operands; zero remaining operands yield the empty predicate and one passes through unwrapped.

func Not

func Not(p Predicate) Predicate

Not negates a predicate. Negating the empty predicate fails the statement.

func Or

func Or(preds ...Predicate) Predicate

Or disjoins predicates with the same empty-operand rules as And.

type Query

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

Query is a query expression: Select or Compound, the statements SQL grammar admits inside a CTE, a derived table, a subquery operand, and INSERT ... SELECT. The interface is sealed by an unexported marker, so those positions accept exactly the query expressions at compile time; the write statements render at the outermost position only and never implement it.

type ReturningRenderer

type ReturningRenderer interface {
	RenderReturning(w Writer, cols []Column)
}

ReturningRenderer is the capability for the declared-native returning clause on the write statements — an engine's way of handing back the rows a write affected, which has no standard emission. A provider's dialect opts in and writes its engine's clause at the statement tail — no leading space, columns through Writer.Column. Absent, a statement carrying a Returning list fails with UnsupportedFeatureError: the capability pattern's native-only direction, failing typed rather than falling back.

type SQL

type SQL struct {
	Text string
	Args []any
}

SQL is one rendered statement — the render product every statement's Render method returns: the SQL text and its bound arguments in placeholder order. The execution layer runs SQL values; the operation layer's envelopes group them.

type Select

type Select struct {
	With     []CTE
	Distinct bool
	Columns  []Column
	From     TableRef
	Where    Predicate
	GroupBy  []Expression
	Having   Predicate
	OrderBy  []Order
	Paging   *Paging
}

Select is a query specification as a value: build it as a struct literal and render it with Select.Render. Zero fields are absent clauses. WITH is valid only on the outermost statement, and a subquery orders only when it pages.

func (Select) Render

func (s Select) Render(d database.Dialect) (SQL, error)

Render renders the statement through the dialect. A structural defect wraps ErrInvalidStatement; a nil dialect panics as a wiring defect.

type SetOp

type SetOp string

SetOp is a compound query's set operator.

const (
	SetUnion     SetOp = "UNION"
	SetIntersect SetOp = "INTERSECT"
	SetExcept    SetOp = "EXCEPT"
)

type TableRef

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

TableRef is a FROM clause element: a named table, an aliased derived table, or a join tree built by the join methods. The zero value fails the statement that renders it.

func Derived

func Derived(q Query) TableRef

Derived wraps a query as a derived table. It must be aliased with TableRef.As before it renders, and its query carries no WITH — the standard places WITH on the outermost statement; declare CTEs there.

func Table

func Table(name string) TableRef

Table references a named table or view, rendered verbatim.

func (TableRef) As

func (t TableRef) As(alias string) TableRef

As sets the correlation name. Table aliases render without AS — the one spelling every engine accepts. Only a table or derived table takes an alias; aliasing a join fails the statement.

func (TableRef) FullJoin

func (t TableRef) FullJoin(right TableRef, on Predicate) TableRef

FullJoin composes a FULL JOIN with the ON predicate.

func (TableRef) Join

func (t TableRef) Join(right TableRef, on Predicate) TableRef

Join composes an INNER JOIN with the ON predicate.

func (TableRef) LeftJoin

func (t TableRef) LeftJoin(right TableRef, on Predicate) TableRef

LeftJoin composes a LEFT JOIN with the ON predicate.

func (TableRef) RightJoin

func (t TableRef) RightJoin(right TableRef, on Predicate) TableRef

RightJoin composes a RIGHT JOIN with the ON predicate.

type UnsupportedFeatureError

type UnsupportedFeatureError struct {
	Feature string
	Dialect string
}

UnsupportedFeatureError reports a well-formed statement using a declared native feature the dialect does not implement. Unlike ErrInvalidStatement the statement itself is sound; the engine has no rendering for the feature, and the vocabulary fails typed rather than emitting SQL the engine would reject.

func (*UnsupportedFeatureError) Error

func (e *UnsupportedFeatureError) Error() string

type Update

type Update struct {
	Table     string
	Set       []Assignment
	Where     Predicate
	Returning []Column
}

Update is an update statement as a value: the plain table name — joined or aliased DML targets are engine-divergent and stay out of the vocabulary — the SET list, and the WHERE predicate. An absent Where updates every row; guard against that at the operation layer, not here. Returning is the declared-native clause, rendered only through ReturningRenderer.

func (Update) Render

func (u Update) Render(d database.Dialect) (SQL, error)

Render renders the statement through the dialect, with the same contract as Select.Render; a Returning list on a dialect without ReturningRenderer fails with UnsupportedFeatureError.

type Writer

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

Writer is the surface a dialect render extension writes into: literal SQL text through SQL, bound arguments through Bind, and select-list columns through Column — so an extension composes its clause without reaching the package's internals, and bound arguments stay in placeholder order.

func (Writer) Bind

func (w Writer) Bind(v any)

Bind binds a value and writes its placeholder.

func (Writer) Column

func (w Writer) Column(c Column)

Column renders one select-list column: its expression, and AS with the alias when one is set.

func (Writer) SQL

func (w Writer) SQL(s string)

SQL writes literal SQL text.

Jump to

Keyboard shortcuts

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