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
22 changes: 18 additions & 4 deletions ast/ast.go
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,14 @@ type TableExpression struct {
Sample *SampleClause `json:"sample,omitempty"`
// ColumnAliases holds the column alias list of "t(a, b, ...)".
ColumnAliases []string `json:"column_aliases,omitempty"`
// Stream is set for FROM t STREAM [BOUNDED] [UNORDERED] [CURSOR {...}] [WATERMARK ...].
Stream *StreamSettings `json:"stream,omitempty"`
}

// StreamSettings holds a table's STREAM clause. Only the watermark
// expression appears in EXPLAIN AST.
type StreamSettings struct {
Watermark Expression `json:"watermark,omitempty"`
}

func (t *TableExpression) Pos() token.Position { return t.Position }
Expand Down Expand Up @@ -333,8 +341,8 @@ type CreateQuery struct {
AlterUser bool `json:"alter_user,omitempty"`
HasAuthenticationData bool `json:"has_authentication_data,omitempty"`
AuthenticationValues []string `json:"authentication_values,omitempty"` // Password/hash values from IDENTIFIED BY
AuthValidUntil map[int]string `json:"auth_valid_until,omitempty"` // VALID UNTIL per AuthenticationValues index
UserValidUntil string `json:"user_valid_until,omitempty"` // VALID UNTIL not attached to an auth method
AuthValidUntil map[int]Expression `json:"auth_valid_until,omitempty"` // VALID UNTIL per AuthenticationValues index
UserValidUntil Expression `json:"user_valid_until,omitempty"` // VALID UNTIL not attached to an auth method
SSHKeyCount int `json:"ssh_key_count,omitempty"` // Number of SSH keys for ssh_key auth
CreateDictionary bool `json:"create_dictionary,omitempty"`
DictionaryAttrs []*DictionaryAttributeDeclaration `json:"dictionary_attrs,omitempty"`
Expand Down Expand Up @@ -364,6 +372,7 @@ type ColumnDeclaration struct {
PrimaryKey bool `json:"primary_key,omitempty"` // PRIMARY KEY constraint
Comment string `json:"comment,omitempty"`
Settings []*SettingExpr `json:"settings,omitempty"` // Column-level SETTINGS
Collation string `json:"collation,omitempty"` // COLLATE name
}

func (c *ColumnDeclaration) Pos() token.Position { return c.Position }
Expand Down Expand Up @@ -611,6 +620,7 @@ type UpdateQuery struct {
Table string `json:"table"`
Assignments []*Assignment `json:"assignments"`
Where Expression `json:"where,omitempty"`
Settings []*SettingExpr `json:"settings,omitempty"`
}

func (u *UpdateQuery) Pos() token.Position { return u.Position }
Expand Down Expand Up @@ -993,6 +1003,7 @@ type OptimizeQuery struct {
Manifest bool `json:"manifest,omitempty"`
OnCluster string `json:"on_cluster,omitempty"`
Settings []*SettingExpr `json:"settings,omitempty"`
Format string `json:"format,omitempty"`
}

func (o *OptimizeQuery) Pos() token.Position { return o.Position }
Expand Down Expand Up @@ -1268,6 +1279,7 @@ type ShowCreateRowPolicyQuery struct {
Position token.Position `json:"-"`
Format string `json:"format,omitempty"`
Masking bool `json:"masking,omitempty"` // MASKING POLICY
Plural bool `json:"plural,omitempty"` // names a set of policies
}

func (s *ShowCreateRowPolicyQuery) Pos() token.Position { return s.Position }
Expand Down Expand Up @@ -1908,8 +1920,10 @@ func (e *ExecuteAsQuery) statementNode() {}
// ShowAccessEntitiesQuery represents SHOW USERS, SHOW ROLES, SHOW [ROW] POLICIES, etc.
type ShowAccessEntitiesQuery struct {
Position token.Position `json:"-"`
Keyword string `json:"keyword"` // e.g. "USERS", "ROW POLICIES"
Format string `json:"format,omitempty"`
Keyword string `json:"keyword"` // e.g. "USERS", "ROW POLICIES"
Format string `json:"format,omitempty"`
OutFile string `json:"out_file,omitempty"`
HasSettings bool `json:"has_settings,omitempty"`
}

func (s *ShowAccessEntitiesQuery) Pos() token.Position { return s.Position }
Expand Down
7 changes: 7 additions & 0 deletions internal/explain/dictionary.go
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,13 @@ func explainDictionaryLayout(sb *strings.Builder, n *ast.DictionaryLayout, inden
fmt.Fprintf(sb, "%sDictionary layout (children %d)\n", indent, children)
fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", indent, len(n.Args))
for _, arg := range n.Args {
// Layout parameters are parsed as literals, so an array of tuples
// stays one literal
if lit, ok := arg.Value.(*ast.Literal); ok && (lit.Type == ast.LiteralArray || lit.Type == ast.LiteralTuple) && containsOnlyLiterals(lit) {
fmt.Fprintf(sb, "%s pair (children 1)\n", indent)
fmt.Fprintf(sb, "%s Literal %s\n", indent, FormatLiteral(lit))
continue
}
explainKeyValuePair(sb, arg, indent+" ", depth+2)
}
} else {
Expand Down
48 changes: 43 additions & 5 deletions internal/explain/explain.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,21 @@ var inSubqueryContext bool
// This affects whether FORMAT is output at SelectWithUnionQuery level (it shouldn't be, as CreateQuery outputs it)
var inCreateQueryContext bool

// substituteNullParams is set when unset Nullable query parameters are
// replaced with NULL, as ClickHouse does outside parameterized views.
var substituteNullParams bool

func setParamSubstitution(stmt ast.Statement) {
cq, ok := stmt.(*ast.CreateQuery)
substituteNullParams = !ok || cq.View == ""
}

// 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
setParamSubstitution(stmt)
var sb strings.Builder
Node(&sb, stmt, 0)
return sb.String()
Expand All @@ -42,6 +52,7 @@ func ExplainStatements(stmts []ast.Statement) string {
explainMu.Lock()
defer explainMu.Unlock()
constructionDisabled = 0
setParamSubstitution(stmts[0])
var sb strings.Builder
Node(&sb, stmts[0], 0)

Expand Down Expand Up @@ -287,12 +298,30 @@ func Node(sb *strings.Builder, node interface{}, depth int) {
fmt.Fprintf(sb, "%sDROP ROW POLICY query\n", indent)
}
case *ast.ShowAccessEntitiesQuery:
children := 0
if n.OutFile != "" {
children++
}
if n.Format != "" {
fmt.Fprintf(sb, "%sSHOW %s query (children 1)\n", indent, n.Keyword)
fmt.Fprintf(sb, "%s Identifier %s\n", indent, n.Format)
children++
}
if n.HasSettings {
children++
}
if children > 0 {
fmt.Fprintf(sb, "%sSHOW %s query (children %d)\n", indent, n.Keyword, children)
} else {
fmt.Fprintf(sb, "%sSHOW %s query\n", indent, n.Keyword)
}
if n.OutFile != "" {
fmt.Fprintf(sb, "%s Literal \\'%s\\'\n", indent, escapeStringLiteral(n.OutFile))
}
if n.Format != "" {
fmt.Fprintf(sb, "%s Identifier %s\n", indent, n.Format)
}
if n.HasSettings {
fmt.Fprintf(sb, "%s Set\n", indent)
}
case *ast.ShowCreateRowPolicyQuery:
if n.Masking {
if n.Format != "" {
Expand All @@ -303,12 +332,15 @@ func Node(sb *strings.Builder, node interface{}, depth int) {
}
break
}
// ClickHouse uses "ROW POLICIES" (plural) when FORMAT is present
kw := "ROW POLICY"
if n.Plural {
kw = "ROW POLICIES"
}
if n.Format != "" {
fmt.Fprintf(sb, "%sSHOW CREATE ROW POLICIES query (children 1)\n", indent)
fmt.Fprintf(sb, "%sSHOW CREATE %s query (children 1)\n", indent, kw)
fmt.Fprintf(sb, "%s Identifier %s\n", indent, n.Format)
} else {
fmt.Fprintf(sb, "%sSHOW CREATE ROW POLICY query\n", indent)
fmt.Fprintf(sb, "%sSHOW CREATE %s query\n", indent, kw)
}
case *ast.CreateRoleQuery:
fmt.Fprintf(sb, "%sCreateRoleQuery\n", indent)
Expand Down Expand Up @@ -492,6 +524,9 @@ func Column(sb *strings.Builder, col *ast.ColumnDeclaration, depth int) {
if col.Comment != "" {
children++
}
if col.Collation != "" {
children++
}
if children > 0 {
fmt.Fprintf(sb, "%sColumnDeclaration %s (children %d)\n", indent, sanitizeUTF8(col.Name), children)
} else {
Expand Down Expand Up @@ -529,6 +564,9 @@ func Column(sb *strings.Builder, col *ast.ColumnDeclaration, depth int) {
if col.TTL != nil {
Node(sb, col.TTL, depth+1)
}
if col.Collation != "" {
fmt.Fprintf(sb, "%s Collation\n", indent)
}
}

// explainCodecExpr handles CODEC expressions in column declarations
Expand Down
19 changes: 5 additions & 14 deletions internal/explain/expressions.go
Original file line number Diff line number Diff line change
Expand Up @@ -111,10 +111,7 @@ func explainLiteral(sb *strings.Builder, n *ast.Literal, indent string, depth in
for _, e := range exprs {
// Check for parenthesized literals
if lit, isLit := e.(*ast.Literal); isLit {
if lit.Parenthesized {
hasParenthesizedElement = true
break
}
// ClickHouse 26 folds parenthesized literals into the tuple literal
// Nested tuples that contain only primitive literals are OK
if lit.Type == ast.LiteralTuple {
if !containsOnlyPrimitiveLiteralsWithUnary(lit) {
Expand Down Expand Up @@ -175,9 +172,7 @@ func explainLiteral(sb *strings.Builder, n *ast.Literal, indent string, depth in
for _, e := range exprs {
if lit, ok := e.(*ast.Literal); ok {
// Parenthesized elements require Function array format
if lit.Parenthesized {
shouldUseFunctionArray = true
}

if lit.Type == ast.LiteralArray {
hasNestedArrays = true
// Check if inner array needs Function array format:
Expand Down Expand Up @@ -300,11 +295,9 @@ func containsOnlyArraysOrTuples(exprs []ast.Expression) bool {
// or parenthesized literals (which need Function array format)
func containsNonLiteralExpressions(exprs []ast.Expression) bool {
for _, e := range exprs {
if lit, ok := e.(*ast.Literal); ok {
if _, ok := e.(*ast.Literal); ok {
// Parenthesized literals need Function array format
if lit.Parenthesized {
return true
}

continue
}
// Unary minus of a literal (negative number) is also acceptable
Expand Down Expand Up @@ -377,9 +370,7 @@ func containsNonLiteralExpressionsRecursive(exprs []ast.Expression) bool {
for _, e := range exprs {
if lit, ok := e.(*ast.Literal); ok {
// Parenthesized literals need Function array format
if lit.Parenthesized {
return true
}

if lit.Type == ast.LiteralArray {
if innerExprs, ok := lit.Value.([]ast.Expression); ok {
// Recursively check nested arrays
Expand Down
11 changes: 11 additions & 0 deletions internal/explain/format.go
Original file line number Diff line number Diff line change
Expand Up @@ -433,7 +433,18 @@ func formatExprForType(expr ast.Expression) string {
return "[" + strings.Join(parts, ", ") + "]"
}
}
if e.Type == ast.LiteralString {
return fmt.Sprintf("\\\\\\'%s\\\\\\'", escapeStringForTypeParam(fmt.Sprintf("%v", e.Value)))
}
return fmt.Sprintf("%v", e.Value)
case *ast.CastExpr:
typ := ""
if e.TypeExpr != nil {
typ = formatExprForType(e.TypeExpr)
} else {
typ = fmt.Sprintf("\\\\\\'%s\\\\\\'", FormatDataType(e.Type))
}
return "CAST(" + formatExprForType(e.Expr) + ", " + typ + ")"
case *ast.Identifier:
return e.Name()
case *ast.FunctionCall:
Expand Down
13 changes: 9 additions & 4 deletions internal/explain/functions.go
Original file line number Diff line number Diff line change
Expand Up @@ -618,6 +618,9 @@ func explainCastExprWithAlias(sb *strings.Builder, n *ast.CastExpr, alias string
} else {
fmt.Fprintf(sb, "%s Literal Bool_0\n", indent)
}
} else if !castOperandIsPlainText(lit) {
// nan/inf are words, so the operand is parsed as an expression
Node(sb, lit, depth+2)
} else {
// Simple literal - format as string (escape special chars for string literals)
exprStr := formatExprAsString(lit)
Expand All @@ -626,6 +629,8 @@ func explainCastExprWithAlias(sb *strings.Builder, n *ast.CastExpr, alias string
}
fmt.Fprintf(sb, "%s Literal \\'%s\\'\n", indent, exprStr)
}
} else if u, ok := n.Expr.(*ast.UnaryExpr); ok && u.Op == "-" && !castOperandIsPlainText(u.Operand) {
Node(sb, n.Expr, depth+2)
} else if negatedLit := extractNegatedLiteral(n.Expr); negatedLit != "" {
// Handle negated literal like -0::Int16 -> CAST('-0', 'Int16')
fmt.Fprintf(sb, "%s Literal \\'%s\\'\n", indent, negatedLit)
Expand Down Expand Up @@ -1078,7 +1083,7 @@ func explainInExpr(sb *strings.Builder, n *ast.InExpr, indent string, depth int)
} else {
// Check if we have a single tuple literal that should be wrapped in Function tuple
if len(n.List) == 1 {
if lit, ok := n.List[0].(*ast.Literal); ok && lit.Type == ast.LiteralTuple {
if lit, ok := n.List[0].(*ast.Literal); ok && lit.Type == ast.LiteralTuple && false {
// Single tuple literal gets wrapped in Function tuple, so count as 1
argCount++
} else if n.TrailingComma {
Expand Down Expand Up @@ -1110,7 +1115,7 @@ func explainInExpr(sb *strings.Builder, n *ast.InExpr, indent string, depth int)
// Single element in the list
// If it's a tuple literal, wrap it in Function tuple
// Otherwise, output the element directly
if lit, ok := n.List[0].(*ast.Literal); ok && lit.Type == ast.LiteralTuple {
if lit, ok := n.List[0].(*ast.Literal); ok && lit.Type == ast.LiteralTuple && false {
// Wrap tuple literal in Function tuple
// Check if all elements are parenthesized primitives - if so, expand them
// Otherwise, keep the tuple as a Literal
Expand Down Expand Up @@ -1289,7 +1294,7 @@ func explainInExprWithAlias(sb *strings.Builder, n *ast.InExpr, alias string, in
argCount++
} else {
if len(n.List) == 1 {
if lit, ok := n.List[0].(*ast.Literal); ok && lit.Type == ast.LiteralTuple {
if lit, ok := n.List[0].(*ast.Literal); ok && lit.Type == ast.LiteralTuple && false {
argCount++
} else if n.TrailingComma {
// Single element with trailing comma (e.g., (2,)) gets wrapped in Function tuple
Expand Down Expand Up @@ -1328,7 +1333,7 @@ func explainInExprWithAlias(sb *strings.Builder, n *ast.InExpr, alias string, in
}
fmt.Fprintf(sb, "%s Literal %s\n", indent, FormatLiteral(tupleLit))
} else if len(n.List) == 1 {
if lit, ok := n.List[0].(*ast.Literal); ok && lit.Type == ast.LiteralTuple {
if lit, ok := n.List[0].(*ast.Literal); ok && lit.Type == ast.LiteralTuple && false {
// Use explainTupleInInList to properly handle primitive-only tuples as Literal Tuple_
explainTupleInInList(sb, lit, indent+" ", depth+2)
} else if n.TrailingComma {
Expand Down
44 changes: 42 additions & 2 deletions internal/explain/secrets.go
Original file line number Diff line number Diff line change
Expand Up @@ -106,8 +106,19 @@ func argIsLiteral(e ast.Expression) bool {
if isSettingsArg(e) {
return false
}
_, ok := e.(*ast.Literal)
return ok
lit, ok := e.(*ast.Literal)
if !ok {
return false
}
// An array or tuple with non-literal elements is a function call in ClickHouse
if elems, isList := lit.Value.([]ast.Expression); isList && (lit.Type == ast.LiteralArray || lit.Type == ast.LiteralTuple) {
for _, el := range elems {
if _, isLit := el.(*ast.Literal); isLit && !argIsLiteral(el) || !isLiteralLike(el) {
return false
}
}
}
return true
}

func argIsIdentifier(e ast.Expression) bool {
Expand Down Expand Up @@ -875,6 +886,9 @@ func (f *secretFinder) findOrdinaryFunction() {
case name == "sipHash64Keyed" || name == "sipHash128Keyed" || name == "sipHash128ReferenceKeyed":
f.markSecret(0, false)
return
case name == "bigquery":
f.findBigQuery()
return
}

var find func()
Expand Down Expand Up @@ -914,6 +928,10 @@ func (f *secretFinder) findOrdinaryFunction() {
}

func (f *secretFinder) findTableEngine() {
if f.name == "BigQuery" {
f.findBigQuery()
return
}
var find func()
switch f.name {
case "ExternalDistributed":
Expand Down Expand Up @@ -1105,6 +1123,28 @@ func hideLiteralsInSubtree(e ast.Expression) ast.Expression {
c := *n
c.Operand = hideLiteralsInSubtree(n.Operand)
return &c
case *ast.InExpr:
c := *n
c.Expr = hideLiteralsInSubtree(n.Expr)
if n.List != nil {
allLiterals := true
for _, el := range n.List {
if !isLiteralLike(el) {
allLiterals = false
}
}
if allLiterals {
// The list is one tuple literal in ClickHouse
c.List = []ast.Expression{stringLiteral(hiddenValue)}
c.TrailingComma = false
} else {
c.List = make([]ast.Expression, len(n.List))
for i, el := range n.List {
c.List[i] = hideLiteralsInSubtree(el)
}
}
}
return &c
}
return e
}
Expand Down
Loading
Loading