Documentation
¶
Overview ¶
Package sql provides SQL parsing using a custom recursive descent parser.
Index ¶
- func IsAggregate(name string) bool
- func RebuildSQL(info *SelectInfo, rewrittenWhere Node) string
- func SetAlertIntervalFloorForTest(d time.Duration) func()
- type AlterAlertInfo
- type AlterTableInfo
- type AnalyzeTableInfo
- type AndNode
- type AnyAllExpr
- type ArrayLitNode
- type BetweenExpr
- type BinaryOp
- type CTEDef
- type CaseNode
- type CastNode
- type CmpExpr
- type ColRef
- type ColumnDef
- type CreateAlertInfo
- type CreateFunctionInfo
- type CreateSnapshotInfo
- type CreateTableInfo
- type CreateViewInfo
- type DeleteInfo
- type DescribeInfo
- type DropAlertInfo
- type DropFunctionInfo
- type DropTableInfo
- type DropViewInfo
- type ExistsNode
- type ExplainInfo
- type FrameBound
- type FrameBoundType
- type FrameMode
- type FuncCallNode
- type InExpr
- type InsertInfo
- type IntervalLit
- type IsExpr
- type JoinInfo
- type LikeExpr
- type Lit
- type LiteralKind
- type LiteralPlaceholder
- type MergeInfo
- type MergeWhenClause
- type Node
- func ParseExpression(sql string) (Node, error)
- func ReplaceAggregate(node Node, aggName string) Node
- func ReplaceAllAggregates(node Node, replacements map[string]string) Node
- func RewriteOuterRefs(node Node, outerTables map[string]bool, vals map[string]any) Node
- func RewriteUnqualifiedOuterRefs(node Node, unqualOuter map[string]string, vals map[string]any) Node
- type NotNode
- type OrNode
- type OrderByItem
- type OuterRef
- type ParenNode
- type ParsedQuery
- type QueryType
- type SelectColumn
- type SelectInfo
- type SetClause
- type SetOp
- type StarNode
- type SubqueryNode
- type TableRef
- type TokenType
- type TupleNode
- type UnaryOp
- type UnionInfo
- type UpdateInfo
- type WhenClause
- type WindowFrame
- type WindowFuncNode
- type WindowOrderBy
- type WindowOrderItem
- type WindowSpec
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func IsAggregate ¶
IsAggregate returns true if the function name is a known aggregate.
func RebuildSQL ¶
func RebuildSQL(info *SelectInfo, rewrittenWhere Node) string
RebuildSQL reconstructs a full SELECT SQL string from a SelectInfo, using the provided expression as the WHERE clause instead of the original. This is used by the correlated subquery evaluator to substitute outer values.
func SetAlertIntervalFloorForTest ¶
SetAlertIntervalFloorForTest lowers the CREATE ALERT interval floor for the duration of a test. Call the returned function (typically with defer) to restore the production floor.
Types ¶
type AlterAlertInfo ¶
AlterAlertInfo holds details for ALTER ALERT ... ENABLE|DISABLE.
type AlterTableInfo ¶
type AlterTableInfo struct {
Table string
Action string // "ADD COLUMN", "DROP COLUMN", "RENAME COLUMN"
ColumnName string
NewColumnName string // for RENAME COLUMN
ColumnType string // for ADD COLUMN
Nullable bool // for ADD COLUMN (default true)
}
AlterTableInfo holds details for an ALTER TABLE statement.
type AnalyzeTableInfo ¶
type AnalyzeTableInfo struct {
Name string
}
AnalyzeTableInfo holds details for an ANALYZE TABLE statement.
type AnyAllExpr ¶
type AnyAllExpr struct {
Left Node
Op string // =, !=, <, <=, >, >=
Modifier string // "ANY", "ALL", "SOME"
Values []Node // value list or single SubqueryNode
}
AnyAllExpr is expr op ANY/ALL/SOME (subquery or values).
func (*AnyAllExpr) String ¶
func (a *AnyAllExpr) String() string
type ArrayLitNode ¶
type ArrayLitNode struct {
Elements []Node
}
ArrayLitNode is ARRAY[expr, expr, ...].
func (*ArrayLitNode) String ¶
func (a *ArrayLitNode) String() string
type BetweenExpr ¶
BetweenExpr is expr [NOT] BETWEEN low AND high.
func (*BetweenExpr) String ¶
func (b *BetweenExpr) String() string
type CTEDef ¶
type CTEDef struct {
Name string // CTE name (lowercased for matching)
SQL string // the CTE body SQL (the SELECT inside the parentheses)
Columns []string // optional column name list
Recursive bool // WITH RECURSIVE
}
CTEDef represents a Common Table Expression definition.
type CaseNode ¶
type CaseNode struct {
Subject Node // nil for searched CASE
Whens []WhenClause // at least one
Else Node // nil if no ELSE
}
CaseNode is a CASE expression.
type ColumnDef ¶
type ColumnDef struct {
Name string
Type string
Nullable bool // true by default; NOT NULL sets it to false
}
ColumnDef defines a column in a CREATE TABLE statement.
type CreateAlertInfo ¶
type CreateAlertInfo struct {
Name string
QueryText string // raw SELECT text, re-parsed at eval time
Interval time.Duration // validated >= 10s at parse time
WebhookURL string // "" if no webhook sink
Headers map[string]string
InsertInto string // "" if no table sink; at least one sink required
}
CreateAlertInfo holds details for a CREATE ALERT statement.
type CreateFunctionInfo ¶
type CreateFunctionInfo struct {
Name string
Params []string
Body string
Replace bool // CREATE OR REPLACE
Locked bool // WITH LOCK
}
CreateFunctionInfo holds details for a CREATE FUNCTION statement.
type CreateSnapshotInfo ¶
type CreateSnapshotInfo struct{}
CreateSnapshotInfo is the AST for a CREATE SNAPSHOT statement. Empty in v1 — statement takes no arguments.
type CreateTableInfo ¶
CreateTableInfo holds details for a CREATE TABLE statement.
type CreateViewInfo ¶
type CreateViewInfo struct {
Name string
SQL string // the view definition SQL
Replace bool // CREATE OR REPLACE VIEW
}
CreateViewInfo holds details for a CREATE VIEW statement.
type DeleteInfo ¶
type DeleteInfo struct {
Table string // table name
WhereSQL string // raw WHERE clause SQL (empty = delete all rows)
}
DeleteInfo holds details for a DELETE statement.
type DescribeInfo ¶
type DescribeInfo struct {
TableName string
}
DescribeInfo holds details for a DESCRIBE/SHOW COLUMNS statement.
type DropAlertInfo ¶
DropAlertInfo holds details for a DROP ALERT statement.
type DropFunctionInfo ¶
DropFunctionInfo holds details for a DROP FUNCTION statement.
type DropTableInfo ¶
DropTableInfo holds details for a DROP TABLE statement.
type DropViewInfo ¶
DropViewInfo holds details for a DROP VIEW statement.
type ExistsNode ¶
ExistsNode is [NOT] EXISTS (SELECT ...).
func (*ExistsNode) String ¶
func (e *ExistsNode) String() string
type ExplainInfo ¶
ExplainInfo holds details for an EXPLAIN statement.
type FrameBound ¶
type FrameBound struct {
Type FrameBoundType
Offset Node // nil for UNBOUNDED/CURRENT ROW
}
FrameBound describes one end of a window frame.
type FrameBoundType ¶
type FrameBoundType int
FrameBoundType identifies the type of a frame bound.
const ( BoundUnboundedPreceding FrameBoundType = iota BoundPreceding BoundCurrentRow BoundFollowing BoundUnboundedFollowing )
type FuncCallNode ¶
type FuncCallNode struct {
Name string
Args []Node
Distinct bool // COUNT(DISTINCT col)
Star bool // COUNT(*)
}
FuncCallNode is a function call expression.
func FindAllAggregates ¶
func FindAllAggregates(node Node) []*FuncCallNode
FindAllAggregates walks an expression tree and returns all aggregate function calls found. For multi-aggregate expressions like MAX(x) - MIN(x), this returns both aggregates.
func FindNestedAggregate ¶
func FindNestedAggregate(node Node) *FuncCallNode
FindNestedAggregate walks an expression tree and returns the first aggregate function call found, or nil if none exists. This detects aggregates nested inside binary expressions like SUM(x) * 0.0001.
func (*FuncCallNode) String ¶
func (f *FuncCallNode) String() string
type InsertInfo ¶
type InsertInfo struct {
Table string // table name
Columns []string // target column names (empty = all columns)
Values [][]string // rows of value expressions
}
InsertInfo holds details for an INSERT statement.
type IntervalLit ¶
type IntervalLit struct {
Value int
Unit string // "day", "month", "year", "hour", "minute", "second"
}
IntervalLit represents INTERVAL 'N' DAY or INTERVAL 'N days' expressions.
func (*IntervalLit) String ¶
func (i *IntervalLit) String() string
type JoinInfo ¶
type JoinInfo struct {
Type string // join, left join, right join, full outer join, cross join
LeftTable string
RightTable string
RightAlias string
RightTableRef *TableRef // full right-side table ref (includes function info)
Condition string
CondExpr Node
Lateral bool // LATERAL join — right side can reference left side columns
}
JoinInfo describes a JOIN clause.
type Lit ¶
type Lit struct {
Value string
Kind LiteralKind
}
Lit is a literal value (string, number, bool, null).
type LiteralKind ¶
type LiteralKind int
LiteralKind identifies the kind of literal value.
const ( LitString LiteralKind = iota LitNumber LitBool LitNull )
type LiteralPlaceholder ¶
type LiteralPlaceholder struct {
Name string
}
LiteralPlaceholder marks a deferred literal whose value is computed at stage-dispatch time from the output of a prerequisite stage. The physical planner inserts these when a filter expression's subquery references a CTE whose distributed-pipeline output would diverge from single-process evaluation; the native-DAG coordinator rewrites the serialized filter expression by string-replacing ":<Name>" with the concrete literal before dispatching the task. String renders as ":<Name>" so any code path that accidentally serializes the expression before substitution produces an unambiguous syntax error instead of silently coercing.
func (*LiteralPlaceholder) String ¶
func (l *LiteralPlaceholder) String() string
type MergeInfo ¶
type MergeInfo struct {
Target string // target table name
TargetAlias string
Source string // source table/subquery
SourceAlias string
OnCondition string // MERGE ON condition
WhenClauses []MergeWhenClause // WHEN MATCHED / NOT MATCHED clauses
}
MergeInfo holds details for a MERGE statement.
type MergeWhenClause ¶
type MergeWhenClause struct {
Matched bool // true = WHEN MATCHED, false = WHEN NOT MATCHED
Condition string // optional AND condition
Action string // "UPDATE", "DELETE", "INSERT"
SQL string // raw SET/VALUES clause
}
MergeWhenClause represents a WHEN clause in a MERGE statement.
type Node ¶
type Node interface {
String() string
// contains filtered or unexported methods
}
Node is the base interface for all SQL expression AST nodes. Every concrete node type must implement nodeTag (a marker method) and String.
func ParseExpression ¶
ParseExpression parses a single expression from a SQL string. Used for standalone expression parsing (e.g., UDF bodies, WHERE clauses).
func ReplaceAggregate ¶
ReplaceAggregate replaces the first aggregate function call in the expression tree with a ColRef pointing to the aggregate output column name.
func ReplaceAllAggregates ¶
ReplaceAllAggregates replaces all aggregate function calls in the expression tree with ColRef nodes. The replacements map maps lowercase aggregate expression strings (e.g., "sum(rx_bytes)") to output column names.
func RewriteOuterRefs ¶
RewriteOuterRefs returns a deep copy of the AST with correlated ColRef nodes replaced by literal values from vals. Keys in vals are "table.column" (lowercased).
func RewriteUnqualifiedOuterRefs ¶
func RewriteUnqualifiedOuterRefs(node Node, unqualOuter map[string]string, vals map[string]any) Node
RewriteUnqualifiedOuterRefs replaces unqualified column references that were detected as outer refs (via column mapping). unqualOuter maps column names (lowercased) to their resolved table. vals contains "table.column" → value.
type OrderByItem ¶
type OrderByItem struct {
Column string
Desc bool
NullsFirst *bool // nil = default, true = NULLS FIRST, false = NULLS LAST
}
OrderByItem describes an ORDER BY element.
type OuterRef ¶
type OuterRef struct {
Table string // outer table alias (lowercased)
Column string // column name (lowercased)
}
OuterRef represents a correlated column reference to an outer query scope.
func FindCorrelatedRefs ¶
FindCorrelatedRefs parses a subquery SQL string and returns any column references that refer to tables in outerTables but not to tables defined within the subquery itself. An empty result means the subquery is uncorrelated.
func FindCorrelatedRefsWithColumns ¶
func FindCorrelatedRefsWithColumns(subquerySQL string, outerTables map[string]bool, outerCols map[string]string) ([]OuterRef, error)
FindCorrelatedRefsWithColumns is like FindCorrelatedRefs but also accepts a column-to-table mapping for resolving unqualified column references.
type ParsedQuery ¶
type ParsedQuery struct {
Type QueryType
TableName string
SQL string
Explain *ExplainInfo
Describe *DescribeInfo
CreateFunction *CreateFunctionInfo
DropFunction *DropFunctionInfo
CreateTable *CreateTableInfo
DropTable *DropTableInfo
AnalyzeTable *AnalyzeTableInfo
CreateView *CreateViewInfo
DropView *DropViewInfo
AlterTable *AlterTableInfo
Merge *MergeInfo
Update *UpdateInfo
Delete *DeleteInfo
Insert *InsertInfo
CreateAlert *CreateAlertInfo
DropAlert *DropAlertInfo
AlterAlert *AlterAlertInfo
CreateSnapshot *CreateSnapshotInfo
Windows []WindowSpec // extracted window function specs
CTEs []CTEDef // extracted CTE definitions
SelectInfo *SelectInfo // parsed SELECT info (replaces AST)
}
ParsedQuery represents a parsed SQL query.
func Parse ¶
func Parse(sql string) (*ParsedQuery, error)
Parse parses a SQL string into a ParsedQuery.
type QueryType ¶
type QueryType int
QueryType identifies the kind of SQL statement.
const ( QuerySelect QueryType = iota QueryExplain QueryDescribe QueryCreateFunction QueryDropFunction QueryShowFunctions QueryCreateTable QueryDropTable QueryAnalyzeTable QueryShowTables QueryUpdate QueryDelete QueryInsert QueryCreateView QueryDropView QueryAlterTable QueryMerge QueryCreateAlert QueryDropAlert QueryAlterAlert QueryCreateSnapshot QueryUnsupported )
type SelectColumn ¶
type SelectColumn struct {
Expr string
Alias string
Star bool
IsAgg bool
AggFunc string
AggArg string
AggArgExpr Node // AST for aggregate argument expression
AggDistinct bool // COUNT(DISTINCT col)
IsWindow bool // true if this is a window function
WindowSpec *WindowSpec // window function details
ColumnRef string
TableRef string
ASTExpr Node // our AST expression node
}
SelectColumn describes a column in a SELECT clause.
type SelectInfo ¶
type SelectInfo struct {
Tables []TableRef
Joins []JoinInfo
Columns []SelectColumn
Where string
WhereExpr Node
GroupBy []string
GroupByExprs []Node // AST for GROUP BY expressions (parallel to GroupBy)
GroupingSets [][]string // GROUPING SETS / CUBE / ROLLUP (nil = simple GROUP BY)
Having string
HavingExpr Node
Distinct bool
Qualify string
QualifyExpr Node
OrderBy []OrderByItem
Limit string
Offset string
Windows []WindowSpec // window function specs extracted during pre-parse
CTEs []CTEDef // CTE definitions extracted during pre-parse
Union *UnionInfo // non-nil if this is a UNION query
}
SelectInfo contains extracted information from a SELECT statement.
func ExtractSelect ¶
func ExtractSelect(pq *ParsedQuery) (*SelectInfo, error)
ExtractSelect returns the SelectInfo from a parsed query.
type SubqueryNode ¶
type SubqueryNode struct {
SQL string
}
SubqueryNode wraps a subquery as raw SQL.
func (*SubqueryNode) String ¶
func (s *SubqueryNode) String() string
type TableRef ¶
type TableRef struct {
Name string
Alias string
IsFunction bool // true for table functions like read_json(...)
FuncArgs []string // positional arguments
FuncNamedArgs map[string]string // named arguments (key=value)
WithOrdinality bool // UNNEST(...) WITH ORDINALITY
ColumnAliases []string // AS alias(col1, col2, ...)
SampleMethod string // TABLESAMPLE method: BERNOULLI, SYSTEM
SamplePercent string // percentage for TABLESAMPLE
}
TableRef is a reference to a table or table-producing function.
type TokenType ¶
type TokenType int
TokenType identifies the kind of lexical token.
const ( // Special TokenError TokenType = iota // lexing error (val contains message) TokenEOF // end of input // Literals TokenIdent // unquoted identifier TokenString // single-quoted string literal (val has quotes stripped, ” unescaped) TokenNumber // integer or decimal // Punctuation TokenLParen // ( TokenRParen // ) TokenComma // , TokenSemicolon // ; TokenStar // * TokenDot // . TokenLBracket // [ TokenRBracket // ] TokenLBrace // { TokenRBrace // } // Operators TokenPlus // + TokenMinus // - TokenSlash // / TokenPercent // % TokenConcat // || TokenDoubleColon // :: TokenJSONArrow // -> TokenJSONDoubleArrow // ->> TokenEq // = TokenNotEq // != or <> TokenLT // < TokenLTEq // <= TokenGT // > TokenGTEq // >= // Keywords (case-insensitive, val is always uppercase) TokenKWCreate TokenKWOr TokenKWReplace TokenKWFunction TokenKWAs TokenKWDrop TokenKWIf TokenKWExists TokenKWShow TokenKWFunctions TokenKWColumns TokenKWFrom TokenKWExplain TokenKWVerbose TokenKWAnalyze TokenKWDescribe TokenKWDesc TokenKWWith TokenKWLock TokenKWTable TokenKWTables TokenKWNot TokenKWNull TokenKWPartition TokenKWBy // SQL query keywords TokenKWSelect TokenKWWhere TokenKWGroup TokenKWHaving TokenKWOrder TokenKWLimit TokenKWOffset TokenKWAsc TokenKWDistinct TokenKWAll TokenKWUnion TokenKWIntersect TokenKWExcept TokenKWAnd TokenKWIn TokenKWBetween TokenKWLike TokenKWILike TokenKWIs TokenKWTrue TokenKWFalse TokenKWCase TokenKWWhen TokenKWThen TokenKWElse TokenKWEnd TokenKWCast TokenKWJoin TokenKWOn TokenKWInner TokenKWLeft TokenKWRight TokenKWOuter TokenKWFull TokenKWCross TokenKWNatural TokenKWOver TokenKWNulls TokenKWFirst TokenKWLast TokenKWRows TokenKWRange TokenKWUnbounded TokenKWPreceding TokenKWFollowing TokenKWCurrent TokenKWRow TokenKWCube TokenKWRollup TokenKWGrouping TokenKWSets // Clause keywords TokenKWFetch TokenKWView TokenKWAlter TokenKWAdd TokenKWColumn TokenKWRename TokenKWTo // DML keywords TokenKWUpdate TokenKWSet TokenKWDelete TokenKWInsert TokenKWInto TokenKWValues TokenKWMerge TokenKWUsing TokenKWMatched // Alert DDL keywords TokenKWAlert TokenKWEvery TokenKWWebhook TokenKWHeaders TokenKWEnable TokenKWDisable TokenKWSeconds TokenKWMinutes TokenKWHours // Snapshot keywords TokenKWSnapshot // Raw capture TokenRawBody // everything after AS until terminator )
type TupleNode ¶
type TupleNode struct {
Elements []Node
}
TupleNode represents a tuple expression: (a, b, c).
type UnionInfo ¶
type UnionInfo struct {
Left *SelectInfo
Right *SelectInfo
All bool // true for UNION ALL / INTERSECT ALL / EXCEPT ALL (no dedup)
Op SetOp // the set operation type (defaults to UNION for backwards compat)
}
UnionInfo describes a set operation (UNION, INTERSECT, EXCEPT) with left and right sides.
type UpdateInfo ¶
type UpdateInfo struct {
Table string // table name
SetClauses []SetClause // SET column = value pairs
WhereSQL string // raw WHERE clause SQL (empty = update all rows)
}
UpdateInfo holds details for an UPDATE statement.
type WhenClause ¶
WhenClause is a single WHEN ... THEN ... clause.
type WindowFrame ¶
type WindowFrame struct {
Mode FrameMode
Start FrameBound
End *FrameBound // nil means "to CURRENT ROW"
}
WindowFrame describes a window frame specification.
type WindowFuncNode ¶
type WindowFuncNode struct {
Func *FuncCallNode
PartitionBy []Node
OrderBy []WindowOrderBy
Frame *WindowFrame
}
WindowFuncNode represents a window function call: FUNC(...) OVER (...)
func (*WindowFuncNode) String ¶
func (n *WindowFuncNode) String() string
type WindowOrderBy ¶
WindowOrderBy describes ordering in a window function's OVER clause.
type WindowOrderItem ¶
WindowOrderItem describes a column + direction in a window ORDER BY.
type WindowSpec ¶
type WindowSpec struct {
FuncName string
Args string // raw arg string (e.g., "amount", "*", "")
PartitionBy []string
OrderBy []WindowOrderItem
Alias string // output column name
Frame *WindowFrame // optional frame specification
}
WindowSpec describes a window function specification.