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
4 changes: 2 additions & 2 deletions internal/explain/explain.go
Original file line number Diff line number Diff line change
Expand Up @@ -485,9 +485,9 @@ func Column(sb *strings.Builder, col *ast.ColumnDeclaration, depth int) {
children++
}
if children > 0 {
fmt.Fprintf(sb, "%sColumnDeclaration %s (children %d)\n", indent, strings.ReplaceAll(sanitizeUTF8(col.Name), "'", "\\'"), children)
fmt.Fprintf(sb, "%sColumnDeclaration %s (children %d)\n", indent, sanitizeUTF8(escapeDumpName(col.Name)), children)
} else {
fmt.Fprintf(sb, "%sColumnDeclaration %s\n", indent, sanitizeUTF8(col.Name))
fmt.Fprintf(sb, "%sColumnDeclaration %s\n", indent, sanitizeUTF8(escapeDumpName(col.Name)))
}
// Children follow ClickHouse's order: type, default, comment, codec,
// settings, statistics, TTL.
Expand Down
40 changes: 37 additions & 3 deletions internal/explain/expressions.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,9 +66,37 @@ func explainIdentifier(sb *strings.Builder, n *ast.Identifier, indent string) {
// escapeIdentifierPart escapes backslashes and single quotes in an identifier part
// and sanitizes invalid UTF-8 bytes
func escapeIdentifierPart(s string) string {
s = strings.ReplaceAll(s, "\\", "\\\\")
s = strings.ReplaceAll(s, "'", "\\'")
return sanitizeUTF8(s)
return sanitizeUTF8(escapeDumpName(s))
}

// escapeDumpName escapes a name the way ClickHouse's writeEscapedString does
// when it dumps an AST: backslash, single quote and the common control
// characters get a backslash escape.
func escapeDumpName(s string) string {
var sb strings.Builder
for i := 0; i < len(s); i++ {
switch c := s[i]; c {
case '\\':
sb.WriteString("\\\\")
case '\'':
sb.WriteString("\\'")
case '\b':
sb.WriteString("\\b")
case '\f':
sb.WriteString("\\f")
case '\n':
sb.WriteString("\\n")
case '\r':
sb.WriteString("\\r")
case '\t':
sb.WriteString("\\t")
case 0:
sb.WriteString("\\0")
default:
sb.WriteByte(c)
}
}
return sb.String()
}

// formatIdentifierName formats an identifier name, handling JSON path notation,
Expand Down Expand Up @@ -909,6 +937,12 @@ func explainWithElement(sb *strings.Builder, n *ast.WithElement, indent string,
}
case *ast.FunctionCall:
explainFunctionCallWithAlias(sb, e, n.Name, indent, depth)
case *ast.Parameter:
if n.Name != "" {
explainAliasedExpr(sb, &ast.AliasedExpr{Expr: e, Alias: n.Name}, depth)
} else {
Node(sb, e, depth)
}
case *ast.Lambda:
explainLambdaWithAlias(sb, e, n.Name, indent, depth)
case *ast.BinaryExpr:
Expand Down
28 changes: 26 additions & 2 deletions internal/explain/select.go
Original file line number Diff line number Diff line change
Expand Up @@ -232,10 +232,14 @@ func explainSelectQueryWithInheritedWith(sb *strings.Builder, stmt ast.Statement
}

// Inherited WITH clause (ExpressionList) - output at the END
// ClickHouse clones these elements into every later SELECT, and a cloned
// join element lists its TableJoin before its TableExpression.
fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", indent, len(inheritedWith))
clonedAST++
for _, w := range inheritedWith {
Node(sb, w, depth+2)
}
clonedAST--
}

// ExplainSelectWithInheritedWith recursively explains a select statement with inherited WITH clause
Expand Down Expand Up @@ -846,8 +850,16 @@ func groupSelectsByUnionMode(selects []ast.Statement, unionModes []string) []ast

