ast

package
v1.7.0 Latest Latest
Warning

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

Go to latest
Published: Feb 12, 2026 License: AGPL-3.0 Imports: 6 Imported by: 0

README

AST Package

Overview

The ast package provides comprehensive Abstract Syntax Tree (AST) node definitions for SQL statements. It represents the parsed structure of SQL queries with 73.4% test coverage and full support for DDL, DML, CTEs, set operations, and window functions.

Key Features

  • Complete SQL Statement Types: SELECT, INSERT, UPDATE, DELETE, CREATE, ALTER, DROP
  • Expression System: Binary/unary operations, functions, literals, identifiers
  • Advanced SQL: WITH (CTEs), UNION/EXCEPT/INTERSECT, window functions
  • Object Pooling: Statement and expression pools for memory efficiency
  • Visitor Pattern: AST traversal and inspection support
  • Type Safety: Strongly-typed node hierarchy with Go interfaces

Core Interfaces

Node

Base interface for all AST nodes:

type Node interface {
    TokenLiteral() string  // Returns the literal token value
    Children() []Node      // Returns child nodes for traversal
}
Statement

Represents SQL statements (extends Node):

type Statement interface {
    Node
    statementNode()  // Marker method
}
Expression

Represents SQL expressions (extends Node):

type Expression interface {
    Node
    expressionNode()  // Marker method
}

Statement Types

SelectStatement

Represents SELECT queries with full SQL features:

type SelectStatement struct {
    Distinct bool
    Columns  []Expression        // SELECT columns
    From     []TableReference    // FROM clause
    Joins    []JoinClause       // JOIN clauses
    Where    Expression         // WHERE condition
    GroupBy  []Expression       // GROUP BY columns
    Having   Expression         // HAVING condition
    OrderBy  []OrderByExpression // ORDER BY with NULLS FIRST/LAST
    Limit    *int64             // LIMIT value
    Offset   *int64             // OFFSET value
}

Example Usage:

if stmt, ok := astNode.(*ast.SelectStatement); ok {
    fmt.Printf("SELECT has %d columns\n", len(stmt.Columns))

    if stmt.Where != nil {
        fmt.Println("Has WHERE clause")
    }

    for _, join := range stmt.Joins {
        fmt.Printf("JOIN type: %s\n", join.Type)
    }
}
InsertStatement

Represents INSERT operations:

type InsertStatement struct {
    Table   string
    Columns []string
    Values  [][]Expression  // Multi-row support
}
UpdateStatement

Represents UPDATE operations:

type UpdateStatement struct {
    Table string
    Set   []UpdateSetClause
    Where Expression
}
DeleteStatement

Represents DELETE operations:

type DeleteStatement struct {
    Table string
    Where Expression
}

Expression Types

Identifier

Column, table, or alias names:

type Identifier struct {
    Name string
}
Literal

Constant values:

type Literal struct {
    Type  LiteralType  // STRING, NUMBER, BOOLEAN, NULL
    Value interface{}
}
BinaryExpression

Binary operations (=, >, AND, OR, etc.):

type BinaryExpression struct {
    Left     Expression
    Operator string      // =, >, <, AND, OR, LIKE, etc.
    Right    Expression
}
FunctionCall

Function invocations (with optional window spec):

type FunctionCall struct {
    Name       string
    Arguments  []Expression
    Over       *WindowSpec  // For window functions
}

Advanced Features

Common Table Expressions (CTEs)
type WithClause struct {
    Recursive bool
    CTEs      []*CommonTableExpr
}

type CommonTableExpr struct {
    Name         string
    Columns      []string       // Optional column list
    Statement    Statement      // CTE query
    Materialized *bool         // MATERIALIZED hint
}

Example:

if stmt, ok := astNode.(*ast.SelectStatement); ok {
    // Check for CTEs
    // (CTEs are represented at statement level)
}
Set Operations
type SetOperation struct {
    Left     Statement
    Operator string  // UNION, EXCEPT, INTERSECT
    Right    Statement
    All      bool    // true for UNION ALL
}
Window Functions
type WindowSpec struct {
    PartitionBy []Expression
    OrderBy     []OrderByExpression
    Frame       *WindowFrame
}

