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
21 changes: 21 additions & 0 deletions ast/ast.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ type SelectWithUnionQuery struct {
func (s *SelectWithUnionQuery) Pos() token.Position { return s.Position }
func (s *SelectWithUnionQuery) End() token.Position { return s.Position }
func (s *SelectWithUnionQuery) statementNode() {}
func (s *SelectWithUnionQuery) expressionNode() {}

// SelectIntersectExceptQuery represents SELECT ... INTERSECT/EXCEPT ... queries.
type SelectIntersectExceptQuery struct {
Expand Down Expand Up @@ -294,10 +295,14 @@ type CreateQuery struct {
HasRefresh bool `json:"has_refresh,omitempty"` // Has REFRESH clause
TimeSeriesTargets []*TimeSeriesTarget `json:"time_series_targets,omitempty"` // TimeSeries DATA/TAGS/METRICS/SAMPLES targets
SQLSecurity bool `json:"sql_security,omitempty"` // Has DEFINER = ... / SQL SECURITY ...
TableSQLSecurity bool `json:"table_sql_security,omitempty"` // SQL SECURITY on a table (no AS SELECT)
Attach bool `json:"attach,omitempty"` // ATTACH instead of CREATE
RefreshType string `json:"refresh_type,omitempty"` // AFTER or EVERY
RefreshInterval Expression `json:"refresh_interval,omitempty"` // Interval value
RefreshUnit string `json:"refresh_unit,omitempty"` // SECOND, MINUTE, etc.
RefreshAppend bool `json:"refresh_append,omitempty"` // APPEND TO was specified
RefreshDependsOn []*TableIdentifier `json:"refresh_depends_on,omitempty"` // DEPENDS ON tables
RefreshSettings []*SettingExpr `json:"refresh_settings,omitempty"` // REFRESH ... SETTINGS
Empty bool `json:"empty,omitempty"` // EMPTY keyword was specified
Columns []*ColumnDeclaration `json:"columns,omitempty"`
Indexes []*IndexDefinition `json:"indexes,omitempty"`
Expand Down Expand Up @@ -410,6 +415,17 @@ type KeyValuePair struct {
Value Expression `json:"value"`
}

// KeyValueList is a parenthesized list of key-value pairs used as a pair's
// value, as in SOURCE(HTTP(headers(header(name 'a' value 'b')))).
type KeyValueList struct {
Position token.Position `json:"-"`
Pairs []*KeyValuePair `json:"pairs"`
}

func (k *KeyValueList) Pos() token.Position { return k.Position }
func (k *KeyValueList) End() token.Position { return k.Position }
func (k *KeyValueList) expressionNode() {}

func (k *KeyValuePair) Pos() token.Position { return k.Position }
func (k *KeyValuePair) End() token.Position { return k.Position }

Expand Down Expand Up @@ -620,6 +636,7 @@ func (a *AlterQuery) statementNode() {}
type AlterCommand struct {
Position token.Position `json:"-"`
Type AlterCommandType `json:"type"`
ExecuteArgs []Expression `json:"execute_args,omitempty"`
Column *ColumnDeclaration `json:"column,omitempty"`
ColumnName string `json:"column_name,omitempty"`
AfterColumn string `json:"after_column,omitempty"`
Expand Down Expand Up @@ -746,6 +763,8 @@ const (
AlterRemoveSampleBy AlterCommandType = "REMOVE_SAMPLE_BY"
AlterApplyDeletedMask AlterCommandType = "APPLY_DELETED_MASK"
AlterRewriteParts AlterCommandType = "REWRITE_PARTS"
AlterModifyConstraint AlterCommandType = "MODIFY_CONSTRAINT"
AlterExecuteCommand AlterCommandType = "EXECUTE_COMMAND"
)

// TruncateQuery represents a TRUNCATE statement.
Expand Down Expand Up @@ -1339,6 +1358,7 @@ type CreateHandlerQuery struct {
Position token.Position `json:"-"`
Name string `json:"name"`
Query Statement `json:"query,omitempty"`
IsAlter bool `json:"is_alter,omitempty"`
}

func (c *CreateHandlerQuery) Pos() token.Position { return c.Position }
Expand Down Expand Up @@ -1377,6 +1397,7 @@ type CreateIndexQuery struct {
TypeArguments []Expression `json:"type_arguments,omitempty"` // Index type arguments, e.g. 0.01 in bloom_filter(0.01)
TypeHasParentheses bool `json:"type_has_parentheses,omitempty"` // True if the type was written with (...)
Granularity int `json:"granularity,omitempty"` // GRANULARITY value
Hypothetical bool `json:"hypothetical,omitempty"`
}

func (c *CreateIndexQuery) Pos() token.Position { return c.Position }
Expand Down
9 changes: 9 additions & 0 deletions internal/explain/explain.go
Original file line number Diff line number Diff line change
Expand Up @@ -414,6 +414,15 @@ func Node(sb *strings.Builder, node interface{}, depth int) {
explainDictionarySource(sb, n, indent, depth)
case *ast.KeyValuePair:
explainKeyValuePair(sb, n, indent, depth)
case *ast.KeyValueList:
if len(n.Pairs) == 0 {
fmt.Fprintf(sb, "%sExpressionList\n", indent)
} else {
fmt.Fprintf(sb, "%sExpressionList (children %d)\n", indent, len(n.Pairs))
for _, kv := range n.Pairs {
explainKeyValuePair(sb, kv, indent+" ", depth+1)
}
}
case *ast.DictionaryLifetime:
explainDictionaryLifetime(sb, n, indent, depth)
case *ast.DictionaryLayout:
Expand Down
63 changes: 59 additions & 4 deletions internal/explain/statements.go
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,20 @@ func explainInsertQuery(sb *strings.Builder, n *ast.InsertQuery, indent string,
}

func explainCreateQuery(sb *strings.Builder, n *ast.CreateQuery, indent string, depth int) {
if n != nil && n.Attach {
// ATTACH prints exactly like CREATE under a different name
var tmp strings.Builder
n.Attach = false
explainCreateQuery(&tmp, n, indent, depth)
n.Attach = true
out := tmp.String()
prefix := indent + "CreateQuery"
if strings.HasPrefix(out, prefix) {
out = indent + "AttachQuery" + out[len(prefix):]
}
sb.WriteString(out)
return
}
// A table engine's SETTINGS clause drops query-level settings.
if n.Table != "" && n.Engine != nil && len(n.Settings) > 0 && (n.Comment == "" || n.SettingsBeforeComment) && engineDropsQuerySettings(n.Engine.Name) {
var kept []*ast.SettingExpr
Expand Down Expand Up @@ -245,6 +259,9 @@ func explainCreateQuery(sb *strings.Builder, n *ast.CreateQuery, indent string,
if n.SQLSecurity && n.AsSelect != nil {
children++ // View SQL Security
}
if n.TableSQLSecurity {
children++
}
if len(n.TimeSeriesTargets) > 0 {
children++ // ViewTargets
}
Expand Down Expand Up @@ -370,8 +387,24 @@ func explainCreateQuery(sb *strings.Builder, n *ast.CreateQuery, indent string,
}
// Output REFRESH strategy for materialized views with REFRESH clause
if n.HasRefresh {
fmt.Fprintf(sb, "%s Refresh strategy definition (children 1)\n", indent)
rc := 1
if len(n.RefreshDependsOn) > 0 {
rc++
}
if len(n.RefreshSettings) > 0 {
rc++
}
fmt.Fprintf(sb, "%s Refresh strategy definition (children %d)\n", indent, rc)
fmt.Fprintf(sb, "%s TimeInterval\n", indent)
if len(n.RefreshDependsOn) > 0 {
fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", indent, len(n.RefreshDependsOn))
for _, t := range n.RefreshDependsOn {
explainTableIdentifier(sb, t, indent+" ")
}
}
if len(n.RefreshSettings) > 0 {
fmt.Fprintf(sb, "%s Set\n", indent)
}
}
// COMMENT comes before the SELECT (and the view targets) for views.
commentDone := false
Expand Down Expand Up @@ -619,6 +652,9 @@ func explainCreateQuery(sb *strings.Builder, n *ast.CreateQuery, indent string,
inCreateQueryContext = false
}
}
if n.TableSQLSecurity {
fmt.Fprintf(sb, "%s View SQL Security\n", indent)
}
// Output FORMAT clause if present
if hasFormat {
fmt.Fprintf(sb, "%s Identifier %s\n", indent, n.Format)
Expand Down Expand Up @@ -1902,7 +1938,16 @@ func explainAlterCommand(sb *strings.Builder, cmd *ast.AlterCommand, indent stri
fmt.Fprintf(sb, "%s Identifier %s\n", indent, cmd.ColumnName)
}
explainAlterPartition(sb, cmd, indent, depth)
case ast.AlterAddConstraint:
case ast.AlterExecuteCommand:
if len(cmd.ExecuteArgs) > 0 {
fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", indent, len(cmd.ExecuteArgs))
for _, a := range cmd.ExecuteArgs {
Node(sb, a, depth+2)
}
} else {
fmt.Fprintf(sb, "%s ExpressionList\n", indent)
}
case ast.AlterAddConstraint, ast.AlterModifyConstraint:
if cmd.Constraint != nil {
if cmd.Constraint.Expression != nil {
fmt.Fprintf(sb, "%s Constraint (children 1)\n", indent)
Expand Down Expand Up @@ -1950,6 +1995,7 @@ func explainAlterCommand(sb *strings.Builder, cmd *ast.AlterCommand, indent stri
case ast.AlterFreeze:
// No children
case ast.AlterDeleteWhere:
explainAlterPartition(sb, cmd, indent, depth)
if cmd.Where != nil {
Node(sb, cmd.Where, depth+1)
}
Expand Down Expand Up @@ -2244,7 +2290,9 @@ func countAlterCommandChildren(cmd *ast.AlterCommand) int {
if cmd.Partition != nil {
children++
}
case ast.AlterAddConstraint:
case ast.AlterExecuteCommand:
children = 1
case ast.AlterAddConstraint, ast.AlterModifyConstraint:
if cmd.Constraint != nil {
children++
}
Expand All @@ -2266,6 +2314,9 @@ func countAlterCommandChildren(cmd *ast.AlterCommand) int {
case ast.AlterFreeze:
// No children
case ast.AlterDeleteWhere:
if cmd.Partition != nil {
children++
}
if cmd.Where != nil {
children++
}
Expand Down Expand Up @@ -2613,7 +2664,11 @@ func explainCreateIndexQuery(sb *strings.Builder, n *ast.CreateIndexQuery, inden
if n.Database != "" {
children = 4
}
fmt.Fprintf(sb, "%sCreateIndexQuery %s %s (children %d)\n", indent, n.Database, n.Table, children)
name := "CreateIndexQuery"
if n.Hypothetical {
name = "CreateHypotheticalIndexQuery"
}
fmt.Fprintf(sb, "%s%s %s %s (children %d)\n", indent, name, n.Database, n.Table, children)

// Child 1: Index name
fmt.Fprintf(sb, "%s Identifier %s\n", indent, n.IndexName)
Expand Down
27 changes: 27 additions & 0 deletions internal/explain/tables.go
Original file line number Diff line number Diff line change
Expand Up @@ -296,7 +296,27 @@ func explainViewExplain(sb *strings.Builder, n *ast.ExplainQuery, alias string,
Node(sb, n.Statement, depth+10)
}

// tableIdentifierParams returns the query parameters ({name:Type}) among a
// table identifier's parts. ClickHouse prints such an identifier with an
// empty name and the parameters as children.
func tableIdentifierParams(n *ast.TableIdentifier) []string {
var params []string
for _, part := range []string{n.Database, n.Table} {
if len(part) > 2 && part[0] == '{' && part[len(part)-1] == '}' {
params = append(params, part[1:len(part)-1])
}
}
return params
}

func explainTableIdentifierWithAlias(sb *strings.Builder, n *ast.TableIdentifier, alias string, indent string) {
if params := tableIdentifierParams(n); len(params) > 0 && n.Database != "" {
fmt.Fprintf(sb, "%sTableIdentifier (alias %s) (children %d)\n", indent, alias, len(params))
for _, prm := range params {
fmt.Fprintf(sb, "%s QueryParameter %s\n", indent, prm)
}
return
}
name := n.Table
if n.Database != "" {
name = n.Database + "." + n.Table
Expand All @@ -305,6 +325,13 @@ func explainTableIdentifierWithAlias(sb *strings.Builder, n *ast.TableIdentifier
}

func explainTableIdentifier(sb *strings.Builder, n *ast.TableIdentifier, indent string) {
if params := tableIdentifierParams(n); len(params) > 0 && n.Database != "" {
fmt.Fprintf(sb, "%sTableIdentifier (children %d)\n", indent, len(params))
for _, prm := range params {
fmt.Fprintf(sb, "%s QueryParameter %s\n", indent, prm)
}
return
}
name := n.Table
if n.Database != "" {
name = n.Database + "." + n.Table
Expand Down
24 changes: 24 additions & 0 deletions parser/expression.go
Original file line number Diff line number Diff line change
Expand Up @@ -848,6 +848,20 @@ func (p *Parser) parseFunctionCall(name string, pos token.Position) *ast.Functio
if (strings.EqualFold(name, "view") || strings.EqualFold(name, "eval")) && (p.isQueryStart()) {
subquery := p.parseSelectWithUnion()
fn.Arguments = []ast.Expression{&ast.Subquery{Position: pos, Query: subquery}}
} else if strings.EqualFold(name, "viewIfPermitted") && p.isQueryStart() {
// viewIfPermitted(SELECT ... ELSE fallback_table_function(...))
fn.Arguments = []ast.Expression{p.parseSelectWithUnion()}
if p.currentIs(token.ELSE) {
p.nextToken()
if (p.currentIs(token.IDENT) || p.current.Token.IsKeyword()) && p.peekIs(token.LPAREN) {
fpos := p.current.Pos
fname := p.current.Value
p.nextToken()
fn.Arguments = append(fn.Arguments, p.parseFunctionCall(fname, fpos))
} else {
fn.Arguments = append(fn.Arguments, p.parseExpression(LOWEST))
}
}
} else if !p.currentIs(token.RPAREN) && !(p.isSettingsClauseInArgs()) {
// Parse arguments, but allow Settings['key'] map access (SETTINGS followed by [)
fn.Arguments = p.parseFunctionArgumentList()
Expand Down Expand Up @@ -2335,6 +2349,16 @@ func (p *Parser) parseInExpression(left ast.Expression, not bool) ast.Expression
} else {
// Parse IN list manually to detect trailing comma
expr.List, expr.TrailingComma = p.parseInList()
// IN ((SELECT ...) UNION (SELECT ...)): the list's only element is
// the first operand of a set operation.
if len(expr.List) == 1 && !expr.TrailingComma &&
(p.currentIs(token.UNION) || p.currentIs(token.EXCEPT) || p.currentIs(token.INTERSECT)) {
if sq, ok := expr.List[0].(*ast.Subquery); ok && sq.Alias == "" {
q := &ast.SelectWithUnionQuery{Position: sq.Position}
expr.Query = p.continueSelectWithUnion(q, sq.Query, true)
expr.List = nil
}
}
}
p.expect(token.RPAREN)
} else if p.currentIs(token.LBRACKET) {
Expand Down
Loading
Loading