Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions ast/ast.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ type SelectQuery struct {
LimitByLimit Expression `json:"limit_by_limit,omitempty"` // LIMIT value before BY (e.g., LIMIT 1 BY x LIMIT 3)
LimitByOffset Expression `json:"limit_by_offset,omitempty"` // Offset for LIMIT BY (e.g., LIMIT 2, 3 BY x -> offset=2)
LimitByHasLimit bool `json:"limit_by_has_limit,omitempty"` // true if LIMIT BY was followed by another LIMIT
LimitByAll bool `json:"limit_by_all,omitempty"` // LIMIT n BY ALL
Offset Expression `json:"offset,omitempty"`
Settings []*SettingExpr `json:"settings,omitempty"`
SettingsAfterFormat bool `json:"settings_after_format,omitempty"` // true if SETTINGS came after FORMAT (at union level)
Expand Down
29 changes: 28 additions & 1 deletion internal/explain/explain.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,15 @@ package explain
import (
"fmt"
"strings"
"sync"

"github.com/sqlc-dev/doubleclick/ast"
)

// explainMu serializes EXPLAIN printing: the printer keeps its context in
// package-level variables.
var explainMu sync.Mutex

// inSubqueryContext is a package-level flag to track when we're inside a Subquery
// This affects how negated literals with aliases are formatted
var inSubqueryContext bool
Expand All @@ -18,6 +23,9 @@ var inCreateQueryContext bool

// Explain returns the EXPLAIN AST output for a statement, matching ClickHouse's format.
func Explain(stmt ast.Statement) string {
explainMu.Lock()
defer explainMu.Unlock()
constructionDisabled = 0
var sb strings.Builder
Node(&sb, stmt, 0)
return sb.String()
Expand All @@ -31,6 +39,9 @@ func ExplainStatements(stmts []ast.Statement) string {
return ""
}

explainMu.Lock()
defer explainMu.Unlock()
constructionDisabled = 0
var sb strings.Builder
Node(&sb, stmts[0], 0)

Expand Down Expand Up @@ -486,7 +497,13 @@ func Column(sb *strings.Builder, col *ast.ColumnDeclaration, depth int) {
Node(sb, col.Default, depth+1)
} else if hasEphemeralDefault {
// EPHEMERAL columns without explicit default value show defaultValueOfTypeName function
fmt.Fprintf(sb, "%s Function defaultValueOfTypeName\n", indent)
if col.Type != nil {
fmt.Fprintf(sb, "%s Function defaultValueOfTypeName (children 1)\n", indent)
fmt.Fprintf(sb, "%s ExpressionList (children 1)\n", indent)
fmt.Fprintf(sb, "%s Literal \\'%s\\'\n", indent, ephemeralTypeName(col.Type))
} else {
fmt.Fprintf(sb, "%s Function defaultValueOfTypeName\n", indent)
}
}
if col.Comment != "" {
fmt.Fprintf(sb, "%s Literal \\'%s\\'\n", indent, col.Comment)
Expand Down Expand Up @@ -583,3 +600,13 @@ func Index(sb *strings.Builder, idx *ast.IndexDefinition, depth int) {
}
}
}

// ephemeralTypeName formats a column type as the argument of
// defaultValueOfTypeName.
func ephemeralTypeName(t *ast.DataType) string {
typeStr := FormatDataType(t)
if len(t.Parameters) == 0 {
typeStr = escapeStringLiteral(typeStr)
}
return typeStr
}
60 changes: 43 additions & 17 deletions internal/explain/functions.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package explain

import (
"fmt"
"math"
"strings"

"github.com/sqlc-dev/doubleclick/ast"
Expand Down Expand Up @@ -266,22 +267,6 @@ func handleSpecialFunction(sb *strings.Builder, n *ast.FunctionCall, alias strin
return handleDateDiff(sb, n, alias, indent, depth)
}

// TRIM functions with empty string as trim characters - simplify to just the string
// Only for SQL standard syntax: trim(LEADING '' FROM 'foo') -> just 'foo'
// Direct function calls like trimLeft('foo', '') are NOT simplified
if n.SQLStandard && (fnName == "TRIM" || fnName == "LTRIM" || fnName == "RTRIM" ||
fnName == "TRIMLEFT" || fnName == "TRIMRIGHT" || fnName == "TRIMBOTH") {
if len(n.Arguments) == 2 {
if lit, ok := n.Arguments[1].(*ast.Literal); ok {
if lit.Type == ast.LiteralString && lit.Value == "" {
// Trim with empty string is a no-op, just output the original string
Node(sb, n.Arguments[0], depth)
return true
}
}
}
}

return false
}

Expand Down Expand Up @@ -590,6 +575,9 @@ func explainCastExprWithAlias(sb *strings.Builder, n *ast.CastExpr, alias string
if lit.Type == ast.LiteralArray || lit.Type == ast.LiteralTuple {
// Determine format based on both content and target type
useArrayFormat = shouldUseArrayFormat(lit, n.Type)
if elems, ok := lit.Value.([]ast.Expression); ok && lit.Type == ast.LiteralTuple && len(elems) == 1 {
useArrayFormat = false
}
}
}
}
Expand All @@ -612,7 +600,7 @@ func explainCastExprWithAlias(sb *strings.Builder, n *ast.CastExpr, alias string
if lit.Type == ast.LiteralArray || lit.Type == ast.LiteralTuple {
if useArrayFormat {
fmt.Fprintf(sb, "%s Literal %s\n", indent, FormatLiteral(lit))
} else if containsCastExpressions(lit) || !containsOnlyLiterals(lit) {
} else if containsCastExpressions(lit) || !containsOnlyLiterals(lit) || !castOperandIsPlainText(lit) {
// Array contains CastExpr or non-literal elements - output as Function array with children
Node(sb, n.Expr, depth+2)
} else {
Expand Down Expand Up @@ -2104,3 +2092,41 @@ func explainInListHeader(sb *strings.Builder, indent string, n int) {
}
fmt.Fprintf(sb, "%sExpressionList (children %d)\n", indent, n)
}

// castOperandIsPlainText mirrors ParserCastOperator: the operand of x::T is
// kept as source text only when it is made of numbers, strings and
// brackets. A one-element tuple "(x,)" (trailing comma), an empty tuple, or
// a word such as nan/inf/NULL/true makes it parse as an ordinary expression.
func castOperandIsPlainText(e ast.Expression) bool {
switch v := e.(type) {
case *ast.Literal:
switch v.Type {
case ast.LiteralInteger, ast.LiteralString:
return true
case ast.LiteralFloat:
f, _ := v.Value.(float64)
return !math.IsNaN(f) && !math.IsInf(f, 0)
case ast.LiteralArray, ast.LiteralTuple:
elems, ok := v.Value.([]ast.Expression)
if !ok {
return false
}
if v.Type == ast.LiteralTuple && len(elems) == 1 {
return false
}
for _, el := range elems {
if !castOperandIsPlainText(el) {
return false
}
}
return true
}
case *ast.UnaryExpr:
if v.Op == "-" {
if lit, ok := v.Operand.(*ast.Literal); ok && (lit.Type == ast.LiteralInteger || lit.Type == ast.LiteralFloat) {
return castOperandIsPlainText(lit)
}
}
}
return false
}
Loading
Loading