type WindowFrame struct {
    Type   string  // ROWS or RANGE
    Start  *WindowFrameBound
    End    *WindowFrameBound
}
ORDER BY with NULL Ordering
type OrderByExpression struct {
    Expression Expression
    Ascending  bool
    NullsFirst *bool  // nil=database default, true=FIRST, false=LAST
}

Object Pooling

AST Pool

Reuse AST container objects:

// Get from pool
astObj := ast.NewAST()
defer ast.ReleaseAST(astObj)  // ALWAYS defer release

// Use AST
astObj.Root = selectStmt
Statement Pools

Individual pools for each statement type:

// SELECT statements
selectStmt := ast.NewSelectStatement()
defer ast.ReleaseSelectStatement(selectStmt)

// INSERT statements
insertStmt := ast.NewInsertStatement()
defer ast.ReleaseInsertStatement(insertStmt)
Expression Pools
// Identifiers
id := ast.NewIdentifier("column_name")
defer ast.ReleaseIdentifier(id)

// Binary expressions
binExpr := ast.NewBinaryExpression()
defer ast.ReleaseBinaryExpression(binExpr)

Visitor Pattern

Walk Function

Traverse the AST with a visitor:

ast.Walk(astNode, func(n ast.Node) bool {
    // Visit each node
    fmt.Printf("Visiting: %T\n", n)

    // Return true to continue, false to stop
    return true
})
Inspector

Inspect specific node types:

inspector := ast.NewInspector(astNode)

// Find all identifiers
inspector.WithStack(func(n ast.Node, push bool, stack []ast.Node) bool {
    if id, ok := n.(*ast.Identifier); ok {
        fmt.Printf("Found identifier: %s\n", id.Name)
    }
    return true
})

Common Usage Patterns

1. Extract All Table Names
func ExtractTables(stmt *ast.SelectStatement) []string {
    tables := []string{}

    for _, table := range stmt.From {
        if tableRef, ok := table.(*ast.TableReference); ok {
            tables = append(tables, tableRef.Name)
        }
    }

    for _, join := range stmt.Joins {
        if tableRef, ok := join.Table.(*ast.TableReference); ok {
            tables = append(tables, tableRef.Name)
        }
    }

    return tables
}
2. Find All WHERE Conditions
func ExtractWhereConditions(stmt *ast.SelectStatement) []string {
    conditions := []string{}

    if stmt.Where != nil {
        // Traverse WHERE expression tree
        ast.Walk(stmt.Where, func(n ast.Node) bool {
            if binExpr, ok := n.(*ast.BinaryExpression); ok {
                conditions = append(conditions, binExpr.Operator)
            }
            return true
        })
    }

    return conditions
}
3. Detect Window Functions
func HasWindowFunctions(stmt *ast.SelectStatement) bool {
    hasWindow := false

    for _, col := range stmt.Columns {
        ast.Walk(col, func(n ast.Node) bool {
            if funcCall, ok := n.(*ast.FunctionCall); ok {
                if funcCall.Over != nil {
                    hasWindow = true
                    return false  // Stop walking
                }
            }
            return true
        })

        if hasWindow {
            break
        }
    }

    return hasWindow
}

Testing

Run AST tests:

# All tests (73.4% coverage)
go test -v ./pkg/sql/ast/

# With race detection
go test -race ./pkg/sql/ast/

# Coverage report
go test -cover -coverprofile=coverage.out ./pkg/sql/ast/
go tool cover -html=coverage.out

# Specific features
go test -v -run TestSelectStatement ./pkg/sql/ast/
go test -v -run TestWindowSpec ./pkg/sql/ast/
go test -v -run TestVisitor ./pkg/sql/ast/

Best Practices

1. Always Use Object Pools
// GOOD: Use pool
selectStmt := ast.NewSelectStatement()
defer ast.ReleaseSelectStatement(selectStmt)

// BAD: Direct instantiation
selectStmt := &ast.SelectStatement{}  // Misses pool benefits
2. Check Node Types Safely
// GOOD: Type assertion with check
if selectStmt, ok := node.(*ast.SelectStatement); ok {
    // Use selectStmt
}