// Create a nested SelectWithUnionQuery for selects 0..modeChangeIdx (inclusive)
// modeChangeIdx is the index of the union operator, so we include selects[0] through selects[modeChangeIdx]
nestedSelects := selects[:modeChangeIdx+1]
nestedModes := unionModes[:modeChangeIdx]
// ClickHouse flattens every union inside the DISTINCT group into one
// list (NormalizeSelectWithUnionQueryMatcher::getSelectsFromUnionListNode).
var nestedSelects []ast.Statement
for _, sel := range selects[:modeChangeIdx+1] {
nestedSelects = appendFlattenedSelects(nestedSelects, sel)
}
nestedModes := make([]string, len(nestedSelects)-1)
for i := range nestedModes {
nestedModes[i] = "DISTINCT"
}

nested := &ast.SelectWithUnionQuery{
Selects: nestedSelects,
Expand Down Expand Up @@ -981,3 +993,15 @@ func unionFormat(n *ast.SelectWithUnionQuery) ast.Expression {
}
return nil
}

// appendFlattenedSelects appends sel to selects, replacing any union with its
// selects, recursively.
func appendFlattenedSelects(selects []ast.Statement, sel ast.Statement) []ast.Statement {
if u, ok := sel.(*ast.SelectWithUnionQuery); ok {
for _, inner := range u.Selects {
selects = appendFlattenedSelects(selects, inner)
}
return selects
}
return append(selects, sel)
}
4 changes: 2 additions & 2 deletions internal/explain/statements.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ func explainInsertQuery(sb *strings.Builder, n *ast.InsertQuery, indent string,
} else if len(n.Columns) > 0 {
fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", indent, len(n.Columns))
for _, col := range n.Columns {
fmt.Fprintf(sb, "%s Identifier %s\n", indent, col.Parts[len(col.Parts)-1])
fmt.Fprintf(sb, "%s Identifier %s\n", indent, escapeIdentifierPart(col.Parts[len(col.Parts)-1]))
}
}

Expand Down Expand Up @@ -538,7 +538,7 @@ func explainCreateQuery(sb *strings.Builder, n *ast.CreateQuery, indent string,
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()))
fmt.Fprintf(sb, "%s Identifier %s\n", storageIndent, formatIdentifierName(ident))
} else {
Node(sb, n.OrderBy[0], storageChildDepth)
}
Expand Down
22 changes: 21 additions & 1 deletion internal/explain/tables.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,14 @@ func explainTablesInSelectQueryElement(sb *strings.Builder, n *ast.TablesInSelec
children = 1 // Fallback
}
fmt.Fprintf(sb, "%sTablesInSelectQueryElement (children %d)\n", indent, children)
if clonedAST > 0 && n.Join != nil {
// ASTTablesInSelectQueryElement::clone adds table_join first
Node(sb, n.Join, depth+1)
if n.Table != nil {
Node(sb, n.Table, depth+1)
}
return
}
if n.Table != nil {
Node(sb, n.Table, depth+1)
}
Expand All @@ -42,6 +50,10 @@ func explainTablesInSelectQueryElement(sb *strings.Builder, n *ast.TablesInSelec
}
}

// clonedAST is non-zero while printing nodes that ClickHouse has cloned.
// Printing is serialized by the explain mutex.
var clonedAST int

