Documentation
¶
Overview ¶
Package ast provides Abstract Syntax Tree (AST) node definitions, visitor-based traversal, and SQL() serialization for SQL statements parsed by GoSQLX.
Key types include AST (the root container), Statement (SelectStatement, InsertStatement, UpdateStatement, DeleteStatement, MergeStatement, etc.), Expression (Identifier, BinaryExpression, FunctionCall, CaseExpression, etc.), and WindowSpec for window-function specifications. Use NewAST/ReleaseAST, GetSelectStatement/PutSelectStatement, and analogous pool helpers to minimize allocations. Traverse any AST with Walk (Visitor interface) or Inspect (function-based). Call SQL() on any node to serialize it back to a SQL string.
This package implements a comprehensive AST representation for SQL with support for multiple SQL dialects (PostgreSQL, MySQL, SQL Server, Oracle, SQLite). It includes extensive object pooling for memory efficiency and high-performance SQL parsing.
Architecture Overview ¶
The AST package follows a hierarchical node structure with three primary interfaces:
- Node: Base interface for all AST nodes (TokenLiteral, Children methods)
- Statement: Interface for SQL statements (SELECT, INSERT, UPDATE, DELETE, etc.)
- Expression: Interface for SQL expressions (binary ops, functions, literals, etc.)
All AST nodes implement the Node interface, providing a uniform way to traverse and inspect the syntax tree using the visitor pattern.
Node Interface Hierarchy ¶
Node (base interface)
├── Statement (SQL statements)
│ ├── SelectStatement
│ ├── InsertStatement
│ ├── UpdateStatement
│ ├── DeleteStatement
│ ├── CreateTableStatement
│ ├── MergeStatement
│ ├── TruncateStatement
│ ├── DropStatement
│ ├── CreateViewStatement
│ ├── CreateMaterializedViewStatement
│ ├── WithClause (CTEs)
│ └── SetOperation (UNION, EXCEPT, INTERSECT)
└── Expression (SQL expressions)
├── Identifier
├── LiteralValue
├── BinaryExpression
├── UnaryExpression
├── FunctionCall
├── CaseExpression
├── BetweenExpression
├── InExpression
├── ExistsExpression
├── SubqueryExpression
├── CastExpression
└── AliasedExpression
Object Pooling for Performance ¶
The ast package provides extensive object pooling to minimize memory allocations and improve performance in high-throughput scenarios. Object pools are available for all major AST node types.
Pool Usage Pattern (MANDATORY for optimal performance):
// Get AST from pool astObj := ast.NewAST() defer ast.ReleaseAST(astObj) // ALWAYS use defer to prevent leaks // Get statements from pools stmt := ast.GetSelectStatement() defer ast.PutSelectStatement(stmt) // Get expressions from pools expr := ast.GetBinaryExpression() defer ast.PutBinaryExpression(expr) // Use pooled objects // ... build and use AST nodes ...
Available Pools:
- AST Pool: NewAST() / ReleaseAST()
- Statement Pools: GetSelectStatement(), GetInsertStatement(), GetUpdateStatement(), GetDeleteStatement()
- Expression Pools: GetIdentifier(), GetBinaryExpression(), GetLiteralValue(), GetFunctionCall(), etc.
- Slice Pools: GetExpressionSlice() / PutExpressionSlice()
Performance Impact: Object pooling provides 60-80% memory reduction and significantly reduces GC pressure in production workloads with 95%+ pool hit rates.
Visitor Pattern for Tree Traversal ¶
The package provides a visitor pattern implementation for traversing and inspecting AST nodes. The visitor pattern is defined in visitor.go and provides two interfaces:
- Visitor: Standard visitor interface with Visit(Node) method
- Inspector: Simplified function-based visitor
Example - Walking the AST tree:
// Using the Visitor interface
type MyVisitor struct {
depth int
}
func (v *MyVisitor) Visit(node ast.Node) (ast.Visitor, error) {
if node == nil {
return nil, nil
}
fmt.Printf("Visiting: %s at depth %d\n", node.TokenLiteral(), v.depth)
return &MyVisitor{depth: v.depth + 1}, nil
}
visitor := &MyVisitor{depth: 0}
ast.Walk(visitor, astNode)
Example - Using Inspector for simplified traversal:
// Count all SELECT statements in the AST
selectCount := 0
ast.Inspect(astNode, func(n ast.Node) bool {
if _, ok := n.(*ast.SelectStatement); ok {
selectCount++
}
return true // Continue traversal
})
Example - Finding specific node types:
// Find all binary expressions with AND operator
var andExprs []*ast.BinaryExpression
ast.Inspect(astNode, func(n ast.Node) bool {
if binExpr, ok := n.(*ast.BinaryExpression); ok {
if binExpr.Operator == "AND" {
andExprs = append(andExprs, binExpr)
}
}
return true
})
SQL Feature Support ¶
Version 1.6.0 Feature Matrix:
Core SQL Features:
- DDL: CREATE TABLE, ALTER TABLE, DROP TABLE, CREATE INDEX
- DML: SELECT, INSERT, UPDATE, DELETE with full expression support
- JOINs: All join types (INNER, LEFT, RIGHT, FULL, CROSS, NATURAL)
- Subqueries: Scalar subqueries, correlated subqueries, table subqueries
- CTEs: WITH clause, recursive CTEs, materialized/non-materialized hints
- Set Operations: UNION, EXCEPT, INTERSECT (with ALL modifier support)
- Window Functions: Complete SQL-99 window function support with frames
Advanced SQL-99/SQL:2003 Features:
- GROUPING SETS, ROLLUP, CUBE: Advanced aggregation (SQL-99 T431)
- MERGE: MERGE INTO statements (SQL:2003 F312)
- FETCH: FETCH FIRST/NEXT clause (SQL-99 F861, F862)
- Materialized Views: CREATE/REFRESH MATERIALIZED VIEW
- TRUNCATE: TRUNCATE TABLE with RESTART/CONTINUE IDENTITY
Expression Operators:
- BETWEEN: Range expressions with NOT modifier
- IN: Value list and subquery membership tests
- LIKE/ILIKE: Pattern matching with wildcards
- IS NULL/IS NOT NULL: Null checking
- EXISTS: Existential quantification over subqueries
- ANY/ALL: Quantified comparison predicates
PostgreSQL Extensions (v1.6.0):
- LATERAL JOIN: Correlated table subqueries in FROM clause
- DISTINCT ON: PostgreSQL-specific row selection
- FILTER Clause: Conditional aggregation (aggregate FILTER (WHERE condition))
- RETURNING Clause: Return modified rows from INSERT/UPDATE/DELETE
- JSON/JSONB Operators: ->, ->>, #>, #>>, @>, <@, ?, ?|, ?&, #-
- NULLS FIRST/LAST: Explicit null ordering in ORDER BY
Statement Types ¶
DML Statements:
SelectStatement: SELECT queries with full SQL-99 feature support Fields: Columns, From, Joins, Where, GroupBy, Having, OrderBy, Limit, Offset, Fetch New in v1.6.0: DistinctOnColumns (DISTINCT ON), Fetch (FETCH FIRST/NEXT)
InsertStatement: INSERT INTO statements Fields: TableName, Columns, Values, Query (INSERT...SELECT), Returning, OnConflict New in v1.6.0: Returning clause support
UpdateStatement: UPDATE statements Fields: TableName, Updates, From, Where, Returning New in v1.6.0: Returning clause support, FROM clause for PostgreSQL
DeleteStatement: DELETE FROM statements Fields: TableName, Using, Where, Returning New in v1.6.0: Returning clause support, USING clause for PostgreSQL
DDL Statements:
- CreateTableStatement: CREATE TABLE with constraints and partitioning
- CreateViewStatement: CREATE VIEW with column list
- CreateMaterializedViewStatement: CREATE MATERIALIZED VIEW (PostgreSQL)
- CreateIndexStatement: CREATE INDEX with partial indexes and expressions
- AlterTableStatement: ALTER TABLE with multiple action types
- DropStatement: DROP TABLE/VIEW/INDEX with CASCADE/RESTRICT
Advanced Statements:
MergeStatement: MERGE INTO for upsert operations (SQL:2003 F312) New in v1.6.0: Complete MERGE support with MATCHED/NOT MATCHED clauses
TruncateStatement: TRUNCATE TABLE with identity control New in v1.6.0: RESTART/CONTINUE IDENTITY, CASCADE/RESTRICT options
RefreshMaterializedViewStatement: REFRESH MATERIALIZED VIEW New in v1.6.0: CONCURRENTLY option for non-blocking refresh
Expression Types ¶
Basic Expressions:
- Identifier: Column or table names, optionally qualified (table.column)
- LiteralValue: Integer, float, string, boolean, NULL literals
- AliasedExpression: Expressions with aliases (expr AS alias)
Operator Expressions:
BinaryExpression: Binary operations (=, <, >, +, -, *, /, AND, OR, etc.) New in v1.6.0: CustomOp field for PostgreSQL custom operators JSON/JSONB operators: ->, ->>, #>, #>>, @>, <@, ?, ?|, ?&, #-
UnaryExpression: Unary operations (NOT, -, +, etc.) Supports PostgreSQL-specific operators: ~, |/, ||/, !, !!, @
BetweenExpression: Range expressions (expr BETWEEN lower AND upper)
InExpression: Membership tests (expr IN (values) or expr IN (subquery))
Function and Aggregate Expressions:
FunctionCall: Function calls with OVER clause for window functions Fields: Name, Arguments, Over (WindowSpec), Distinct, Filter, OrderBy New in v1.6.0: Filter field for FILTER clause (aggregate FILTER (WHERE condition)) New in v1.6.0: OrderBy field for aggregate functions (STRING_AGG, ARRAY_AGG)
WindowSpec: Window specifications (PARTITION BY, ORDER BY, frame clause) Fields: Name, PartitionBy, OrderBy, FrameClause
WindowFrame: Frame specifications (ROWS/RANGE with bounds) Fields: Type (ROWS or RANGE), Start, End (WindowFrameBound)
WindowFrameBound: Frame boundary specifications Types: CURRENT ROW, UNBOUNDED PRECEDING/FOLLOWING, n PRECEDING/FOLLOWING
Subquery Expressions:
- SubqueryExpression: Scalar subqueries (SELECT returning single value)
- ExistsExpression: EXISTS (subquery) predicates
- AnyExpression: expr op ANY (subquery) quantified comparisons
- AllExpression: expr op ALL (subquery) quantified comparisons
Conditional Expressions:
CaseExpression: CASE WHEN ... THEN ... ELSE ... END expressions Fields: Value (optional), WhenClauses, ElseClause
CastExpression: CAST(expr AS type) type conversions
Advanced Grouping Expressions (SQL-99 T431):
RollupExpression: ROLLUP(cols) for hierarchical grouping Generates grouping sets: (a,b,c), (a,b), (a), ()
CubeExpression: CUBE(cols) for all grouping combinations Generates all possible grouping sets from columns
GroupingSetsExpression: GROUPING SETS(...) for explicit grouping sets Allows arbitrary specification of grouping combinations
SQL-99 Features:
FetchClause: FETCH FIRST/NEXT n ROWS ONLY/WITH TIES (SQL-99 F861, F862) Fields: OffsetValue, FetchValue, FetchType, IsPercent, WithTies
OrderByExpression: ORDER BY with NULLS FIRST/LAST (SQL-99 F851) Fields: Expression, Ascending, NullsFirst
Common Table Expressions (CTEs) ¶
WithClause: WITH clause for Common Table Expressions
type WithClause struct {
Recursive bool // RECURSIVE keyword
CTEs []*CommonTableExpr // List of CTEs
}
CommonTableExpr: Individual CTE definition
type CommonTableExpr struct {
Name string // CTE name
Columns []string // Optional column list
Statement Statement // CTE query
Materialized *bool // nil=default, true=MATERIALIZED, false=NOT MATERIALIZED
}
New in v1.6.0: Materialized field for PostgreSQL optimization hints
Example CTE Structure:
WITH RECURSIVE employee_tree (id, name, manager_id, level) AS (
SELECT id, name, manager_id, 1 FROM employees WHERE manager_id IS NULL
UNION ALL
SELECT e.id, e.name, e.manager_id, t.level + 1
FROM employees e JOIN employee_tree t ON e.manager_id = t.id
)
SELECT * FROM employee_tree ORDER BY level;
Set Operations ¶
SetOperation: UNION, EXCEPT, INTERSECT operations
type SetOperation struct {
Left Statement // Left statement
Operator string // UNION, EXCEPT, INTERSECT
Right Statement // Right statement
All bool // ALL modifier (UNION ALL vs UNION)
}
Set operations support left-associative parsing for multiple operations:
SELECT * FROM t1 UNION SELECT * FROM t2 EXCEPT SELECT * FROM t3 Parsed as: (t1 UNION t2) EXCEPT t3
Window Functions ¶
Complete SQL-99 window function support with frame specifications:
WindowSpec: Defines window for function evaluation
type WindowSpec struct {
Name string // Optional window name
PartitionBy []Expression // PARTITION BY clause
OrderBy []OrderByExpression // ORDER BY clause
FrameClause *WindowFrame // Frame specification
}
WindowFrame: Frame clause (ROWS/RANGE)
type WindowFrame struct {
Type string // ROWS or RANGE
Start WindowFrameBound // Starting bound
End *WindowFrameBound // Optional ending bound
}
WindowFrameBound: Frame boundary specification
type WindowFrameBound struct {
Type string // CURRENT ROW, UNBOUNDED PRECEDING, etc.
Value Expression // For n PRECEDING/FOLLOWING
}
Example Window Function Query:
SELECT
name,
salary,
ROW_NUMBER() OVER (ORDER BY salary DESC) as rank,
AVG(salary) OVER (
PARTITION BY department
ORDER BY hire_date
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW
) as rolling_avg
FROM employees;
JOIN Support ¶
JoinClause: All SQL join types with proper precedence
type JoinClause struct {
Type string // INNER, LEFT, RIGHT, FULL, CROSS, NATURAL
Left TableReference // Left table
Right TableReference // Right table
Condition Expression // ON condition or USING clause
}
TableReference: Table reference with subquery and LATERAL support
type TableReference struct {
Name string // Table name
Alias string // Optional alias
Subquery *SelectStatement // Derived table (subquery)
Lateral bool // LATERAL keyword (PostgreSQL v1.6.0)
}
New in v1.6.0: Lateral field enables correlated subqueries in FROM clause
Example LATERAL JOIN (PostgreSQL):
SELECT u.name, r.order_date
FROM users u,
LATERAL (
SELECT * FROM orders
WHERE user_id = u.id
ORDER BY order_date DESC
LIMIT 3
) r;
PostgreSQL Extensions (v1.6.0) ¶
DISTINCT ON: PostgreSQL-specific row selection
type SelectStatement struct {
DistinctOnColumns []Expression // DISTINCT ON (expr, ...)
// ... other fields
}
Example:
SELECT DISTINCT ON (dept_id) dept_id, name, salary FROM employees ORDER BY dept_id, salary DESC;
FILTER Clause: Conditional aggregation
type FunctionCall struct {
Filter Expression // WHERE clause for aggregate functions
// ... other fields
}
Example:
SELECT
COUNT(*) FILTER (WHERE status = 'active') AS active_count,
SUM(amount) FILTER (WHERE type = 'credit') AS total_credits
FROM transactions;
RETURNING Clause: Return modified rows
type InsertStatement struct {
Returning []Expression // RETURNING clause
// ... other fields
}
Example:
INSERT INTO users (name, email)
VALUES ('John', 'john@example.com')
RETURNING id, created_at;
JSON/JSONB Operators: PostgreSQL JSON/JSONB operations
BinaryExpression operators: -> (Arrow) : JSON field/array element access ->> (LongArrow) : JSON field/array element access as text #> (HashArrow) : JSON path access #>> (HashLongArrow) : JSON path access as text @> (AtArrow) : JSON contains operator <@ (ArrowAt) : JSON contained by operator ? (Question) : JSON key exists ?| (QuestionPipe) : JSON any key exists ?& (QuestionAnd) : JSON all keys exist #- (HashMinus) : JSON delete operator
Example:
SELECT
data->>'name' AS name,
data->'address'->>'city' AS city,
data #> '{tags, 0}' AS first_tag
FROM users
WHERE data @> '{"active": true}'
AND data ? 'email';
Operator Support ¶
UnaryOperator: Unary operators for expressions
const (
Plus UnaryOperator = iota // +expr
Minus // -expr
Not // NOT expr
PGBitwiseNot // ~expr (PostgreSQL)
PGSquareRoot // |/expr (PostgreSQL)
PGCubeRoot // ||/expr (PostgreSQL)
PGPostfixFactorial // expr! (PostgreSQL)
PGPrefixFactorial // !!expr (PostgreSQL)
PGAbs // @expr (PostgreSQL)
BangNot // !expr (Hive)
)
BinaryOperator: Binary operators for expressions
const (
// Arithmetic operators
BinaryPlus, BinaryMinus, Multiply, Divide, Modulo
// Comparison operators
Eq, NotEq, Lt, Gt, LtEq, GtEq, Spaceship
// Logical operators
And, Or, Xor
// String/Array operators
StringConcat // ||
// Bitwise operators
BitwiseAnd, BitwiseOr, BitwiseXor
PGBitwiseXor, PGBitwiseShiftLeft, PGBitwiseShiftRight
// PostgreSQL-specific operators
PGExp, PGOverlap, PGRegexMatch, PGRegexIMatch
PGRegexNotMatch, PGRegexNotIMatch, PGStartsWith
// JSON/JSONB operators (PostgreSQL v1.6.0)
Arrow, LongArrow, HashArrow, HashLongArrow
AtArrow, ArrowAt, Question, QuestionAnd, QuestionPipe, HashMinus
// Other operators
Overlaps // SQL OVERLAPS for datetime periods
)
CustomBinaryOperator: PostgreSQL custom operators
type CustomBinaryOperator struct {
Parts []string // Operator parts for schema-qualified operators
}
Example: OPERATOR(schema.custom_op)
MERGE Statement (SQL:2003 F312) ¶
MergeStatement: MERGE INTO for upsert operations
type MergeStatement struct {
TargetTable TableReference // Table being merged into
TargetAlias string // Optional target alias
SourceTable TableReference // Source table or subquery
SourceAlias string // Optional source alias
OnCondition Expression // Join/match condition
WhenClauses []*MergeWhenClause // WHEN clauses
}
MergeWhenClause: WHEN clause in MERGE
type MergeWhenClause struct {
Type string // MATCHED, NOT_MATCHED, NOT_MATCHED_BY_SOURCE
Condition Expression // Optional AND condition
Action *MergeAction // UPDATE, INSERT, or DELETE action
}
MergeAction: Action in MERGE WHEN clause
type MergeAction struct {
ActionType string // UPDATE, INSERT, DELETE
SetClauses []SetClause // For UPDATE
Columns []string // For INSERT
Values []Expression // For INSERT
DefaultValues bool // INSERT DEFAULT VALUES
}
Example MERGE statement:
MERGE INTO target_table t
USING source_table s ON t.id = s.id
WHEN MATCHED THEN
UPDATE SET t.name = s.name, t.value = s.value
WHEN NOT MATCHED THEN
INSERT (id, name, value) VALUES (s.id, s.name, s.value);
Memory Management and Performance ¶
The ast package is designed for high-performance SQL parsing with minimal memory allocations. Key performance features:
Object Pooling:
- sync.Pool for all major AST node types
- 60-80% memory reduction in production workloads
- 95%+ pool hit rates with proper usage patterns
- Zero-copy semantics where possible
Performance Characteristics:
- 1.38M+ operations/second sustained throughput
- Up to 1.5M ops/sec peak performance
- <1μs latency for complex queries with window functions
- Thread-safe: Zero race conditions (validated with 20,000+ concurrent operations)
Memory Safety:
- Iterative cleanup to prevent stack overflow with deeply nested expressions
- Configurable recursion depth limits (MaxCleanupDepth = 100)
- Work queue size limits (MaxWorkQueueSize = 1000)
Pool Configuration Constants:
const (
MaxCleanupDepth = 100 // Prevents stack overflow in cleanup
MaxWorkQueueSize = 1000 // Limits work queue for iterative cleanup
)
Thread Safety ¶
All AST operations are thread-safe and race-free:
- Object pools use sync.Pool (thread-safe by design)
- All node types are immutable after construction
- No shared mutable state between goroutines
- Validated with comprehensive concurrent testing (20,000+ operations)
Usage Examples ¶
Example 1: Building a SELECT statement with pooling
// Get statement from pool
stmt := ast.GetSelectStatement()
defer ast.PutSelectStatement(stmt)
// Build column list
col1 := ast.GetIdentifier()
col1.Name = "id"
col2 := ast.GetIdentifier()
col2.Name = "name"
stmt.Columns = []ast.Expression{col1, col2}
// Add WHERE clause
whereExpr := ast.GetBinaryExpression()
whereExpr.Operator = "="
whereExpr.Left = ast.GetIdentifier()
whereExpr.Left.(*ast.Identifier).Name = "active"
whereExpr.Right = ast.GetLiteralValue()
whereExpr.Right.(*ast.LiteralValue).Value = true
whereExpr.Right.(*ast.LiteralValue).Type = "BOOLEAN"
stmt.Where = whereExpr
// Use the statement
// ... process statement ...
Example 2: Creating a window function expression
// Build function call with window specification
fnCall := ast.GetFunctionCall()
fnCall.Name = "ROW_NUMBER"
fnCall.Over = &ast.WindowSpec{
OrderBy: []ast.OrderByExpression{
{
Expression: &ast.Identifier{Name: "salary"},
Ascending: false, // DESC
},
},
}
Example 3: Traversing AST to find all tables
var tables []string
ast.Inspect(astNode, func(n ast.Node) bool {
if ref, ok := n.(*ast.TableReference); ok {
if ref.Name != "" {
tables = append(tables, ref.Name)
}
}
return true
})
fmt.Printf("Tables referenced: %v\n", tables)
Example 4: PostgreSQL JSON operator expression
// data->>'email' expression
jsonExpr := ast.GetBinaryExpression()
jsonExpr.Left = &ast.Identifier{Name: "data"}
jsonExpr.Operator = "->>"
jsonExpr.Right = &ast.LiteralValue{Value: "email", Type: "STRING"}
Example 5: Building a CTE with materialization hint
cte := &ast.CommonTableExpr{
Name: "active_users",
Columns: []string{"id", "name", "email"},
Statement: selectStmt,
Materialized: &trueVal, // MATERIALIZED hint
}
withClause := &ast.WithClause{
Recursive: false,
CTEs: []*ast.CommonTableExpr{cte},
}
Testing and Validation ¶
The ast package has comprehensive test coverage:
- 73.4% code coverage (AST nodes with edge case testing)
- 100% coverage for models package (underlying data structures)
- Thread safety validated with race detection (20,000+ concurrent ops)
- Memory leak testing with extended load tests
- Performance benchmarks for all major operations
Version History ¶
v1.0.0 - Initial release:
- Basic DML statements (SELECT, INSERT, UPDATE, DELETE)
- DDL statements (CREATE TABLE, ALTER TABLE, DROP TABLE)
- Expression support (binary, unary, literals)
v1.1.0 - Phase 1 JOINs:
- All JOIN types (INNER, LEFT, RIGHT, FULL, CROSS, NATURAL)
- USING clause support
- Left-associative JOIN parsing
v1.2.0 - Phase 2 CTEs and Set Operations:
- WITH clause for CTEs
- Recursive CTEs
- UNION, EXCEPT, INTERSECT operations
- Set operation precedence handling
v1.3.0 - Phase 2.5 Window Functions:
- WindowSpec for window specifications
- WindowFrame for frame clauses (ROWS/RANGE)
- WindowFrameBound for boundary specifications
- FunctionCall.Over for window functions
v1.4.0 - Advanced Grouping:
- GROUPING SETS, ROLLUP, CUBE (SQL-99 T431)
- Enhanced GROUP BY expressions
v1.5.0 - MERGE and Views:
- MERGE statement (SQL:2003 F312)
- CREATE MATERIALIZED VIEW
- REFRESH MATERIALIZED VIEW
v1.6.0 - PostgreSQL Extensions:
- LATERAL JOIN support (TableReference.Lateral)
- DISTINCT ON clause (SelectStatement.DistinctOnColumns)
- FILTER clause for aggregates (FunctionCall.Filter)
- RETURNING clause (InsertStatement/UpdateStatement/DeleteStatement.Returning)
- JSON/JSONB operators (Arrow, LongArrow, HashArrow, etc.)
- FETCH FIRST/NEXT clause (FetchClause)
- TRUNCATE statement with identity control
- Materialized CTE hints (CommonTableExpr.Materialized)
- Aggregate ORDER BY (FunctionCall.OrderBy)
- NULLS FIRST/LAST (OrderByExpression.NullsFirst)
Related Packages ¶
- pkg/sql/parser: Recursive descent parser that builds AST nodes
- pkg/sql/tokenizer: Zero-copy tokenizer for SQL input
- pkg/models: Core data structures (tokens, spans, locations)
- pkg/errors: Structured error handling with position information
References ¶
- SQL-99 Standard: ISO/IEC 9075:1999 (window functions, CTEs)
- SQL:2003 Standard: ISO/IEC 9075:2003 (MERGE, FILTER clause)
- PostgreSQL Documentation: https://www.postgresql.org/docs/
- MySQL Documentation: https://dev.mysql.com/doc/
License ¶
Copyright (c) 2024 GoSQLX Contributors Licensed under the Apache License, Version 2.0
This file provides SQL formatting option types shared between the AST and the formatter package.
Rendering logic lives in pkg/formatter — AST nodes are pure data structures (no Format() methods). This separation mirrors the go/ast + go/printer split.
This file contains backward-compatibility shims for the Format(FormatOptions) string methods that were removed in the refactor/move-formatting PR (#342). They now delegate to pkg/formatter via hooks (FormatStatementFunc, etc.) that pkg/formatter sets in its init() function, avoiding the import cycle:
pkg/sql/ast → pkg/formatter → pkg/sql/ast
If pkg/formatter has not been imported the methods fall back to SQL() output. All methods are marked deprecated; callers should migrate to pkg/formatter.FormatStatement(), FormatExpression() or FormatAST() directly.
This file defines unary and binary operator types for SQL expressions, including standard SQL operators and PostgreSQL-specific extensions.
This file implements comprehensive object pooling for all major AST node types using sync.Pool. The pooling system provides 60-80% memory reduction in production workloads and 95%+ pool hit rates with proper usage patterns.
IMPORTANT: Always use defer when returning pooled objects to prevent leaks. See doc.go for complete pooling documentation and usage examples.
This file implements SQL() string methods on all AST node types, enabling AST→SQL roundtrip serialization.
Index ¶
- Constants
- Variables
- func GetExpressionSlice() *[]Expression
- func GetSpan(node interface{}) models.Span
- func Inspect(node Node, f func(Node) bool)
- func ParseStructTags(tag string) map[string]string
- func PutAliasedExpression(ae *AliasedExpression)
- func PutAlterStatement(stmt *AlterStatement)
- func PutAlterTableStatement(stmt *AlterTableStatement)
- func PutArrayConstructor(ac *ArrayConstructorExpression)
- func PutArraySliceExpression(ase *ArraySliceExpression)
- func PutArraySubscriptExpression(ase *ArraySubscriptExpression)
- func PutBetweenExpression(be *BetweenExpression)
- func PutBinaryExpression(expr *BinaryExpression)
- func PutCaseExpression(ce *CaseExpression)
- func PutCastExpression(ce *CastExpression)
- func PutCreateIndexStatement(stmt *CreateIndexStatement)
- func PutCreateMaterializedViewStatement(stmt *CreateMaterializedViewStatement)
- func PutCreateTableStatement(stmt *CreateTableStatement)
- func PutCreateViewStatement(stmt *CreateViewStatement)
- func PutDeleteStatement(stmt *DeleteStatement)
- func PutDescribeStatement(stmt *DescribeStatement)
- func PutDropStatement(stmt *DropStatement)
- func PutExpression(expr Expression)
- func PutExpressionSlice(slice *[]Expression)
- func PutFunctionCall(fc *FunctionCall)
- func PutIdentifier(ident *Identifier)
- func PutInExpression(ie *InExpression)
- func PutInsertStatement(stmt *InsertStatement)
- func PutIntervalExpression(ie *IntervalExpression)
- func PutLiteralValue(lit *LiteralValue)
- func PutMergeStatement(stmt *MergeStatement)
- func PutRefreshMaterializedViewStatement(stmt *RefreshMaterializedViewStatement)
- func PutReplaceStatement(stmt *ReplaceStatement)
- func PutSelectStatement(stmt *SelectStatement)
- func PutShowStatement(stmt *ShowStatement)
- func PutSubqueryExpression(se *SubqueryExpression)
- func PutTruncateStatement(stmt *TruncateStatement)
- func PutTupleExpression(te *TupleExpression)
- func PutUpdateExpression(expr *UpdateExpression)
- func PutUpdateStatement(stmt *UpdateStatement)
- func ReleaseAST(ast *AST)
- func ReleaseStatements(stmts []Statement)
- func SetSpan(node interface{}, span models.Span)
- func UnionSpans(spans []models.Span) models.Span
- func Walk(v Visitor, node Node) error
- type AST
- type AliasedExpression
- type AllExpression
- type AlterColumnOperation
- type AlterConnectorOperation
- type AlterConnectorOwner
- type AlterOperation
- type AlterPolicyOpType
- type AlterPolicyOperation
- type AlterRoleOpType
- type AlterRoleOperation
- type AlterStatement
- type AlterTableAction
- type AlterTableOpType
- type AlterTableOperation
- type AlterTableStatement
- type AlterType
- type AnyExpression
- type ArrayBracketType
- type ArrayConstructorExpression
- type ArrayElemTypeDef
- type ArraySliceExpression
- type ArraySubscriptExpression
- type ArrayType
- type AttachedToken
- func (a AttachedToken) Compare(other AttachedToken) int
- func (a AttachedToken) Empty() AttachedToken
- func (a AttachedToken) Equal(other AttachedToken) bool
- func (a AttachedToken) GoString() string
- func (a AttachedToken) Hash(h hash.Hash)
- func (a AttachedToken) String() string
- func (a AttachedToken) UnwrapToken() TokenWithSpan
- type BetweenExpression
- type BinaryExpression
- type BinaryLength
- type BinaryOperator
- type BinaryType
- type BooleanType
- type CaseExpression
- type CastExpression
- type CharLengthUnits
- type CharacterLength
- type CharacterType
- type ClusteredBy
- type ColumnConstraint
- type ColumnDef
- type ColumnPosition
- type CommentDef
- type CommonTableExpr
- type CreateIndexStatement
- type CreateMaterializedViewStatement
- type CreateTable
- type CreateTableBuilder
- func (b *CreateTableBuilder) Build() *StatementImpl
- func (b *CreateTableBuilder) SetAggregationPolicy(v *ObjectName) *CreateTableBuilder
- func (b *CreateTableBuilder) SetAutoIncrementOffset(v *uint32) *CreateTableBuilder
- func (b *CreateTableBuilder) SetBaseLocation(v *string) *CreateTableBuilder
- func (b *CreateTableBuilder) SetCatalog(v *string) *CreateTableBuilder
- func (b *CreateTableBuilder) SetCatalogSync(v *string) *CreateTableBuilder
- func (b *CreateTableBuilder) SetChangeTracking(v *bool) *CreateTableBuilder
- func (b *CreateTableBuilder) SetClone(v *ObjectName) *CreateTableBuilder
- func (b *CreateTableBuilder) SetClusterBy(v *WrappedCollection[[]Ident]) *CreateTableBuilder
- func (b *CreateTableBuilder) SetClusteredBy(v *ClusteredBy) *CreateTableBuilder
- func (b *CreateTableBuilder) SetCollation(v *string) *CreateTableBuilder
- func (b *CreateTableBuilder) SetColumns(v []ColumnDef) *CreateTableBuilder
- func (b *CreateTableBuilder) SetComment(v *CommentDef) *CreateTableBuilder
- func (b *CreateTableBuilder) SetConstraints(v []TableConstraint) *CreateTableBuilder
- func (b *CreateTableBuilder) SetCopyGrants(v bool) *CreateTableBuilder
- func (b *CreateTableBuilder) SetDataRetentionDays(v *uint64) *CreateTableBuilder
- func (b *CreateTableBuilder) SetDefaultCharset(v *string) *CreateTableBuilder
- func (b *CreateTableBuilder) SetDefaultDDLCollation(v *string) *CreateTableBuilder
- func (b *CreateTableBuilder) SetEnableSchemaEvolution(v *bool) *CreateTableBuilder
- func (b *CreateTableBuilder) SetEngine(v *TableEngine) *CreateTableBuilder
- func (b *CreateTableBuilder) SetExternal(v bool) *CreateTableBuilder
- func (b *CreateTableBuilder) SetExternalVolume(v *string) *CreateTableBuilder
- func (b *CreateTableBuilder) SetFileFormat(v *FileFormat) *CreateTableBuilder
- func (b *CreateTableBuilder) SetGlobal(v *bool) *CreateTableBuilder
- func (b *CreateTableBuilder) SetHiveDistribution(v HiveDistributionStyle) *CreateTableBuilder
- func (b *CreateTableBuilder) SetHiveFormats(v *HiveFormat) *CreateTableBuilder
- func (b *CreateTableBuilder) SetIceberg(v bool) *CreateTableBuilder
- func (b *CreateTableBuilder) SetIfNotExists(v bool) *CreateTableBuilder
- func (b *CreateTableBuilder) SetLike(v *ObjectName) *CreateTableBuilder
- func (b *CreateTableBuilder) SetLocation(v *string) *CreateTableBuilder
- func (b *CreateTableBuilder) SetMaxDataExtensionDays(v *uint64) *CreateTableBuilder
- func (b *CreateTableBuilder) SetOnCluster(v *Ident) *CreateTableBuilder
- func (b *CreateTableBuilder) SetOnCommit(v *OnCommit) *CreateTableBuilder
- func (b *CreateTableBuilder) SetOptions(v *[]SqlOption) *CreateTableBuilder
- func (b *CreateTableBuilder) SetOrReplace(v bool) *CreateTableBuilder
- func (b *CreateTableBuilder) SetOrderBy(v *OneOrManyWithParens[Expr]) *CreateTableBuilder
- func (b *CreateTableBuilder) SetPartitionBy(v *Expr) *CreateTableBuilder
- func (b *CreateTableBuilder) SetPrimaryKey(v *Expr) *CreateTableBuilder
- func (b *CreateTableBuilder) SetQuery(v *Query) *CreateTableBuilder
- func (b *CreateTableBuilder) SetRowAccessPolicy(v *RowAccessPolicy) *CreateTableBuilder
- func (b *CreateTableBuilder) SetSerializationPolicy(v *StorageSerializationPolicy) *CreateTableBuilder
- func (b *CreateTableBuilder) SetStrict(v bool) *CreateTableBuilder
- func (b *CreateTableBuilder) SetTableProperties(v []SqlOption) *CreateTableBuilder
- func (b *CreateTableBuilder) SetTags(v *[]Tag) *CreateTableBuilder
- func (b *CreateTableBuilder) SetTemporary(v bool) *CreateTableBuilder
- func (b *CreateTableBuilder) SetTransient(v bool) *CreateTableBuilder
- func (b *CreateTableBuilder) SetVolatile(v bool) *CreateTableBuilder
- func (b *CreateTableBuilder) SetWithOptions(v []SqlOption) *CreateTableBuilder
- func (b *CreateTableBuilder) SetWithoutRowID(v bool) *CreateTableBuilder
- type CreateTableStatement
- type CreateViewStatement
- type CubeExpression
- type CustomBinaryOperator
- type CustomType
- type DataLoadingOption
- type DataLoadingOptionType
- type DataLoadingOptions
- type DataType
- type DataTypeVariant
- type DateTimeField
- type DateType
- type Delete
- type DeleteStatement
- type DescribeStatement
- type DollarQuotedString
- type DropBehavior
- type DropStatement
- type EnumMember
- type EnumType
- type ExactNumberInfo
- type ExistsExpression
- type Expr
- type Expression
- type ExtractExpression
- type FetchClause
- type FileFormat
- type FileStagingCommand
- type FloatType
- type ForClause
- type FormatOptions
- type FunctionCall
- type FunctionDesc
- type GroupingSetsExpression
- type HiveDistributionStyle
- type HiveFormat
- type Ident
- type Identifier
- type InExpression
- type IndentStyle
- type IndexColumn
- type IndexOption
- type IndexOptionType
- type IndexType
- type InputFormatClause
- type Insert
- type InsertStatement
- type Inspector
- type IntegerType
- type IntervalExpression
- type JoinClause
- type JsonType
- type KeywordCase
- type ListExpression
- type LiteralValue
- type Location
- type MergeAction
- type MergeStatement
- type MergeWhenClause
- type Node
- type NormalizationForm
- type NullsDistinctOption
- type Number
- type NumericType
- type ObjectName
- type OnCommit
- type OnConflict
- type OnConflictAction
- type OneOrManyWithParens
- type OrderByExpression
- type Partition
- type PartitionBy
- type PartitionDefinition
- type PositionExpression
- type PragmaStatement
- type Query
- type QueryExpression
- type ReferenceDefinition
- type RefreshMaterializedViewStatement
- type ReplaceStatement
- type RoleOption
- type RoleOptionType
- type RollupExpression
- type RowAccessPolicy
- type Select
- type SelectStatement
- type SetClause
- type SetOperation
- type SetType
- type Setting
- type ShowStatement
- type Span
- type Spanned
- type SpannedNode
- type SqlOption
- type StageLoadSelectItem
- type StageParamsObject
- type Statement
- type StatementImpl
- type StatementVariant
- type StorageSerializationPolicy
- type StructBracketKind
- type StructField
- type SubqueryExpression
- type SubstringExpression
- type Table
- type TableConstraint
- type TableEngine
- type TableOption
- type TableReference
- type TableType
- type Tag
- type TimeType
- type TimestampType
- type TimezoneInfo
- type Token
- type TokenType
- type TokenWithSpan
- type TopClause
- type TriggerEvent
- type TriggerEventType
- type TriggerExecBody
- type TriggerExecBodyType
- type TriggerObject
- type TriggerPeriod
- type TriggerReferencing
- type TriggerReferencingType
- type TrimWhereField
- type TruncateStatement
- type TupleExpression
- type UnaryExpression
- type UnaryOperator
- type Update
- type UpdateExpression
- type UpdateStatement
- func (u UpdateStatement) Children() []Node
- func (u *UpdateStatement) Format(opts FormatOptions) stringdeprecated
- func (u *UpdateStatement) GetUpdates() []UpdateExpressiondeprecated
- func (u *UpdateStatement) SQL() string
- func (u *UpdateStatement) Span() models.Span
- func (u UpdateStatement) TokenLiteral() string
- type UpsertClause
- type Value
- type ValueType
- type Values
- type VarcharType
- type VisitFunc
- type Visitor
- type WhenClause
- type WindowFrame
- type WindowFrameBound
- type WindowSpec
- type WithClause
- type WrappedCollection
Constants ¶
const ( // MaxCleanupDepth limits recursion depth to prevent stack overflow during cleanup. // Set to 100 based on typical SQL query complexity. Deeply nested expressions // use iterative cleanup instead of recursion. MaxCleanupDepth = 100 // MaxWorkQueueSize limits the work queue for iterative cleanup operations. // This prevents excessive memory usage when cleaning up extremely large ASTs // with thousands of nested expressions. Set to 1000 based on production workloads. MaxWorkQueueSize = 1000 )
Pool configuration constants control cleanup behavior to prevent resource exhaustion.
Variables ¶
var FormatASTFunc func(*AST, FormatOptions) string
FormatASTFunc is set by pkg/formatter.init() to enable the deprecated AST.Format() wrapper.
Deprecated: internal bridge — use pkg/formatter.FormatAST() directly.
var FormatExpressionFunc func(Expression, FormatOptions) string
FormatExpressionFunc is set by pkg/formatter.init() to enable deprecated Expression.Format() wrappers.
Deprecated: internal bridge — use pkg/formatter.FormatExpression() directly.
var FormatStatementFunc func(Statement, FormatOptions) string
FormatStatementFunc is set by pkg/formatter.init() to enable deprecated Statement.Format() wrappers.
Deprecated: internal bridge — use pkg/formatter.FormatStatement() directly.
Functions ¶
func GetExpressionSlice ¶
func GetExpressionSlice() *[]Expression
GetExpressionSlice gets a slice of Expression from the pool
func Inspect ¶
Inspect traverses an AST in depth-first order using a simple function.
Inspect is a convenience wrapper around Walk that allows AST traversal using a simple function instead of implementing the full Visitor interface. It's ideal for one-off traversals and simple node inspection tasks.
Traversal Behavior:
- Calls f(node) for each node in depth-first order
- If f returns true, continues to children
- If f returns false, skips children (prunes that subtree)
- After visiting children, calls f(nil) to signal completion
Parameters:
- node: Starting node for traversal (must not be nil)
- f: Function called for each node, returns true to continue to children
Example - Finding all table references:
var tables []string
ast.Inspect(astNode, func(n ast.Node) bool {
if ref, ok := n.(*ast.TableReference); ok {
if ref.Name != "" {
tables = append(tables, ref.Name)
}
}
return true // Continue traversing
})
fmt.Printf("Tables: %v\n", tables)
Example - Finding binary expressions with specific operator:
var comparisons []*ast.BinaryExpression
ast.Inspect(astNode, func(n ast.Node) bool {
if binExpr, ok := n.(*ast.BinaryExpression); ok {
if binExpr.Operator == "=" {
comparisons = append(comparisons, binExpr)
}
}
return true
})
Example - Stopping at specific node types:
// Find all columns in SELECT, but don't traverse into subqueries
var columns []string
ast.Inspect(astNode, func(n ast.Node) bool {
if sel, ok := n.(*ast.SelectStatement); ok {
for _, col := range sel.Columns {
if id, ok := col.(*ast.Identifier); ok {
columns = append(columns, id.Name)
}
}
return false // Don't traverse into SELECT's children
}
return true
})
Example - Collecting PostgreSQL JSON operators (v1.6.0):
var jsonOps []string
ast.Inspect(astNode, func(n ast.Node) bool {
if binExpr, ok := n.(*ast.BinaryExpression); ok {
switch binExpr.Operator {
case "->", "->>", "#>", "#>>", "@>", "<@", "?", "?|", "?&", "#-":
jsonOps = append(jsonOps, binExpr.Operator)
}
}
return true
})
fmt.Printf("JSON operators found: %v\n", jsonOps)
Example - Finding window functions:
var windowFuncs []string
ast.Inspect(astNode, func(n ast.Node) bool {
if fn, ok := n.(*ast.FunctionCall); ok {
if fn.Over != nil {
windowFuncs = append(windowFuncs, fn.Name)
}
}
return true
})
fmt.Printf("Window functions: %v\n", windowFuncs)
See also: Walk(), Inspector, Visitor
func ParseStructTags ¶
ParseStructTags parses struct field tags into a map
func PutAliasedExpression ¶ added in v1.6.0
func PutAliasedExpression(ae *AliasedExpression)
PutAliasedExpression returns an AliasedExpression to the pool
func PutAlterStatement ¶ added in v1.9.3
func PutAlterStatement(stmt *AlterStatement)
PutAlterStatement returns an AlterStatement to the pool. It zeroes all fields; the Operation interface value is cleared but its internal allocations are not recursively pooled (they use custom types).
func PutAlterTableStatement ¶ added in v1.9.3
func PutAlterTableStatement(stmt *AlterTableStatement)
PutAlterTableStatement returns an AlterTableStatement to the pool. It recursively releases nested expressions in column definitions and constraints.
func PutArrayConstructor ¶ added in v1.7.0
func PutArrayConstructor(ac *ArrayConstructorExpression)
PutArrayConstructor returns an ArrayConstructorExpression to the pool
func PutArraySliceExpression ¶ added in v1.7.0
func PutArraySliceExpression(ase *ArraySliceExpression)
PutArraySliceExpression returns an ArraySliceExpression to the pool
func PutArraySubscriptExpression ¶ added in v1.7.0
func PutArraySubscriptExpression(ase *ArraySubscriptExpression)
PutArraySubscriptExpression returns an ArraySubscriptExpression to the pool
func PutBetweenExpression ¶ added in v1.6.0
func PutBetweenExpression(be *BetweenExpression)
PutBetweenExpression returns a BetweenExpression to the pool
func PutBinaryExpression ¶
func PutBinaryExpression(expr *BinaryExpression)
PutBinaryExpression returns a BinaryExpression to the pool
func PutCaseExpression ¶ added in v1.6.0
func PutCaseExpression(ce *CaseExpression)
PutCaseExpression returns a CaseExpression to the pool
func PutCastExpression ¶ added in v1.6.0
func PutCastExpression(ce *CastExpression)
PutCastExpression returns a CastExpression to the pool
func PutCreateIndexStatement ¶ added in v1.9.3
func PutCreateIndexStatement(stmt *CreateIndexStatement)
PutCreateIndexStatement returns a CreateIndexStatement to the pool. It releases the optional WHERE expression.
func PutCreateMaterializedViewStatement ¶ added in v1.9.3
func PutCreateMaterializedViewStatement(stmt *CreateMaterializedViewStatement)
PutCreateMaterializedViewStatement returns a CreateMaterializedViewStatement to the pool. It recursively releases the nested query statement.
func PutCreateTableStatement ¶ added in v1.9.3
func PutCreateTableStatement(stmt *CreateTableStatement)
PutCreateTableStatement returns a CreateTableStatement to the pool. It recursively releases any nested expressions (column defaults, check constraints, etc.).
func PutCreateViewStatement ¶ added in v1.9.3
func PutCreateViewStatement(stmt *CreateViewStatement)
PutCreateViewStatement returns a CreateViewStatement to the pool. It recursively releases the nested query statement.
func PutDeleteStatement ¶
func PutDeleteStatement(stmt *DeleteStatement)
PutDeleteStatement returns a DeleteStatement to the pool
func PutDescribeStatement ¶ added in v1.9.3
func PutDescribeStatement(stmt *DescribeStatement)
PutDescribeStatement returns a DescribeStatement to the pool.
func PutDropStatement ¶ added in v1.9.3
func PutDropStatement(stmt *DropStatement)
PutDropStatement returns a DropStatement to the pool.
func PutExpression ¶
func PutExpression(expr Expression)
PutExpression returns any Expression to the appropriate pool with iterative cleanup.
PutExpression is the primary function for returning expression nodes to their respective pools. It handles all expression types and uses iterative cleanup to prevent stack overflow with deeply nested expression trees.
Key Features:
- Supports all expression types (30+ pooled types)
- Iterative cleanup algorithm (no recursion limits)
- Prevents stack overflow for deeply nested expressions
- Work queue size limits (MaxWorkQueueSize = 1000)
- Nil-safe (ignores nil expressions)
Supported Expression Types:
- Identifier, LiteralValue, AliasedExpression
- BinaryExpression, UnaryExpression
- FunctionCall, CaseExpression
- BetweenExpression, InExpression
- SubqueryExpression, ExistsExpression, AnyExpression, AllExpression
- CastExpression, ExtractExpression, PositionExpression, SubstringExpression
- ListExpression
Iterative Cleanup Algorithm:
- Use work queue instead of recursion
- Process expressions breadth-first
- Collect child expressions and add to queue
- Clean and return to pool
- Limit queue size to prevent memory exhaustion
Parameters:
- expr: Expression to return to pool (nil-safe)
Usage Pattern:
expr := ast.GetBinaryExpression() defer ast.PutExpression(expr) // Build expression tree...
Example - Cleaning up complex expression:
// Build: (age > 18 AND status = 'active') OR (role = 'admin')
expr := &ast.BinaryExpression{
Left: &ast.BinaryExpression{
Left: &ast.BinaryExpression{...},
Operator: "AND",
Right: &ast.BinaryExpression{...},
},
Operator: "OR",
Right: &ast.BinaryExpression{...},
}
// Cleanup all nested expressions
ast.PutExpression(expr) // Handles entire tree iteratively
Performance Characteristics:
- O(n) time complexity where n = number of nodes
- O(min(n, MaxWorkQueueSize)) space complexity
- No stack overflow risk regardless of nesting depth
- Efficient for both shallow and deeply nested expressions
Safety Guarantees:
- Thread-safe (uses sync.Pool internally)
- Nil-safe (gracefully handles nil expressions)
- Stack-safe (iterative, not recursive)
- Memory-safe (work queue size limits)
IMPORTANT: This function should be used for all expression cleanup. Direct pool returns (e.g., binaryExprPool.Put()) bypass the iterative cleanup and may leave child expressions unreleased.
See also: GetBinaryExpression(), GetFunctionCall(), GetIdentifier()
func PutExpressionSlice ¶
func PutExpressionSlice(slice *[]Expression)
PutExpressionSlice returns a slice of Expression to the pool
func PutFunctionCall ¶ added in v1.6.0
func PutFunctionCall(fc *FunctionCall)
PutFunctionCall returns a FunctionCall to the pool
func PutIdentifier ¶
func PutIdentifier(ident *Identifier)
PutIdentifier returns an Identifier to the pool
func PutInExpression ¶ added in v1.6.0
func PutInExpression(ie *InExpression)
PutInExpression returns an InExpression to the pool
func PutInsertStatement ¶
func PutInsertStatement(stmt *InsertStatement)
PutInsertStatement returns an InsertStatement to the pool
func PutIntervalExpression ¶ added in v1.7.0
func PutIntervalExpression(ie *IntervalExpression)
PutIntervalExpression returns an IntervalExpression to the pool
func PutLiteralValue ¶
func PutLiteralValue(lit *LiteralValue)
PutLiteralValue returns a LiteralValue to the pool
func PutMergeStatement ¶ added in v1.9.3
func PutMergeStatement(stmt *MergeStatement)
PutMergeStatement returns a MergeStatement to the pool. It recursively releases nested expressions in WHEN clauses and OUTPUT.
func PutRefreshMaterializedViewStatement ¶ added in v1.9.3
func PutRefreshMaterializedViewStatement(stmt *RefreshMaterializedViewStatement)
PutRefreshMaterializedViewStatement returns a RefreshMaterializedViewStatement to the pool.
func PutReplaceStatement ¶ added in v1.9.3
func PutReplaceStatement(stmt *ReplaceStatement)
PutReplaceStatement returns a ReplaceStatement to the pool. It recursively releases nested column and value expressions.
func PutSelectStatement ¶
func PutSelectStatement(stmt *SelectStatement)
PutSelectStatement returns a SelectStatement to the pool Uses iterative cleanup via PutExpression to handle deeply nested expressions
func PutShowStatement ¶ added in v1.9.3
func PutShowStatement(stmt *ShowStatement)
PutShowStatement returns a ShowStatement to the pool.
func PutSubqueryExpression ¶ added in v1.6.0
func PutSubqueryExpression(se *SubqueryExpression)
PutSubqueryExpression returns a SubqueryExpression to the pool
func PutTruncateStatement ¶ added in v1.9.3
func PutTruncateStatement(stmt *TruncateStatement)
PutTruncateStatement returns a TruncateStatement to the pool.
func PutTupleExpression ¶ added in v1.7.0
func PutTupleExpression(te *TupleExpression)
PutTupleExpression returns a TupleExpression to the pool
func PutUpdateExpression ¶
func PutUpdateExpression(expr *UpdateExpression)
PutUpdateExpression returns an UpdateExpression to the pool
func PutUpdateStatement ¶
func PutUpdateStatement(stmt *UpdateStatement)
PutUpdateStatement returns an UpdateStatement to the pool
func ReleaseAST ¶
func ReleaseAST(ast *AST)
ReleaseAST returns an AST container to the pool for reuse.
ReleaseAST cleans up and returns the AST to the pool, allowing it to be reused in future NewAST() calls. This is critical for memory efficiency and performance.
Cleanup Process:
- Returns all statement objects to their respective pools
- Clears all statement references
- Resets the Statements slice (preserves capacity)
- Returns the AST container to astPool
Usage Pattern (MANDATORY):
astObj := ast.NewAST() defer ast.ReleaseAST(astObj) // ALWAYS use defer
Parameters:
- ast: AST container to return (nil-safe, ignores nil)
The function is nil-safe and will return immediately if passed a nil AST.
CRITICAL: This function must be called for every AST obtained from NewAST(). Use defer immediately after NewAST() to ensure cleanup even on error paths.
Performance Impact:
- Prevents memory leaks by returning objects to pools
- Maintains 95%+ pool hit rates
- Reduces GC overhead by reusing allocations
- Essential for sustained high throughput (1.38M+ ops/sec)
Example - Correct usage:
func processSQL(sql string) error {
astObj := ast.NewAST()
defer ast.ReleaseAST(astObj) // Cleanup guaranteed
// ... process astObj ...
return nil
}
See also: NewAST(), PutSelectStatement(), PutInsertStatement()
func ReleaseStatements ¶ added in v1.9.3
func ReleaseStatements(stmts []Statement)
ReleaseStatements returns a slice of statements back to their respective pools. Use this to clean up statements returned by ParseWithRecovery, which returns []Statement rather than an *AST.
Example:
stmts, errs := parser.ParseWithRecovery(tokens) defer ast.ReleaseStatements(stmts) // ... process stmts and errs ...
func UnionSpans ¶
UnionSpans returns the union of all spans in the given slice
func Walk ¶
Walk traverses an AST in depth-first order using the visitor pattern.
Walk performs a depth-first traversal of the Abstract Syntax Tree starting from the given node. It uses the Visitor interface to allow custom processing at each node.
Traversal Algorithm:
- Call v.Visit(node) for the current node
- If Visit returns a non-nil visitor w and no error: - Recursively walk all children with visitor w - Call w.Visit(nil) after all children are visited
- If Visit returns nil visitor, skip children
- If Visit returns an error, stop immediately and return that error
Parameters:
- v: Visitor interface implementation to process each node
- node: Starting node for traversal (must not be nil)
Returns:
- error: First error encountered during traversal, or nil
Example - Finding all function calls:
type FunctionCollector struct {
functions []string
}
func (f *FunctionCollector) Visit(node ast.Node) (ast.Visitor, error) {
if node == nil {
return nil, nil
}
if fn, ok := node.(*ast.FunctionCall); ok {
f.functions = append(f.functions, fn.Name)
}
return f, nil // Continue traversing
}
collector := &FunctionCollector{}
if err := ast.Walk(collector, astNode); err != nil {
log.Fatal(err)
}
fmt.Printf("Functions found: %v\n", collector.functions)
Example - Validating tree structure:
type StructureValidator struct{}
func (s *StructureValidator) Visit(node ast.Node) (ast.Visitor, error) {
if node == nil {
return nil, nil
}
// Validate: SELECT statements must have at least one column
if sel, ok := node.(*ast.SelectStatement); ok {
if len(sel.Columns) == 0 {
return nil, fmt.Errorf("SELECT statement has no columns")
}
}
return s, nil
}
validator := &StructureValidator{}
if err := ast.Walk(validator, astNode); err != nil {
fmt.Printf("Validation error: %v\n", err)
}
See also: Inspect(), Visitor, Inspector
Types ¶
type AST ¶
type AST struct {
Statements []Statement
Comments []models.Comment // Comments captured during tokenization, preserved during formatting
}
AST represents the root of the Abstract Syntax Tree produced by parsing one or more SQL statements.
AST is obtained from the pool via NewAST and must be returned via ReleaseAST when the caller no longer needs it:
tree, err := p.ParseFromModelTokens(tokens)
if err != nil { return err }
defer ast.ReleaseAST(tree)
The Statements slice contains one entry per SQL statement separated by semicolons. Comments captured during tokenization are preserved in Comments for formatters that wish to round-trip them.
SQL() returns the canonical SQL string for all statements joined by ";\n". Span() returns the union of all statement spans for source-location tracking.
func NewAST ¶
func NewAST() *AST
NewAST retrieves a new AST container from the pool.
NewAST returns a pooled AST container with pre-allocated statement capacity. This is the primary entry point for creating AST objects with memory pooling.
Usage Pattern (MANDATORY):
astObj := ast.NewAST() defer ast.ReleaseAST(astObj) // ALWAYS use defer to prevent leaks // Use astObj...
The returned AST has:
- Empty Statements slice with capacity for 8 statements
- Clean state ready for population
Performance:
- 95%+ pool hit rate in production workloads
- Eliminates allocation overhead for AST containers
- Reduces GC pressure by reusing objects
CRITICAL: Always call ReleaseAST() when done, preferably via defer. Failure to return objects to the pool causes memory leaks and degrades performance by forcing new allocations.
Example:
func parseQuery(sql string) (*ast.AST, error) {
astObj := ast.NewAST()
defer ast.ReleaseAST(astObj)
// Parse and populate AST
stmt := ast.GetSelectStatement()
defer ast.PutSelectStatement(stmt)
// ... build statement ...
astObj.Statements = append(astObj.Statements, stmt)
return astObj, nil
}
See also: ReleaseAST(), GetSelectStatement(), GetInsertStatement()
func (AST) Children ¶
Children implements Node and returns all top-level statements as a slice of Node.
func (AST) Format
deprecated
added in
v1.9.3
func (a AST) Format(opts FormatOptions) string
Format returns the formatted SQL for the full AST.
Deprecated: use pkg/formatter.FormatAST() instead.
func (AST) TokenLiteral ¶
TokenLiteral implements Node. Returns an empty string — the AST root has no representative keyword.
type AliasedExpression ¶ added in v1.6.0
type AliasedExpression struct {
Expr Expression
Alias string
}
AliasedExpression represents an expression with an alias (expr AS alias)
func GetAliasedExpression ¶ added in v1.6.0
func GetAliasedExpression() *AliasedExpression
GetAliasedExpression retrieves an AliasedExpression from the pool
func (AliasedExpression) Children ¶ added in v1.6.0
func (a AliasedExpression) Children() []Node
func (*AliasedExpression) SQL ¶ added in v1.9.3
func (a *AliasedExpression) SQL() string
SQL returns the SQL representation of this aliased expression in the form "expr AS alias".
func (AliasedExpression) TokenLiteral ¶ added in v1.6.0
func (a AliasedExpression) TokenLiteral() string
type AllExpression ¶ added in v1.6.0
type AllExpression struct {
Expr Expression
Operator string
Subquery Statement
}
AllExpression represents expr op ALL (subquery)
func (AllExpression) Children ¶ added in v1.6.0
func (al AllExpression) Children() []Node
func (*AllExpression) SQL ¶ added in v1.9.3
func (a *AllExpression) SQL() string
SQL returns the SQL representation of this ALL expression as "expr op ALL (subquery)".
func (AllExpression) TokenLiteral ¶ added in v1.6.0
func (al AllExpression) TokenLiteral() string
type AlterColumnOperation ¶
type AlterColumnOperation int
AlterColumnOperation represents operations that can be performed on columns
const ( AlterColumnSetDefault AlterColumnOperation = iota AlterColumnDropDefault AlterColumnSetNotNull AlterColumnDropNotNull )
func (*AlterColumnOperation) Children ¶
func (a *AlterColumnOperation) Children() []Node
Children implements Node and returns nil — AlterColumnOperation has no child nodes.
func (*AlterColumnOperation) TokenLiteral ¶
func (a *AlterColumnOperation) TokenLiteral() string
TokenLiteral implements Node and returns the SQL keyword phrase for this ALTER COLUMN operation (e.g. "SET DEFAULT", "DROP NOT NULL").
type AlterConnectorOperation ¶
type AlterConnectorOperation struct {
Properties map[string]string
URL string
Owner *AlterConnectorOwner
}
AlterConnectorOperation represents operations that can be performed on a connector
func (AlterConnectorOperation) Children ¶
func (a AlterConnectorOperation) Children() []Node
Children implements Node and returns nil — AlterConnectorOperation has no child nodes.
func (AlterConnectorOperation) TokenLiteral ¶
func (a AlterConnectorOperation) TokenLiteral() string
TokenLiteral implements Node and returns "ALTER CONNECTOR".
type AlterConnectorOwner ¶
AlterConnectorOwner represents the new owner of a connector
type AlterOperation ¶
type AlterOperation interface {
Node
// contains filtered or unexported methods
}
AlterOperation represents the operation to be performed
type AlterPolicyOpType ¶
type AlterPolicyOpType int
AlterPolicyOpType represents the type of policy alteration
const ( RenamePolicy AlterPolicyOpType = iota ModifyPolicy )
type AlterPolicyOperation ¶
type AlterPolicyOperation struct {
Type AlterPolicyOpType
NewName string
To []string
Using Expression
WithCheck Expression
}
AlterPolicyOperation represents operations that can be performed on a policy
func (AlterPolicyOperation) Children ¶
func (a AlterPolicyOperation) Children() []Node
Children implements Node and returns the USING and WITH CHECK expressions as child nodes (any nil expressions are omitted).
func (AlterPolicyOperation) TokenLiteral ¶
func (a AlterPolicyOperation) TokenLiteral() string
TokenLiteral implements Node and returns "ALTER POLICY".
type AlterRoleOpType ¶
type AlterRoleOpType int
AlterRoleOpType represents the type of role alteration
const ( RenameRole AlterRoleOpType = iota AddMember DropMember SetConfig ResetConfig WithOptions )
type AlterRoleOperation ¶
type AlterRoleOperation struct {
Type AlterRoleOpType
NewName string
Options []RoleOption
MemberName string
ConfigName string
ConfigValue Expression
InDatabase string
}
AlterRoleOperation represents operations that can be performed on a role
func (AlterRoleOperation) Children ¶
func (a AlterRoleOperation) Children() []Node
Children implements Node and returns the ConfigValue expression as a child, or nil if no config value is set.
func (AlterRoleOperation) TokenLiteral ¶
func (a AlterRoleOperation) TokenLiteral() string
TokenLiteral implements Node and returns "ALTER ROLE".
type AlterStatement ¶
type AlterStatement struct {
Type AlterType
Name string // Name of the object being altered
Operation AlterOperation
}
AlterStatement represents an ALTER statement
func GetAlterStatement ¶ added in v1.9.3
func GetAlterStatement() *AlterStatement
GetAlterStatement gets an AlterStatement from the pool.
func (AlterStatement) Children ¶
func (a AlterStatement) Children() []Node
Children implements Node and returns the alter operation as a single child, or nil if no operation is set.
func (AlterStatement) TokenLiteral ¶
func (a AlterStatement) TokenLiteral() string
TokenLiteral implements Node and returns "ALTER".
type AlterTableAction ¶
type AlterTableAction struct {
Type string // ADD COLUMN, DROP COLUMN, MODIFY COLUMN, etc.
ColumnName string
ColumnDef *ColumnDef
Constraint *TableConstraint
}
AlterTableAction represents an action in ALTER TABLE
func (AlterTableAction) Children ¶
func (a AlterTableAction) Children() []Node
func (AlterTableAction) TokenLiteral ¶
func (a AlterTableAction) TokenLiteral() string
type AlterTableOpType ¶
type AlterTableOpType int
AlterTableOpType represents the type of table alteration
const ( AddConstraint AlterTableOpType = iota AddColumn AddProjection AlterColumn ChangeColumn ClearProjection DropColumn DropConstraint DropPartition DropProjection MaterializeProjection ModifyColumn RenameColumn RenameConstraint RenamePartitions RenameTable )
type AlterTableOperation ¶
type AlterTableOperation struct {
Type AlterTableOpType
ColumnKeyword bool // Used for AddColumn
IfNotExists bool // Used for AddColumn, AddPartition
IfExists bool // Used for DropColumn, DropConstraint, DropPartition
ColumnDef *ColumnDef // Used for AddColumn
ColumnPosition *ColumnPosition // Used for AddColumn, ChangeColumn, ModifyColumn
Constraint *TableConstraint // Used for AddConstraint
ProjectionName *Ident // Used for AddProjection, DropProjection
ProjectionSelect *Select // Used for AddProjection
PartitionName *Ident // Used for MaterializeProjection, ClearProjection
OldColumnName *Ident // Used for RenameColumn
NewColumnName *Ident // Used for RenameColumn
TableName ObjectName // Used for RenameTable
NewTableName ObjectName // Used for RenameTable
OldPartitions []*Expression // Used for RenamePartitions
NewPartitions []*Expression // Used for RenamePartitions
Partitions []*Partition // Used for AddPartitions
DropBehavior DropBehavior // Used for DropColumn, DropConstraint
ConstraintName *Ident // Used for DropConstraint
OldName *Ident // Used for RenameConstraint
NewName *Ident // Used for RenameConstraint
ColumnName *Ident // Used for AlterColumn
AlterColumnOp *AlterColumnOperation // Used for AlterColumn
CascadeDrops bool // Used for DropColumn, DropConstraint
}
AlterTableOperation represents operations that can be performed on a table
func (AlterTableOperation) Children ¶
func (a AlterTableOperation) Children() []Node
Children implements Node and returns the child nodes involved in this ALTER TABLE operation: the column definition, constraint, projection select, and/or alter column operation, depending on the operation type.
func (AlterTableOperation) TokenLiteral ¶
func (a AlterTableOperation) TokenLiteral() string
TokenLiteral implements Node and returns "ALTER TABLE".
type AlterTableStatement ¶
type AlterTableStatement struct {
Table string
Actions []AlterTableAction
}
AlterTableStatement represents an ALTER TABLE statement.
Maintenance note ¶
AlterTableStatement is NOT produced by the parser. Parser.Parse* methods return AlterStatement (defined in alter.go) with Type == AlterTypeTable. AlterTableStatement is retained only so that existing code that constructs it directly (e.g. in tests or manual AST construction) continues to compile.
Migration guide — prefer AlterStatement for all new code:
// Wrong (type assertion will never succeed at runtime): stmt := tree.Statements[0].(*ast.AlterTableStatement) // Correct: stmt := tree.Statements[0].(*ast.AlterStatement) tableName := stmt.Name // AlterStatement.Name holds the table name
func GetAlterTableStatement ¶ added in v1.9.3
func GetAlterTableStatement() *AlterTableStatement
GetAlterTableStatement gets an AlterTableStatement from the pool.
func (AlterTableStatement) Children ¶
func (a AlterTableStatement) Children() []Node
func (*AlterTableStatement) Format
deprecated
added in
v1.9.3
func (a *AlterTableStatement) Format(opts FormatOptions) string
Format returns the formatted SQL for this ALTER TABLE statement.
Deprecated: use pkg/formatter.FormatStatement() instead.
func (*AlterTableStatement) SQL ¶ added in v1.9.3
func (a *AlterTableStatement) SQL() string
SQL returns the SQL representation of this ALTER TABLE statement. Note: the parser returns AlterStatement (in alter.go); this method is for manually-constructed AlterTableStatement values.
func (AlterTableStatement) TokenLiteral ¶
func (a AlterTableStatement) TokenLiteral() string
type AnyExpression ¶ added in v1.6.0
type AnyExpression struct {
Expr Expression
Operator string
Subquery Statement
}
AnyExpression represents expr op ANY (subquery)
func (AnyExpression) Children ¶ added in v1.6.0
func (a AnyExpression) Children() []Node
func (*AnyExpression) SQL ¶ added in v1.9.3
func (a *AnyExpression) SQL() string
SQL returns the SQL representation of this ANY expression as "expr op ANY (subquery)".
func (AnyExpression) TokenLiteral ¶ added in v1.6.0
func (a AnyExpression) TokenLiteral() string
type ArrayBracketType ¶
type ArrayBracketType int
ArrayBracketType identifies the bracket style used to express an array type.
const ( // NoBrackets represents a bare ARRAY keyword with no type argument. NoBrackets ArrayBracketType = iota // AngleBrackets represents the ARRAY<T> syntax (e.g. BigQuery). AngleBrackets // SquareBrackets represents the T[] or T[N] syntax (e.g. PostgreSQL). SquareBrackets // Parentheses represents the Array(T) syntax. Parentheses )
type ArrayConstructorExpression ¶ added in v1.7.0
type ArrayConstructorExpression struct {
Elements []Expression // Elements inside ARRAY[...]
Subquery *SelectStatement // For ARRAY(SELECT ...) syntax (optional)
}
ArrayConstructorExpression represents PostgreSQL ARRAY constructor syntax. Creates an array value from a list of expressions or a subquery.
Examples:
ARRAY[1, 2, 3] - Integer array literal ARRAY['admin', 'moderator'] - Text array literal ARRAY(SELECT id FROM users) - Array from subquery
func GetArrayConstructor ¶ added in v1.7.0
func GetArrayConstructor() *ArrayConstructorExpression
GetArrayConstructor gets an ArrayConstructorExpression from the pool
func (ArrayConstructorExpression) Children ¶ added in v1.7.0
func (a ArrayConstructorExpression) Children() []Node
func (*ArrayConstructorExpression) SQL ¶ added in v1.9.3
func (a *ArrayConstructorExpression) SQL() string
SQL returns the SQL representation of this ARRAY constructor. From a subquery: "ARRAY(SELECT ...)". From an element list: "ARRAY[e1, e2, e3]".
func (ArrayConstructorExpression) TokenLiteral ¶ added in v1.7.0
func (a ArrayConstructorExpression) TokenLiteral() string
type ArrayElemTypeDef ¶
type ArrayElemTypeDef struct {
Type *DataType
Size *uint64
Brackets ArrayBracketType
}
ArrayElemTypeDef represents array element type definition
func (*ArrayElemTypeDef) String ¶
func (a *ArrayElemTypeDef) String() string
String returns the SQL representation of this array element type definition, e.g. "ARRAY<INT>", "INT[]", "INT[10]", or "Array(INT)".
type ArraySliceExpression ¶ added in v1.7.0
type ArraySliceExpression struct {
Array Expression // The array expression being sliced
Start Expression // Start index (nil means from beginning)
End Expression // End index (nil means to end)
}
ArraySliceExpression represents array slicing syntax for extracting subarrays. Supports PostgreSQL-style array slicing with optional start/end bounds.
Examples:
arr[1:3] - Slice from index 1 to 3 (inclusive) arr[2:] - Slice from index 2 to end arr[:5] - Slice from start to index 5 arr[:] - Full array slice (copy)
func GetArraySliceExpression ¶ added in v1.7.0
func GetArraySliceExpression() *ArraySliceExpression
GetArraySliceExpression gets an ArraySliceExpression from the pool
func (ArraySliceExpression) Children ¶ added in v1.7.0
func (a ArraySliceExpression) Children() []Node
func (*ArraySliceExpression) SQL ¶ added in v1.9.3
func (a *ArraySliceExpression) SQL() string
SQL returns the SQL representation of this array slice expression, e.g. "arr[1:3]", "arr[2:]", "arr[:5]", or "arr[:]".
func (ArraySliceExpression) TokenLiteral ¶ added in v1.7.0
func (a ArraySliceExpression) TokenLiteral() string
type ArraySubscriptExpression ¶ added in v1.7.0
type ArraySubscriptExpression struct {
Array Expression // The array expression being subscripted
Indices []Expression // Subscript indices (one or more for multi-dimensional arrays)
}
ArraySubscriptExpression represents array element access syntax. Supports single and multi-dimensional array subscripting.
Examples:
tags[1] - Single subscript matrix[2][3] - Multi-dimensional subscript arr[i] - Subscript with variable (SELECT arr)[1] - Subscript on subquery result
func GetArraySubscriptExpression ¶ added in v1.7.0
func GetArraySubscriptExpression() *ArraySubscriptExpression
GetArraySubscriptExpression gets an ArraySubscriptExpression from the pool
func (ArraySubscriptExpression) Children ¶ added in v1.7.0
func (a ArraySubscriptExpression) Children() []Node
func (*ArraySubscriptExpression) SQL ¶ added in v1.9.3
func (a *ArraySubscriptExpression) SQL() string
SQL returns the SQL representation of this array subscript expression, e.g. "arr[1]" or "matrix[i][j]" for multi-dimensional subscripts.
func (ArraySubscriptExpression) TokenLiteral ¶ added in v1.7.0
func (a ArraySubscriptExpression) TokenLiteral() string
type AttachedToken ¶
type AttachedToken struct {
Token TokenWithSpan
}
AttachedToken is a wrapper over TokenWithSpan that ignores the token and source location in comparisons and hashing.
This type is used when the token and location is not relevant for semantics, but is still needed for accurate source location tracking.
Note: ALL AttachedTokens are equal.
Examples:
Same token, different location are equal:
// commas @ line 1, column 10
tok1 := NewTokenWithSpan(
Token{Type: Comma},
Span{Start: Location{Line: 1, Column: 10}, End: Location{Line: 1, Column: 11}},
)
// commas @ line 2, column 20
tok2 := NewTokenWithSpan(
Token{Type: Comma},
Span{Start: Location{Line: 2, Column: 20}, End: Location{Line: 2, Column: 21}},
)
// token with locations are *not* equal
fmt.Println(tok1 != tok2) // true
// attached tokens are equal
fmt.Println(AttachedToken{tok1} == AttachedToken{tok2}) // true
Different token, different location are equal:
// commas @ line 1, column 10
tok1 := NewTokenWithSpan(
Token{Type: Comma},
Span{Start: Location{Line: 1, Column: 10}, End: Location{Line: 1, Column: 11}},
)
// period @ line 2, column 20
tok2 := NewTokenWithSpan(
Token{Type: Period},
Span{Start: Location{Line: 2, Column: 20}, End: Location{Line: 2, Column: 21}},
)
// token with locations are *not* equal
fmt.Println(tok1 != tok2) // true
// attached tokens are equal
fmt.Println(AttachedToken{tok1} == AttachedToken{tok2}) // true
func NewAttachedToken ¶
func NewAttachedToken(token TokenWithSpan) AttachedToken
NewAttachedToken creates a new AttachedToken from a TokenWithSpan
func WrapToken ¶
func WrapToken(token TokenWithSpan) AttachedToken
WrapToken wraps a TokenWithSpan in an AttachedToken
func (AttachedToken) Compare ¶
func (a AttachedToken) Compare(other AttachedToken) int
Compare implements comparison Note: ALL AttachedTokens are equal
func (AttachedToken) Empty ¶
func (a AttachedToken) Empty() AttachedToken
Empty returns a new Empty AttachedToken
func (AttachedToken) Equal ¶
func (a AttachedToken) Equal(other AttachedToken) bool
Equal implements equality comparison Note: ALL AttachedTokens are equal
func (AttachedToken) GoString ¶
func (a AttachedToken) GoString() string
GoString implements fmt.GoStringer
func (AttachedToken) Hash ¶
func (a AttachedToken) Hash(h hash.Hash)
Hash implements hashing Note: ALL AttachedTokens have the same hash
func (AttachedToken) UnwrapToken ¶
func (a AttachedToken) UnwrapToken() TokenWithSpan
UnwrapToken returns the underlying TokenWithSpan
type BetweenExpression ¶
type BetweenExpression struct {
Expr Expression
Lower Expression
Upper Expression
Not bool
Pos models.Location // Source position of the BETWEEN keyword (1-based line and column)
}
BetweenExpression represents expr BETWEEN lower AND upper
func GetBetweenExpression ¶ added in v1.6.0
func GetBetweenExpression() *BetweenExpression
GetBetweenExpression gets a BetweenExpression from the pool
func (BetweenExpression) Children ¶
func (b BetweenExpression) Children() []Node
func (*BetweenExpression) Format
deprecated
added in
v1.9.3
func (b *BetweenExpression) Format(opts FormatOptions) string
Format returns the formatted SQL for this BETWEEN expression.
Deprecated: use pkg/formatter.FormatExpression() instead.
func (*BetweenExpression) SQL ¶ added in v1.9.3
func (b *BetweenExpression) SQL() string
SQL returns the SQL representation of this BETWEEN expression. The NOT modifier is included when BetweenExpression.Not is true.
func (BetweenExpression) TokenLiteral ¶
func (b BetweenExpression) TokenLiteral() string
type BinaryExpression ¶
type BinaryExpression struct {
Left Expression
Operator string
Right Expression
Not bool // For NOT (expr)
CustomOp *CustomBinaryOperator // For PostgreSQL custom operators
Pos models.Location // Source position of the operator (1-based line and column)
}
BinaryExpression represents binary operations between two expressions.
BinaryExpression supports all standard SQL binary operators plus PostgreSQL-specific operators including JSON/JSONB operators added in v1.6.0.
Fields:
- Left: Left-hand side expression
- Operator: Binary operator (=, <, >, +, -, *, /, AND, OR, ->, #>, etc.)
- Right: Right-hand side expression
- Not: NOT modifier for negation (NOT expr)
- CustomOp: PostgreSQL custom operators (OPERATOR(schema.name))
Supported Operator Categories:
- Comparison: =, <>, <, >, <=, >=, <=> (spaceship)
- Arithmetic: +, -, *, /, %, DIV, // (integer division)
- Logical: AND, OR, XOR
- String: || (concatenation)
- Bitwise: &, |, ^, <<, >> (shifts)
- Pattern: LIKE, ILIKE, SIMILAR TO
- Range: OVERLAPS
- PostgreSQL JSON/JSONB (v1.6.0): ->, ->>, #>, #>>, @>, <@, ?, ?|, ?&, #-
Example - Basic comparison:
BinaryExpression{
Left: &Identifier{Name: "age"},
Operator: ">",
Right: &LiteralValue{Value: 18, Type: "INTEGER"},
}
// SQL: age > 18
Example - Logical AND:
BinaryExpression{
Left: &BinaryExpression{
Left: &Identifier{Name: "active"},
Operator: "=",
Right: &LiteralValue{Value: true, Type: "BOOLEAN"},
},
Operator: "AND",
Right: &BinaryExpression{
Left: &Identifier{Name: "status"},
Operator: "=",
Right: &LiteralValue{Value: "pending", Type: "STRING"},
},
}
// SQL: active = true AND status = 'pending'
Example - PostgreSQL JSON operator -> (v1.6.0):
BinaryExpression{
Left: &Identifier{Name: "data"},
Operator: "->",
Right: &LiteralValue{Value: "name", Type: "STRING"},
}
// SQL: data->'name'
Example - PostgreSQL JSON operator ->> (v1.6.0):
BinaryExpression{
Left: &Identifier{Name: "data"},
Operator: "->>",
Right: &LiteralValue{Value: "email", Type: "STRING"},
}
// SQL: data->>'email' (returns text)
Example - PostgreSQL JSON contains @> (v1.6.0):
BinaryExpression{
Left: &Identifier{Name: "attributes"},
Operator: "@>",
Right: &LiteralValue{Value: `{"color": "red"}`, Type: "STRING"},
}
// SQL: attributes @> '{"color": "red"}'
Example - PostgreSQL JSON key exists ? (v1.6.0):
BinaryExpression{
Left: &Identifier{Name: "profile"},
Operator: "?",
Right: &LiteralValue{Value: "email", Type: "STRING"},
}
// SQL: profile ? 'email'
Example - Custom PostgreSQL operator:
BinaryExpression{
Left: &Identifier{Name: "point1"},
Operator: "",
Right: &Identifier{Name: "point2"},
CustomOp: &CustomBinaryOperator{Parts: []string{"pg_catalog", "<->"}},
}
// SQL: point1 OPERATOR(pg_catalog.<->) point2
New in v1.6.0:
- JSON/JSONB operators: ->, ->>, #>, #>>, @>, <@, ?, ?|, ?&, #-
- CustomOp field for PostgreSQL custom operators
PostgreSQL JSON/JSONB Operator Reference:
- -> (Arrow): Extract JSON field or array element (returns JSON)
- ->> (LongArrow): Extract JSON field or array element as text
- #> (HashArrow): Extract JSON at path (returns JSON)
- #>> (HashLongArrow): Extract JSON at path as text
- @> (AtArrow): JSON contains (does left JSON contain right?)
- <@ (ArrowAt): JSON is contained by (is left JSON contained in right?)
- ? (Question): JSON key exists
- ?| (QuestionPipe): Any of the keys exist
- ?& (QuestionAnd): All of the keys exist
- #- (HashMinus): Delete key from JSON
func GetBinaryExpression ¶
func GetBinaryExpression() *BinaryExpression
GetBinaryExpression gets a BinaryExpression from the pool
func (BinaryExpression) Children ¶
func (b BinaryExpression) Children() []Node
func (*BinaryExpression) SQL ¶ added in v1.9.3
func (b *BinaryExpression) SQL() string
SQL returns the SQL representation of this binary expression. The operator, left, and right sub-expressions are serialized in infix notation. NOT-qualified operators (LIKE, ILIKE, SIMILAR TO) are rendered as "x NOT OP y".
func (*BinaryExpression) Span ¶
func (e *BinaryExpression) Span() models.Span
Span returns the source location span for expressions
func (*BinaryExpression) TokenLiteral ¶
func (b *BinaryExpression) TokenLiteral() string
type BinaryLength ¶
BinaryLength represents binary length information
func (*BinaryLength) String ¶
func (b *BinaryLength) String() string
String returns the SQL representation of this binary length: "MAX" when IsMax is true, otherwise the numeric length as a string.
type BinaryOperator ¶
type BinaryOperator int
BinaryOperator represents binary operators in SQL expressions.
BinaryOperator defines all binary operators that can be applied between two expressions. This includes standard SQL operators and database-specific extensions, notably PostgreSQL's JSON/JSONB operators added in v1.6.0.
Operator Categories:
- Comparison: Eq (=), NotEq (<>), Lt (<), Gt (>), LtEq (<=), GtEq (>=), Spaceship (<=>)
- Arithmetic: BinaryPlus (+), BinaryMinus (-), Multiply (*), Divide (/), Modulo (%)
- Logical: And (AND), Or (OR), Xor (XOR)
- String: StringConcat (||)
- Bitwise: BitwiseAnd (&), BitwiseOr (|), BitwiseXor (^)
- Bitwise Shifts: PGBitwiseShiftLeft (<<), PGBitwiseShiftRight (>>)
- Pattern Matching: PGRegexMatch (~), PGRegexIMatch (~*), PGLikeMatch (~~), PGILikeMatch (~~*)
- PostgreSQL Math: PGExp (^), DuckIntegerDivide (//), MyIntegerDivide (DIV)
- PostgreSQL JSON/JSONB (v1.6.0): Arrow (->), LongArrow (->>), HashArrow (#>), etc.
- Range: Overlaps (OVERLAPS)
PostgreSQL JSON/JSONB Operators (v1.6.0):
- Arrow (->): Extract JSON field or array element (returns JSON)
- LongArrow (->>): Extract JSON field or array element as text
- HashArrow (#>): Extract JSON at path (returns JSON)
- HashLongArrow (#>>): Extract JSON at path as text
- AtArrow (@>): JSON contains operator
- ArrowAt (<@): JSON is contained by operator
- Question (?): JSON key exists
- QuestionPipe (?|): Any of the keys exist
- QuestionAnd (?&): All of the keys exist
- HashMinus (#-): Delete key from JSON
Example - Comparison operator:
// Build: age > 18
expr := &ast.BinaryExpression{
Left: &ast.Identifier{Name: "age"},
Operator: ast.Gt.String(), // ">"
Right: &ast.LiteralValue{Value: 18, Type: "INTEGER"},
}
Example - Logical operator:
// Build: active = true AND status = 'pending'
expr := &ast.BinaryExpression{
Left: &ast.BinaryExpression{
Left: &ast.Identifier{Name: "active"},
Operator: ast.Eq.String(),
Right: &ast.LiteralValue{Value: true, Type: "BOOLEAN"},
},
Operator: ast.And.String(),
Right: &ast.BinaryExpression{
Left: &ast.Identifier{Name: "status"},
Operator: ast.Eq.String(),
Right: &ast.LiteralValue{Value: "pending", Type: "STRING"},
},
}
Example - PostgreSQL JSON operator (v1.6.0):
// Build: data->>'email'
expr := &ast.BinaryExpression{
Left: &ast.Identifier{Name: "data"},
Operator: ast.LongArrow.String(), // "->>"
Right: &ast.LiteralValue{Value: "email", Type: "STRING"},
}
// SQL: data->>'email' (extracts email field as text)
Example - PostgreSQL JSON contains (v1.6.0):
// Build: attributes @> '{"color": "red"}'
expr := &ast.BinaryExpression{
Left: &ast.Identifier{Name: "attributes"},
Operator: ast.AtArrow.String(), // "@>"
Right: &ast.LiteralValue{Value: `{"color": "red"}`, Type: "STRING"},
}
// SQL: attributes @> '{"color": "red"}'
Note: Use the String() method to get the operator symbol for BinaryExpression.Operator.
New in v1.6.0:
- JSON/JSONB operators: Arrow, LongArrow, HashArrow, HashLongArrow
- JSON existence operators: Question, QuestionPipe, QuestionAnd
- JSON manipulation: HashMinus, AtArrow, ArrowAt
See also: UnaryOperator, BinaryExpression, CustomBinaryOperator
const ( // BinaryOpNone represents no operator (zero value) BinaryOpNone BinaryOperator = iota // BinaryPlus represents addition operator, e.g. a + b BinaryPlus // BinaryMinus represents subtraction operator, e.g. a - b BinaryMinus // Multiply represents multiplication operator, e.g. a * b Multiply // Divide represents division operator, e.g. a / b Divide // Modulo represents modulo operator, e.g. a % b Modulo // StringConcat represents string/array concatenation operator, e.g. a || b StringConcat // Gt represents greater than operator, e.g. a > b Gt // Lt represents less than operator, e.g. a < b Lt // GtEq represents greater than or equal operator, e.g. a >= b GtEq // LtEq represents less than or equal operator, e.g. a <= b LtEq // Spaceship represents spaceship operator, e.g. a <=> b Spaceship // Eq represents equality operator, e.g. a = b Eq // NotEq represents inequality operator, e.g. a <> b NotEq // And represents logical AND operator, e.g. a AND b And // Or represents logical OR operator, e.g. a OR b Or // Xor represents logical XOR operator, e.g. a XOR b Xor // BitwiseOr represents bitwise OR operator, e.g. a | b BitwiseOr // BitwiseAnd represents bitwise AND operator, e.g. a & b BitwiseAnd // BitwiseXor represents bitwise XOR operator, e.g. a ^ b BitwiseXor // DuckIntegerDivide represents DuckDB integer division operator, e.g. a // b DuckIntegerDivide // MyIntegerDivide represents MySQL DIV integer division operator MyIntegerDivide // PGBitwiseXor represents PostgreSQL bitwise XOR operator, e.g. a # b PGBitwiseXor // PGBitwiseShiftLeft represents PostgreSQL bitwise shift left operator, e.g. a << b PGBitwiseShiftLeft // PGBitwiseShiftRight represents PostgreSQL bitwise shift right operator, e.g. a >> b PGBitwiseShiftRight // PGExp represents PostgreSQL exponentiation operator, e.g. a ^ b PGExp // PGOverlap represents PostgreSQL overlap operator, e.g. a && b PGOverlap // PGRegexMatch represents PostgreSQL case-sensitive regex match operator, e.g. a ~ b PGRegexMatch // PGRegexIMatch represents PostgreSQL case-insensitive regex match operator, e.g. a ~* b PGRegexIMatch // PGRegexNotMatch represents PostgreSQL case-sensitive regex non-match operator, e.g. a !~ b PGRegexNotMatch // PGRegexNotIMatch represents PostgreSQL case-insensitive regex non-match operator, e.g. a !~* b PGRegexNotIMatch // PGLikeMatch represents PostgreSQL case-sensitive LIKE match operator, e.g. a ~~ b PGLikeMatch // PGILikeMatch represents PostgreSQL case-insensitive LIKE match operator, e.g. a ~~* b PGILikeMatch // PGNotLikeMatch represents PostgreSQL case-sensitive NOT LIKE match operator, e.g. a !~~ b PGNotLikeMatch // PGNotILikeMatch represents PostgreSQL case-insensitive NOT LIKE match operator, e.g. a !~~* b PGNotILikeMatch // PGStartsWith represents PostgreSQL starts-with operator, e.g. a ^@ b PGStartsWith // Arrow represents JSON field/array element access operator, e.g. a -> b Arrow // LongArrow represents JSON field/array element access with text conversion operator, e.g. a ->> b LongArrow // HashArrow represents JSON path access operator, e.g. a #> b HashArrow // HashLongArrow represents JSON path access with text conversion operator, e.g. a #>> b HashLongArrow // AtAt represents PostgreSQL text/JSON search operator, e.g. a @@ b AtAt // AtArrow represents PostgreSQL contains operator, e.g. a @> b AtArrow // ArrowAt represents PostgreSQL contained by operator, e.g. a <@ b ArrowAt // HashMinus represents PostgreSQL JSON delete operator, e.g. a #- b HashMinus // AtQuestion represents PostgreSQL JSON path exists operator, e.g. a @? b AtQuestion // Question represents PostgreSQL JSON key exists operator, e.g. a ? b Question // QuestionAnd represents PostgreSQL JSON all keys exist operator, e.g. a ?& b QuestionAnd // QuestionPipe represents PostgreSQL JSON any key exists operator, e.g. a ?| b QuestionPipe // Overlaps represents SQL OVERLAPS operator for datetime periods Overlaps )
func (BinaryOperator) String ¶
func (op BinaryOperator) String() string
String returns the string representation of the binary operator
type BinaryType ¶
type BinaryType struct {
Length *BinaryLength
}
Basic data types
func (*BinaryType) String ¶
func (t *BinaryType) String() string
String returns the SQL representation of this BINARY type, e.g. "BINARY", "BINARY(16)", or "BINARY(MAX)".
type CaseExpression ¶
type CaseExpression struct {
Value Expression // Optional CASE value
WhenClauses []WhenClause
ElseClause Expression
Pos models.Location // Source position of the CASE keyword (1-based line and column)
}
CaseExpression represents a CASE expression
func GetCaseExpression ¶ added in v1.6.0
func GetCaseExpression() *CaseExpression
GetCaseExpression gets a CaseExpression from the pool
func (CaseExpression) Children ¶
func (c CaseExpression) Children() []Node
func (*CaseExpression) Format
deprecated
added in
v1.9.3
func (c *CaseExpression) Format(opts FormatOptions) string
Format returns the formatted SQL for this CASE expression.
Deprecated: use pkg/formatter.FormatExpression() instead.
func (*CaseExpression) SQL ¶ added in v1.9.3
func (c *CaseExpression) SQL() string
SQL returns the SQL representation of this CASE expression including all WHEN/THEN clauses and an optional ELSE clause.
func (CaseExpression) TokenLiteral ¶
func (c CaseExpression) TokenLiteral() string
type CastExpression ¶
type CastExpression struct {
Expr Expression
Type string
}
CastExpression represents CAST(expr AS type)
func GetCastExpression ¶ added in v1.6.0
func GetCastExpression() *CastExpression
GetCastExpression gets a CastExpression from the pool
func (CastExpression) Children ¶
func (c CastExpression) Children() []Node
func (*CastExpression) SQL ¶ added in v1.9.3
func (c *CastExpression) SQL() string
SQL returns the SQL representation of this CAST expression in the form "CAST(expr AS type)".
func (*CastExpression) Span ¶
func (e *CastExpression) Span() models.Span
Span returns the source location span for this CAST expression. It delegates to the inner expression's span, or returns an empty span if the inner expression does not implement Spanned.
func (CastExpression) TokenLiteral ¶
func (c CastExpression) TokenLiteral() string
type CharLengthUnits ¶
type CharLengthUnits int
CharLengthUnits represents possible units for characters
const ( Characters CharLengthUnits = iota Octets )
func (CharLengthUnits) String ¶
func (u CharLengthUnits) String() string
String returns the SQL keyword for this character length unit: "CHARACTERS" or "OCTETS".
type CharacterLength ¶
type CharacterLength struct {
Length uint64
Unit *CharLengthUnits
}
CharacterLength represents character length information
func (*CharacterLength) String ¶
func (c *CharacterLength) String() string
String returns the SQL representation of this character length specification, e.g. "10" or "10 CHARACTERS".
type CharacterType ¶
type CharacterType struct {
Length *CharacterLength
}
Basic data types
func (*CharacterType) String ¶
func (t *CharacterType) String() string
String returns the SQL representation of this CHARACTER type, e.g. "CHARACTER" or "CHARACTER(10)".
type ClusteredBy ¶
ClusteredBy represents CLUSTERED BY clause
func (*ClusteredBy) Children ¶
func (c *ClusteredBy) Children() []Node
Children implements Node and returns the columns used in the CLUSTERED BY clause.
func (*ClusteredBy) TokenLiteral ¶
func (c *ClusteredBy) TokenLiteral() string
TokenLiteral implements Node and returns "CLUSTERED BY".
type ColumnConstraint ¶
type ColumnConstraint struct {
Type string // NOT NULL, UNIQUE, PRIMARY KEY, etc.
Default Expression
References *ReferenceDefinition
Check Expression
AutoIncrement bool
}
ColumnConstraint represents a column constraint
func (ColumnConstraint) Children ¶
func (c ColumnConstraint) Children() []Node
func (*ColumnConstraint) String ¶
func (c *ColumnConstraint) String() string
String returns a string representation of a ColumnConstraint
func (ColumnConstraint) TokenLiteral ¶
func (c ColumnConstraint) TokenLiteral() string
type ColumnDef ¶
type ColumnDef struct {
Name string
Type string
Constraints []ColumnConstraint
}
ColumnDef represents a column definition in CREATE TABLE
func (ColumnDef) TokenLiteral ¶
type ColumnPosition ¶
ColumnPosition represents the position of a column in a table
type CommentDef ¶
type CommentDef struct {
Text string
}
CommentDef represents a comment on a database object
func (*CommentDef) Children ¶
func (c *CommentDef) Children() []Node
Children implements Node and returns nil — CommentDef has no child nodes.
func (*CommentDef) TokenLiteral ¶
func (c *CommentDef) TokenLiteral() string
TokenLiteral implements Node and returns "COMMENT".
type CommonTableExpr ¶
type CommonTableExpr struct {
Name string
Columns []string
Statement Statement
Materialized *bool // nil = default, true = MATERIALIZED, false = NOT MATERIALIZED
Pos models.Location // Source position of the CTE name (1-based line and column)
}
CommonTableExpr represents a single Common Table Expression in a WITH clause. It supports optional column specifications and any statement type as the CTE query. Phase 2 Complete: Full parser support with column specifications. Phase 2.6: Added MATERIALIZED/NOT MATERIALIZED support for query optimization hints.
func (CommonTableExpr) Children ¶
func (c CommonTableExpr) Children() []Node
func (CommonTableExpr) TokenLiteral ¶
func (c CommonTableExpr) TokenLiteral() string
type CreateIndexStatement ¶
type CreateIndexStatement struct {
Unique bool
IfNotExists bool
Name string
Table string
Columns []IndexColumn
Using string
Where Expression
}
CreateIndexStatement represents a CREATE INDEX statement
func GetCreateIndexStatement ¶ added in v1.9.3
func GetCreateIndexStatement() *CreateIndexStatement
GetCreateIndexStatement gets a CreateIndexStatement from the pool.
func (CreateIndexStatement) Children ¶
func (c CreateIndexStatement) Children() []Node
func (*CreateIndexStatement) Format
deprecated
added in
v1.9.3
func (c *CreateIndexStatement) Format(opts FormatOptions) string
Format returns the formatted SQL for this CREATE INDEX statement.
Deprecated: use pkg/formatter.FormatStatement() instead.
func (*CreateIndexStatement) SQL ¶ added in v1.9.3
func (c *CreateIndexStatement) SQL() string
SQL returns the full SQL string for this CREATE INDEX statement including the UNIQUE modifier, IF NOT EXISTS, USING method, column list, and WHERE predicate.
func (CreateIndexStatement) TokenLiteral ¶
func (c CreateIndexStatement) TokenLiteral() string
type CreateMaterializedViewStatement ¶ added in v1.6.0
type CreateMaterializedViewStatement struct {
IfNotExists bool
Name string
Columns []string // Optional column list
Query Statement // The SELECT statement
WithData *bool // nil = default, true = WITH DATA, false = WITH NO DATA
Tablespace string // Optional tablespace (PostgreSQL)
}
CreateMaterializedViewStatement represents a CREATE MATERIALIZED VIEW statement Syntax: CREATE MATERIALIZED VIEW [IF NOT EXISTS] name [(columns)] AS select [WITH [NO] DATA]
func GetCreateMaterializedViewStatement ¶ added in v1.9.3
func GetCreateMaterializedViewStatement() *CreateMaterializedViewStatement
GetCreateMaterializedViewStatement gets a CreateMaterializedViewStatement from the pool.
func (CreateMaterializedViewStatement) Children ¶ added in v1.6.0
func (c CreateMaterializedViewStatement) Children() []Node
func (*CreateMaterializedViewStatement) Format
deprecated
added in
v1.9.3
func (c *CreateMaterializedViewStatement) Format(opts FormatOptions) string
Format returns the formatted SQL for this CREATE MATERIALIZED VIEW statement.
Deprecated: use pkg/formatter.FormatStatement() instead.
func (*CreateMaterializedViewStatement) SQL ¶ added in v1.9.3
func (c *CreateMaterializedViewStatement) SQL() string
SQL returns the full SQL string for this CREATE MATERIALIZED VIEW statement.
func (CreateMaterializedViewStatement) TokenLiteral ¶ added in v1.6.0
func (c CreateMaterializedViewStatement) TokenLiteral() string
type CreateTable ¶
type CreateTable struct {
Name ObjectName
Columns []ColumnDef
Constraints []TableConstraint
Options *[]SqlOption
IfNotExists bool
Temporary bool
External bool
Stored bool
Transient bool
OrReplace bool
Global *bool
Volatile bool
Iceberg bool
HiveDistribution HiveDistributionStyle
HiveFormats *HiveFormat
TableProperties []SqlOption
WithOptions []SqlOption
FileFormat *FileFormat
Location *string
Query *Query
WithoutRowID bool
Like *ObjectName
Clone *ObjectName
Engine *TableEngine
Comment *CommentDef
AutoIncrementOffset *uint32
DefaultCharset *string
Collation *string
OnCommit *OnCommit
OnCluster *Ident
PrimaryKey *Expr
OrderBy *OneOrManyWithParens[Expr]
PartitionBy *Expr
ClusterBy *WrappedCollection[[]Ident]
ClusteredBy *ClusteredBy
Strict bool
CopyGrants bool
EnableSchemaEvolution *bool
ChangeTracking *bool
DataRetentionDays *uint64
MaxDataExtensionDays *uint64
DefaultDDLCollation *string
AggregationPolicy *ObjectName
RowAccessPolicy *RowAccessPolicy
Tags *[]Tag
BaseLocation *string
ExternalVolume *string
Catalog *string
CatalogSync *string
SerializationPolicy *StorageSerializationPolicy
}
CreateTable represents a CREATE TABLE statement
func (*CreateTable) Children ¶
func (c *CreateTable) Children() []Node
Children implements Node and returns all child nodes: the table name, column definitions, constraints, optional subquery, LIKE/CLONE targets, comment, and CLUSTERED BY / ROW ACCESS POLICY clauses.
func (*CreateTable) TokenLiteral ¶
func (c *CreateTable) TokenLiteral() string
TokenLiteral implements Node and returns "CREATE TABLE".
type CreateTableBuilder ¶
type CreateTableBuilder struct {
OrReplace bool
Temporary bool
External bool
Global *bool
IfNotExists bool
Transient bool
Volatile bool
Iceberg bool
Name ObjectName
Columns []ColumnDef
Constraints []TableConstraint
HiveDistribution HiveDistributionStyle
HiveFormats *HiveFormat
TableProperties []SqlOption
WithOptions []SqlOption
FileFormat *FileFormat
Location *string
Query *Query
WithoutRowID bool
Like *ObjectName
Clone *ObjectName
Engine *TableEngine
Comment *CommentDef
AutoIncrementOffset *uint32
DefaultCharset *string
Collation *string
OnCommit *OnCommit
OnCluster *Ident
PrimaryKey *Expr
OrderBy *OneOrManyWithParens[Expr]
PartitionBy *Expr
ClusterBy *WrappedCollection[[]Ident]
ClusteredBy *ClusteredBy
Options *[]SqlOption
Strict bool
CopyGrants bool
EnableSchemaEvolution *bool
ChangeTracking *bool
DataRetentionDays *uint64
MaxDataExtensionDays *uint64
DefaultDDLCollation *string
AggregationPolicy *ObjectName
RowAccessPolicy *RowAccessPolicy
Tags *[]Tag
BaseLocation *string
ExternalVolume *string
Catalog *string
CatalogSync *string
SerializationPolicy *StorageSerializationPolicy
}
CreateTableBuilder helps in building and accessing a create table statement with more ease. Example:
builder := NewCreateTableBuilder(ObjectName{Idents: []Ident{{Value: "table_name"}}}).
SetIfNotExists(true).
SetColumns([]ColumnDef{{
Name: Ident{Value: "c1"},
DataType: &DataType{Variant: &Int32Type{}},
}})
func FromStatement ¶
func FromStatement(stmt *StatementImpl) (*CreateTableBuilder, error)
FromStatement attempts to create a CreateTableBuilder from a Statement
func NewCreateTableBuilder ¶
func NewCreateTableBuilder(name ObjectName) *CreateTableBuilder
NewCreateTableBuilder creates a new CreateTableBuilder with default values
func (*CreateTableBuilder) Build ¶
func (b *CreateTableBuilder) Build() *StatementImpl
Build converts the builder into a CreateTable statement
func (*CreateTableBuilder) SetAggregationPolicy ¶
func (b *CreateTableBuilder) SetAggregationPolicy(v *ObjectName) *CreateTableBuilder
func (*CreateTableBuilder) SetAutoIncrementOffset ¶
func (b *CreateTableBuilder) SetAutoIncrementOffset(v *uint32) *CreateTableBuilder
func (*CreateTableBuilder) SetBaseLocation ¶
func (b *CreateTableBuilder) SetBaseLocation(v *string) *CreateTableBuilder
func (*CreateTableBuilder) SetCatalog ¶
func (b *CreateTableBuilder) SetCatalog(v *string) *CreateTableBuilder
func (*CreateTableBuilder) SetCatalogSync ¶
func (b *CreateTableBuilder) SetCatalogSync(v *string) *CreateTableBuilder
func (*CreateTableBuilder) SetChangeTracking ¶
func (b *CreateTableBuilder) SetChangeTracking(v *bool) *CreateTableBuilder
func (*CreateTableBuilder) SetClone ¶
func (b *CreateTableBuilder) SetClone(v *ObjectName) *CreateTableBuilder
func (*CreateTableBuilder) SetClusterBy ¶
func (b *CreateTableBuilder) SetClusterBy(v *WrappedCollection[[]Ident]) *CreateTableBuilder
func (*CreateTableBuilder) SetClusteredBy ¶
func (b *CreateTableBuilder) SetClusteredBy(v *ClusteredBy) *CreateTableBuilder
func (*CreateTableBuilder) SetCollation ¶
func (b *CreateTableBuilder) SetCollation(v *string) *CreateTableBuilder
func (*CreateTableBuilder) SetColumns ¶
func (b *CreateTableBuilder) SetColumns(v []ColumnDef) *CreateTableBuilder
func (*CreateTableBuilder) SetComment ¶
func (b *CreateTableBuilder) SetComment(v *CommentDef) *CreateTableBuilder
func (*CreateTableBuilder) SetConstraints ¶
func (b *CreateTableBuilder) SetConstraints(v []TableConstraint) *CreateTableBuilder
func (*CreateTableBuilder) SetCopyGrants ¶
func (b *CreateTableBuilder) SetCopyGrants(v bool) *CreateTableBuilder
func (*CreateTableBuilder) SetDataRetentionDays ¶
func (b *CreateTableBuilder) SetDataRetentionDays(v *uint64) *CreateTableBuilder
func (*CreateTableBuilder) SetDefaultCharset ¶
func (b *CreateTableBuilder) SetDefaultCharset(v *string) *CreateTableBuilder
func (*CreateTableBuilder) SetDefaultDDLCollation ¶
func (b *CreateTableBuilder) SetDefaultDDLCollation(v *string) *CreateTableBuilder
func (*CreateTableBuilder) SetEnableSchemaEvolution ¶
func (b *CreateTableBuilder) SetEnableSchemaEvolution(v *bool) *CreateTableBuilder
func (*CreateTableBuilder) SetEngine ¶
func (b *CreateTableBuilder) SetEngine(v *TableEngine) *CreateTableBuilder
func (*CreateTableBuilder) SetExternal ¶
func (b *CreateTableBuilder) SetExternal(v bool) *CreateTableBuilder
func (*CreateTableBuilder) SetExternalVolume ¶
func (b *CreateTableBuilder) SetExternalVolume(v *string) *CreateTableBuilder
func (*CreateTableBuilder) SetFileFormat ¶
func (b *CreateTableBuilder) SetFileFormat(v *FileFormat) *CreateTableBuilder
func (*CreateTableBuilder) SetGlobal ¶
func (b *CreateTableBuilder) SetGlobal(v *bool) *CreateTableBuilder
func (*CreateTableBuilder) SetHiveDistribution ¶
func (b *CreateTableBuilder) SetHiveDistribution(v HiveDistributionStyle) *CreateTableBuilder
func (*CreateTableBuilder) SetHiveFormats ¶
func (b *CreateTableBuilder) SetHiveFormats(v *HiveFormat) *CreateTableBuilder
func (*CreateTableBuilder) SetIceberg ¶
func (b *CreateTableBuilder) SetIceberg(v bool) *CreateTableBuilder
func (*CreateTableBuilder) SetIfNotExists ¶
func (b *CreateTableBuilder) SetIfNotExists(v bool) *CreateTableBuilder
func (*CreateTableBuilder) SetLike ¶
func (b *CreateTableBuilder) SetLike(v *ObjectName) *CreateTableBuilder
func (*CreateTableBuilder) SetLocation ¶
func (b *CreateTableBuilder) SetLocation(v *string) *CreateTableBuilder
func (*CreateTableBuilder) SetMaxDataExtensionDays ¶
func (b *CreateTableBuilder) SetMaxDataExtensionDays(v *uint64) *CreateTableBuilder
func (*CreateTableBuilder) SetOnCluster ¶
func (b *CreateTableBuilder) SetOnCluster(v *Ident) *CreateTableBuilder
func (*CreateTableBuilder) SetOnCommit ¶
func (b *CreateTableBuilder) SetOnCommit(v *OnCommit) *CreateTableBuilder
func (*CreateTableBuilder) SetOptions ¶
func (b *CreateTableBuilder) SetOptions(v *[]SqlOption) *CreateTableBuilder
func (*CreateTableBuilder) SetOrReplace ¶
func (b *CreateTableBuilder) SetOrReplace(v bool) *CreateTableBuilder
Fluent builder methods
func (*CreateTableBuilder) SetOrderBy ¶
func (b *CreateTableBuilder) SetOrderBy(v *OneOrManyWithParens[Expr]) *CreateTableBuilder
func (*CreateTableBuilder) SetPartitionBy ¶
func (b *CreateTableBuilder) SetPartitionBy(v *Expr) *CreateTableBuilder
func (*CreateTableBuilder) SetPrimaryKey ¶
func (b *CreateTableBuilder) SetPrimaryKey(v *Expr) *CreateTableBuilder
func (*CreateTableBuilder) SetQuery ¶
func (b *CreateTableBuilder) SetQuery(v *Query) *CreateTableBuilder
func (*CreateTableBuilder) SetRowAccessPolicy ¶
func (b *CreateTableBuilder) SetRowAccessPolicy(v *RowAccessPolicy) *CreateTableBuilder
func (*CreateTableBuilder) SetSerializationPolicy ¶
func (b *CreateTableBuilder) SetSerializationPolicy(v *StorageSerializationPolicy) *CreateTableBuilder
func (*CreateTableBuilder) SetStrict ¶
func (b *CreateTableBuilder) SetStrict(v bool) *CreateTableBuilder
func (*CreateTableBuilder) SetTableProperties ¶
func (b *CreateTableBuilder) SetTableProperties(v []SqlOption) *CreateTableBuilder
func (*CreateTableBuilder) SetTags ¶
func (b *CreateTableBuilder) SetTags(v *[]Tag) *CreateTableBuilder
func (*CreateTableBuilder) SetTemporary ¶
func (b *CreateTableBuilder) SetTemporary(v bool) *CreateTableBuilder
func (*CreateTableBuilder) SetTransient ¶
func (b *CreateTableBuilder) SetTransient(v bool) *CreateTableBuilder
func (*CreateTableBuilder) SetVolatile ¶
func (b *CreateTableBuilder) SetVolatile(v bool) *CreateTableBuilder
func (*CreateTableBuilder) SetWithOptions ¶
func (b *CreateTableBuilder) SetWithOptions(v []SqlOption) *CreateTableBuilder
func (*CreateTableBuilder) SetWithoutRowID ¶
func (b *CreateTableBuilder) SetWithoutRowID(v bool) *CreateTableBuilder
type CreateTableStatement ¶
type CreateTableStatement struct {
IfNotExists bool
Temporary bool
Name string
Columns []ColumnDef
Constraints []TableConstraint
Inherits []string
PartitionBy *PartitionBy
Partitions []PartitionDefinition // Individual partition definitions
Options []TableOption
WithoutRowID bool // SQLite: CREATE TABLE ... WITHOUT ROWID
}
CreateTableStatement represents a CREATE TABLE statement
func GetCreateTableStatement ¶ added in v1.9.3
func GetCreateTableStatement() *CreateTableStatement
GetCreateTableStatement gets a CreateTableStatement from the pool.
func (CreateTableStatement) Children ¶
func (c CreateTableStatement) Children() []Node
func (*CreateTableStatement) Format
deprecated
added in
v1.9.3
func (c *CreateTableStatement) Format(opts FormatOptions) string
Format returns the formatted SQL for this CREATE TABLE statement.
Deprecated: use pkg/formatter.FormatStatement() instead.
func (*CreateTableStatement) SQL ¶ added in v1.9.3
func (c *CreateTableStatement) SQL() string
SQL returns the full SQL string for this CREATE TABLE statement including column definitions, table constraints, INHERITS, PARTITION BY, and table options.
func (CreateTableStatement) TokenLiteral ¶
func (c CreateTableStatement) TokenLiteral() string
type CreateViewStatement ¶ added in v1.6.0
type CreateViewStatement struct {
OrReplace bool
Temporary bool
IfNotExists bool
Name string
Columns []string // Optional column list
Query Statement // The SELECT statement
WithOption string // PostgreSQL: WITH (CHECK OPTION | CASCADED | LOCAL)
}
CreateViewStatement represents a CREATE VIEW statement Syntax: CREATE [OR REPLACE] [TEMP|TEMPORARY] VIEW [IF NOT EXISTS] name [(columns)] AS select
func GetCreateViewStatement ¶ added in v1.9.3
func GetCreateViewStatement() *CreateViewStatement
GetCreateViewStatement gets a CreateViewStatement from the pool.
func (CreateViewStatement) Children ¶ added in v1.6.0
func (c CreateViewStatement) Children() []Node
func (*CreateViewStatement) Format
deprecated
added in
v1.9.3
func (c *CreateViewStatement) Format(opts FormatOptions) string
Format returns the formatted SQL for this CREATE VIEW statement.
Deprecated: use pkg/formatter.FormatStatement() instead.
func (*CreateViewStatement) SQL ¶ added in v1.9.3
func (c *CreateViewStatement) SQL() string
SQL returns the full SQL string for this CREATE VIEW statement including the optional OR REPLACE, TEMPORARY, IF NOT EXISTS, column list, SELECT query, and WITH CHECK OPTION clause.
func (CreateViewStatement) TokenLiteral ¶ added in v1.6.0
func (c CreateViewStatement) TokenLiteral() string
type CubeExpression ¶ added in v1.6.0
type CubeExpression struct {
Expressions []Expression
}
CubeExpression represents CUBE(col1, col2, ...) in GROUP BY clause CUBE generates all possible combinations of grouping sets Example: CUBE(a, b) generates grouping sets:
(a, b), (a), (b), ()
func (CubeExpression) Children ¶ added in v1.6.0
func (c CubeExpression) Children() []Node
func (*CubeExpression) SQL ¶ added in v1.9.3
func (c *CubeExpression) SQL() string
SQL returns the SQL representation of this CUBE expression as "CUBE(col1, col2, ...)".
func (CubeExpression) TokenLiteral ¶ added in v1.6.0
func (c CubeExpression) TokenLiteral() string
type CustomBinaryOperator ¶
type CustomBinaryOperator struct {
Parts []string
}
CustomBinaryOperator represents a custom binary operator (PostgreSQL-specific)
func (*CustomBinaryOperator) String ¶
func (op *CustomBinaryOperator) String() string
String returns the string representation of the custom binary operator
type CustomType ¶
type CustomType struct {
Name ObjectName
Modifiers []string
}
Basic data types
func (*CustomType) String ¶
func (t *CustomType) String() string
String returns the SQL representation of this custom/user-defined type, e.g. "my_type" or "my_type(arg1, arg2)".
type DataLoadingOption ¶
type DataLoadingOption struct {
OptionName string
OptionType DataLoadingOptionType
Value string
}
DataLoadingOption represents a single data loading option
func NewBooleanOption ¶
func NewBooleanOption(name string, value bool) DataLoadingOption
NewBooleanOption creates a new boolean-type DataLoadingOption
func NewEnumOption ¶
func NewEnumOption(name, value string) DataLoadingOption
NewEnumOption creates a new enum-type DataLoadingOption
func NewNumberOption ¶
func NewNumberOption(name string, value interface{}) DataLoadingOption
NewNumberOption creates a new number-type DataLoadingOption
func NewStringOption ¶
func NewStringOption(name, value string) DataLoadingOption
NewStringOption creates a new string-type DataLoadingOption
func (*DataLoadingOption) String ¶
func (d *DataLoadingOption) String() string
String implements the Stringer interface for DataLoadingOption
type DataLoadingOptionType ¶
type DataLoadingOptionType int
DataLoadingOptionType represents the type of a data loading option
const ( DataLoadingOptionTypeString DataLoadingOptionType = iota DataLoadingOptionTypeBoolean DataLoadingOptionTypeEnum DataLoadingOptionTypeNumber )
type DataLoadingOptions ¶
type DataLoadingOptions struct {
Options []DataLoadingOption
}
DataLoadingOptions represents a collection of data loading options
func (*DataLoadingOptions) String ¶
func (d *DataLoadingOptions) String() string
String implements the Stringer interface for DataLoadingOptions
type DataTypeVariant ¶
DataTypeVariant represents the different variants of SQL data types
type DateTimeField ¶
type DateTimeField int
DateTimeField represents date/time fields that can be extracted or used in operations
const ( Year DateTimeField = iota Years Month Months Week Weeks Day DayOfWeek DayOfYear Days Date Datetime Hour Hours Minute Minutes Second Seconds Century Decade Dow Doy Epoch Isodow IsoWeek Isoyear Julian Microsecond Microseconds Millenium //nolint:misspell // intentional: SQL accepts both spellings Millennium Millisecond Milliseconds Nanosecond Nanoseconds Quarter Time Timezone TimezoneAbbr TimezoneHour TimezoneMinute TimezoneRegion NoDateTime CustomDateTime )
func (DateTimeField) String ¶
func (d DateTimeField) String() string
String returns the SQL keyword for this date/time field (e.g. "YEAR", "MONTH", "DAY", "HOUR", "MINUTE", "SECOND", etc.).
type Delete ¶
type Delete struct {
Table TableReference
Where Expression
ReturningClause []Expression
}
Delete represents a DELETE statement
func (Delete) Children ¶
Children implements Node and returns all child nodes of this Delete statement.
func (*Delete) SQL ¶ added in v1.9.3
SQL returns the SQL representation of this Delete node (dml.go type). For the full-featured DELETE use DeleteStatement.SQL() instead.
func (Delete) TokenLiteral ¶
TokenLiteral implements Node and returns "DELETE".
type DeleteStatement ¶
type DeleteStatement struct {
With *WithClause
TableName string
Alias string
Using []TableReference
Where Expression
Returning []Expression
Pos models.Location // Source position of the DELETE keyword (1-based line and column)
}
DeleteStatement represents a DELETE SQL statement
func GetDeleteStatement ¶
func GetDeleteStatement() *DeleteStatement
GetDeleteStatement gets a DeleteStatement from the pool
func (DeleteStatement) Children ¶
func (d DeleteStatement) Children() []Node
func (*DeleteStatement) Format
deprecated
added in
v1.9.3
func (d *DeleteStatement) Format(opts FormatOptions) string
Format returns the formatted SQL for this DELETE statement.
Deprecated: use pkg/formatter.FormatStatement() instead.
func (*DeleteStatement) SQL ¶ added in v1.9.3
func (d *DeleteStatement) SQL() string
SQL returns the full SQL string for this DELETE statement, including the optional WITH clause, USING clause, WHERE condition, and RETURNING clause.
func (*DeleteStatement) Span ¶
func (d *DeleteStatement) Span() models.Span
Span returns the source location span for the DeleteStatement
func (DeleteStatement) TokenLiteral ¶
func (d DeleteStatement) TokenLiteral() string
type DescribeStatement ¶ added in v1.9.3
type DescribeStatement struct {
TableName string
}
DescribeStatement represents MySQL DESCRIBE/DESC/EXPLAIN table commands
func GetDescribeStatement ¶ added in v1.9.3
func GetDescribeStatement() *DescribeStatement
GetDescribeStatement gets a DescribeStatement from the pool.
func (DescribeStatement) Children ¶ added in v1.9.3
func (d DescribeStatement) Children() []Node
func (DescribeStatement) TokenLiteral ¶ added in v1.9.3
func (d DescribeStatement) TokenLiteral() string
type DollarQuotedString ¶
DollarQuotedString represents a dollar-quoted string with an optional tag
type DropBehavior ¶
type DropBehavior int
DropBehavior specifies the behavior when dropping objects
const ( DropCascade DropBehavior = iota DropRestrict )
type DropStatement ¶ added in v1.6.0
type DropStatement struct {
ObjectType string // TABLE, VIEW, MATERIALIZED VIEW, INDEX, etc.
IfExists bool
Names []string // Can drop multiple objects
CascadeType string // CASCADE, RESTRICT, or empty
}
DropStatement represents a DROP statement for tables, views, indexes, etc. Syntax: DROP object_type [IF EXISTS] name [CASCADE|RESTRICT]
func GetDropStatement ¶ added in v1.9.3
func GetDropStatement() *DropStatement
GetDropStatement gets a DropStatement from the pool.
func (DropStatement) Children ¶ added in v1.6.0
func (d DropStatement) Children() []Node
func (*DropStatement) Format
deprecated
added in
v1.9.3
func (d *DropStatement) Format(opts FormatOptions) string
Format returns the formatted SQL for this DROP statement.
Deprecated: use pkg/formatter.FormatStatement() instead.
func (*DropStatement) SQL ¶ added in v1.9.3
func (d *DropStatement) SQL() string
SQL returns the SQL representation of this DROP statement, including the object type, optional IF EXISTS, object names, and CASCADE/RESTRICT behavior.
func (DropStatement) TokenLiteral ¶ added in v1.6.0
func (d DropStatement) TokenLiteral() string
type EnumMember ¶
type EnumMember struct {
Name string
Value Expression
}
EnumMember represents a member of an ENUM type
func (*EnumMember) String ¶
func (e *EnumMember) String() string
String returns the SQL representation of this enum member, e.g. "'label'" or "'label' = expr".
type ExactNumberInfo ¶
ExactNumberInfo represents precision and scale information
func (*ExactNumberInfo) String ¶
func (e *ExactNumberInfo) String() string
String returns the SQL precision/scale clause, e.g. "(10)", "(10,2)", or "" when no precision is specified.
type ExistsExpression ¶
type ExistsExpression struct {
Subquery Statement
}
ExistsExpression represents EXISTS (subquery)
func (ExistsExpression) Children ¶
func (e ExistsExpression) Children() []Node
func (*ExistsExpression) Format
deprecated
added in
v1.9.3
func (e *ExistsExpression) Format(opts FormatOptions) string
Format returns the formatted SQL for this EXISTS expression.
Deprecated: use pkg/formatter.FormatExpression() instead.
func (*ExistsExpression) SQL ¶ added in v1.9.3
func (e *ExistsExpression) SQL() string
SQL returns the SQL representation of this EXISTS expression as "EXISTS (subquery)".
func (ExistsExpression) TokenLiteral ¶
func (e ExistsExpression) TokenLiteral() string
type Expr ¶
type Expr interface {
Node
// contains filtered or unexported methods
}
Expr represents a SQL expression
type Expression ¶
type Expression interface {
Node
// contains filtered or unexported methods
}
Expression represents a SQL expression node in the AST.
Expression extends the Node interface and represents SQL expressions that can appear within statements, such as literals, identifiers, binary operations, function calls, subqueries, etc.
All expression types implement both Node and Expression interfaces. The expressionNode() method is a marker method to distinguish expressions from statements at compile time.
Supported Expression Types:
- Basic: Identifier, LiteralValue, AliasedExpression
- Operators: BinaryExpression, UnaryExpression, BetweenExpression, InExpression
- Functions: FunctionCall (with window function support)
- Subqueries: SubqueryExpression, ExistsExpression, AnyExpression, AllExpression
- Conditional: CaseExpression, CastExpression
- Grouping: RollupExpression, CubeExpression, GroupingSetsExpression
Example - Building an expression:
// Build: column = 'value'
expr := &BinaryExpression{
Left: &Identifier{Name: "column"},
Operator: "=",
Right: &LiteralValue{Value: "value", Type: "STRING"},
}
type ExtractExpression ¶
type ExtractExpression struct {
Field string
Source Expression
}
ExtractExpression represents EXTRACT(field FROM source)
func (ExtractExpression) Children ¶
func (e ExtractExpression) Children() []Node
func (*ExtractExpression) SQL ¶ added in v1.9.3
func (e *ExtractExpression) SQL() string
SQL returns "EXTRACT(field FROM source)" as a SQL string.
func (ExtractExpression) TokenLiteral ¶
func (e ExtractExpression) TokenLiteral() string
type FetchClause ¶ added in v1.6.0
type FetchClause struct {
// OffsetValue is the number of rows to skip (OFFSET n ROWS)
OffsetValue *int64
// FetchValue is the number of rows to fetch (FETCH n ROWS)
FetchValue *int64
// FetchType is either "FIRST" or "NEXT"
FetchType string
// IsPercent indicates FETCH ... PERCENT ROWS
IsPercent bool
// WithTies indicates FETCH ... WITH TIES (includes tied rows)
WithTies bool
}
FetchClause represents the SQL-99 FETCH FIRST/NEXT clause (F861, F862) Syntax: [OFFSET n {ROW | ROWS}] FETCH {FIRST | NEXT} n [{ROW | ROWS}] {ONLY | WITH TIES} Examples:
- OFFSET 20 ROWS FETCH NEXT 10 ROWS ONLY
- FETCH FIRST 5 ROWS ONLY
- FETCH FIRST 10 PERCENT ROWS WITH TIES
func (FetchClause) Children ¶ added in v1.6.0
func (f FetchClause) Children() []Node
func (FetchClause) TokenLiteral ¶ added in v1.6.0
func (f FetchClause) TokenLiteral() string
type FileFormat ¶
type FileFormat int
FileFormat represents file format specifications
const ( FileFormatNone FileFormat = iota FileFormatCSV FileFormatJSON FileFormatParquet )
type FileStagingCommand ¶
type FileStagingCommand struct {
Stage ObjectName
Pattern *string
}
FileStagingCommand represents a file staging command
func (*FileStagingCommand) String ¶
func (f *FileStagingCommand) String() string
String implements the Stringer interface for FileStagingCommand
type ForClause ¶ added in v1.7.0
type ForClause struct {
// LockType specifies the type of lock:
// "UPDATE" - exclusive lock for UPDATE operations
// "SHARE" - shared lock for read operations
// "NO KEY UPDATE" - PostgreSQL: exclusive lock that doesn't block SHARE locks on same row
// "KEY SHARE" - PostgreSQL: shared lock that doesn't block UPDATE locks
LockType string
// Tables specifies which tables to lock (FOR UPDATE OF table_name)
// Empty slice means lock all tables in the query
Tables []string
// NoWait indicates NOWAIT option (fail immediately if lock cannot be acquired)
NoWait bool
// SkipLocked indicates SKIP LOCKED option (skip rows that can't be locked)
SkipLocked bool
}
ForClause represents row-level locking clauses in SELECT statements (SQL:2003, PostgreSQL, MySQL) Syntax: FOR {UPDATE | SHARE | NO KEY UPDATE | KEY SHARE} [OF table_name [, ...]] [NOWAIT | SKIP LOCKED] Examples:
- FOR UPDATE
- FOR SHARE NOWAIT
- FOR UPDATE OF orders SKIP LOCKED
- FOR NO KEY UPDATE
- FOR KEY SHARE
func (ForClause) TokenLiteral ¶ added in v1.7.0
type FormatOptions ¶ added in v1.9.3
type FormatOptions struct {
// IndentStyle selects spaces or tabs.
IndentStyle IndentStyle
// IndentWidth is the number of spaces (or tabs) per indent level.
IndentWidth int
// KeywordCase controls keyword casing.
KeywordCase KeywordCase
// LineWidth is the target max line width. 0 means no limit (compact).
LineWidth int
// NewlinePerClause puts each major clause (FROM, WHERE, etc.) on its own line.
NewlinePerClause bool
// AddSemicolon appends a semicolon to each statement.
AddSemicolon bool
}
FormatOptions configures SQL formatting behavior.
func CompactStyle ¶ added in v1.9.3
func CompactStyle() FormatOptions
CompactStyle returns formatting options for minimal whitespace output.
func ReadableStyle ¶ added in v1.9.3
func ReadableStyle() FormatOptions
ReadableStyle returns formatting options for human-readable output.
type FunctionCall ¶
type FunctionCall struct {
Name string
Arguments []Expression // Renamed from Args for consistency
Over *WindowSpec // For window functions
Distinct bool
Filter Expression // WHERE clause for aggregate functions
OrderBy []OrderByExpression // ORDER BY clause for aggregate functions (STRING_AGG, ARRAY_AGG, etc.)
WithinGroup []OrderByExpression // ORDER BY clause for ordered-set aggregates (PERCENTILE_CONT, etc.)
Pos models.Location // Source position of the function name (1-based line and column)
}
FunctionCall represents a function call expression with full SQL-99/PostgreSQL support.
FunctionCall supports:
- Scalar functions: UPPER(), LOWER(), COALESCE(), etc.
- Aggregate functions: COUNT(), SUM(), AVG(), MAX(), MIN(), etc.
- Window functions: ROW_NUMBER(), RANK(), DENSE_RANK(), LAG(), LEAD(), etc.
- DISTINCT modifier: COUNT(DISTINCT column)
- FILTER clause: Conditional aggregation (PostgreSQL v1.6.0)
- ORDER BY clause: For order-sensitive aggregates like STRING_AGG, ARRAY_AGG (v1.6.0)
- OVER clause: Window specifications for window functions
Fields:
- Name: Function name (e.g., "COUNT", "SUM", "ROW_NUMBER")
- Arguments: Function arguments (expressions)
- Over: Window specification for window functions (OVER clause)
- Distinct: DISTINCT modifier for aggregates (COUNT(DISTINCT col))
- Filter: FILTER clause for conditional aggregation (PostgreSQL v1.6.0)
- OrderBy: ORDER BY clause for order-sensitive aggregates (v1.6.0)
Example - Basic aggregate:
FunctionCall{
Name: "COUNT",
Arguments: []Expression{&Identifier{Name: "id"}},
}
// SQL: COUNT(id)
Example - Window function:
FunctionCall{
Name: "ROW_NUMBER",
Over: &WindowSpec{
PartitionBy: []Expression{&Identifier{Name: "dept_id"}},
OrderBy: []OrderByExpression{{Expression: &Identifier{Name: "salary"}, Ascending: false}},
},
}
// SQL: ROW_NUMBER() OVER (PARTITION BY dept_id ORDER BY salary DESC)
Example - FILTER clause (PostgreSQL v1.6.0):
FunctionCall{
Name: "COUNT",
Arguments: []Expression{&Identifier{Name: "id"}},
Filter: &BinaryExpression{Left: &Identifier{Name: "status"}, Operator: "=", Right: &LiteralValue{Value: "active"}},
}
// SQL: COUNT(id) FILTER (WHERE status = 'active')
Example - ORDER BY in aggregate (PostgreSQL v1.6.0):
FunctionCall{
Name: "STRING_AGG",
Arguments: []Expression{&Identifier{Name: "name"}, &LiteralValue{Value: ", "}},
OrderBy: []OrderByExpression{{Expression: &Identifier{Name: "name"}, Ascending: true}},
}
// SQL: STRING_AGG(name, ', ' ORDER BY name)
Example - Window function with frame:
FunctionCall{
Name: "AVG",
Arguments: []Expression{&Identifier{Name: "amount"}},
Over: &WindowSpec{
OrderBy: []OrderByExpression{{Expression: &Identifier{Name: "date"}, Ascending: true}},
FrameClause: &WindowFrame{
Type: "ROWS",
Start: WindowFrameBound{Type: "2 PRECEDING"},
End: &WindowFrameBound{Type: "CURRENT ROW"},
},
},
}
// SQL: AVG(amount) OVER (ORDER BY date ROWS BETWEEN 2 PRECEDING AND CURRENT ROW)
New in v1.6.0:
- Filter: FILTER clause for conditional aggregation
- OrderBy: ORDER BY clause for order-sensitive aggregates (STRING_AGG, ARRAY_AGG, etc.)
- WithinGroup: ORDER BY clause for ordered-set aggregates (PERCENTILE_CONT, PERCENTILE_DISC, MODE, etc.)
func GetFunctionCall ¶ added in v1.6.0
func GetFunctionCall() *FunctionCall
GetFunctionCall gets a FunctionCall from the pool
func (FunctionCall) Children ¶
func (f FunctionCall) Children() []Node
func (*FunctionCall) SQL ¶ added in v1.9.3
func (f *FunctionCall) SQL() string
SQL returns the SQL representation of this function call including arguments, optional DISTINCT modifier, ORDER BY clause (for aggregates like STRING_AGG), WITHIN GROUP (for ordered-set aggregates), FILTER (WHERE ...) clause, and OVER (...) window specification.
func (*FunctionCall) Span ¶
func (e *FunctionCall) Span() models.Span
Span returns the union of source location spans for all arguments of this function call. Returns an empty span if no arguments implement Spanned.
func (FunctionCall) TokenLiteral ¶
func (f FunctionCall) TokenLiteral() string
type FunctionDesc ¶
type FunctionDesc struct {
Name ObjectName
Schema string // Optional schema qualifier
Arguments []string
}
FunctionDesc represents a function descriptor used in SQL statements
func (FunctionDesc) Children ¶
func (f FunctionDesc) Children() []Node
Children implements Node and returns nil — FunctionDesc has no child nodes.
func (FunctionDesc) String ¶
func (f FunctionDesc) String() string
String returns the SQL representation of this function descriptor, including the optional schema qualifier and argument list (e.g. "schema.func(arg1, arg2)").
func (FunctionDesc) TokenLiteral ¶
func (f FunctionDesc) TokenLiteral() string
TokenLiteral implements Node and returns the SQL representation of this function descriptor (delegates to String).
type GroupingSetsExpression ¶ added in v1.6.0
type GroupingSetsExpression struct {
Sets [][]Expression // Each inner slice is one grouping set
}
GroupingSetsExpression represents GROUPING SETS(...) in GROUP BY clause Allows explicit specification of grouping sets Example: GROUPING SETS((a, b), (a), ())
func (GroupingSetsExpression) Children ¶ added in v1.6.0
func (g GroupingSetsExpression) Children() []Node
func (*GroupingSetsExpression) SQL ¶ added in v1.9.3
func (g *GroupingSetsExpression) SQL() string
SQL returns the SQL representation of this GROUPING SETS expression as "GROUPING SETS((a, b), (a), ())".
func (GroupingSetsExpression) TokenLiteral ¶ added in v1.6.0
func (g GroupingSetsExpression) TokenLiteral() string
type HiveDistributionStyle ¶
type HiveDistributionStyle int
HiveDistributionStyle represents Hive-specific distribution styles
const ( HiveDistributionNone HiveDistributionStyle = iota HiveDistributionHash HiveDistributionRandom )
type HiveFormat ¶
type HiveFormat int
HiveFormat represents Hive-specific storage formats
const ( HiveFormatNone HiveFormat = iota HiveFormatORC HiveFormatParquet HiveFormatAvro )
type Ident ¶
type Ident struct {
Name string
}
Ident represents an identifier in SQL (table name, column name, etc.)
func (*Ident) SQL ¶ added in v1.9.3
SQL returns the unquoted identifier name. Used for round-trip serialization.
func (*Ident) TokenLiteral ¶
TokenLiteral implements Node and returns the identifier name.
type Identifier ¶
type Identifier struct {
Name string
Table string // Optional table qualifier
Pos models.Location // Source position of this identifier (1-based line and column)
}
Identifier represents a column or table name
func GetIdentifier ¶
func GetIdentifier() *Identifier
GetIdentifier gets an Identifier from the pool
func (Identifier) Children ¶
func (i Identifier) Children() []Node
func (*Identifier) SQL ¶ added in v1.9.3
func (i *Identifier) SQL() string
SQL returns the SQL representation of the identifier. Identifiers are emitted unescaped because they have already been validated during parsing — the tokenizer and parser only accept syntactically valid identifiers (or quoted identifiers whose quotes are preserved in the AST). Re-escaping here would be redundant and could introduce double-quoting bugs.
func (Identifier) TokenLiteral ¶
func (i Identifier) TokenLiteral() string
type InExpression ¶
type InExpression struct {
Expr Expression
List []Expression // For value list: IN (1, 2, 3)
Subquery Statement // For subquery: IN (SELECT ...)
Not bool
Pos models.Location // Source position of the IN keyword (1-based line and column)
}
InExpression represents expr IN (values) or expr IN (subquery)
func GetInExpression ¶ added in v1.6.0
func GetInExpression() *InExpression
GetInExpression gets an InExpression from the pool
func (InExpression) Children ¶
func (i InExpression) Children() []Node
func (*InExpression) Format
deprecated
added in
v1.9.3
func (i *InExpression) Format(opts FormatOptions) string
Format returns the formatted SQL for this IN expression.
Deprecated: use pkg/formatter.FormatExpression() instead.
func (*InExpression) SQL ¶ added in v1.9.3
func (i *InExpression) SQL() string
SQL returns the SQL representation of this IN expression. The NOT modifier is included when InExpression.Not is true. Supports both value lists "x IN (1, 2, 3)" and subqueries "x IN (SELECT ...)".
func (InExpression) TokenLiteral ¶
func (i InExpression) TokenLiteral() string
type IndentStyle ¶ added in v1.9.3
type IndentStyle int
IndentStyle controls the indentation character.
const ( // IndentSpaces uses spaces for indentation. IndentSpaces IndentStyle = iota // IndentTabs uses tabs for indentation. IndentTabs )
type IndexColumn ¶
type IndexColumn struct {
Column string
Collate string
Direction string // ASC, DESC
NullsLast bool
}
IndexColumn represents a column in an index definition
func (IndexColumn) Children ¶
func (i IndexColumn) Children() []Node
func (IndexColumn) TokenLiteral ¶
func (i IndexColumn) TokenLiteral() string
type IndexOption ¶
type IndexOption struct {
Type IndexOptionType
Using *IndexType // Used for Using
Comment string // Used for Comment
}
IndexOption represents MySQL index options
func (*IndexOption) String ¶
func (opt *IndexOption) String() string
String returns the SQL representation of this index option (e.g. "USING BTREE" or "COMMENT 'text'").
type IndexOptionType ¶
type IndexOptionType int
IndexOptionType identifies which kind of index option is represented.
const ( // UsingIndex specifies the index access method (e.g. USING BTREE). UsingIndex IndexOptionType = iota // CommentIndex attaches a comment string to the index. CommentIndex )
type InputFormatClause ¶
InputFormatClause represents the format specification for input data
type Insert ¶
type Insert struct {
Table TableReference
Columns []Expression
Values [][]Expression
ReturningClause []Expression
}
Insert represents an INSERT statement
func (Insert) Children ¶
Children implements Node and returns all child nodes of this Insert statement.
func (*Insert) SQL ¶ added in v1.9.3
SQL returns the SQL representation of this Insert node (dml.go type). For the full-featured INSERT use InsertStatement.SQL() instead.
func (Insert) TokenLiteral ¶
TokenLiteral implements Node and returns "INSERT".
type InsertStatement ¶
type InsertStatement struct {
With *WithClause
TableName string
Columns []Expression
Output []Expression // SQL Server OUTPUT clause columns
Values [][]Expression // Multi-row support: each inner slice is one row of values
Query QueryExpression // For INSERT ... SELECT (SelectStatement or SetOperation)
Returning []Expression
OnConflict *OnConflict
OnDuplicateKey *UpsertClause // MySQL: ON DUPLICATE KEY UPDATE
Pos models.Location // Source position of the INSERT keyword (1-based line and column)
}
InsertStatement represents an INSERT SQL statement
func GetInsertStatement ¶
func GetInsertStatement() *InsertStatement
GetInsertStatement gets an InsertStatement from the pool
func (InsertStatement) Children ¶
func (i InsertStatement) Children() []Node
func (*InsertStatement) Format
deprecated
added in
v1.9.3
func (i *InsertStatement) Format(opts FormatOptions) string
Format returns the formatted SQL for this INSERT statement.
Deprecated: use pkg/formatter.FormatStatement() instead.
func (*InsertStatement) SQL ¶ added in v1.9.3
func (i *InsertStatement) SQL() string
SQL returns the full SQL string for this INSERT statement, including the optional WITH clause, column list, VALUES rows or SELECT subquery, ON CONFLICT clause, and RETURNING clause.
func (*InsertStatement) Span ¶
func (i *InsertStatement) Span() models.Span
Span returns the source location span for the InsertStatement
func (InsertStatement) TokenLiteral ¶
func (i InsertStatement) TokenLiteral() string
type Inspector ¶
Inspector represents a function-based AST visitor for simplified traversal.
Inspector is a function type that can be used to traverse the AST without creating a custom visitor type. It's a convenience wrapper around the Visitor interface for simple use cases.
The function receives each node and returns a boolean:
- true: Continue traversing this node's children
- false: Skip this node's children (prune subtree)
Example - Counting specific node types:
selectCount := 0
inspector := ast.Inspector(func(node ast.Node) bool {
if _, ok := node.(*ast.SelectStatement); ok {
selectCount++
}
return true // Continue traversing
})
ast.Walk(inspector, astNode)
See also: Inspect() for a more convenient function form
func (Inspector) Visit ¶
Visit implements the Visitor interface for Inspector.
Visit wraps the inspector function to conform to the Visitor interface. It calls the inspector function and returns the appropriate visitor based on the boolean result:
- true: Returns self to continue traversing children
- false: Returns nil to skip children
This method enables Inspector to be used with Walk().
type IntegerType ¶
Basic data types
func (*IntegerType) String ¶
func (t *IntegerType) String() string
String returns the SQL representation of this INTEGER type, e.g. "INTEGER", "INTEGER(11)", or "INTEGER UNSIGNED".
type IntervalExpression ¶ added in v1.7.0
type IntervalExpression struct {
Value string // The interval specification string (e.g., '1 day', '2 hours')
}
IntervalExpression represents INTERVAL 'value' for date/time arithmetic Examples: INTERVAL '1 day', INTERVAL '2 hours', INTERVAL '1 year 2 months'
func GetIntervalExpression ¶ added in v1.7.0
func GetIntervalExpression() *IntervalExpression
GetIntervalExpression gets an IntervalExpression from the pool
func (IntervalExpression) Children ¶ added in v1.7.0
func (i IntervalExpression) Children() []Node
func (*IntervalExpression) SQL ¶ added in v1.9.3
func (i *IntervalExpression) SQL() string
SQL returns the SQL representation of this interval as "INTERVAL 'value'".
func (*IntervalExpression) Span ¶ added in v1.7.0
func (i *IntervalExpression) Span() models.Span
Span returns an empty source location span for this interval expression. IntervalExpression stores no child expressions, so no span can be derived.
func (IntervalExpression) TokenLiteral ¶ added in v1.7.0
func (i IntervalExpression) TokenLiteral() string
type JoinClause ¶
type JoinClause struct {
Type string // INNER, LEFT, RIGHT, FULL
Left TableReference
Right TableReference
Condition Expression
Pos models.Location // Source position of the JOIN keyword (1-based line and column)
}
JoinClause represents a JOIN clause in SQL
func (JoinClause) Children ¶
func (j JoinClause) Children() []Node
func (JoinClause) TokenLiteral ¶
func (j JoinClause) TokenLiteral() string
type KeywordCase ¶ added in v1.9.3
type KeywordCase int
KeywordCase controls how SQL keywords are emitted.
const ( // KeywordUpper converts keywords to uppercase (SELECT, FROM, WHERE). KeywordUpper KeywordCase = iota // KeywordLower converts keywords to lowercase (select, from, where). KeywordLower // KeywordPreserve keeps keywords in their original case. KeywordPreserve )
type ListExpression ¶
type ListExpression struct {
Values []Expression
}
ListExpression represents a list of expressions (1, 2, 3)
func (ListExpression) Children ¶
func (l ListExpression) Children() []Node
func (*ListExpression) SQL ¶ added in v1.9.3
func (l *ListExpression) SQL() string
SQL returns the SQL representation of this list expression as a comma-separated parenthesized list: "(v1, v2, v3)".
func (ListExpression) TokenLiteral ¶
func (l ListExpression) TokenLiteral() string
type LiteralValue ¶
type LiteralValue struct {
Value interface{}
Type string // INTEGER, FLOAT, STRING, BOOLEAN, NULL, etc.
}
LiteralValue represents a literal value in SQL
func GetLiteralValue ¶
func GetLiteralValue() *LiteralValue
GetLiteralValue gets a LiteralValue from the pool
func (LiteralValue) Children ¶
func (l LiteralValue) Children() []Node
func (*LiteralValue) SQL ¶ added in v1.9.3
func (l *LiteralValue) SQL() string
SQL returns the SQL literal representation of this value. Strings are single-quoted with proper escaping; NULLs are returned as "NULL"; booleans are returned in uppercase (TRUE/FALSE); numbers are returned as-is.
func (LiteralValue) TokenLiteral ¶
func (l LiteralValue) TokenLiteral() string
type MergeAction ¶ added in v1.6.0
type MergeAction struct {
ActionType string // "UPDATE", "INSERT", "DELETE"
SetClauses []SetClause // For UPDATE: SET column = value pairs
Columns []string // For INSERT: column list
Values []Expression // For INSERT: value list
DefaultValues bool // For INSERT: use DEFAULT VALUES
}
MergeAction represents the action in a WHEN clause ActionType: UPDATE, INSERT, DELETE
func (MergeAction) Children ¶ added in v1.6.0
func (a MergeAction) Children() []Node
func (MergeAction) TokenLiteral ¶ added in v1.6.0
func (a MergeAction) TokenLiteral() string
type MergeStatement ¶ added in v1.6.0
type MergeStatement struct {
TargetTable TableReference // The table being merged into
TargetAlias string // Optional alias for target
SourceTable TableReference // The source table or subquery
SourceAlias string // Optional alias for source
OnCondition Expression // The join/match condition
WhenClauses []*MergeWhenClause // List of WHEN clauses
Output []Expression // SQL Server OUTPUT clause columns
}
MergeStatement represents a MERGE statement (SQL:2003 F312) Syntax: MERGE INTO target USING source ON condition
WHEN MATCHED THEN UPDATE/DELETE WHEN NOT MATCHED THEN INSERT WHEN NOT MATCHED BY SOURCE THEN UPDATE/DELETE
func GetMergeStatement ¶ added in v1.9.3
func GetMergeStatement() *MergeStatement
GetMergeStatement gets a MergeStatement from the pool.
func (MergeStatement) Children ¶ added in v1.6.0
func (m MergeStatement) Children() []Node
func (*MergeStatement) Format
deprecated
added in
v1.9.3
func (m *MergeStatement) Format(opts FormatOptions) string
Format returns the formatted SQL for this MERGE statement.
Deprecated: use pkg/formatter.FormatStatement() instead.
func (*MergeStatement) SQL ¶ added in v1.9.3
func (m *MergeStatement) SQL() string
SQL returns the full SQL string for this MERGE statement including the target, source, ON condition, and all WHEN MATCHED/NOT MATCHED clauses.
func (MergeStatement) TokenLiteral ¶ added in v1.6.0
func (m MergeStatement) TokenLiteral() string
type MergeWhenClause ¶ added in v1.6.0
type MergeWhenClause struct {
Type string // "MATCHED", "NOT_MATCHED", "NOT_MATCHED_BY_SOURCE"
Condition Expression // Optional AND condition
Action *MergeAction // The action to perform (UPDATE/INSERT/DELETE)
}
MergeWhenClause represents a WHEN clause in a MERGE statement Types: MATCHED, NOT_MATCHED, NOT_MATCHED_BY_SOURCE
func (MergeWhenClause) Children ¶ added in v1.6.0
func (w MergeWhenClause) Children() []Node
func (MergeWhenClause) TokenLiteral ¶ added in v1.6.0
func (w MergeWhenClause) TokenLiteral() string
type Node ¶
Node represents any node in the Abstract Syntax Tree.
Node is the base interface that all AST nodes must implement. It provides two core methods for tree inspection and traversal:
- TokenLiteral(): Returns the literal token value that starts this node
- Children(): Returns all child nodes for tree traversal
The Node interface enables the visitor pattern for AST traversal. Use the Walk() and Inspect() functions from visitor.go to traverse the tree.
Example - Checking node type:
switch node := astNode.(type) {
case *SelectStatement:
fmt.Println("Found SELECT statement")
case *BinaryExpression:
fmt.Printf("Binary operator: %s\n", node.Operator)
}
type NormalizationForm ¶
type NormalizationForm int
NormalizationForm represents Unicode normalization forms
const ( NFC NormalizationForm = iota NFD NFKC NFKD )
func (NormalizationForm) String ¶
func (n NormalizationForm) String() string
String returns the Unicode normalization form name ("NFC", "NFD", "NFKC", or "NFKD").
type NullsDistinctOption ¶
type NullsDistinctOption int
NullsDistinctOption represents Postgres unique index nulls handling
const ( NullsDistinctNone NullsDistinctOption = iota NullsDistinct NullsNotDistinct )
func (NullsDistinctOption) String ¶
func (opt NullsDistinctOption) String() string
String returns the SQL keyword phrase for this nulls-distinct option: "NULLS DISTINCT", "NULLS NOT DISTINCT", or an empty string for the default.
type NumericType ¶
type NumericType struct {
Info *ExactNumberInfo
}
Basic data types
func (*NumericType) String ¶
func (t *NumericType) String() string
String returns the SQL representation of this NUMERIC type, e.g. "NUMERIC", "NUMERIC(10)", or "NUMERIC(10,2)".
type ObjectName ¶
type ObjectName struct {
Name string
}
ObjectName represents a qualified or unqualified object name
func (ObjectName) Children ¶
func (o ObjectName) Children() []Node
Children implements Node and returns nil — ObjectName has no child nodes.
func (ObjectName) String ¶
func (o ObjectName) String() string
String returns the object name as a plain string.
func (ObjectName) TokenLiteral ¶
func (o ObjectName) TokenLiteral() string
TokenLiteral implements Node and returns the object name string.
type OnConflict ¶
type OnConflict struct {
Target []Expression // Target columns
Constraint string // Optional constraint name
Action OnConflictAction
}
OnConflict represents ON CONFLICT DO UPDATE/NOTHING clause
func (OnConflict) Children ¶
func (o OnConflict) Children() []Node
func (OnConflict) TokenLiteral ¶
func (o OnConflict) TokenLiteral() string
type OnConflictAction ¶
type OnConflictAction struct {
DoNothing bool
DoUpdate []UpdateExpression
Where Expression
}
OnConflictAction represents DO UPDATE/NOTHING in ON CONFLICT clause
type OneOrManyWithParens ¶
type OneOrManyWithParens[T any] struct { Items []T }
OneOrManyWithParens represents a list of items enclosed in parentheses
func (*OneOrManyWithParens[T]) Children ¶
func (o *OneOrManyWithParens[T]) Children() []Node
Children implements Node and returns all items as Node values (items that do not implement Node are represented as nil slots).
func (*OneOrManyWithParens[T]) TokenLiteral ¶
func (o *OneOrManyWithParens[T]) TokenLiteral() string
TokenLiteral implements Node and returns "(" to represent the opening parenthesis of the parenthesized list.
type OrderByExpression ¶ added in v1.6.0
type OrderByExpression struct {
Expression Expression // The expression to order by
Ascending bool // true for ASC (default), false for DESC
NullsFirst *bool // nil = default behavior, true = NULLS FIRST, false = NULLS LAST
}
OrderByExpression represents an ORDER BY clause element with direction and NULL ordering
func (*OrderByExpression) Children ¶ added in v1.6.0
func (o *OrderByExpression) Children() []Node
func (*OrderByExpression) TokenLiteral ¶ added in v1.6.0
func (o *OrderByExpression) TokenLiteral() string
type PartitionBy ¶
type PartitionBy struct {
Type string // RANGE, LIST, HASH
Columns []string
Boundary []Expression
}
PartitionBy represents a PARTITION BY clause
func (PartitionBy) Children ¶
func (p PartitionBy) Children() []Node
func (PartitionBy) TokenLiteral ¶
func (p PartitionBy) TokenLiteral() string
type PartitionDefinition ¶ added in v1.6.0
type PartitionDefinition struct {
Name string
Type string // FOR VALUES, IN, LESS THAN
Values []Expression // Partition values or bounds
LessThan Expression // For RANGE: LESS THAN (value)
From Expression // For RANGE: FROM (value)
To Expression // For RANGE: TO (value)
InValues []Expression // For LIST: IN (values)
Tablespace string // Optional tablespace
}
PartitionDefinition represents a partition definition in CREATE TABLE Syntax: PARTITION name VALUES { LESS THAN (expr) | IN (list) | FROM (expr) TO (expr) }
func (PartitionDefinition) Children ¶ added in v1.6.0
func (p PartitionDefinition) Children() []Node
func (PartitionDefinition) TokenLiteral ¶ added in v1.6.0
func (p PartitionDefinition) TokenLiteral() string
type PositionExpression ¶
type PositionExpression struct {
Substr Expression
Str Expression
}
PositionExpression represents POSITION(substr IN str)
func (PositionExpression) Children ¶
func (p PositionExpression) Children() []Node
func (*PositionExpression) SQL ¶ added in v1.9.3
func (p *PositionExpression) SQL() string
SQL returns "POSITION(substr IN str)" as a SQL string.
func (PositionExpression) TokenLiteral ¶
func (p PositionExpression) TokenLiteral() string
type PragmaStatement ¶ added in v1.9.3
type PragmaStatement struct {
Name string // Pragma name, e.g. "table_info"
Arg string // Optional: parenthesized arg, e.g. "users"
Value string // Optional: assigned value, e.g. "WAL"
}
PragmaStatement represents a SQLite PRAGMA statement. Examples: PRAGMA table_info(users), PRAGMA journal_mode = WAL, PRAGMA integrity_check
func (PragmaStatement) Children ¶ added in v1.9.3
func (p PragmaStatement) Children() []Node
func (PragmaStatement) TokenLiteral ¶ added in v1.9.3
func (p PragmaStatement) TokenLiteral() string
type Query ¶
type Query struct {
Text string
}
Query represents a SQL query
func (*Query) TokenLiteral ¶
TokenLiteral implements Node and returns "QUERY".
type QueryExpression ¶ added in v1.9.3
type QueryExpression interface {
Statement
// contains filtered or unexported methods
}
QueryExpression is a Statement that can appear as the source of INSERT ... SELECT. Only *SelectStatement and *SetOperation satisfy this interface.
type ReferenceDefinition ¶
type ReferenceDefinition struct {
Table string
Columns []string
OnDelete string
OnUpdate string
Match string
}
ReferenceDefinition represents a REFERENCES clause
func (ReferenceDefinition) Children ¶
func (r ReferenceDefinition) Children() []Node
func (*ReferenceDefinition) String ¶
func (r *ReferenceDefinition) String() string
String returns a string representation of a ReferenceDefinition
func (ReferenceDefinition) TokenLiteral ¶
func (r ReferenceDefinition) TokenLiteral() string
type RefreshMaterializedViewStatement ¶ added in v1.6.0
type RefreshMaterializedViewStatement struct {
Concurrently bool
Name string
WithData *bool // nil = default, true = WITH DATA, false = WITH NO DATA
}
RefreshMaterializedViewStatement represents a REFRESH MATERIALIZED VIEW statement Syntax: REFRESH MATERIALIZED VIEW [CONCURRENTLY] name [WITH [NO] DATA]
func GetRefreshMaterializedViewStatement ¶ added in v1.9.3
func GetRefreshMaterializedViewStatement() *RefreshMaterializedViewStatement
GetRefreshMaterializedViewStatement gets a RefreshMaterializedViewStatement from the pool.
func (RefreshMaterializedViewStatement) Children ¶ added in v1.6.0
func (r RefreshMaterializedViewStatement) Children() []Node
func (*RefreshMaterializedViewStatement) Format
deprecated
added in
v1.9.3
func (r *RefreshMaterializedViewStatement) Format(opts FormatOptions) string
Format returns the formatted SQL for this REFRESH MATERIALIZED VIEW statement.
Deprecated: use pkg/formatter.FormatStatement() instead.
func (*RefreshMaterializedViewStatement) SQL ¶ added in v1.9.3
func (r *RefreshMaterializedViewStatement) SQL() string
SQL returns the SQL string for this REFRESH MATERIALIZED VIEW statement.
func (RefreshMaterializedViewStatement) TokenLiteral ¶ added in v1.6.0
func (r RefreshMaterializedViewStatement) TokenLiteral() string
type ReplaceStatement ¶ added in v1.9.3
type ReplaceStatement struct {
TableName string
Columns []Expression
Values [][]Expression
}
ReplaceStatement represents MySQL REPLACE INTO statement
func GetReplaceStatement ¶ added in v1.9.3
func GetReplaceStatement() *ReplaceStatement
GetReplaceStatement gets a ReplaceStatement from the pool.
func (ReplaceStatement) Children ¶ added in v1.9.3
func (r ReplaceStatement) Children() []Node
func (ReplaceStatement) TokenLiteral ¶ added in v1.9.3
func (r ReplaceStatement) TokenLiteral() string
type RoleOption ¶
type RoleOption struct {
Name string
Type RoleOptionType
Value interface{} // Can be bool or Expression depending on Type
}
RoleOption represents an option in ROLE statement
func (*RoleOption) String ¶
func (opt *RoleOption) String() string
String returns the SQL keyword phrase for this role option (e.g. "SUPERUSER", "NOSUPERUSER", "LOGIN", "CONNECTION LIMIT 10", "PASSWORD NULL", etc.).
type RoleOptionType ¶
type RoleOptionType int
RoleOptionType identifies which role attribute is being set.
const ( // BypassRLS controls whether the role bypasses row-level security policies. BypassRLS RoleOptionType = iota // ConnectionLimit sets the maximum number of concurrent connections for the role. ConnectionLimit // CreateDB allows or prevents the role from creating new databases. CreateDB // CreateRole allows or prevents the role from creating new roles. CreateRole // Inherit controls whether the role inherits privileges of roles it is a member of. Inherit // Login allows or prevents the role from logging in. Login // Password sets the password for the role. Password // Replication controls whether the role can initiate streaming replication. Replication // SuperUser grants or revokes superuser privileges. SuperUser // ValidUntil sets the date and time after which the role's password is no longer valid. ValidUntil )
type RollupExpression ¶ added in v1.6.0
type RollupExpression struct {
Expressions []Expression
}
RollupExpression represents ROLLUP(col1, col2, ...) in GROUP BY clause ROLLUP generates hierarchical grouping sets from right to left Example: ROLLUP(a, b, c) generates grouping sets:
(a, b, c), (a, b), (a), ()
func (RollupExpression) Children ¶ added in v1.6.0
func (r RollupExpression) Children() []Node
func (*RollupExpression) SQL ¶ added in v1.9.3
func (r *RollupExpression) SQL() string
SQL returns the SQL representation of this ROLLUP expression as "ROLLUP(col1, col2, ...)".
func (RollupExpression) TokenLiteral ¶ added in v1.6.0
func (r RollupExpression) TokenLiteral() string
type RowAccessPolicy ¶
RowAccessPolicy represents row-level access policy
func (*RowAccessPolicy) Children ¶
func (r *RowAccessPolicy) Children() []Node
Children implements Node and returns the filter expression if present, or nil.
func (*RowAccessPolicy) TokenLiteral ¶
func (r *RowAccessPolicy) TokenLiteral() string
TokenLiteral implements Node and returns "ROW ACCESS POLICY".
type Select ¶
type Select struct {
Distinct bool
Columns []Expression
From []TableReference
Where Expression
GroupBy []Expression
Having Expression
OrderBy []OrderByExpression
Limit *int64
Offset *int64
}
Select represents a SELECT statement
func (Select) Children ¶
Children implements Node and returns all child nodes of this Select statement.
func (*Select) SQL ¶ added in v1.9.3
SQL returns the SQL representation of this Select node (dml.go type), which is a simplified SELECT structure used in compatibility code paths. For full-featured SELECT parsing use SelectStatement.SQL() instead.
func (Select) TokenLiteral ¶
TokenLiteral implements Node and returns "SELECT".
type SelectStatement ¶
type SelectStatement struct {
With *WithClause
Distinct bool
DistinctOnColumns []Expression // PostgreSQL DISTINCT ON (expr, ...) clause
Top *TopClause // SQL Server TOP N [PERCENT] clause
Columns []Expression
From []TableReference
TableName string // Added for pool operations
Joins []JoinClause
Where Expression
GroupBy []Expression
Having Expression
Windows []WindowSpec
OrderBy []OrderByExpression
Limit *int
Offset *int
Fetch *FetchClause // SQL-99 FETCH FIRST/NEXT clause (F861, F862)
For *ForClause // Row-level locking clause (SQL:2003, PostgreSQL, MySQL)
Pos models.Location // Source position of the SELECT keyword (1-based line and column)
}
SelectStatement represents a SELECT SQL statement with full SQL-99/SQL:2003 support.
SelectStatement is the primary query statement type supporting:
- CTEs (WITH clause)
- DISTINCT and DISTINCT ON (PostgreSQL)
- Multiple FROM tables and subqueries
- All JOIN types with LATERAL support
- WHERE, GROUP BY, HAVING, ORDER BY clauses
- Window functions with PARTITION BY and frame specifications
- LIMIT/OFFSET and SQL-99 FETCH clause
Fields:
- With: WITH clause for Common Table Expressions (CTEs)
- Distinct: DISTINCT keyword for duplicate elimination
- DistinctOnColumns: DISTINCT ON (expr, ...) for PostgreSQL (v1.6.0)
- Columns: SELECT list expressions (columns, *, functions, etc.)
- From: FROM clause table references (tables, subqueries, LATERAL)
- TableName: Table name for simple queries (pool optimization)
- Joins: JOIN clauses (INNER, LEFT, RIGHT, FULL, CROSS, NATURAL)
- Where: WHERE clause filter condition
- GroupBy: GROUP BY expressions (including ROLLUP, CUBE, GROUPING SETS)
- Having: HAVING clause filter condition
- Windows: Window specifications (WINDOW clause)
- OrderBy: ORDER BY expressions with NULLS FIRST/LAST
- Limit: LIMIT clause (number of rows)
- Offset: OFFSET clause (skip rows)
- Fetch: SQL-99 FETCH FIRST/NEXT clause (v1.6.0)
Example - Basic SELECT:
SelectStatement{
Columns: []Expression{&Identifier{Name: "id"}, &Identifier{Name: "name"}},
From: []TableReference{{Name: "users"}},
Where: &BinaryExpression{...},
}
// SQL: SELECT id, name FROM users WHERE ...
Example - DISTINCT ON (PostgreSQL v1.6.0):
SelectStatement{
DistinctOnColumns: []Expression{&Identifier{Name: "dept_id"}},
Columns: []Expression{&Identifier{Name: "dept_id"}, &Identifier{Name: "name"}},
From: []TableReference{{Name: "employees"}},
}
// SQL: SELECT DISTINCT ON (dept_id) dept_id, name FROM employees
Example - Window function with FETCH (v1.6.0):
SelectStatement{
Columns: []Expression{
&FunctionCall{
Name: "ROW_NUMBER",
Over: &WindowSpec{
OrderBy: []OrderByExpression{{Expression: &Identifier{Name: "salary"}, Ascending: false}},
},
},
},
From: []TableReference{{Name: "employees"}},
Fetch: &FetchClause{FetchValue: ptrInt64(10), FetchType: "FIRST"},
}
// SQL: SELECT ROW_NUMBER() OVER (ORDER BY salary DESC) FROM employees FETCH FIRST 10 ROWS ONLY
New in v1.6.0:
- DistinctOnColumns for PostgreSQL DISTINCT ON
- Fetch for SQL-99 FETCH FIRST/NEXT clause
- Enhanced LATERAL JOIN support via TableReference.Lateral
- FILTER clause support via FunctionCall.Filter
func GetSelectStatement ¶
func GetSelectStatement() *SelectStatement
GetSelectStatement gets a SelectStatement from the pool
func (SelectStatement) Children ¶
func (s SelectStatement) Children() []Node
func (*SelectStatement) Format
deprecated
added in
v1.9.3
func (s *SelectStatement) Format(opts FormatOptions) string
Format returns the formatted SQL for this SELECT statement.
Deprecated: use pkg/formatter.FormatStatement() instead.
func (*SelectStatement) SQL ¶ added in v1.9.3
func (s *SelectStatement) SQL() string
SQL returns the full SQL string for this SELECT statement, including all clauses: WITH, DISTINCT ON/DISTINCT, SELECT list, FROM, JOIN, WHERE, GROUP BY, HAVING, WINDOW, ORDER BY, LIMIT, OFFSET, FETCH, and FOR. This enables round-trip serialization of parsed queries.
func (*SelectStatement) Span ¶
func (s *SelectStatement) Span() models.Span
Span returns the source location span for the SelectStatement
func (SelectStatement) TokenLiteral ¶
func (s SelectStatement) TokenLiteral() string
type SetClause ¶ added in v1.6.0
type SetClause struct {
Column string
Value Expression
}
SetClause represents a SET clause in UPDATE (also used in MERGE UPDATE)
func (SetClause) TokenLiteral ¶ added in v1.6.0
type SetOperation ¶
type SetOperation struct {
Left Statement
Operator string // UNION, EXCEPT, INTERSECT
Right Statement
All bool // UNION ALL vs UNION
}
SetOperation represents set operations (UNION, EXCEPT, INTERSECT) between two statements. It supports the ALL modifier (e.g., UNION ALL) and proper left-associative parsing. Phase 2 Complete: Full parser support with left-associative precedence.
func (SetOperation) Children ¶
func (s SetOperation) Children() []Node
func (*SetOperation) Format
deprecated
added in
v1.9.3
func (s *SetOperation) Format(opts FormatOptions) string
Format returns the formatted SQL for this SET operation.
Deprecated: use pkg/formatter.FormatStatement() instead.
func (*SetOperation) SQL ¶ added in v1.9.3
func (s *SetOperation) SQL() string
SQL returns the SQL representation of this set operation as "left UNION|EXCEPT|INTERSECT [ALL] right".
func (SetOperation) TokenLiteral ¶
func (s SetOperation) TokenLiteral() string
type Setting ¶
type Setting struct {
Column *Ident
Value Expression
}
Setting represents a SET clause in an UPDATE statement
type ShowStatement ¶ added in v1.9.3
type ShowStatement struct {
ShowType string // TABLES, DATABASES, CREATE TABLE, COLUMNS, INDEX, etc.
ObjectName string // For SHOW CREATE TABLE x, SHOW COLUMNS FROM x, etc.
From string // For SHOW ... FROM database
}
ShowStatement represents MySQL SHOW commands (SHOW TABLES, SHOW DATABASES, SHOW CREATE TABLE x, etc.)
func GetShowStatement ¶ added in v1.9.3
func GetShowStatement() *ShowStatement
GetShowStatement gets a ShowStatement from the pool.
func (ShowStatement) Children ¶ added in v1.9.3
func (s ShowStatement) Children() []Node
func (ShowStatement) TokenLiteral ¶ added in v1.9.3
func (s ShowStatement) TokenLiteral() string
type Spanned ¶
type Spanned interface {
// Span returns the source location span for this node
Span() models.Span
}
Spanned represents an AST node that has source location information
type SpannedNode ¶
type SpannedNode struct {
// contains filtered or unexported fields
}
SpannedNode represents a basic AST node with source location information
func (*SpannedNode) SetSpan ¶
func (n *SpannedNode) SetSpan(span models.Span)
SetSpan sets the source location span for this node
func (*SpannedNode) Span ¶
func (n *SpannedNode) Span() models.Span
Span returns the source location span for this node
type StageLoadSelectItem ¶
StageLoadSelectItem represents a select item in stage loading operations
func (*StageLoadSelectItem) String ¶
func (s *StageLoadSelectItem) String() string
String implements the Stringer interface for StageLoadSelectItem
type StageParamsObject ¶
type StageParamsObject struct {
URL *string
Encryption DataLoadingOptions
Endpoint *string
StorageIntegration *string
Credentials DataLoadingOptions
}
StageParamsObject represents parameters for stage operations in data loading
func (*StageParamsObject) String ¶
func (s *StageParamsObject) String() string
String implements the Stringer interface for StageParamsObject
type Statement ¶
type Statement interface {
Node
// contains filtered or unexported methods
}
Statement represents a SQL statement node in the AST.
Statement extends the Node interface and represents top-level SQL statements such as SELECT, INSERT, UPDATE, DELETE, CREATE TABLE, etc. Statements form the root nodes of the syntax tree.
All statement types implement both Node and Statement interfaces. The statementNode() method is a marker method to distinguish statements from expressions at compile time.
Supported Statement Types:
- DML: SelectStatement, InsertStatement, UpdateStatement, DeleteStatement
- DDL: CreateTableStatement, AlterTableStatement, DropStatement
- Advanced: MergeStatement, TruncateStatement, WithClause, SetOperation
- Views: CreateViewStatement, CreateMaterializedViewStatement
Example - Type assertion:
if stmt, ok := node.(Statement); ok {
fmt.Printf("Statement type: %s\n", stmt.TokenLiteral())
}
type StatementImpl ¶
type StatementImpl struct {
Variant StatementVariant
}
StatementImpl represents a concrete implementation of a SQL statement
func (*StatementImpl) Children ¶
func (s *StatementImpl) Children() []Node
Children implements Node and returns the wrapped StatementVariant as a single child.
func (*StatementImpl) TokenLiteral ¶
func (s *StatementImpl) TokenLiteral() string
TokenLiteral implements Node by delegating to the wrapped StatementVariant.
type StatementVariant ¶
type StatementVariant interface {
Node
// contains filtered or unexported methods
}
StatementVariant represents a specific type of SQL statement
type StorageSerializationPolicy ¶
type StorageSerializationPolicy int
StorageSerializationPolicy represents storage serialization policy
const ( StorageSerializationNone StorageSerializationPolicy = iota StorageSerializationJSON StorageSerializationAvro )
type StructBracketKind ¶
type StructBracketKind int
StructBracketKind represents the type of brackets used in STRUCT type
const ( ParenthesesBrackets StructBracketKind = iota AngleBracketsBrackets )
type StructField ¶
StructField represents a field in a struct type
func GetStructFields ¶
func GetStructFields(t reflect.Type) []StructField
GetStructFields returns the fields of a struct type
type SubqueryExpression ¶ added in v1.6.0
type SubqueryExpression struct {
Subquery Statement
Pos models.Location // Source position of the opening parenthesis (1-based line and column)
}
SubqueryExpression represents a scalar subquery (SELECT ...)
func GetSubqueryExpression ¶ added in v1.6.0
func GetSubqueryExpression() *SubqueryExpression
GetSubqueryExpression gets a SubqueryExpression from the pool
func (SubqueryExpression) Children ¶ added in v1.6.0
func (s SubqueryExpression) Children() []Node
func (*SubqueryExpression) Format
deprecated
added in
v1.9.3
func (s *SubqueryExpression) Format(opts FormatOptions) string
Format returns the formatted SQL for this subquery expression.
Deprecated: use pkg/formatter.FormatExpression() instead.
func (*SubqueryExpression) SQL ¶ added in v1.9.3
func (s *SubqueryExpression) SQL() string
SQL returns the SQL representation of this scalar subquery as "(SELECT ...)".
func (SubqueryExpression) TokenLiteral ¶ added in v1.6.0
func (s SubqueryExpression) TokenLiteral() string
type SubstringExpression ¶
type SubstringExpression struct {
Str Expression
Start Expression
Length Expression
}
SubstringExpression represents SUBSTRING(str FROM start [FOR length])
func (SubstringExpression) Children ¶
func (s SubstringExpression) Children() []Node
func (*SubstringExpression) SQL ¶ added in v1.9.3
func (s *SubstringExpression) SQL() string
SQL returns the SQL representation of this SUBSTRING expression. With a length: "SUBSTRING(str FROM start FOR length)". Without a length: "SUBSTRING(str FROM start)".
func (SubstringExpression) TokenLiteral ¶
func (s SubstringExpression) TokenLiteral() string
type Table ¶
type Table struct {
Name string
Columns []*ColumnDef
Constraints []*TableConstraint
Options map[string]string
}
Table represents a table definition
type TableConstraint ¶
type TableConstraint struct {
Name string
Type string // PRIMARY KEY, UNIQUE, FOREIGN KEY, CHECK
Columns []string
References *ReferenceDefinition
Check Expression
}
TableConstraint represents a table constraint
func (TableConstraint) Children ¶
func (t TableConstraint) Children() []Node
func (TableConstraint) TokenLiteral ¶
func (t TableConstraint) TokenLiteral() string
type TableOption ¶
TableOption represents table options like ENGINE, CHARSET, etc.
func (TableOption) Children ¶
func (t TableOption) Children() []Node
func (TableOption) TokenLiteral ¶
func (t TableOption) TokenLiteral() string
type TableReference ¶
type TableReference struct {
Name string // Table name (empty if this is a derived table)
Alias string // Optional alias
Subquery *SelectStatement // For derived tables: (SELECT ...) AS alias
Lateral bool // LATERAL keyword for correlated subqueries (PostgreSQL)
TableHints []string // SQL Server table hints: WITH (NOLOCK), WITH (ROWLOCK, UPDLOCK), etc.
}
TableReference represents a table reference in a FROM clause.
TableReference can represent either a simple table name or a derived table (subquery). It supports PostgreSQL's LATERAL keyword for correlated subqueries.
Fields:
- Name: Table name (empty if this is a derived table/subquery)
- Alias: Optional table alias (AS alias)
- Subquery: Subquery for derived tables: (SELECT ...) AS alias
- Lateral: LATERAL keyword for correlated subqueries (PostgreSQL v1.6.0)
The Lateral field enables PostgreSQL's LATERAL JOIN feature, which allows subqueries in the FROM clause to reference columns from preceding tables.
Example - Simple table reference:
TableReference{
Name: "users",
Alias: "u",
}
// SQL: FROM users u
Example - Derived table (subquery):
TableReference{
Alias: "recent_orders",
Subquery: selectStmt,
}
// SQL: FROM (SELECT ...) AS recent_orders
Example - LATERAL JOIN (PostgreSQL v1.6.0):
TableReference{
Lateral: true,
Alias: "r",
Subquery: correlatedSelectStmt,
}
// SQL: FROM users u, LATERAL (SELECT * FROM orders WHERE user_id = u.id) r
New in v1.6.0: Lateral field for PostgreSQL LATERAL JOIN support.
func (TableReference) Children ¶
func (t TableReference) Children() []Node
func (TableReference) TokenLiteral ¶
func (t TableReference) TokenLiteral() string
type TimestampType ¶
type TimestampType struct {
Precision *uint64
Timezone TimezoneInfo
}
Basic data types
func (*TimestampType) String ¶
func (t *TimestampType) String() string
String returns the SQL representation of this TIMESTAMP type, e.g. "TIMESTAMP", "TIMESTAMP(3)", or "TIMESTAMP WITH TIME ZONE".
type TimezoneInfo ¶
type TimezoneInfo int
TimezoneInfo represents timezone information for temporal types
const ( NoTimezone TimezoneInfo = iota WithTimeZone WithoutTimeZone Tz )
func (TimezoneInfo) String ¶
func (t TimezoneInfo) String() string
String returns the SQL timezone clause for this timezone info, e.g. " WITH TIME ZONE", " WITHOUT TIME ZONE", or "" for NoTimezone.
type TokenWithSpan ¶
TokenWithSpan represents a token with its source location span
func NewTokenWithSpan ¶
func NewTokenWithSpan(token Token, span Span) TokenWithSpan
NewTokenWithSpan creates a new TokenWithSpan
func NewTokenWithSpanEOF ¶
func NewTokenWithSpanEOF() TokenWithSpan
NewTokenWithSpanEOF creates a new EOF TokenWithSpan
func (TokenWithSpan) GoString ¶
func (t TokenWithSpan) GoString() string
GoString implements fmt.GoStringer
type TopClause ¶ added in v1.9.3
type TopClause struct {
Count Expression // Number of rows (or percentage) as an expression
IsPercent bool // Whether PERCENT keyword was specified
WithTies bool // Whether WITH TIES was specified (SQL Server)
}
TopClause represents SQL Server's TOP N [PERCENT] clause Syntax: SELECT TOP n [PERCENT] columns... Count is an Expression to support TOP (10), TOP (@var), TOP (subquery)
func (TopClause) TokenLiteral ¶ added in v1.9.3
type TriggerEvent ¶
type TriggerEvent struct {
Type TriggerEventType
Columns []Identifier // Only used for UPDATE events
}
TriggerEvent describes trigger events
func (TriggerEvent) Children ¶
func (t TriggerEvent) Children() []Node
Children implements Node and returns nil — TriggerEvent has no child nodes.
func (TriggerEvent) String ¶
func (t TriggerEvent) String() string
String returns the SQL representation of this trigger event: "INSERT", "UPDATE", "UPDATE OF col1, col2", "DELETE", or "TRUNCATE".
func (TriggerEvent) TokenLiteral ¶
func (t TriggerEvent) TokenLiteral() string
TokenLiteral implements Node and returns the SQL representation of this trigger event (e.g. "INSERT", "UPDATE OF col", "DELETE").
type TriggerEventType ¶
type TriggerEventType int
TriggerEventType identifies which DML event fires the trigger.
const ( // TriggerEventInsert fires the trigger on INSERT. TriggerEventInsert TriggerEventType = iota // TriggerEventUpdate fires the trigger on UPDATE (optionally of specific columns). TriggerEventUpdate // TriggerEventDelete fires the trigger on DELETE. TriggerEventDelete // TriggerEventTruncate fires the trigger on TRUNCATE. TriggerEventTruncate )
type TriggerExecBody ¶
type TriggerExecBody struct {
ExecType TriggerExecBodyType
FuncDesc FunctionDesc
}
TriggerExecBody represents the execution body of a trigger
func (TriggerExecBody) Children ¶
func (t TriggerExecBody) Children() []Node
Children implements Node and returns nil — TriggerExecBody has no child nodes.
func (TriggerExecBody) String ¶
func (t TriggerExecBody) String() string
String returns the SQL representation of this trigger execution body, e.g. "FUNCTION schema.my_func()" or "PROCEDURE my_proc()".
func (TriggerExecBody) TokenLiteral ¶
func (t TriggerExecBody) TokenLiteral() string
TokenLiteral implements Node and returns the SQL representation of this trigger execution body.
type TriggerExecBodyType ¶
type TriggerExecBodyType int
TriggerExecBodyType represents types of trigger body execution
const ( TriggerExecBodyFunction TriggerExecBodyType = iota TriggerExecBodyProcedure )
func (TriggerExecBodyType) String ¶
func (t TriggerExecBodyType) String() string
String returns the SQL keyword for this execution body type: "FUNCTION" or "PROCEDURE".
type TriggerObject ¶
type TriggerObject int
TriggerObject specifies whether the trigger function should be fired once for every row affected by the trigger event, or just once per SQL statement.
const ( TriggerObjectRow TriggerObject = iota TriggerObjectStatement )
func (TriggerObject) Children ¶
func (t TriggerObject) Children() []Node
Children implements Node and returns nil — TriggerObject has no child nodes.
func (TriggerObject) String ¶
func (t TriggerObject) String() string
String returns the SQL keyword for this trigger object: "ROW" or "STATEMENT".
func (TriggerObject) TokenLiteral ¶
func (t TriggerObject) TokenLiteral() string
TokenLiteral implements Node and returns the SQL keyword for this trigger object.
type TriggerPeriod ¶
type TriggerPeriod int
TriggerPeriod represents when the trigger should be executed
const ( TriggerPeriodAfter TriggerPeriod = iota TriggerPeriodBefore TriggerPeriodInsteadOf )
func (TriggerPeriod) Children ¶
func (t TriggerPeriod) Children() []Node
Children implements Node and returns nil — TriggerPeriod has no child nodes.
func (TriggerPeriod) String ¶
func (t TriggerPeriod) String() string
String returns the SQL keyword for this trigger period: "AFTER", "BEFORE", or "INSTEAD OF".
func (TriggerPeriod) TokenLiteral ¶
func (t TriggerPeriod) TokenLiteral() string
TokenLiteral implements Node and returns the SQL keyword for this trigger period ("AFTER", "BEFORE", or "INSTEAD OF").
type TriggerReferencing ¶
type TriggerReferencing struct {
ReferType TriggerReferencingType
IsAs bool
TransitionRelationName ObjectName
}
TriggerReferencing represents a declaration of relation names that provide access to the transition relations of the triggering statement
func (TriggerReferencing) Children ¶
func (t TriggerReferencing) Children() []Node
Children implements Node and returns nil — TriggerReferencing has no child nodes.
func (TriggerReferencing) String ¶
func (t TriggerReferencing) String() string
String returns the SQL representation of this transition relation declaration, e.g. "OLD TABLE AS old_rows" or "NEW TABLE new_rows".
func (TriggerReferencing) TokenLiteral ¶
func (t TriggerReferencing) TokenLiteral() string
TokenLiteral implements Node and returns the SQL representation of this transition relation declaration.
type TriggerReferencingType ¶
type TriggerReferencingType int
TriggerReferencingType indicates whether the following relation name is for the before-image transition relation or the after-image transition relation
const ( TriggerReferencingOldTable TriggerReferencingType = iota TriggerReferencingNewTable )
func (TriggerReferencingType) String ¶
func (t TriggerReferencingType) String() string
String returns the SQL phrase for this referencing type: "OLD TABLE" or "NEW TABLE".
type TrimWhereField ¶
type TrimWhereField int
TrimWhereField represents the type of trimming operation
const ( Both TrimWhereField = iota Leading Trailing )
func (TrimWhereField) String ¶
func (t TrimWhereField) String() string
String returns the SQL keyword for this trim direction: "BOTH", "LEADING", or "TRAILING".
type TruncateStatement ¶ added in v1.6.0
type TruncateStatement struct {
Tables []string // Table names to truncate
RestartIdentity bool // RESTART IDENTITY - reset sequences
ContinueIdentity bool // CONTINUE IDENTITY - keep sequences (default)
CascadeType string // CASCADE, RESTRICT, or empty
}
TruncateStatement represents a TRUNCATE TABLE statement Syntax: TRUNCATE [TABLE] table_name [, table_name ...] [RESTART IDENTITY | CONTINUE IDENTITY] [CASCADE | RESTRICT]
func GetTruncateStatement ¶ added in v1.9.3
func GetTruncateStatement() *TruncateStatement
GetTruncateStatement gets a TruncateStatement from the pool.
func (TruncateStatement) Children ¶ added in v1.6.0
func (t TruncateStatement) Children() []Node
func (*TruncateStatement) Format
deprecated
added in
v1.9.3
func (t *TruncateStatement) Format(opts FormatOptions) string
Format returns the formatted SQL for this TRUNCATE statement.
Deprecated: use pkg/formatter.FormatStatement() instead.
func (*TruncateStatement) SQL ¶ added in v1.9.3
func (t *TruncateStatement) SQL() string
SQL returns the SQL representation of this TRUNCATE statement, including table names, RESTART/CONTINUE IDENTITY options, and CASCADE/RESTRICT behavior.
func (TruncateStatement) TokenLiteral ¶ added in v1.6.0
func (t TruncateStatement) TokenLiteral() string
type TupleExpression ¶ added in v1.7.0
type TupleExpression struct {
Expressions []Expression
}
TupleExpression represents a row constructor / tuple (col1, col2) for multi-column comparisons Used in: WHERE (user_id, status) IN ((1, 'active'), (2, 'pending'))
func GetTupleExpression ¶ added in v1.7.0
func GetTupleExpression() *TupleExpression
GetTupleExpression gets a TupleExpression from the pool
func (TupleExpression) Children ¶ added in v1.7.0
func (t TupleExpression) Children() []Node
func (*TupleExpression) SQL ¶ added in v1.9.3
func (t *TupleExpression) SQL() string
SQL returns the SQL representation of this tuple expression as a parenthesized comma-separated list: "(v1, v2, v3)".
func (TupleExpression) TokenLiteral ¶ added in v1.7.0
func (t TupleExpression) TokenLiteral() string
type UnaryExpression ¶
type UnaryExpression struct {
Operator UnaryOperator
Expr Expression
Pos models.Location // Source position of the operator (1-based line and column)
}
UnaryExpression represents operations like NOT expr
func (UnaryExpression) Children ¶
func (u UnaryExpression) Children() []Node
func (*UnaryExpression) SQL ¶ added in v1.9.3
func (u *UnaryExpression) SQL() string
SQL returns the SQL representation of this unary expression. Prefix operators (NOT, +, -, etc.) are prepended; the PostgreSQL postfix factorial operator (!) is appended.
func (*UnaryExpression) Span ¶
func (e *UnaryExpression) Span() models.Span
Span returns the source location span for this unary expression. It delegates to the inner expression's span, or returns an empty span if the inner expression does not implement Spanned.
func (*UnaryExpression) TokenLiteral ¶
func (u *UnaryExpression) TokenLiteral() string
type UnaryOperator ¶
type UnaryOperator int
UnaryOperator represents unary operators in SQL expressions.
UnaryOperator defines all unary operators that can be applied to a single expression. This includes standard SQL operators (NOT, +, -) and database-specific operators (PostgreSQL bitwise, factorial, mathematical operators).
Supported Operators:
- Standard SQL: Plus (+expr), Minus (-expr), Not (NOT expr)
- PostgreSQL Bitwise: PGBitwiseNot (~expr)
- PostgreSQL Math: PGSquareRoot (|/expr), PGCubeRoot (||/expr), PGAbs (@expr)
- PostgreSQL Factorial: PGPostfixFactorial (expr!), PGPrefixFactorial (!!expr)
- Hive: BangNot (!expr)
Example - Using unary operators:
// NOT expression
notExpr := &ast.UnaryExpression{
Operator: ast.Not,
Expr: &ast.Identifier{Name: "active"},
}
// SQL: NOT active
// Negation
negExpr := &ast.UnaryExpression{
Operator: ast.Minus,
Expr: &ast.LiteralValue{Value: 42, Type: "INTEGER"},
}
// SQL: -42
// PostgreSQL square root
sqrtExpr := &ast.UnaryExpression{
Operator: ast.PGSquareRoot,
Expr: &ast.LiteralValue{Value: 9, Type: "INTEGER"},
}
// SQL: |/9 (PostgreSQL)
See also: BinaryOperator, UnaryExpression
const ( // Plus represents unary plus operator, e.g. +9 Plus UnaryOperator = iota // Minus represents unary minus operator, e.g. -9 Minus // Not represents logical NOT operator, e.g. NOT(true) Not // PGBitwiseNot represents PostgreSQL bitwise NOT operator, e.g. ~9 PGBitwiseNot // PGSquareRoot represents PostgreSQL square root operator, e.g. |/9 PGSquareRoot // PGCubeRoot represents PostgreSQL cube root operator, e.g. ||/27 PGCubeRoot // PGPostfixFactorial represents PostgreSQL postfix factorial operator, e.g. 9! PGPostfixFactorial // PGPrefixFactorial represents PostgreSQL prefix factorial operator, e.g. !!9 PGPrefixFactorial // PGAbs represents PostgreSQL absolute value operator, e.g. @ -9 PGAbs // BangNot represents Hive-specific logical NOT operator, e.g. ! false BangNot )
func (UnaryOperator) String ¶
func (op UnaryOperator) String() string
String returns the string representation of the unary operator
type Update ¶
type Update struct {
Table TableReference
Updates []UpdateExpression
Where Expression
ReturningClause []Expression
}
Update represents an UPDATE statement
func (Update) Children ¶
Children implements Node and returns all child nodes of this Update statement.
func (*Update) SQL ¶ added in v1.9.3
SQL returns the SQL representation of this Update node (dml.go type). For the full-featured UPDATE use UpdateStatement.SQL() instead.
func (Update) TokenLiteral ¶
TokenLiteral implements Node and returns "UPDATE".
type UpdateExpression ¶
type UpdateExpression struct {
Column Expression
Value Expression
}
UpdateExpression represents a column=value expression in UPDATE
func GetUpdateExpression ¶
func GetUpdateExpression() *UpdateExpression
GetUpdateExpression gets an UpdateExpression from the pool
func (UpdateExpression) Children ¶
func (u UpdateExpression) Children() []Node
func (UpdateExpression) TokenLiteral ¶
func (u UpdateExpression) TokenLiteral() string
type UpdateStatement ¶
type UpdateStatement struct {
With *WithClause
TableName string
Alias string
Assignments []UpdateExpression // SET clause assignments
From []TableReference
Where Expression
Returning []Expression
Pos models.Location // Source position of the UPDATE keyword (1-based line and column)
}
UpdateStatement represents an UPDATE SQL statement
func GetUpdateStatement ¶
func GetUpdateStatement() *UpdateStatement
GetUpdateStatement gets an UpdateStatement from the pool
func (UpdateStatement) Children ¶
func (u UpdateStatement) Children() []Node
func (*UpdateStatement) Format
deprecated
added in
v1.9.3
func (u *UpdateStatement) Format(opts FormatOptions) string
Format returns the formatted SQL for this UPDATE statement.
Deprecated: use pkg/formatter.FormatStatement() instead.
func (*UpdateStatement) GetUpdates
deprecated
added in
v1.9.3
func (u *UpdateStatement) GetUpdates() []UpdateExpression
GetUpdates returns Assignments for backward compatibility.
Deprecated: Use Assignments directly instead.
func (*UpdateStatement) SQL ¶ added in v1.9.3
func (u *UpdateStatement) SQL() string
SQL returns the full SQL string for this UPDATE statement, including the optional WITH clause, SET assignments, FROM clause, WHERE condition, and RETURNING clause.
func (*UpdateStatement) Span ¶
func (u *UpdateStatement) Span() models.Span
Span returns the source location span for the UpdateStatement
func (UpdateStatement) TokenLiteral ¶
func (u UpdateStatement) TokenLiteral() string
type UpsertClause ¶
type UpsertClause struct {
Updates []UpdateExpression
}
UpsertClause represents INSERT ... ON DUPLICATE KEY UPDATE
func (UpsertClause) Children ¶
func (u UpsertClause) Children() []Node
func (UpsertClause) TokenLiteral ¶
func (u UpsertClause) TokenLiteral() string
type Value ¶
type Value struct {
Type ValueType
Value interface{}
}
Value represents primitive SQL values such as number and string
func (Value) String ¶
String returns the SQL literal representation of this value, including appropriate quoting and escaping for each ValueType (e.g. single-quoted strings, dollar-quoted strings, hex strings, boolean literals, NULL, etc.).
func (Value) TokenLiteral ¶
TokenLiteral implements Node and returns the SQL literal representation of this value (delegates to String).
type ValueType ¶
type ValueType int
ValueType represents the type of a SQL value
const ( // NumberValue represents a numeric literal. NumberValue ValueType = iota // SingleQuotedStringValue represents a single-quoted string literal. SingleQuotedStringValue // DollarQuotedStringValue represents a PostgreSQL dollar-quoted string literal. DollarQuotedStringValue // TripleSingleQuotedStringValue represents a triple-single-quoted string literal. TripleSingleQuotedStringValue // TripleDoubleQuotedStringValue represents a triple-double-quoted string literal. TripleDoubleQuotedStringValue // EscapedStringLiteralValue represents a C-style escaped string (E'...'). EscapedStringLiteralValue // UnicodeStringLiteralValue represents a Unicode string literal (U&'...'). UnicodeStringLiteralValue // SingleQuotedByteStringLiteralValue represents a byte string with single quotes (B'...'). SingleQuotedByteStringLiteralValue // DoubleQuotedByteStringLiteralValue represents a byte string with double quotes (B"..."). DoubleQuotedByteStringLiteralValue // TripleSingleQuotedByteStringLiteralValue represents a byte string with triple single quotes. TripleSingleQuotedByteStringLiteralValue // TripleDoubleQuotedByteStringLiteralValue represents a byte string with triple double quotes. TripleDoubleQuotedByteStringLiteralValue // SingleQuotedRawStringLiteralValue represents a raw string with single quotes (R'...'). SingleQuotedRawStringLiteralValue // DoubleQuotedRawStringLiteralValue represents a raw string with double quotes (R"..."). DoubleQuotedRawStringLiteralValue // TripleSingleQuotedRawStringLiteralValue represents a raw string with triple single quotes. TripleSingleQuotedRawStringLiteralValue // TripleDoubleQuotedRawStringLiteralValue represents a raw string with triple double quotes. TripleDoubleQuotedRawStringLiteralValue // NationalStringLiteralValue represents a national character string literal (N'...'). NationalStringLiteralValue // HexStringLiteralValue represents a hexadecimal string literal (X'...'). HexStringLiteralValue // DoubleQuotedStringValue represents a double-quoted string literal. DoubleQuotedStringValue // BooleanValue represents a boolean literal (TRUE or FALSE). BooleanValue // NullValue represents the SQL NULL literal. NullValue // PlaceholderValue represents a query parameter placeholder (e.g. $1, ?, :name). PlaceholderValue )
type Values ¶
type Values struct {
Rows [][]Expression
}
Values represents VALUES clause
func (*Values) SQL ¶ added in v1.9.3
SQL returns the SQL representation of this VALUES clause as "VALUES (v1, v2), (v3, v4), ...".
func (Values) TokenLiteral ¶
type VarcharType ¶
type VarcharType struct {
Length *CharacterLength
}
Basic data types
func (*VarcharType) String ¶
func (t *VarcharType) String() string
String returns the SQL representation of this VARCHAR type, e.g. "VARCHAR" or "VARCHAR(255)".
type VisitFunc ¶
VisitFunc is a function type that can be used to implement custom visitors without creating a new type.
type Visitor ¶
Visitor defines an interface for traversing the AST using the visitor pattern.
The Visitor interface enables systematic traversal of the Abstract Syntax Tree with full control over the traversal process. The Visit method is called for each node encountered by Walk.
Traversal Behavior:
- Walk calls v.Visit(node) for each node in the tree
- If Visit returns a non-nil visitor w, Walk recursively visits all children with w
- After visiting all children, Walk calls w.Visit(nil) to signal completion
- If Visit returns nil visitor, Walk skips the children of that node
- If Visit returns an error, Walk stops immediately and returns that error
Return Values:
- w (Visitor): Visitor to use for children (nil to skip children)
- err (error): Error to stop traversal (nil to continue)
Example - Implementing a custom visitor:
type DepthCounter struct {
depth int
maxDepth int
}
func (d *DepthCounter) Visit(node ast.Node) (ast.Visitor, error) {
if node == nil {
// Called after visiting all children
return nil, nil
}
d.depth++
if d.depth > d.maxDepth {
d.maxDepth = d.depth
}
// Return new visitor with incremented depth for children
return &DepthCounter{depth: d.depth, maxDepth: d.maxDepth}, nil
}
// Usage:
counter := &DepthCounter{depth: 0, maxDepth: 0}
ast.Walk(counter, astNode)
fmt.Printf("Maximum tree depth: %d\n", counter.maxDepth)
Example - Stopping traversal on error:
type ErrorFinder struct{}
func (e *ErrorFinder) Visit(node ast.Node) (ast.Visitor, error) {
if node == nil {
return nil, nil
}
if _, ok := node.(*ast.SelectStatement); ok {
return nil, fmt.Errorf("found SELECT statement")
}
return e, nil
}
See also: Walk(), Inspect(), Inspector
type WhenClause ¶
type WhenClause struct {
Condition Expression
Result Expression
Pos models.Location // Source position of the WHEN keyword (1-based line and column)
}
WhenClause represents WHEN ... THEN ... in CASE expression
func (WhenClause) Children ¶
func (w WhenClause) Children() []Node
func (*WhenClause) SQL ¶ added in v1.9.3
func (w *WhenClause) SQL() string
SQL returns the SQL representation of this WHEN clause in the form "WHEN condition THEN result".
func (WhenClause) TokenLiteral ¶
func (w WhenClause) TokenLiteral() string
type WindowFrame ¶
type WindowFrame struct {
Type string // ROWS, RANGE
Start WindowFrameBound
End *WindowFrameBound
}
WindowFrame represents window frame clause
func (WindowFrame) Children ¶
func (w WindowFrame) Children() []Node
func (WindowFrame) TokenLiteral ¶
func (w WindowFrame) TokenLiteral() string
type WindowFrameBound ¶
type WindowFrameBound struct {
Type string // CURRENT ROW, UNBOUNDED PRECEDING, etc.
Value Expression
}
WindowFrameBound represents window frame bound
func (WindowFrameBound) Children ¶ added in v1.6.0
func (w WindowFrameBound) Children() []Node
func (WindowFrameBound) TokenLiteral ¶ added in v1.6.0
func (w WindowFrameBound) TokenLiteral() string
type WindowSpec ¶
type WindowSpec struct {
Name string
PartitionBy []Expression
OrderBy []OrderByExpression
FrameClause *WindowFrame
}
WindowSpec represents a window specification
func (WindowSpec) Children ¶
func (w WindowSpec) Children() []Node
func (WindowSpec) TokenLiteral ¶
func (w WindowSpec) TokenLiteral() string
type WithClause ¶
type WithClause struct {
Recursive bool
CTEs []*CommonTableExpr
Pos models.Location // Source position of the WITH keyword (1-based line and column)
}
WithClause represents a WITH clause in a SQL statement. It supports both simple and recursive Common Table Expressions (CTEs). Phase 2 Complete: Full parser integration with all statement types.
func (WithClause) Children ¶
func (w WithClause) Children() []Node
func (*WithClause) SQL ¶ added in v1.9.3
func (w *WithClause) SQL() string
SQL returns the SQL representation of this WITH clause including any RECURSIVE modifier and all CTE definitions.
func (WithClause) TokenLiteral ¶
func (w WithClause) TokenLiteral() string
type WrappedCollection ¶
WrappedCollection represents a collection of items with optional wrapper
func (*WrappedCollection[T]) Children ¶
func (w *WrappedCollection[T]) Children() []Node
Children implements Node and returns all items as Node values (items that do not implement Node are represented as nil slots).
func (*WrappedCollection[T]) TokenLiteral ¶
func (w *WrappedCollection[T]) TokenLiteral() string
TokenLiteral implements Node and returns the wrapper keyword (e.g. the SQL keyword that introduces the collection).