// BAD: Unsafe type assertion
selectStmt := node.(*ast.SelectStatement)  // Panics if wrong type
3. Use Visitor Pattern for Traversal
// GOOD: Visitor pattern
ast.Walk(node, func(n ast.Node) bool {
    // Visit each node systematically
    return true
})

// BAD: Manual recursion
func traverse(n ast.Node) {
    // Complex, error-prone manual traversal
}

Node Type Reference

Statements
  • SelectStatement - SELECT queries
  • InsertStatement - INSERT operations
  • UpdateStatement - UPDATE operations
  • DeleteStatement - DELETE operations
  • CreateTableStatement - CREATE TABLE DDL
  • AlterTableStatement - ALTER TABLE DDL
  • DropTableStatement - DROP TABLE DDL
  • WithClause - Common Table Expressions
  • SetOperation - UNION/EXCEPT/INTERSECT
Expressions
  • Identifier - Column/table/alias names
  • Literal - Constant values
  • BinaryExpression - Binary operations
  • UnaryExpression - Unary operations
  • FunctionCall - Function invocations
  • CaseExpression - CASE WHEN expressions
  • InExpression - IN predicates
  • BetweenExpression - BETWEEN predicates
  • SubqueryExpression - Subqueries in expressions
Special Types
  • JoinClause - JOIN specifications
  • TableReference - Table references with aliases
  • WindowSpec - Window function specifications
  • WindowFrame - Window frame clauses
  • OrderByExpression - ORDER BY with NULL ordering
  • parser: Builds AST from tokens
  • tokenizer: Provides input to parser
  • visitor: AST traversal utilities
  • token: Token definitions

Documentation

Version History

  • v1.5.0: OrderByExpression with NullsFirst support (SQL-99 F851)
  • v1.4.0: Production validation, pool optimization
  • v1.3.0: Window functions (WindowSpec, WindowFrame, WindowFrameBound)
  • v1.2.0: CTEs (WithClause, CommonTableExpr) and set operations
  • v1.0.0: Core DML/DDL statements and expressions

Documentation

Overview

Package ast provides Abstract Syntax Tree (AST) node definitions for SQL statements.

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.

For complete documentation including architecture overview, usage examples, visitor pattern, and feature support matrix, see the package-level documentation in doc.go.

Key features:

  • Complete SQL-99/SQL:2003 statement support (DDL, DML, CTEs, window functions)
  • PostgreSQL extensions (LATERAL, DISTINCT ON, FILTER, RETURNING, JSON operators)
  • Advanced grouping (GROUPING SETS, ROLLUP, CUBE)
  • MERGE statements (SQL:2003 F312)
  • Object pooling for 60-80% memory reduction
  • Thread-safe with zero race conditions
  • Visitor pattern for AST traversal

Quick Start Example:

// Get AST from pool
astObj := ast.NewAST()
defer ast.ReleaseAST(astObj)  // Always use defer

// Get SELECT statement from pool
stmt := ast.GetSelectStatement()
defer ast.PutSelectStatement(stmt)

// Build and use AST nodes...

Version 1.6.0 adds PostgreSQL extensions including LATERAL JOIN, DISTINCT ON, FILTER clause, RETURNING clause, JSON/JSONB operators, and FETCH FIRST/NEXT.

Package ast provides Abstract Syntax Tree (AST) node definitions for SQL statements.

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

License

Copyright (c) 2024 GoSQLX Contributors Licensed under the Apache License, Version 2.0

Package ast provides operator definitions for SQL expressions.

This file defines unary and binary operators supported in SQL expressions, including standard SQL operators and PostgreSQL-specific extensions.

Package ast provides object pooling for AST nodes to minimize allocations.

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
  • 95%+ pool hit rates with proper usage patterns
  • Thread-safe operations (zero race conditions)
  • Iterative cleanup to prevent stack overflow

IMPORTANT: Always use defer when returning pooled objects to prevent leaks.

See also: doc.go for complete pooling documentation and usage examples

Index

Constants

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

This section is empty.

Functions

func GetExpressionSlice

func GetExpressionSlice() *[]Expression