func explainTableExpression(sb *strings.Builder, n *ast.TableExpression, indent string, depth int) {
children := 1 // table
if n.Sample != nil {
Expand Down Expand Up @@ -291,7 +303,12 @@ func explainViewExplain(sb *strings.Builder, n *ast.ExplainQuery, alias string,
fmt.Fprintf(sb, "%s TableExpression (children %d)\n", indent, 1)
// Now output the viewExplain function
fmt.Fprintf(sb, "%s Function viewExplain (children %d)\n", indent, 1)
fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", indent, 3)
args := 3
if n.Statement == nil {
// EXPLAIN CURRENT TRANSACTION explains no query
args = 2
}
fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", indent, args)
// First argument: 'EXPLAIN' or 'EXPLAIN AST' or 'EXPLAIN SYNTAX' etc.
// PLAN is the default and never shown; other types like AST, SYNTAX should be shown
explainTypeStr := "EXPLAIN"
Expand All @@ -302,6 +319,9 @@ func explainViewExplain(sb *strings.Builder, n *ast.ExplainQuery, alias string,
// Second argument: options string (e.g., "actions = 1")
options := n.OptionsString
fmt.Fprintf(sb, "%s Literal \\'%s\\'\n", indent, options)
if n.Statement == nil {
return
}
// Third argument: the subquery being explained
fmt.Fprintf(sb, "%s Subquery (children %d)\n", indent, 1)
Node(sb, n.Statement, depth+10)
Expand Down
106 changes: 56 additions & 50 deletions lexer/lexer.go
Original file line number Diff line number Diff line change
Expand Up @@ -656,7 +656,7 @@ func (l *Lexer) readQuotedIdentifier() Item {
if l.ch == '\\' {
l.readChar()
if !l.eof {
sb.WriteRune(l.ch)
l.readIdentifierEscape(&sb)
l.readChar()
}
continue
Expand Down Expand Up @@ -733,55 +733,7 @@ func (l *Lexer) readBacktickIdentifier() Item {
if l.eof {
break
}
// Interpret escape sequence (same as readString)
switch l.ch {
case '\'':
sb.WriteRune('\'')
case '"':
sb.WriteRune('"')
case '\\':
sb.WriteRune('\\')
case '`':
sb.WriteRune('`')
case 'n':
sb.WriteRune('\n')
case 't':
sb.WriteRune('\t')
case 'r':
sb.WriteRune('\r')
case '0':
sb.WriteRune('\x00')
case 'a':
sb.WriteRune('\a')
case 'b':
sb.WriteRune('\b')
case 'f':
sb.WriteRune('\f')
case 'v':
sb.WriteRune('\v')
case 'e':
sb.WriteRune('\x1b') // escape character (ASCII 27)
case 'x':
// Hex escape: \xNN
l.readChar()
if l.eof {
break
}
hex1 := l.ch
l.readChar()
if l.eof {
sb.WriteRune(rune(hexValue(hex1)))
continue
}
hex2 := l.ch
// Convert hex digits to byte
val := hexValue(hex1)*16 + hexValue(hex2)
sb.WriteByte(byte(val))
default:
// Unknown escape, preserve both the backslash and the character
sb.WriteRune('\\')
sb.WriteRune(l.ch)
}
l.readIdentifierEscape(&sb)
l.readChar()
continue
}
Expand Down Expand Up @@ -1281,3 +1233,57 @@ func Tokenize(r io.Reader) []Item {
}
return items
}

// readIdentifierEscape interprets the escape sequence after a backslash in a
// quoted identifier. l.ch is the character after the backslash. Unknown
// escapes keep the backslash, as ClickHouse does.
func (l *Lexer) readIdentifierEscape(sb *strings.Builder) {
switch l.ch {
case '\'':
sb.WriteRune('\'')
case '"':
sb.WriteRune('"')
case '\\':
sb.WriteRune('\\')
case '`':
sb.WriteRune('`')
case 'n':
sb.WriteRune('\n')
case 't':
sb.WriteRune('\t')
case 'r':
sb.WriteRune('\r')
case '0':
sb.WriteRune('\x00')
case 'a':
sb.WriteRune('\a')
case 'b':
sb.WriteRune('\b')
case 'f':
sb.WriteRune('\f')
case 'v':
sb.WriteRune('\v')
case 'e':
sb.WriteRune('\x1b') // escape character (ASCII 27)
case 'x':
// Hex escape: \xNN
l.readChar()
if l.eof {
break
}
hex1 := l.ch
l.readChar()
if l.eof {
sb.WriteRune(rune(hexValue(hex1)))
return
}
hex2 := l.ch
// Convert hex digits to byte
val := hexValue(hex1)*16 + hexValue(hex2)
sb.WriteByte(byte(val))
default:
// Unknown escape, preserve both the backslash and the character
sb.WriteRune('\\')
sb.WriteRune(l.ch)
}
}
4 changes: 2 additions & 2 deletions parser/expression.go
Original file line number Diff line number Diff line change
Expand Up @@ -398,7 +398,7 @@ func (p *Parser) parseImplicitAlias(expr ast.Expression) ast.Expression {
if !canBeAlias {
// Some keywords can be used as implicit aliases in ClickHouse
switch p.current.Token {
case token.KEY, token.INDEX, token.VIEW, token.DATABASE, token.TABLE, token.SYNC, token.CLUSTER, token.ALIAS:
case token.KEY, token.INDEX, token.VIEW, token.DATABASE, token.TABLE, token.SYNC, token.CLUSTER, token.ALIAS, token.COLUMN:
canBeAlias = true
case token.COMMENT:
// "SELECT 1 comment" uses comment as an alias, but COMMENT 'text'
Expand Down Expand Up @@ -530,7 +530,7 @@ func (p *Parser) parsePrefixExpression() ast.Expression {
case token.INTERVAL:
// INTERVAL can be a literal (INTERVAL 1 DAY) or identifier reference
// Check if next token can start an interval value
if p.peekIs(token.NUMBER) || p.peekIs(token.LPAREN) || p.peekIs(token.MINUS) || p.peekIs(token.STRING) || p.peekIs(token.IDENT) {
if p.peekIs(token.NUMBER) || p.peekIs(token.LPAREN) || p.peekIs(token.MINUS) || p.peekIs(token.STRING) || p.peekIs(token.IDENT) || p.peekIs(token.CASE) {
return p.parseInterval()
}
// Otherwise treat as identifier
Expand Down
6 changes: 3 additions & 3 deletions parser/parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -7633,8 +7633,8 @@ parseFrom:

// Parse FROM clause (or table/database name for SHOW CREATE TABLE/DATABASE/DICTIONARY/VIEW)
showCreateTypes := show.ShowType == ast.ShowCreate || show.ShowType == ast.ShowCreateDB || show.ShowType == ast.ShowCreateDictionary || show.ShowType == ast.ShowCreateView
if p.currentIs(token.FROM) || (showCreateTypes && (p.currentIs(token.IDENT) || p.current.Token.IsKeyword())) {
if p.currentIs(token.FROM) {
if p.currentIs(token.FROM) || p.currentIs(token.IN) || (showCreateTypes && (p.currentIs(token.IDENT) || p.current.Token.IsKeyword())) {
if p.currentIs(token.FROM) || p.currentIs(token.IN) {
p.nextToken()
}
// Parse table name which can be database.table or just table
Expand Down Expand Up @@ -7765,7 +7765,7 @@ func (p *Parser) parseExplain() *ast.ExplainQuery {
case "CURRENT":
// EXPLAIN CURRENT TRANSACTION
p.nextToken()
if p.currentIs(token.IDENT) && strings.ToUpper(p.current.Value) == "TRANSACTION" {
if p.currentIs(token.TRANSACTION) || (p.currentIs(token.IDENT) && strings.ToUpper(p.current.Value) == "TRANSACTION") {
p.nextToken()
}
explain.ExplainType = ast.ExplainCurrentTransaction
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1 @@
{
"explain_todo": {
"stmt6": true
}
}
{}
8 changes: 1 addition & 7 deletions parser/testdata/01564_test_hint_woes/metadata.json
Original file line number Diff line number Diff line change
@@ -1,7 +1 @@
{
"explain_todo": {
"stmt11": true,
"stmt16": true,
"stmt6": true
}
}
{}
8 changes: 1 addition & 7 deletions parser/testdata/01666_blns_long/metadata.json
Original file line number Diff line number Diff line change
@@ -1,7 +1 @@
{
"explain_todo": {
"stmt13": true,
"stmt15": true,
"stmt3": true
}
}
{}
Original file line number Diff line number Diff line change
@@ -1,10 +1 @@
{
"explain_todo": {
"stmt1": true,
"stmt13": true,
"stmt14": true,
"stmt15": true,
"stmt3": true,
"stmt7": true
}
}
{}
Original file line number Diff line number Diff line change
@@ -1,6 +1 @@
{
"explain_todo": {
"stmt4": true,
"stmt6": true
}
}
{}
6 changes: 1 addition & 5 deletions parser/testdata/02163_operators/metadata.json
Original file line number Diff line number Diff line change
@@ -1,5 +1 @@
{
"explain_todo": {
"stmt1": true
}
}
{}
Loading
Loading