Documentation
¶
Overview ¶
Package astql provides a type-safe SQL query builder with multi-provider support.
The package generates an Abstract Syntax Tree (AST) from fluent builder calls, then renders it to SQL with named parameters compatible with sqlx. Schema validation is available through DBML integration.
Basic Usage ¶
Queries can be built directly using the package-level builder functions:
import "github.com/zoobz-io/astql/postgres"
query := astql.Select(table).
Fields(field1, field2).
Where(condition).
OrderBy(field1, astql.ASC).
Limit(10)
result, err := query.Render(postgres.New())
// result.SQL: SELECT "field1", "field2" FROM "table" WHERE ... ORDER BY "field1" ASC LIMIT 10
// result.RequiredParams: []string{"param_name", ...}
Multi-Provider Support ¶
The package supports multiple SQL dialects through the Renderer interface. Available providers: postgres, mariadb, sqlite, mssql.
import "github.com/zoobz-io/astql/mariadb" result, err := query.Render(mariadb.New())
Schema-Validated Usage ¶
For compile-time safety, create an ASTQL instance from a DBML schema:
instance, err := astql.NewFromDBML(project)
if err != nil {
return err
}
// These panic if the field/table doesn't exist in the schema
users := instance.T("users")
email := instance.F("email")
Supported Operations ¶
The package supports SELECT, INSERT, UPDATE, DELETE, and COUNT operations, along with JOINs, subqueries, window functions, aggregates, CASE expressions, set operations (UNION, INTERSECT, EXCEPT), and PostgreSQL-specific features like DISTINCT ON, row locking, RETURNING, ON CONFLICT, and pgvector operators.
Output Format ¶
All queries use named parameters (`:param_name`) for use with sqlx.NamedExec and similar functions. Identifiers are quoted to handle reserved words.
Index ¶
- Constants
- func Abs(field types.Field) types.FieldExpression
- func As(expr types.FieldExpression, alias string) types.FieldExpression
- func Avg(field types.Field) types.FieldExpression
- func AvgFilter(field types.Field, filter types.ConditionItem) types.FieldExpression
- func Between(field types.Field, low, high types.Param) types.BetweenCondition
- func BinaryExpr(field types.Field, op types.Operator, param types.Param) types.FieldExpression
- func CF(left types.Field, op types.Operator, right types.Field) types.FieldComparison
- func CSub(field types.Field, op types.Operator, subquery types.Subquery) types.SubqueryCondition
- func CSubExists(op types.Operator, subquery types.Subquery) types.SubqueryCondition
- func Cast(field types.Field, castType types.CastType) types.FieldExpression
- func Ceil(field types.Field) types.FieldExpression
- func Coalesce(values ...types.Param) types.FieldExpression
- func Concat(fields ...types.Field) types.FieldExpression
- func CountDistinct(field types.Field) types.FieldExpression
- func CountDistinctFilter(field types.Field, filter types.ConditionItem) types.FieldExpression
- func CountField(field types.Field) types.FieldExpression
- func CountFieldFilter(field types.Field, filter types.ConditionItem) types.FieldExpression
- func CountStar() types.FieldExpression
- func CurrentDate() types.FieldExpression
- func CurrentTime() types.FieldExpression
- func CurrentTimestamp() types.FieldExpression
- func DateTrunc(part types.DatePart, field types.Field) types.FieldExpression
- func Extract(part types.DatePart, field types.Field) types.FieldExpression
- func Floor(field types.Field) types.FieldExpression
- func HavingAvg(field types.Field, op types.Operator, value types.Param) types.AggregateCondition
- func HavingCount(op types.Operator, value types.Param) types.AggregateCondition
- func HavingCountDistinct(field types.Field, op types.Operator, value types.Param) types.AggregateCondition
- func HavingCountField(field types.Field, op types.Operator, value types.Param) types.AggregateCondition
- func HavingMax(field types.Field, op types.Operator, value types.Param) types.AggregateCondition
- func HavingMin(field types.Field, op types.Operator, value types.Param) types.AggregateCondition
- func HavingSum(field types.Field, op types.Operator, value types.Param) types.AggregateCondition
- func LTrim(field types.Field) types.FieldExpression
- func Length(field types.Field) types.FieldExpression
- func Lower(field types.Field) types.FieldExpression
- func Max(field types.Field) types.FieldExpression
- func MaxFilter(field types.Field, filter types.ConditionItem) types.FieldExpression
- func Min(field types.Field) types.FieldExpression
- func MinFilter(field types.Field, filter types.ConditionItem) types.FieldExpression
- func NotBetween(field types.Field, low, high types.Param) types.BetweenCondition
- func Now() types.FieldExpression
- func NullIf(value1, value2 types.Param) types.FieldExpression
- func Power(field types.Field, exponent types.Param) types.FieldExpression
- func RTrim(field types.Field) types.FieldExpression
- func Replace(field types.Field, search types.Param, replacement types.Param) types.FieldExpression
- func Round(field types.Field, precision ...types.Param) types.FieldExpression
- func Sqrt(field types.Field) types.FieldExpression
- func Sub(builder *Builder) types.Subquery
- func Substring(field types.Field, start types.Param, length types.Param) types.FieldExpression
- func Sum(field types.Field) types.FieldExpression
- func SumFilter(field types.Field, filter types.ConditionItem) types.FieldExpression
- func Trim(field types.Field) types.FieldExpression
- func Upper(field types.Field) types.FieldExpression
- type AST
- type ASTQL
- func (*ASTQL) ASC() types.Direction
- func (a *ASTQL) AggC(aggFunc types.AggregateFunc, field *types.Field, op types.Operator, ...) types.AggregateCondition
- func (a *ASTQL) And(conditions ...types.ConditionItem) types.ConditionGroup
- func (*ASTQL) ArrayContainedBy() types.Operator
- func (*ASTQL) ArrayContains() types.Operator
- func (*ASTQL) ArrayOverlap() types.Operator
- func (a *ASTQL) C(field types.Field, op types.Operator, param types.Param) types.Condition
- func (*ASTQL) ConditionItems() []types.ConditionItem
- func (*ASTQL) Conditions() []types.Condition
- func (*ASTQL) DESC() types.Direction
- func (*ASTQL) EQ() types.Operator
- func (*ASTQL) EXISTS() types.Operator
- func (a *ASTQL) F(name string) types.Field
- func (*ASTQL) Fields() []types.Field
- func (*ASTQL) GE() types.Operator
- func (*ASTQL) GT() types.Operator
- func (a *ASTQL) GetInstance() *ASTQL
- func (*ASTQL) ILIKE() types.Operator
- func (*ASTQL) IN() types.Operator
- func (*ASTQL) IsNotNull() types.Operator
- func (*ASTQL) IsNull() types.Operator
- func (a *ASTQL) JSONBPath(field types.Field, key types.Param) types.Field
- func (a *ASTQL) JSONBText(field types.Field, key types.Param) types.Field
- func (*ASTQL) LE() types.Operator
- func (*ASTQL) LIKE() types.Operator
- func (*ASTQL) LT() types.Operator
- func (*ASTQL) NE() types.Operator
- func (*ASTQL) NotExists() types.Operator
- func (*ASTQL) NotILike() types.Operator
- func (*ASTQL) NotIn() types.Operator
- func (*ASTQL) NotLike() types.Operator
- func (a *ASTQL) NotNull(field types.Field) types.Condition
- func (*ASTQL) NotRegexIMatch() types.Operator
- func (*ASTQL) NotRegexMatch() types.Operator
- func (a *ASTQL) Null(field types.Field) types.Condition
- func (*ASTQL) OpCount() types.Operation
- func (*ASTQL) OpDelete() types.Operation
- func (*ASTQL) OpInsert() types.Operation
- func (*ASTQL) OpSelect() types.Operation
- func (*ASTQL) OpUpdate() types.Operation
- func (a *ASTQL) Or(conditions ...types.ConditionItem) types.ConditionGroup
- func (a *ASTQL) P(name string) types.Param
- func (*ASTQL) Params() []types.Param
- func (*ASTQL) RegexIMatch() types.Operator
- func (*ASTQL) RegexMatch() types.Operator
- func (a *ASTQL) T(name string, alias ...string) types.Table
- func (a *ASTQL) TryAggC(aggFunc types.AggregateFunc, field *types.Field, op types.Operator, ...) (types.AggregateCondition, error)
- func (*ASTQL) TryAnd(conditions ...types.ConditionItem) (types.ConditionGroup, error)
- func (a *ASTQL) TryC(field types.Field, op types.Operator, param types.Param) (types.Condition, error)
- func (a *ASTQL) TryF(name string) (types.Field, error)
- func (a *ASTQL) TryNotNull(field types.Field) (types.Condition, error)
- func (a *ASTQL) TryNull(field types.Field) (types.Condition, error)
- func (*ASTQL) TryOr(conditions ...types.ConditionItem) (types.ConditionGroup, error)
- func (*ASTQL) TryP(name string) (types.Param, error)
- func (a *ASTQL) TryT(name string, alias ...string) (types.Table, error)
- func (a *ASTQL) TryWithTable(field types.Field, tableOrAlias string) (types.Field, error)
- func (*ASTQL) ValueMap() map[types.Field]types.Param
- func (*ASTQL) VectorCosineDistance() types.Operator
- func (*ASTQL) VectorInnerProduct() types.Operator
- func (*ASTQL) VectorL1Distance() types.Operator
- func (*ASTQL) VectorL2Distance() types.Operator
- func (a *ASTQL) WithTable(field types.Field, tableOrAlias string) types.Field
- type AggregateCondition
- type AggregateFunc
- type BetweenCondition
- type BinaryExpression
- type Builder
- func (b *Builder) Build() (*types.AST, error)
- func (b *Builder) CrossJoin(table types.Table) *Builder
- func (b *Builder) Distinct() *Builder
- func (b *Builder) DistinctOn(fields ...types.Field) *Builder
- func (b *Builder) Except(other *Builder) *CompoundBuilder
- func (b *Builder) ExceptAll(other *Builder) *CompoundBuilder
- func (b *Builder) Fields(fields ...types.Field) *Builder
- func (b *Builder) ForKeyShare() *Builder
- func (b *Builder) ForNoKeyUpdate() *Builder
- func (b *Builder) ForShare() *Builder
- func (b *Builder) ForUpdate() *Builder
- func (b *Builder) FullOuterJoin(table types.Table, on types.ConditionItem) *Builder
- func (b *Builder) GetAST() *types.AST
- func (b *Builder) GetError() error
- func (b *Builder) GroupBy(fields ...types.Field) *Builder
- func (b *Builder) Having(conditions ...types.Condition) *Builder
- func (b *Builder) HavingAgg(conditions ...types.AggregateCondition) *Builder
- func (b *Builder) InnerJoin(table types.Table, on types.ConditionItem) *Builder
- func (b *Builder) Intersect(other *Builder) *CompoundBuilder
- func (b *Builder) IntersectAll(other *Builder) *CompoundBuilder
- func (b *Builder) Join(table types.Table, on types.ConditionItem) *Builder
- func (b *Builder) LeftJoin(table types.Table, on types.ConditionItem) *Builder
- func (b *Builder) Limit(limit int) *Builder
- func (b *Builder) LimitParam(param types.Param) *Builder
- func (b *Builder) MustBuild() *types.AST
- func (b *Builder) MustRender(renderer Renderer) *QueryResult
- func (b *Builder) Offset(offset int) *Builder
- func (b *Builder) OffsetParam(param types.Param) *Builder
- func (b *Builder) OnConflict(columns ...types.Field) *ConflictBuilder
- func (b *Builder) OrderBy(f types.Field, direction types.Direction) *Builder
- func (b *Builder) OrderByExpr(f types.Field, op types.Operator, p types.Param, direction types.Direction) *Builder
- func (b *Builder) OrderByNulls(f types.Field, direction types.Direction, nulls types.NullsOrdering) *Builder
- func (b *Builder) Render(renderer Renderer) (*QueryResult, error)
- func (b *Builder) Returning(fields ...types.Field) *Builder
- func (b *Builder) RightJoin(table types.Table, on types.ConditionItem) *Builder
- func (b *Builder) SelectBinaryExpr(f types.Field, op types.Operator, p types.Param, alias string) *Builder
- func (b *Builder) SelectExpr(expr types.FieldExpression) *Builder
- func (b *Builder) Set(f types.Field, p types.Param) *Builder
- func (b *Builder) SetError(err error)
- func (b *Builder) SetExpr(f types.Field, expr types.FieldExpression) *Builder
- func (b *Builder) Union(other *Builder) *CompoundBuilder
- func (b *Builder) UnionAll(other *Builder) *CompoundBuilder
- func (b *Builder) Values(valueMap map[types.Field]types.Param) *Builder
- func (b *Builder) Where(condition types.ConditionItem) *Builder
- func (b *Builder) WhereField(f types.Field, op types.Operator, p types.Param) *Builder
- type CaseBuilder
- type CastType
- type CompoundBuilder
- func Except(first, second *Builder) *CompoundBuilder
- func ExceptAll(first, second *Builder) *CompoundBuilder
- func Intersect(first, second *Builder) *CompoundBuilder
- func IntersectAll(first, second *Builder) *CompoundBuilder
- func Union(first, second *Builder) *CompoundBuilder
- func UnionAll(first, second *Builder) *CompoundBuilder
- func (cb *CompoundBuilder) Build() (*types.CompoundQuery, error)
- func (cb *CompoundBuilder) Except(other *Builder) *CompoundBuilder
- func (cb *CompoundBuilder) ExceptAll(other *Builder) *CompoundBuilder
- func (cb *CompoundBuilder) Intersect(other *Builder) *CompoundBuilder
- func (cb *CompoundBuilder) IntersectAll(other *Builder) *CompoundBuilder
- func (cb *CompoundBuilder) Limit(limit int) *CompoundBuilder
- func (cb *CompoundBuilder) LimitParam(param types.Param) *CompoundBuilder
- func (cb *CompoundBuilder) MustBuild() *types.CompoundQuery
- func (cb *CompoundBuilder) MustRender(renderer Renderer) *QueryResult
- func (cb *CompoundBuilder) Offset(offset int) *CompoundBuilder
- func (cb *CompoundBuilder) OffsetParam(param types.Param) *CompoundBuilder
- func (cb *CompoundBuilder) OrderBy(f types.Field, direction types.Direction) *CompoundBuilder
- func (cb *CompoundBuilder) OrderByNulls(f types.Field, direction types.Direction, nulls types.NullsOrdering) *CompoundBuilder
- func (cb *CompoundBuilder) Render(renderer Renderer) (*QueryResult, error)
- func (cb *CompoundBuilder) Union(other *Builder) *CompoundBuilder
- func (cb *CompoundBuilder) UnionAll(other *Builder) *CompoundBuilder
- type CompoundQuery
- type ConditionItem
- type ConflictBuilder
- type Direction
- type FrameBound
- type NullsOrdering
- type Operation
- type Operator
- type QueryResult
- type Renderer
- type SetOperand
- type SetOperation
- type UpdateBuilder
- type WindowBuilder
- func AvgOver(field types.Field) *WindowBuilder
- func CountOver(field ...types.Field) *WindowBuilder
- func DenseRank() *WindowBuilder
- func FirstValue(field types.Field) *WindowBuilder
- func Lag(field types.Field, offset types.Param, defaultVal ...types.Param) *WindowBuilder
- func LastValue(field types.Field) *WindowBuilder
- func Lead(field types.Field, offset types.Param, defaultVal ...types.Param) *WindowBuilder
- func MaxOver(field types.Field) *WindowBuilder
- func MinOver(field types.Field) *WindowBuilder
- func Ntile(n types.Param) *WindowBuilder
- func Rank() *WindowBuilder
- func RowNumber() *WindowBuilder
- func SumOver(field types.Field) *WindowBuilder
- func (wb *WindowBuilder) As(alias string) types.FieldExpression
- func (wb *WindowBuilder) Build() types.FieldExpression
- func (wb *WindowBuilder) Frame(start, end types.FrameBound) *WindowBuilder
- func (wb *WindowBuilder) OrderBy(field types.Field, direction types.Direction) *WindowBuilder
- func (wb *WindowBuilder) Over(spec types.WindowSpec) *WindowBuilder
- func (wb *WindowBuilder) OverBuilder(builder *WindowSpecBuilder) *WindowBuilder
- func (wb *WindowBuilder) PartitionBy(fields ...types.Field) *WindowBuilder
- type WindowFunc
- type WindowSpec
- type WindowSpecBuilder
- func (wsb *WindowSpecBuilder) Build() types.WindowSpec
- func (wsb *WindowSpecBuilder) OrderBy(field types.Field, direction types.Direction) *WindowSpecBuilder
- func (wsb *WindowSpecBuilder) OrderByNulls(field types.Field, direction types.Direction, nulls types.NullsOrdering) *WindowSpecBuilder
- func (wsb *WindowSpecBuilder) PartitionBy(fields ...types.Field) *WindowSpecBuilder
- func (wsb *WindowSpecBuilder) Rows(start, end types.FrameBound) *WindowSpecBuilder
Constants ¶
const ( OpSelect = types.OpSelect OpInsert = types.OpInsert OpUpdate = types.OpUpdate OpDelete = types.OpDelete OpCount = types.OpCount )
Re-export operation constants for public API.
const ( ASC = types.ASC DESC = types.DESC )
Re-export direction constants for public API.
const ( NullsFirst = types.NullsFirst NullsLast = types.NullsLast )
Re-export nulls ordering constants for public API.
const ( // Basic comparison operators. EQ = types.EQ NE = types.NE GT = types.GT GE = types.GE LT = types.LT LE = types.LE // Extended operators. IN = types.IN NotIn = types.NotIn LIKE = types.LIKE NotLike = types.NotLike ILIKE = types.ILIKE NotILike = types.NotILike IsNull = types.IsNull IsNotNull = types.IsNotNull EXISTS = types.EXISTS NotExists = types.NotExists // Regex operators (PostgreSQL). RegexMatch = types.RegexMatch RegexIMatch = types.RegexIMatch NotRegexMatch = types.NotRegexMatch NotRegexIMatch = types.NotRegexIMatch // Array operators (PostgreSQL). ArrayContains = types.ArrayContains ArrayContainedBy = types.ArrayContainedBy ArrayOverlap = types.ArrayOverlap // Vector operators (pgvector). VectorL2Distance = types.VectorL2Distance VectorInnerProduct = types.VectorInnerProduct VectorCosineDistance = types.VectorCosineDistance VectorL1Distance = types.VectorL1Distance )
Re-export operator constants for public API.
const ( AggSum = types.AggSum AggAvg = types.AggAvg AggMin = types.AggMin AggMax = types.AggMax AggCountField = types.AggCountField AggCountDistinct = types.AggCountDistinct )
Re-export aggregate function constants for public API.
const ( CastText = types.CastText CastInteger = types.CastInteger CastBigint = types.CastBigint CastSmallint = types.CastSmallint CastNumeric = types.CastNumeric CastReal = types.CastReal CastDoublePrecision = types.CastDoublePrecision CastBoolean = types.CastBoolean CastDate = types.CastDate CastTime = types.CastTime CastTimestamp = types.CastTimestamp CastTimestampTZ = types.CastTimestampTZ CastInterval = types.CastInterval CastUUID = types.CastUUID CastJSON = types.CastJSON CastJSONB = types.CastJSONB CastBytea = types.CastBytea )
Re-export cast type constants for public API.
const ( WinRowNumber = types.WinRowNumber WinRank = types.WinRank WinDenseRank = types.WinDenseRank WinNtile = types.WinNtile WinLag = types.WinLag WinLead = types.WinLead WinFirstValue = types.WinFirstValue WinLastValue = types.WinLastValue )
Re-export window function constants for public API.
const ( FrameUnboundedPreceding = types.FrameUnboundedPreceding FrameCurrentRow = types.FrameCurrentRow FrameUnboundedFollowing = types.FrameUnboundedFollowing )
Re-export frame bound constants for public API.
const ( SetUnion = types.SetUnion SetUnionAll = types.SetUnionAll SetIntersect = types.SetIntersect SetIntersectAll = types.SetIntersectAll SetExcept = types.SetExcept SetExceptAll = types.SetExceptAll )
Re-export set operation constants for public API.
Variables ¶
This section is empty.
Functions ¶
func As ¶
func As(expr types.FieldExpression, alias string) types.FieldExpression
As adds an alias to a field expression.
func Avg ¶
func Avg(field types.Field) types.FieldExpression
Avg creates an AVG aggregate expression.
func AvgFilter ¶
func AvgFilter(field types.Field, filter types.ConditionItem) types.FieldExpression
AvgFilter creates an AVG aggregate with a FILTER clause.
func BinaryExpr ¶
BinaryExpr creates a binary expression for field <op> param patterns. Commonly used for vector distance calculations, e.g., embedding <-> :query Example: BinaryExpr(embedding, VectorL2Distance, query) -> "embedding" <-> :query
func CSubExists ¶
CSubExists creates an EXISTS/NOT EXISTS subquery condition.
func Coalesce ¶
func Coalesce(values ...types.Param) types.FieldExpression
Coalesce creates a COALESCE expression that returns the first non-null value.
func Concat ¶
func Concat(fields ...types.Field) types.FieldExpression
Concat creates a CONCAT string expression with multiple fields. Example: Concat(field1, field2) -> CONCAT("field1", "field2")
func CountDistinct ¶
func CountDistinct(field types.Field) types.FieldExpression
CountDistinct creates a COUNT(DISTINCT) aggregate expression.
func CountDistinctFilter ¶
func CountDistinctFilter(field types.Field, filter types.ConditionItem) types.FieldExpression
CountDistinctFilter creates a COUNT(DISTINCT field) aggregate with a FILTER clause.
func CountField ¶
func CountField(field types.Field) types.FieldExpression
CountField creates a COUNT aggregate expression for a specific field.
func CountFieldFilter ¶
func CountFieldFilter(field types.Field, filter types.ConditionItem) types.FieldExpression
CountFieldFilter creates a COUNT(field) aggregate with a FILTER clause.
func CountStar ¶
func CountStar() types.FieldExpression
CountStar creates a COUNT(*) aggregate expression for use in SELECT.
func CurrentDate ¶
func CurrentDate() types.FieldExpression
CurrentDate creates a CURRENT_DATE expression returning current date. Example: CurrentDate() -> CURRENT_DATE
func CurrentTime ¶
func CurrentTime() types.FieldExpression
CurrentTime creates a CURRENT_TIME expression returning current time. Example: CurrentTime() -> CURRENT_TIME
func CurrentTimestamp ¶
func CurrentTimestamp() types.FieldExpression
CurrentTimestamp creates a CURRENT_TIMESTAMP expression. Example: CurrentTimestamp() -> CURRENT_TIMESTAMP
func DateTrunc ¶
DateTrunc creates a DATE_TRUNC expression to truncate to specified precision. Example: DateTrunc(PartMonth, field) -> DATE_TRUNC('month', "field")
func Extract ¶
Extract creates an EXTRACT expression to get a part of a date/time field. Example: Extract(PartYear, field) -> EXTRACT(YEAR FROM "field")
func Floor ¶
func Floor(field types.Field) types.FieldExpression
Floor creates a FLOOR math expression.
func HavingCount ¶
Example: HavingCount(GT, param) -> HAVING COUNT(*) > :param.
func HavingCountDistinct ¶
func HavingCountDistinct(field types.Field, op types.Operator, value types.Param) types.AggregateCondition
HavingCountDistinct creates a HAVING COUNT(DISTINCT field) condition.
func HavingCountField ¶
func HavingCountField(field types.Field, op types.Operator, value types.Param) types.AggregateCondition
Example: HavingCountField(field, GT, param) -> HAVING COUNT("field") > :param.
func LTrim ¶
func LTrim(field types.Field) types.FieldExpression
LTrim creates an LTRIM string expression. Example: LTrim(field) -> LTRIM("field")
func Length ¶
func Length(field types.Field) types.FieldExpression
Length creates a LENGTH string expression. Example: Length(field) -> LENGTH("field")
func Lower ¶
func Lower(field types.Field) types.FieldExpression
Lower creates a LOWER string expression. Example: Lower(field) -> LOWER("field")
func Max ¶
func Max(field types.Field) types.FieldExpression
Max creates a MAX aggregate expression.
func MaxFilter ¶
func MaxFilter(field types.Field, filter types.ConditionItem) types.FieldExpression
MaxFilter creates a MAX aggregate with a FILTER clause.
func Min ¶
func Min(field types.Field) types.FieldExpression
Min creates a MIN aggregate expression.
func MinFilter ¶
func MinFilter(field types.Field, filter types.ConditionItem) types.FieldExpression
MinFilter creates a MIN aggregate with a FILTER clause.
func NotBetween ¶
Example: NotBetween(field, low, high) -> field NOT BETWEEN :low AND :high.
func Now ¶
func Now() types.FieldExpression
Now creates a NOW() date expression returning current timestamp. Example: Now() -> NOW()
func NullIf ¶
func NullIf(value1, value2 types.Param) types.FieldExpression
NullIf creates a NULLIF expression that returns NULL if two values are equal.
func RTrim ¶
func RTrim(field types.Field) types.FieldExpression
RTrim creates an RTRIM string expression. Example: RTrim(field) -> RTRIM("field")
func Replace ¶
Replace creates a REPLACE string expression. Example: Replace(field, search, replacement) -> REPLACE("field", :search, :replacement)
func Substring ¶
Substring creates a SUBSTRING string expression. Example: Substring(field, start, length) -> SUBSTRING("field", :start, :length)
func Sum ¶
func Sum(field types.Field) types.FieldExpression
Sum creates a SUM aggregate expression.
func SumFilter ¶
func SumFilter(field types.Field, filter types.ConditionItem) types.FieldExpression
Example: SumFilter(field, condition) -> SUM("field") FILTER (WHERE condition).
Types ¶
type AST ¶
AST represents the abstract syntax tree for a query. This is re-exported from internal/types for use by consumers.
type ASTQL ¶
type ASTQL struct {
// contains filtered or unexported fields
}
ASTQL represents an instance of the query builder with a specific DBML schema.
func NewFromDBML ¶
NewFromDBML creates a new ASTQL instance from a DBML project.
func (*ASTQL) AggC ¶
func (a *ASTQL) AggC(aggFunc types.AggregateFunc, field *types.Field, op types.Operator, param types.Param) types.AggregateCondition
AggC creates a validated aggregate condition for HAVING clauses. Use nil for field to create COUNT(*).
func (*ASTQL) And ¶
func (a *ASTQL) And(conditions ...types.ConditionItem) types.ConditionGroup
And creates an AND condition group.
func (*ASTQL) ArrayContainedBy ¶
ArrayContainedBy returns the array contained by operator constant (PostgreSQL <@).
func (*ASTQL) ArrayContains ¶
ArrayContains returns the array contains operator constant (PostgreSQL @>).
func (*ASTQL) ArrayOverlap ¶
ArrayOverlap returns the array overlap operator constant (PostgreSQL &&).
func (*ASTQL) ConditionItems ¶
func (*ASTQL) ConditionItems() []types.ConditionItem
ConditionItems returns an empty slice of ConditionItem for programmatic query building.
func (*ASTQL) Conditions ¶
Conditions returns an empty slice of Condition for programmatic query building.
func (*ASTQL) GetInstance ¶
GetInstance returns the ASTQL instance (for use by provider packages).
func (*ASTQL) JSONBPath ¶
JSONBPath creates a field with JSONB path access (->). The key is parameterized for safety - renders as: field->:key_param Example: JSONBPath(metadata, P("tags_key")) -> "metadata"->:tags_key
func (*ASTQL) JSONBText ¶
JSONBText creates a field with JSONB text extraction (->>). The key is parameterized for safety - renders as: field->>:key_param Example: JSONBText(metadata, P("status_key")) -> "metadata"->>:status_key
func (*ASTQL) NotRegexIMatch ¶
NotRegexIMatch returns the case-insensitive regex non-match operator constant (PostgreSQL !~*).
func (*ASTQL) NotRegexMatch ¶
NotRegexMatch returns the regex non-match operator constant (PostgreSQL !~).
func (*ASTQL) Or ¶
func (a *ASTQL) Or(conditions ...types.ConditionItem) types.ConditionGroup
Or creates an OR condition group.
func (*ASTQL) RegexIMatch ¶
RegexIMatch returns the case-insensitive regex match operator constant (PostgreSQL ~*).
func (*ASTQL) RegexMatch ¶
RegexMatch returns the regex match operator constant (PostgreSQL ~).
func (*ASTQL) TryAggC ¶
func (a *ASTQL) TryAggC(aggFunc types.AggregateFunc, field *types.Field, op types.Operator, param types.Param) (types.AggregateCondition, error)
TryAggC creates a validated aggregate condition for HAVING clauses. Use nil for field to create COUNT(*).
func (*ASTQL) TryAnd ¶
func (*ASTQL) TryAnd(conditions ...types.ConditionItem) (types.ConditionGroup, error)
TryAnd creates an AND condition group, returning an error if invalid.
func (*ASTQL) TryC ¶
func (a *ASTQL) TryC(field types.Field, op types.Operator, param types.Param) (types.Condition, error)
TryC creates a validated condition, returning an error if invalid.
func (*ASTQL) TryNotNull ¶
TryNotNull creates a NOT NULL condition, returning an error if invalid.
func (*ASTQL) TryOr ¶
func (*ASTQL) TryOr(conditions ...types.ConditionItem) (types.ConditionGroup, error)
TryOr creates an OR condition group, returning an error if invalid.
func (*ASTQL) TryWithTable ¶
TryWithTable creates a new Field with a table/alias prefix, returning an error if invalid.
func (*ASTQL) VectorCosineDistance ¶
VectorCosineDistance returns the vector cosine distance operator constant (pgvector <=>).
func (*ASTQL) VectorInnerProduct ¶
VectorInnerProduct returns the vector negative inner product operator constant (pgvector <#>).
func (*ASTQL) VectorL1Distance ¶
VectorL1Distance returns the vector L1/Manhattan distance operator constant (pgvector <+>).
func (*ASTQL) VectorL2Distance ¶
VectorL2Distance returns the vector L2/Euclidean distance operator constant (pgvector <->).
type AggregateCondition ¶
type AggregateCondition = types.AggregateCondition
AggregateCondition represents a HAVING condition on an aggregate function. Use with Builder.HavingAgg() for conditions like COUNT(*) > 10.
type AggregateFunc ¶
type AggregateFunc = types.AggregateFunc
AggregateFunc represents SQL aggregate functions.
type BetweenCondition ¶
type BetweenCondition = types.BetweenCondition
BetweenCondition represents a BETWEEN condition with two bounds.
type BinaryExpression ¶
type BinaryExpression = types.BinaryExpression
BinaryExpression represents a binary operation between a field and a parameter. Used for expressions like vector distance calculations: field <-> :param
type Builder ¶
type Builder struct {
// contains filtered or unexported fields
}
Builder provides a fluent API for constructing queries.
func (*Builder) DistinctOn ¶
DistinctOn sets DISTINCT ON fields for SELECT queries (PostgreSQL). The query will return only the first row for each unique combination of the specified fields.
func (*Builder) Except ¶
func (b *Builder) Except(other *Builder) *CompoundBuilder
Except creates an EXCEPT between two queries.
func (*Builder) ExceptAll ¶
func (b *Builder) ExceptAll(other *Builder) *CompoundBuilder
ExceptAll creates an EXCEPT ALL between two queries.
func (*Builder) ForKeyShare ¶
ForKeyShare adds FOR KEY SHARE row locking.
func (*Builder) ForNoKeyUpdate ¶
ForNoKeyUpdate adds FOR NO KEY UPDATE row locking.
func (*Builder) FullOuterJoin ¶
FullOuterJoin adds a FULL OUTER JOIN.
func (*Builder) Having ¶
Having adds HAVING conditions (simple field-based conditions). For aggregate conditions like COUNT(*) > 10, use HavingAgg instead.
func (*Builder) HavingAgg ¶
func (b *Builder) HavingAgg(conditions ...types.AggregateCondition) *Builder
HavingAgg adds aggregate HAVING conditions like COUNT(*) > :min_count. Use this for conditions on aggregate functions (COUNT, SUM, AVG, MIN, MAX).
func (*Builder) Intersect ¶
func (b *Builder) Intersect(other *Builder) *CompoundBuilder
Intersect creates an INTERSECT between two queries.
func (*Builder) IntersectAll ¶
func (b *Builder) IntersectAll(other *Builder) *CompoundBuilder
IntersectAll creates an INTERSECT ALL between two queries.
func (*Builder) LimitParam ¶
LimitParam sets the limit to a parameterized value.
func (*Builder) MustRender ¶
func (b *Builder) MustRender(renderer Renderer) *QueryResult
MustRender builds and renders the AST with the provided renderer, or panics on error.
func (*Builder) OffsetParam ¶
OffsetParam sets the offset to a parameterized value.
func (*Builder) OnConflict ¶
func (b *Builder) OnConflict(columns ...types.Field) *ConflictBuilder
OnConflict adds ON CONFLICT clause for INSERT.
func (*Builder) OrderByExpr ¶
func (b *Builder) OrderByExpr(f types.Field, op types.Operator, p types.Param, direction types.Direction) *Builder
OrderByExpr is useful for vector distance ordering: ORDER BY embedding <-> :query_vector ASC.
func (*Builder) OrderByNulls ¶
func (b *Builder) OrderByNulls(f types.Field, direction types.Direction, nulls types.NullsOrdering) *Builder
OrderByNulls adds ordering with NULLS FIRST/LAST.
func (*Builder) Render ¶
func (b *Builder) Render(renderer Renderer) (*QueryResult, error)
Render builds the AST and renders it using the provided renderer.
func (*Builder) SelectBinaryExpr ¶
func (b *Builder) SelectBinaryExpr(f types.Field, op types.Operator, p types.Param, alias string) *Builder
SelectBinaryExpr adds a binary expression (field <op> param) AS alias to SELECT. Useful for vector distance calculations with pgvector.
Example:
builder.SelectBinaryExpr(f, VectorCosineDistance, p, "score") // Renders: "field" <=> :param AS "score"
func (*Builder) SelectExpr ¶
func (b *Builder) SelectExpr(expr types.FieldExpression) *Builder
SelectExpr adds a field expression (aggregate, case, etc) to SELECT.
func (*Builder) SetExpr ¶
SetExpr adds a field update with an expression value for UPDATE queries. Use this for computed assignments like `items_completed = items_completed + :increment`.
func (*Builder) Union ¶
func (b *Builder) Union(other *Builder) *CompoundBuilder
Union creates a UNION between two queries.
func (*Builder) UnionAll ¶
func (b *Builder) UnionAll(other *Builder) *CompoundBuilder
UnionAll creates a UNION ALL between two queries.
func (*Builder) Values ¶
Values adds a row of field-value pairs for INSERT queries. Call Values() multiple times to insert multiple rows. Use instance.ValueMap() to create the map programmatically.
type CaseBuilder ¶
type CaseBuilder struct {
// contains filtered or unexported fields
}
CaseBuilder provides fluent API for building CASE expressions.
func (*CaseBuilder) As ¶
func (cb *CaseBuilder) As(alias string) *CaseBuilder
As adds an alias to the CASE expression.
func (*CaseBuilder) Build ¶
func (cb *CaseBuilder) Build() types.FieldExpression
Build returns the CaseExpression wrapped in a FieldExpression.
func (*CaseBuilder) Else ¶
func (cb *CaseBuilder) Else(result types.Param) *CaseBuilder
Else sets the ELSE clause.
func (*CaseBuilder) When ¶
func (cb *CaseBuilder) When(condition types.ConditionItem, result types.Param) *CaseBuilder
When adds a WHEN...THEN clause.
type CompoundBuilder ¶
type CompoundBuilder struct {
// contains filtered or unexported fields
}
CompoundBuilder handles building compound queries with set operations.
func Except ¶
func Except(first, second *Builder) *CompoundBuilder
Except creates an EXCEPT between two queries (standalone function).
func ExceptAll ¶
func ExceptAll(first, second *Builder) *CompoundBuilder
ExceptAll creates an EXCEPT ALL between two queries (standalone function).
func Intersect ¶
func Intersect(first, second *Builder) *CompoundBuilder
Intersect creates an INTERSECT between two queries (standalone function).
func IntersectAll ¶
func IntersectAll(first, second *Builder) *CompoundBuilder
IntersectAll creates an INTERSECT ALL between two queries (standalone function).
func Union ¶
func Union(first, second *Builder) *CompoundBuilder
Union creates a UNION between two queries (standalone function).
func UnionAll ¶
func UnionAll(first, second *Builder) *CompoundBuilder
UnionAll creates a UNION ALL between two queries (standalone function).
func (*CompoundBuilder) Build ¶
func (cb *CompoundBuilder) Build() (*types.CompoundQuery, error)
Build returns the CompoundQuery or an error.
func (*CompoundBuilder) Except ¶
func (cb *CompoundBuilder) Except(other *Builder) *CompoundBuilder
Except adds an EXCEPT to the compound query.
func (*CompoundBuilder) ExceptAll ¶
func (cb *CompoundBuilder) ExceptAll(other *Builder) *CompoundBuilder
ExceptAll adds an EXCEPT ALL to the compound query.
func (*CompoundBuilder) Intersect ¶
func (cb *CompoundBuilder) Intersect(other *Builder) *CompoundBuilder
Intersect adds an INTERSECT to the compound query.
func (*CompoundBuilder) IntersectAll ¶
func (cb *CompoundBuilder) IntersectAll(other *Builder) *CompoundBuilder
IntersectAll adds an INTERSECT ALL to the compound query.
func (*CompoundBuilder) Limit ¶
func (cb *CompoundBuilder) Limit(limit int) *CompoundBuilder
Limit sets the limit for the compound query to a static integer value.
func (*CompoundBuilder) LimitParam ¶
func (cb *CompoundBuilder) LimitParam(param types.Param) *CompoundBuilder
LimitParam sets the limit for the compound query to a parameterized value.
func (*CompoundBuilder) MustBuild ¶
func (cb *CompoundBuilder) MustBuild() *types.CompoundQuery
MustBuild returns the CompoundQuery or panics on error.
func (*CompoundBuilder) MustRender ¶
func (cb *CompoundBuilder) MustRender(renderer Renderer) *QueryResult
MustRender builds and renders the compound query with the provided renderer, or panics on error.
func (*CompoundBuilder) Offset ¶
func (cb *CompoundBuilder) Offset(offset int) *CompoundBuilder
Offset sets the offset for the compound query to a static integer value.
func (*CompoundBuilder) OffsetParam ¶
func (cb *CompoundBuilder) OffsetParam(param types.Param) *CompoundBuilder
OffsetParam sets the offset for the compound query to a parameterized value.
func (*CompoundBuilder) OrderBy ¶
func (cb *CompoundBuilder) OrderBy(f types.Field, direction types.Direction) *CompoundBuilder
OrderBy adds final ordering to the compound query.
func (*CompoundBuilder) OrderByNulls ¶
func (cb *CompoundBuilder) OrderByNulls(f types.Field, direction types.Direction, nulls types.NullsOrdering) *CompoundBuilder
OrderByNulls adds final ordering with NULLS FIRST/LAST to the compound query.
func (*CompoundBuilder) Render ¶
func (cb *CompoundBuilder) Render(renderer Renderer) (*QueryResult, error)
Render builds and renders the compound query using the provided renderer.
func (*CompoundBuilder) Union ¶
func (cb *CompoundBuilder) Union(other *Builder) *CompoundBuilder
Union adds a UNION to the compound query.
func (*CompoundBuilder) UnionAll ¶
func (cb *CompoundBuilder) UnionAll(other *Builder) *CompoundBuilder
UnionAll adds a UNION ALL to the compound query.
type CompoundQuery ¶
type CompoundQuery = types.CompoundQuery
CompoundQuery represents a query with set operations.
type ConditionItem ¶
type ConditionItem = types.ConditionItem
ConditionItem represents either a single condition or a group of conditions.
type ConflictBuilder ¶
type ConflictBuilder struct {
// contains filtered or unexported fields
}
ConflictBuilder handles ON CONFLICT actions.
func (*ConflictBuilder) DoNothing ¶
func (cb *ConflictBuilder) DoNothing() *Builder
DoNothing sets the conflict action to DO NOTHING.
func (*ConflictBuilder) DoUpdate ¶
func (cb *ConflictBuilder) DoUpdate() *UpdateBuilder
DoUpdate sets the conflict action to DO UPDATE.
type NullsOrdering ¶
type NullsOrdering = types.NullsOrdering
NullsOrdering represents NULL ordering in ORDER BY.
type QueryResult ¶
type QueryResult = types.QueryResult
QueryResult contains the rendered SQL and required parameters.
type Renderer ¶
type Renderer interface {
// Render converts an AST to a QueryResult with dialect-specific SQL.
Render(ast *types.AST) (*types.QueryResult, error)
// RenderCompound converts a CompoundQuery (UNION, INTERSECT, EXCEPT) to SQL.
RenderCompound(query *types.CompoundQuery) (*types.QueryResult, error)
// Capabilities returns the SQL features supported by this dialect.
Capabilities() render.Capabilities
}
Renderer defines the interface for SQL dialect-specific rendering. Implementations convert an AST to dialect-specific SQL with named parameters.
type SetOperand ¶
type SetOperand = types.SetOperand
SetOperand represents one operand in a set operation.
type SetOperation ¶
type SetOperation = types.SetOperation
SetOperation represents SQL set operations (UNION, INTERSECT, EXCEPT).
type UpdateBuilder ¶
type UpdateBuilder struct {
// contains filtered or unexported fields
}
UpdateBuilder handles DO UPDATE SET clause construction.
func (*UpdateBuilder) Build ¶
func (ub *UpdateBuilder) Build() *Builder
Build finalizes the update and returns the builder.
func (*UpdateBuilder) Set ¶
func (ub *UpdateBuilder) Set(field types.Field, param types.Param) *UpdateBuilder
Set adds a field to update on conflict.
type WindowBuilder ¶
type WindowBuilder struct {
// contains filtered or unexported fields
}
WindowBuilder provides a fluent API for building window function expressions.
func AvgOver ¶
func AvgOver(field types.Field) *WindowBuilder
AvgOver creates an AVG() OVER window function.
func CountOver ¶
func CountOver(field ...types.Field) *WindowBuilder
CountOver creates a COUNT(field) OVER window function.
func FirstValue ¶
func FirstValue(field types.Field) *WindowBuilder
FirstValue creates a FIRST_VALUE(field) window function.
func LastValue ¶
func LastValue(field types.Field) *WindowBuilder
LastValue creates a LAST_VALUE(field) window function.
func MaxOver ¶
func MaxOver(field types.Field) *WindowBuilder
MaxOver creates a MAX() OVER window function.
func MinOver ¶
func MinOver(field types.Field) *WindowBuilder
MinOver creates a MIN() OVER window function.
func SumOver ¶
func SumOver(field types.Field) *WindowBuilder
SumOver creates a SUM() OVER window function.
func (*WindowBuilder) As ¶
func (wb *WindowBuilder) As(alias string) types.FieldExpression
As adds an alias to the window function and returns a FieldExpression.
func (*WindowBuilder) Build ¶
func (wb *WindowBuilder) Build() types.FieldExpression
Build returns the FieldExpression without an alias.
func (*WindowBuilder) Frame ¶
func (wb *WindowBuilder) Frame(start, end types.FrameBound) *WindowBuilder
Frame sets the frame clause with ROWS BETWEEN (convenience method).
func (*WindowBuilder) OrderBy ¶
func (wb *WindowBuilder) OrderBy(field types.Field, direction types.Direction) *WindowBuilder
OrderBy adds ORDER BY to the window specification (convenience method).
func (*WindowBuilder) Over ¶
func (wb *WindowBuilder) Over(spec types.WindowSpec) *WindowBuilder
Over sets the window specification for a window function.
func (*WindowBuilder) OverBuilder ¶
func (wb *WindowBuilder) OverBuilder(builder *WindowSpecBuilder) *WindowBuilder
OverBuilder sets the window specification from a builder.
func (*WindowBuilder) PartitionBy ¶
func (wb *WindowBuilder) PartitionBy(fields ...types.Field) *WindowBuilder
PartitionBy adds PARTITION BY fields (convenience method).
type WindowSpecBuilder ¶
type WindowSpecBuilder struct {
// contains filtered or unexported fields
}
WindowSpecBuilder provides a fluent API for building window specifications.
func Window ¶
func Window() *WindowSpecBuilder
Window creates a new WindowSpec for use with window functions.
func (*WindowSpecBuilder) Build ¶
func (wsb *WindowSpecBuilder) Build() types.WindowSpec
Build returns the WindowSpec.
func (*WindowSpecBuilder) OrderBy ¶
func (wsb *WindowSpecBuilder) OrderBy(field types.Field, direction types.Direction) *WindowSpecBuilder
OrderBy adds ORDER BY to the window specification.
func (*WindowSpecBuilder) OrderByNulls ¶
func (wsb *WindowSpecBuilder) OrderByNulls(field types.Field, direction types.Direction, nulls types.NullsOrdering) *WindowSpecBuilder
OrderByNulls adds ORDER BY with NULLS ordering to the window specification.
func (*WindowSpecBuilder) PartitionBy ¶
func (wsb *WindowSpecBuilder) PartitionBy(fields ...types.Field) *WindowSpecBuilder
PartitionBy adds PARTITION BY fields to the window specification.
func (*WindowSpecBuilder) Rows ¶
func (wsb *WindowSpecBuilder) Rows(start, end types.FrameBound) *WindowSpecBuilder
Rows sets the frame clause with ROWS BETWEEN.
Directories
¶
| Path | Synopsis |
|---|---|
|
internal
|
|
|
Package mariadb provides the MariaDB dialect renderer for astql.
|
Package mariadb provides the MariaDB dialect renderer for astql. |
|
Package mssql provides the SQL Server dialect renderer for astql.
|
Package mssql provides the SQL Server dialect renderer for astql. |
|
Package postgres provides the PostgreSQL dialect renderer for astql.
|
Package postgres provides the PostgreSQL dialect renderer for astql. |
|
Package sqlite provides the SQLite dialect renderer for astql.
|
Package sqlite provides the SQLite dialect renderer for astql. |
|
Package testing provides test utilities for astql.
|
Package testing provides test utilities for astql. |