GetExpressionSlice gets a slice of Expression from the pool

func GetSpan

func GetSpan(node interface{}) models.Span

GetSpan gets the source location span for an AST node

func Inspect

func Inspect(node Node, f func(Node) bool)

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

func ParseStructTags(tag string) map[string]string

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 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 PutDeleteStatement

func PutDeleteStatement(stmt *DeleteStatement)

PutDeleteStatement returns a DeleteStatement 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:

  1. Use work queue instead of recursion
  2. Process expressions breadth-first
  3. Collect child expressions and add to queue
  4. Clean and return to pool
  5. 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 PutSelectStatement

func PutSelectStatement(stmt *SelectStatement)

PutSelectStatement returns a SelectStatement to the pool Uses iterative cleanup via PutExpression to handle deeply nested expressions

func PutSubqueryExpression added in v1.6.0

func PutSubqueryExpression(se *SubqueryExpression)

PutSubqueryExpression returns a SubqueryExpression 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:

  1. Returns all statement objects to their respective pools
  2. Clears all statement references
  3. Resets the Statements slice (preserves capacity)
  4. 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 SetSpan

func SetSpan(node interface{}, span models.Span)

SetSpan sets the source location span for an AST node

func UnionSpans

func UnionSpans(spans []models.Span) models.Span

UnionSpans returns the union of all spans in the given slice

func Walk

func Walk(v Visitor, node Node) error

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:

  1. Call v.Visit(node) for the current node
  2. 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
  3. If Visit returns nil visitor, skip children
  4. 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
}

AST represents the root of the Abstract Syntax Tree

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

func (a AST) Children() []Node

func (*AST) Span

func (a *AST) Span() models.Span

Span returns the source location span for the AST

func (AST) TokenLiteral

func (a AST) TokenLiteral() string

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

Make AlterColumnOperation implement Node interface

func (*AlterColumnOperation) TokenLiteral

func (a *AlterColumnOperation) TokenLiteral() string

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

func (AlterConnectorOperation) TokenLiteral

func (a AlterConnectorOperation) TokenLiteral() string

type AlterConnectorOwner

type AlterConnectorOwner struct {
	IsUser bool
	Name   string
}

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

func (AlterPolicyOperation) TokenLiteral

func (a AlterPolicyOperation) TokenLiteral() string

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

func (AlterRoleOperation) TokenLiteral

func (a AlterRoleOperation) TokenLiteral() string

type AlterStatement

type AlterStatement struct {
	Type      AlterType
	Name      string // Name of the object being altered
	Operation AlterOperation
}

AlterStatement represents an ALTER statement

func (AlterStatement) Children

func (a AlterStatement) Children() []Node

func (AlterStatement) TokenLiteral

func (a AlterStatement) TokenLiteral() string

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

func (AlterTableOperation) TokenLiteral

func (a AlterTableOperation) TokenLiteral() string

type AlterTableStatement

type AlterTableStatement struct {
	Table   string
	Actions []AlterTableAction
}

AlterTableStatement represents an ALTER TABLE statement

func (AlterTableStatement) Children

func (a AlterTableStatement) Children() []Node

func (AlterTableStatement) TokenLiteral

func (a AlterTableStatement) TokenLiteral() string

type AlterType

type AlterType int

AlterType represents the type of object being altered

const (
	AlterTypeTable AlterType = iota
	AlterTypeRole
	AlterTypePolicy
	AlterTypeConnector
)

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) TokenLiteral added in v1.6.0

func (a AnyExpression) TokenLiteral() string

type ArrayBracketType

type ArrayBracketType int
const (
	NoBrackets ArrayBracketType = iota
	AngleBrackets
	SquareBrackets
	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) 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

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) 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) TokenLiteral added in v1.7.0

func (a ArraySubscriptExpression) TokenLiteral() string

type ArrayType

type ArrayType struct {
	ElementType *ArrayElemTypeDef
}

Basic data types

func (*ArrayType) String

func (t *ArrayType) String() 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) String

func (a AttachedToken) String() string

String implements fmt.Stringer

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
}

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

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

type BinaryLength struct {
	Length uint64
	IsMax  bool
}

