Skip to content
Merged
629 changes: 326 additions & 303 deletions ast/ast.go

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions internal/explain/format.go
Original file line number Diff line number Diff line change
Expand Up @@ -501,6 +501,8 @@ func OperatorToFunction(op string) string {
return "greaterOrEquals"
case "<=>":
return "isNotDistinctFrom"
case "IS DISTINCT FROM":
return "isDistinctFrom"
case "AND":
return "and"
case "OR":
Expand Down
20 changes: 15 additions & 5 deletions internal/explain/functions.go
Original file line number Diff line number Diff line change
Expand Up @@ -1184,14 +1184,14 @@ func explainInExpr(sb *strings.Builder, n *ast.InExpr, indent string, depth int)
if allTuples {
// Wrap all tuples in Function tuple
fmt.Fprintf(sb, "%s Function tuple (children %d)\n", indent, 1)
fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", indent, len(n.List))
explainInListHeader(sb, indent+" ", len(n.List))
for _, item := range n.List {
explainTupleInInList(sb, item.(*ast.Literal), indent+" ", depth+4)
}
} else {
// Wrap non-literal/non-tuple list items in Function tuple
fmt.Fprintf(sb, "%s Function tuple (children %d)\n", indent, 1)
fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", indent, len(n.List))
explainInListHeader(sb, indent+" ", len(n.List))
for _, item := range n.List {
Node(sb, item, depth+4)
}
Expand Down Expand Up @@ -1316,7 +1316,7 @@ func explainInExprWithAlias(sb *strings.Builder, n *ast.InExpr, alias string, in
break
}
}
if allStringLiterals {
if allStringLiterals && len(n.List) > 0 {
// Large string list - separate children
argCount += len(n.List)
} else {
Expand Down Expand Up @@ -1361,14 +1361,14 @@ func explainInExprWithAlias(sb *strings.Builder, n *ast.InExpr, alias string, in
if allTuples {
// Wrap all tuples in Function tuple
fmt.Fprintf(sb, "%s Function tuple (children %d)\n", indent, 1)
fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", indent, len(n.List))
explainInListHeader(sb, indent+" ", len(n.List))
for _, item := range n.List {
explainTupleInInList(sb, item.(*ast.Literal), indent+" ", depth+4)
}
} else {
// Wrap non-literal/non-tuple list items in Function tuple
fmt.Fprintf(sb, "%s Function tuple (children %d)\n", indent, 1)
fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", indent, len(n.List))
explainInListHeader(sb, indent+" ", len(n.List))
for _, item := range n.List {
Node(sb, item, depth+4)
}
Expand Down Expand Up @@ -2086,3 +2086,13 @@ func explainKQLFilter(sb *strings.Builder, filter *kqlFilter, indent string, dep
fmt.Fprintf(sb, "%s Identifier %s\n", indent, rightVal)
}
}

// explainInListHeader prints the ExpressionList of an IN list; an empty list
// (x IN ()) prints without a children count.
func explainInListHeader(sb *strings.Builder, indent string, n int) {
if n == 0 {
fmt.Fprintf(sb, "%sExpressionList\n", indent)
return
}
fmt.Fprintf(sb, "%sExpressionList (children %d)\n", indent, n)
}
14 changes: 14 additions & 0 deletions internal/explain/select.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ func explainSelectIntersectExceptQuery(sb *strings.Builder, n *ast.SelectInterse

childIndent := strings.Repeat(" ", depth+1)
for i, sel := range n.Selects {
sel = unwrapSingleSelect(sel)
if hasExcept && i == 0 {
// Wrap first operand in SelectWithUnionQuery -> ExpressionList format
// But if it's already a SelectWithUnionQuery, don't double-wrap
Expand All @@ -46,6 +47,18 @@ func explainSelectIntersectExceptQuery(sb *strings.Builder, n *ast.SelectInterse
}
}

// unwrapSingleSelect returns the inner SELECT of a parenthesized operand
// such as (SELECT 1); ClickHouse 26.x drops the SelectWithUnionQuery wrapper.
func unwrapSingleSelect(sel ast.Statement) ast.Statement {
if u, ok := sel.(*ast.SelectWithUnionQuery); ok && len(u.Selects) == 1 && len(u.Settings) == 0 {
if _, isSelect := u.Selects[0].(*ast.SelectQuery); !isSelect {
return sel
}
return u.Selects[0]
}
return sel
}

// extractWithClause extracts the WITH clause from a statement (if it's a SelectQuery)
func extractWithClause(stmt ast.Statement) []ast.Expression {
switch s := stmt.(type) {
Expand Down Expand Up @@ -283,6 +296,7 @@ func explainSelectIntersectExceptQueryWithInheritedWith(sb *strings.Builder, n *
}

for i, sel := range n.Selects {
sel = unwrapSingleSelect(sel)
if hasExcept && i == 0 {
// Wrap first operand in SelectWithUnionQuery format
if _, isUnion := sel.(*ast.SelectWithUnionQuery); isUnion {
Expand Down
155 changes: 129 additions & 26 deletions internal/explain/statements.go
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,10 @@ func explainCreateQuery(sb *strings.Builder, n *ast.CreateQuery, indent string,
return
}
// Handle special CREATE types
if n.CreateFunction && n.Wasm != nil {
explainCreateWasmFunction(sb, n, indent, depth)
return
}
if n.CreateFunction {
children := 2 // identifier + lambda
fmt.Fprintf(sb, "%sCreateFunctionQuery %s (children %d)\n", indent, n.FunctionName, children)
Expand Down Expand Up @@ -461,32 +465,28 @@ func explainCreateQuery(sb *strings.Builder, n *ast.CreateQuery, indent string,
// ORDER BY comes after PRIMARY KEY in EXPLAIN output
if len(n.OrderBy) > 0 {
if len(n.OrderBy) == 1 {
if ident, ok := n.OrderBy[0].(*ast.Identifier); ok {
// When ORDER BY has modifiers (ASC/DESC), wrap in StorageOrderByElement
if n.OrderByHasModifiers {
fmt.Fprintf(sb, "%s StorageOrderByElement (children %d)\n", storageIndent, 1)
fmt.Fprintf(sb, "%s Identifier %s\n", storageIndent, sanitizeUTF8(ident.Name()))
} else {
fmt.Fprintf(sb, "%s Identifier %s\n", storageIndent, sanitizeUTF8(ident.Name()))
}
} else if lit, ok := n.OrderBy[0].(*ast.Literal); ok && lit.Type == ast.LiteralTuple {
// Handle tuple literal - for ORDER BY with modifiers (DESC/ASC),
// ClickHouse outputs just "Function tuple" without children
// For empty tuples or regular tuples without modifiers, output children
if n.OrderByHasModifiers {
fmt.Fprintf(sb, "%s Function tuple\n", storageIndent)
} else {
exprs, _ := lit.Value.([]ast.Expression)
fmt.Fprintf(sb, "%s Function tuple (children %d)\n", storageIndent, 1)
if len(exprs) > 0 {
fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", storageIndent, len(exprs))
for _, e := range exprs {
if lit, ok := n.OrderBy[0].(*ast.Literal); ok && lit.Type == ast.LiteralTuple {
// A DESC element wraps every element in StorageOrderByElement
exprs, _ := lit.Value.([]ast.Expression)
fmt.Fprintf(sb, "%s Function tuple (children %d)\n", storageIndent, 1)
if len(exprs) > 0 {
fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", storageIndent, len(exprs))
for _, e := range exprs {
if n.OrderByDesc {
fmt.Fprintf(sb, "%s StorageOrderByElement (children %d)\n", storageIndent, 1)
Node(sb, e, storageChildDepth+3)
} else {
Node(sb, e, storageChildDepth+2)
}
} else {
fmt.Fprintf(sb, "%s ExpressionList\n", storageIndent)
}
} else {
fmt.Fprintf(sb, "%s ExpressionList\n", storageIndent)
}
} else if n.OrderByDesc {
fmt.Fprintf(sb, "%s StorageOrderByElement (children %d)\n", storageIndent, 1)
Node(sb, n.OrderBy[0], storageChildDepth+1)
} else if ident, ok := n.OrderBy[0].(*ast.Identifier); ok {
fmt.Fprintf(sb, "%s Identifier %s\n", storageIndent, sanitizeUTF8(ident.Name()))
} else {
Node(sb, n.OrderBy[0], storageChildDepth)
}
Expand Down Expand Up @@ -1396,6 +1396,12 @@ func explainObjectTypeArgument(sb *strings.Builder, n *ast.ObjectTypeArgument, i
}
}
}
// Typed paths are printed as ObjectTypedPath since 26.x
if ntp, ok := n.Expr.(*ast.NameTypePair); ok {
fmt.Fprintf(sb, "%s ObjectTypedPath %s (children %d)\n", indent, ntp.Name, 1)
Node(sb, ntp.Type, depth+2)
return
}
Node(sb, n.Expr, depth+1)
}

Expand Down Expand Up @@ -1940,7 +1946,7 @@ func explainAlterCommand(sb *strings.Builder, cmd *ast.AlterCommand, indent stri
Node(sb, assign.Value, depth+3)
}
}
case ast.AlterAddProjection:
case ast.AlterAddProjection, ast.AlterModifyProjection:
if cmd.Projection != nil {
explainProjection(sb, cmd.Projection, indent+" ", depth+1)
}
Expand Down Expand Up @@ -1996,10 +2002,41 @@ func explainProjection(sb *strings.Builder, p *ast.Projection, indent string, de
if p.Select != nil {
children++
}
if p.IndexExpr != nil {
children++
}
if p.IndexType != nil {
children++
}
if len(p.Settings) > 0 {
children++
}
fmt.Fprintf(sb, "%sProjection (children %d)\n", indent, children)
if p.Select != nil {
explainProjectionSelectQuery(sb, p.Select, indent+" ", depth+1)
}
if p.IndexExpr != nil {
fmt.Fprintf(sb, "%s ExpressionList (children 1)\n", indent)
Node(sb, p.IndexExpr, depth+2)
}
if t := p.IndexType; t != nil {
switch {
case len(t.Arguments) > 0:
fmt.Fprintf(sb, "%s Function %s (children 1)\n", indent, t.Name)
fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", indent, len(t.Arguments))
for _, a := range t.Arguments {
Node(sb, a, depth+3)
}
case p.IndexTypeHasParentheses:
fmt.Fprintf(sb, "%s Function %s (children 1)\n", indent, t.Name)
fmt.Fprintf(sb, "%s ExpressionList\n", indent)
default:
fmt.Fprintf(sb, "%s Function %s\n", indent, t.Name)
}
}
if len(p.Settings) > 0 {
fmt.Fprintf(sb, "%s Set\n", indent)
}
}

func explainProjectionSelectQuery(sb *strings.Builder, q *ast.ProjectionSelectQuery, indent string, depth int) {
Expand All @@ -2010,6 +2047,9 @@ func explainProjectionSelectQuery(sb *strings.Builder, q *ast.ProjectionSelectQu
if len(q.Columns) > 0 {
children++
}
if q.Where != nil {
children++
}
if len(q.OrderBy) > 0 {
children++
}
Expand All @@ -2030,6 +2070,9 @@ func explainProjectionSelectQuery(sb *strings.Builder, q *ast.ProjectionSelectQu
Node(sb, col, depth+2)
}
}
if q.Where != nil {
Node(sb, q.Where, depth+1)
}
// GROUP BY comes before ORDER BY in projection output
if len(q.GroupBy) > 0 {
fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", indent, len(q.GroupBy))
Expand Down Expand Up @@ -2210,7 +2253,7 @@ func countAlterCommandChildren(cmd *ast.AlterCommand) int {
if cmd.Where != nil {
children++
}
case ast.AlterAddProjection:
case ast.AlterAddProjection, ast.AlterModifyProjection:
if cmd.Projection != nil {
children++
}
Expand Down Expand Up @@ -2266,11 +2309,17 @@ func explainOptimizeQuery(sb *strings.Builder, n *ast.OptimizeQuery, indent stri
if n.Final {
name += "_final"
}
if n.Dedupe {
name += "_deduplicate"
}
if n.Cleanup {
name += "_cleanup"
}
if n.Dedupe {
name += "_deduplicate"
if n.DryRun {
name += "_dry_run"
}
if n.Manifest {
name += "_manifest"
}

hasSettings := len(n.Settings) > 0
Expand All @@ -2281,6 +2330,9 @@ func explainOptimizeQuery(sb *strings.Builder, n *ast.OptimizeQuery, indent stri
if n.Partition != nil {
children++
}
if len(n.DryRunParts) > 0 {
children++
}
if hasSettings {
children++
}
Expand Down Expand Up @@ -2309,6 +2361,12 @@ func explainOptimizeQuery(sb *strings.Builder, n *ast.OptimizeQuery, indent stri
Node(sb, n.Partition, depth+2)
}
}
if len(n.DryRunParts) > 0 {
fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", indent, len(n.DryRunParts))
for _, part := range n.DryRunParts {
Node(sb, part, depth+2)
}
}
if n.Database != "" {
fmt.Fprintf(sb, "%s Identifier %s\n", indent, n.Database)
}
Expand Down Expand Up @@ -2772,3 +2830,48 @@ func moveInlinePrimaryKeyToStorage(n *ast.CreateQuery) *ast.CreateQuery {
}
return &c
}

// explainCreateWasmFunction prints CREATE FUNCTION ... LANGUAGE WASM. The
// children are the name, arguments, return type, module, source function,
// module hash and ABI.
func explainCreateWasmFunction(sb *strings.Builder, n *ast.CreateQuery, indent string, depth int) {
w := n.Wasm
children := 1
if w.HasArguments {
children++
}
if w.Returns != nil {
children++
}
for _, lit := range []*ast.Literal{w.Module, w.SourceFunction, w.Hash} {
if lit != nil {
children++
}
}
if w.Abi != "" {
children++
}
fmt.Fprintf(sb, "%sCreateWasmFunctionQuery %s (children %d)\n", indent, n.FunctionName, children)
fmt.Fprintf(sb, "%s Identifier %s\n", indent, n.FunctionName)
if w.HasArguments {
if len(w.Arguments) > 0 {
fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", indent, len(w.Arguments))
for _, arg := range w.Arguments {
Node(sb, arg, depth+2)
}
} else {
fmt.Fprintf(sb, "%s ExpressionList\n", indent)
}
}
if w.Returns != nil {
Node(sb, w.Returns, depth+1)
}
for _, lit := range []*ast.Literal{w.Module, w.SourceFunction, w.Hash} {
if lit != nil {
Node(sb, lit, depth+1)
}
}
if w.Abi != "" {
fmt.Fprintf(sb, "%s Identifier %s\n", indent, w.Abi)
}
}
6 changes: 3 additions & 3 deletions lexer/lexer.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import (
// Lexer tokenizes ClickHouse SQL input.
type Lexer struct {
reader *bufio.Reader
ch rune // current character
ch rune // current character
pos token.Position
eof bool
}
Expand Down Expand Up @@ -1200,13 +1200,13 @@ func (l *Lexer) readIdentifier() Item {

// Check for hex string literal: x'...' or X'...'
if (l.ch == 'x' || l.ch == 'X') && l.peekChar() == '\'' {
l.readChar() // skip x
l.readChar() // skip x
return l.readHexString() // read as hex-decoded string
}

// Check for binary string literal: b'...' or B'...'
if (l.ch == 'b' || l.ch == 'B') && l.peekChar() == '\'' {
l.readChar() // skip b
l.readChar() // skip b
return l.readBinaryString() // read as binary-decoded string
}

Expand Down
Loading
Loading