BinaryLength represents binary length information

func (*BinaryLength) String

func (b *BinaryLength) String() 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

type BooleanType

type BooleanType struct{}

Basic data types

func (*BooleanType) String

func (*BooleanType) String() string

type CaseExpression

type CaseExpression struct {
	Value       Expression // Optional CASE value
	WhenClauses []WhenClause
	ElseClause  Expression
}

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

func (e *CastExpression) Span() models.Span

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

type CharacterLength

type CharacterLength struct {
	Length uint64
	Unit   *CharLengthUnits
}

CharacterLength represents character length information

func (*CharacterLength) String

func (c *CharacterLength) String() string

type CharacterType

type CharacterType struct {
	Length *CharacterLength
}

Basic data types

func (*CharacterType) String

func (t *CharacterType) String() string

type ClusteredBy

type ClusteredBy struct {
	Columns []Node
	Buckets int
}

ClusteredBy represents CLUSTERED BY clause

func (*ClusteredBy) Children

func (c *ClusteredBy) Children() []Node

func (*ClusteredBy) TokenLiteral

func (c *ClusteredBy) TokenLiteral() string

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

func (c ColumnDef) Children() []Node

func (*ColumnDef) String

func (c *ColumnDef) String() string

String returns a string representation of a ColumnDef

func (ColumnDef) TokenLiteral

func (c ColumnDef) TokenLiteral() string

type ColumnPosition

type ColumnPosition struct {
	First    bool
	After    *Ident
	Position int
}

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

func (*CommentDef) TokenLiteral

func (c *CommentDef) TokenLiteral() string

type CommonTableExpr

type CommonTableExpr struct {
	Name         string
	Columns      []string
	Statement    Statement
	Materialized *bool // nil = default, true = MATERIALIZED, false = NOT MATERIALIZED
}

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 (CreateIndexStatement) Children

func (c CreateIndexStatement) Children() []Node

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 (CreateMaterializedViewStatement) Children added in v1.6.0

func (c CreateMaterializedViewStatement) Children() []Node

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

func (*CreateTable) TokenLiteral

func (c *CreateTable) TokenLiteral() string

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 (*CreateTableBuilder) SetClusterBy

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 (*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 (*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 (*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 (*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
}

CreateTableStatement represents a CREATE TABLE statement

func (CreateTableStatement) Children

func (c CreateTableStatement) Children() []Node

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 (CreateViewStatement) Children added in v1.6.0

func (c CreateViewStatement) Children() []Node

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

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 DataType

type DataType struct {
	Type DataTypeVariant
}

DataType represents SQL data types

type DataTypeVariant

type DataTypeVariant interface {
	fmt.Stringer
	// contains filtered or unexported methods
}

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
	Millennium
	Millisecond
	Milliseconds
	Nanosecond
	Nanoseconds
	Quarter
	Time
	Timezone
	TimezoneAbbr
	TimezoneHour
	TimezoneMinute
	TimezoneRegion
	NoDateTime
	CustomDateTime
)

func (DateTimeField) String

func (d DateTimeField) String() string

type DateType

type DateType struct{}

Basic data types

func (*DateType) String

func (*DateType) String() string

type Delete

type Delete struct {
	Table           TableReference
	Where           Expression
	ReturningClause []Expression
}

Delete represents a DELETE statement

func (Delete) Children

func (d Delete) Children() []Node

func (Delete) TokenLiteral

func (d Delete) TokenLiteral() string

type DeleteStatement

type DeleteStatement struct {
	With      *WithClause
	TableName string
	Alias     string
	Using     []TableReference
	Where     Expression
	Returning []Expression
}

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

type DollarQuotedString struct {
	Value string
	Tag   string
}

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 (DropStatement) Children added in v1.6.0

func (d DropStatement) Children() []Node

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

type EnumType

type EnumType struct {
	Values []EnumMember
	Bits   *uint8
}

Basic data types

func (*EnumType) String

func (t *EnumType) String() string

type ExactNumberInfo

type ExactNumberInfo struct {
	Precision *uint64
	Scale     *uint64
}

ExactNumberInfo represents precision and scale information

func (*ExactNumberInfo) String

func (e *ExactNumberInfo) String() string

type ExistsExpression

type ExistsExpression struct {
	Subquery Statement
}

ExistsExpression represents EXISTS (subquery)

func (ExistsExpression) Children

func (e ExistsExpression) Children() []Node

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

type FloatType struct {
	Length *uint64
}

Basic data types

func (*FloatType) String

func (t *FloatType) String() string

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) Children added in v1.7.0

func (f ForClause) Children() []Node

func (ForClause) TokenLiteral added in v1.7.0

func (f ForClause) TokenLiteral() string

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.)
}

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

func (e *FunctionCall) Span() models.Span

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

Implement Node interface

func (FunctionDesc) String

func (f FunctionDesc) String() string

func (FunctionDesc) TokenLiteral

func (f FunctionDesc) TokenLiteral() 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) 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) Children

func (i *Ident) Children() []Node

func (*Ident) String

func (i *Ident) String() string

func (*Ident) TokenLiteral

func (i *Ident) TokenLiteral() string

type Identifier

type Identifier struct {
	Name  string
	Table string // Optional table qualifier
}

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

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

func (i InExpression) TokenLiteral() string

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

type IndexOptionType

type IndexOptionType int
const (
	UsingIndex IndexOptionType = iota
	CommentIndex
)

type IndexType

type IndexType int

IndexType represents the indexing method used by an index

const (
	BTree IndexType = iota
	Hash
)

func (IndexType) String

func (t IndexType) String() string

type InputFormatClause

type InputFormatClause struct {
	Format  string
	Options map[string]string
}

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

func (i Insert) Children() []Node

func (Insert) TokenLiteral

func (i Insert) TokenLiteral() string

type InsertStatement

type InsertStatement struct {
	With       *WithClause
	TableName  string
	Columns    []Expression
	Values     [][]Expression   // Multi-row support: each inner slice is one row of values
	Query      *SelectStatement // For INSERT ... SELECT
	Returning  []Expression
	OnConflict *OnConflict
}

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

type Inspector func(Node) bool

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

func (f Inspector) Visit(node Node) (Visitor, error)

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

type IntegerType struct {
	Length   *uint64
	Unsigned bool
}

Basic data types

func (*IntegerType) String

func (t *IntegerType) String() string

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) Span added in v1.7.0

func (i *IntervalExpression) Span() models.Span

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
}

JoinClause represents a JOIN clause in SQL

func (JoinClause) Children

func (j JoinClause) Children() []Node

func (JoinClause) TokenLiteral

func (j JoinClause) TokenLiteral() string

type JsonType

type JsonType struct{}

Basic data types

func (*JsonType) String

func (*JsonType) String() string

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

func (l LiteralValue) TokenLiteral() string

type Location

type Location struct {
	Line   int
	Column int
}

Location represents a source location

func (Location) String

func (l Location) String() string

String implements fmt.Stringer

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
}

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 (MergeStatement) Children added in v1.6.0

func (m MergeStatement) Children() []Node

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

type Node interface {
	TokenLiteral() string
	Children() []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

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

type Number

type Number struct {
	Value string
	Long  bool
}

Number represents a numeric value with a flag indicating if it's a long

type NumericType

type NumericType struct {
	Info *ExactNumberInfo
}

Basic data types

func (*NumericType) String

func (t *NumericType) String() string

type ObjectName

type ObjectName struct {
	Name string
}

ObjectName represents a qualified or unqualified object name

func (ObjectName) Children

func (o ObjectName) Children() []Node

func (ObjectName) String

func (o ObjectName) String() string

func (ObjectName) TokenLiteral

func (o ObjectName) TokenLiteral() string

type OnCommit

type OnCommit int

OnCommit represents the ON COMMIT behavior for temporary tables

const (
	OnCommitNone OnCommit = iota
	OnCommitDelete
	OnCommitPreserve
)

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

func (*OneOrManyWithParens[T]) TokenLiteral

func (o *OneOrManyWithParens[T]) TokenLiteral() string

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 Partition

type Partition struct {
	Name    string
	Columns []*Ident
}

Partition represents table partitioning information

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

func (p PositionExpression) TokenLiteral() string

type Query

type Query struct {
	Text string
}

Query represents a SQL query

func (*Query) Children

func (q *Query) Children() []Node

func (*Query) TokenLiteral

func (q *Query) TokenLiteral() string

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 (RefreshMaterializedViewStatement) Children added in v1.6.0

func (r RefreshMaterializedViewStatement) Children() []Node

func (RefreshMaterializedViewStatement) TokenLiteral added in v1.6.0

func (r RefreshMaterializedViewStatement) 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

type RoleOptionType

type RoleOptionType int
const (
	BypassRLS RoleOptionType = iota
	ConnectionLimit
	CreateDB
	CreateRole
	Inherit
	Login
	Password
	Replication
	SuperUser
	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) TokenLiteral added in v1.6.0

func (r RollupExpression) TokenLiteral() string

type RowAccessPolicy

type RowAccessPolicy struct {
	Name    string
	Filter  Expr
	Enabled bool
}

RowAccessPolicy represents row-level access policy

func (*RowAccessPolicy) Children

func (r *RowAccessPolicy) Children() []Node

func (*RowAccessPolicy) TokenLiteral

func (r *RowAccessPolicy) TokenLiteral() string

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

func (s Select) Children() []Node

func (Select) TokenLiteral

func (s Select) TokenLiteral() string

type SelectStatement

type SelectStatement struct {
	With              *WithClause
	Distinct          bool
	DistinctOnColumns []Expression // PostgreSQL DISTINCT ON (expr, ...) 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)
}

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) 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) Children added in v1.6.0

func (s SetClause) Children() []Node

func (SetClause) TokenLiteral added in v1.6.0

func (s SetClause) TokenLiteral() string

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

func (s SetOperation) TokenLiteral() string

type SetType

type SetType struct {
	Values []string
}

Basic data types

func (*SetType) String

func (t *SetType) String() string

type Setting

type Setting struct {
	Column *Ident
	Value  Expression
}

Setting represents a SET clause in an UPDATE statement

type Span

type Span struct {
	Start Location
	End   Location
}

Span represents a source location span

func (Span) String

func (s Span) String() string

String implements fmt.Stringer

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 SqlOption

type SqlOption struct {
	Name  string
	Value string
}

SqlOption represents SQL-specific options

type StageLoadSelectItem

type StageLoadSelectItem struct {
	Alias      *Ident
	FileColNum int32
	Element    *Ident
	ItemAs     *Ident
}

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

func (*StatementImpl) TokenLiteral

func (s *StatementImpl) TokenLiteral() string

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

type StructField struct {
	Name string
	Type string
	Tags map[string]string
}

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
}

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

type TableEngine string

TableEngine represents the storage engine for a table

type TableOption

type TableOption struct {
	Name  string
	Value string
}

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

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 TableType

type TableType struct {
	Columns []*ColumnDef
}

Basic data types

func (*TableType) String

func (t *TableType) String() string

String implementations for data types

type Tag

type Tag struct {
	Key   string
	Value string
}

Tag represents a key-value metadata tag

type TimeType

type TimeType struct {
	Precision *uint64
	Timezone  TimezoneInfo
}

Basic data types

func (*TimeType) String

func (t *TimeType) String() string

type TimestampType

type TimestampType struct {
	Precision *uint64
	Timezone  TimezoneInfo
}

Basic data types

func (*TimestampType) String

func (t *TimestampType) String() string

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

type Token

type Token struct {
	Type TokenType
}

Token represents a lexical token

func (Token) String

func (t Token) String() string

String implements fmt.Stringer

type TokenType

type TokenType int

TokenType represents the type of a token

const (
	EOF TokenType = iota
	Comma
	Period
)

Token types

type TokenWithSpan

type TokenWithSpan struct {
	Token Token
	Span  Span
}

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

func (TokenWithSpan) String

func (t TokenWithSpan) String() string

String implements fmt.Stringer

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

func (TriggerEvent) String

func (t TriggerEvent) String() string

func (TriggerEvent) TokenLiteral

func (t TriggerEvent) TokenLiteral() string

type TriggerEventType

type TriggerEventType int
const (
	TriggerEventInsert TriggerEventType = iota
	TriggerEventUpdate
	TriggerEventDelete
	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

func (TriggerExecBody) String

func (t TriggerExecBody) String() string

func (TriggerExecBody) TokenLiteral

func (t TriggerExecBody) TokenLiteral() string

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

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

Implement Node interface for trigger types

func (TriggerObject) String

func (t TriggerObject) String() string

func (TriggerObject) TokenLiteral

func (t TriggerObject) TokenLiteral() string

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

func (TriggerPeriod) String

func (t TriggerPeriod) String() string

func (TriggerPeriod) TokenLiteral

func (t TriggerPeriod) TokenLiteral() string

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

func (TriggerReferencing) String

func (t TriggerReferencing) String() string

func (TriggerReferencing) TokenLiteral

func (t TriggerReferencing) TokenLiteral() string

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

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

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 (TruncateStatement) Children added in v1.6.0

func (t TruncateStatement) Children() []Node

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) TokenLiteral added in v1.7.0

func (t TupleExpression) TokenLiteral() string

type UnaryExpression

type UnaryExpression struct {
	Operator UnaryOperator
	Expr     Expression
}

UnaryExpression represents operations like NOT expr

func (UnaryExpression) Children

func (u UnaryExpression) Children() []Node

func (*UnaryExpression) Span

func (e *UnaryExpression) Span() models.Span

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

func (u Update) Children() []Node

func (Update) TokenLiteral

func (u Update) TokenLiteral() string

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
	Updates     []UpdateExpression // Keep for backward compatibility
	Assignments []UpdateExpression // New field for consistency with span.go
	From        []TableReference
	Where       Expression
	Returning   []Expression
}

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

func (v Value) Children() []Node

func (Value) String

func (v Value) String() string

func (Value) TokenLiteral

func (v Value) TokenLiteral() string

type ValueType

type ValueType int

ValueType represents the type of a SQL value

const (
	NumberValue ValueType = iota
	SingleQuotedStringValue
	DollarQuotedStringValue
	TripleSingleQuotedStringValue
	TripleDoubleQuotedStringValue
	EscapedStringLiteralValue
	UnicodeStringLiteralValue
	SingleQuotedByteStringLiteralValue
	DoubleQuotedByteStringLiteralValue
	TripleSingleQuotedByteStringLiteralValue
	TripleDoubleQuotedByteStringLiteralValue
	SingleQuotedRawStringLiteralValue
	DoubleQuotedRawStringLiteralValue
	TripleSingleQuotedRawStringLiteralValue
	TripleDoubleQuotedRawStringLiteralValue
	NationalStringLiteralValue
	HexStringLiteralValue
	DoubleQuotedStringValue
	BooleanValue
	NullValue
	PlaceholderValue
)

type Values

type Values struct {
	Rows [][]Expression
}

Values represents VALUES clause

func (Values) Children

func (v Values) Children() []Node

func (Values) TokenLiteral

func (v Values) TokenLiteral() string

type VarcharType

type VarcharType struct {
	Length *CharacterLength
}

Basic data types

func (*VarcharType) String

func (t *VarcharType) String() string

type VisitFunc

type VisitFunc func(Node) (Visitor, error)

VisitFunc is a function type that can be used to implement custom visitors without creating a new type.

func (VisitFunc) Visit

func (f VisitFunc) Visit(node Node) (Visitor, error)

Visit implements the Visitor interface.

type Visitor

type Visitor interface {
	Visit(node Node) (w Visitor, err error)
}

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
}

WhenClause represents WHEN ... THEN ... in CASE expression

func (WhenClause) Children

func (w WhenClause) Children() []Node

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
}

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

func (w WithClause) TokenLiteral() string

type WrappedCollection

type WrappedCollection[T any] struct {
	Items   []T
	Wrapper string
}

WrappedCollection represents a collection of items with optional wrapper

func (*WrappedCollection[T]) Children

func (w *WrappedCollection[T]) Children() []Node

func (*WrappedCollection[T]) TokenLiteral

func (w *WrappedCollection[T]) TokenLiteral() string

Jump to

Keyboard shortcuts

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