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
58 changes: 47 additions & 11 deletions ast/ast.go
Original file line number Diff line number Diff line change
Expand Up @@ -279,17 +279,19 @@ type CreateQuery struct {
Table string `json:"table,omitempty"`
View string `json:"view,omitempty"`
Materialized bool `json:"materialized,omitempty"`
WindowView bool `json:"window_view,omitempty"` // WINDOW VIEW type
InnerEngine *EngineClause `json:"inner_engine,omitempty"` // INNER ENGINE for window views
ToDatabase string `json:"to_database,omitempty"` // Target database for materialized views
To string `json:"to,omitempty"` // Target table for materialized views
Populate bool `json:"populate,omitempty"` // POPULATE for materialized views
HasRefresh bool `json:"has_refresh,omitempty"` // Has REFRESH clause
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
Empty bool `json:"empty,omitempty"` // EMPTY keyword was specified
WindowView bool `json:"window_view,omitempty"` // WINDOW VIEW type
InnerEngine *EngineClause `json:"inner_engine,omitempty"` // INNER ENGINE for window views
ToDatabase string `json:"to_database,omitempty"` // Target database for materialized views
To string `json:"to,omitempty"` // Target table for materialized views
Populate bool `json:"populate,omitempty"` // POPULATE for materialized views
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 ...
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
Empty bool `json:"empty,omitempty"` // EMPTY keyword was specified
Columns []*ColumnDeclaration `json:"columns,omitempty"`
Indexes []*IndexDefinition `json:"indexes,omitempty"`
Projections []*Projection `json:"projections,omitempty"`
Expand Down Expand Up @@ -319,6 +321,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
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 @@ -729,6 +733,7 @@ const (
AlterMaterializeStatistics AlterCommandType = "MATERIALIZE_STATISTICS"
AlterModifyComment AlterCommandType = "MODIFY_COMMENT"
AlterModifyOrderBy AlterCommandType = "MODIFY_ORDER_BY"
AlterModifySQLSecurity AlterCommandType = "MODIFY_SQL_SECURITY"
AlterModifySampleBy AlterCommandType = "MODIFY_SAMPLE_BY"
AlterModifyQuery AlterCommandType = "MODIFY_QUERY"
AlterRemoveSampleBy AlterCommandType = "REMOVE_SAMPLE_BY"
Expand Down Expand Up @@ -932,6 +937,7 @@ const (
ExplainPlan ExplainType = "PLAN"
ExplainPipeline ExplainType = "PIPELINE"
ExplainEstimate ExplainType = "ESTIMATE"
ExplainAnalyze ExplainType = "ANALYZE"
ExplainQueryTree ExplainType = "QUERY TREE"
ExplainCurrentTransaction ExplainType = "CURRENT TRANSACTION"
)
Expand Down Expand Up @@ -1311,6 +1317,36 @@ func (c *CreateWorkloadQuery) Pos() token.Position { return c.Position }
func (c *CreateWorkloadQuery) End() token.Position { return c.Position }
func (c *CreateWorkloadQuery) statementNode() {}

// TimeSeriesTarget is one DATA/TAGS/METRICS/SAMPLES target of a TimeSeries table.
// Only inner engines and inner columns show up in EXPLAIN AST.
type TimeSeriesTarget struct {
Kind string `json:"kind"`
Table string `json:"table,omitempty"`
Storage *CreateQuery `json:"storage,omitempty"` // holds INNER ENGINE and its options
Columns []*ColumnDeclaration `json:"columns,omitempty"` // INNER COLUMNS
}

// CreateHandlerQuery represents CREATE HANDLER name ... AS query.
type CreateHandlerQuery struct {
Position token.Position `json:"-"`
Name string `json:"name"`
Query Statement `json:"query,omitempty"`
}

func (c *CreateHandlerQuery) Pos() token.Position { return c.Position }
func (c *CreateHandlerQuery) End() token.Position { return c.Position }
func (c *CreateHandlerQuery) statementNode() {}

// DropHandlerQuery represents DROP HANDLER [IF EXISTS] name.
type DropHandlerQuery struct {
Position token.Position `json:"-"`
Name string `json:"name"`
}

func (d *DropHandlerQuery) Pos() token.Position { return d.Position }
func (d *DropHandlerQuery) End() token.Position { return d.Position }
func (d *DropHandlerQuery) statementNode() {}

// DropWorkloadQuery represents a DROP WORKLOAD statement.
type DropWorkloadQuery struct {
Position token.Position `json:"-"`
Expand Down
9 changes: 9 additions & 0 deletions internal/explain/explain.go
Original file line number Diff line number Diff line change
Expand Up @@ -331,6 +331,15 @@ func Node(sb *strings.Builder, node interface{}, depth int) {
fmt.Fprintf(sb, "%sCreateWorkloadQuery %s (children 1)\n", indent, n.Name)
explainIdentifier(sb, &ast.Identifier{Parts: []string{n.Name}}, childIndent)
}
case *ast.CreateHandlerQuery:
if n.Query != nil {
fmt.Fprintf(sb, "%sCreateHandlerQuery (children 1)\n", indent)
Node(sb, n.Query, depth+1)
} else {
fmt.Fprintf(sb, "%sCreateHandlerQuery\n", indent)
}
case *ast.DropHandlerQuery:
fmt.Fprintf(sb, "%sDropHandlerQuery\n", indent)
case *ast.DropWorkloadQuery:
fmt.Fprintf(sb, "%sDropWorkloadQuery\n", indent)
case *ast.ShowGrantsQuery:
Expand Down
134 changes: 108 additions & 26 deletions internal/explain/statements.go
Original file line number Diff line number Diff line change
Expand Up @@ -131,32 +131,7 @@ func explainCreateQuery(sb *strings.Builder, n *ast.CreateQuery, indent string,
return
}
if n.CreateUser || n.AlterUser {
if n.HasAuthenticationData {
// Each authentication value is a separate AuthenticationData child
if len(n.AuthenticationValues) > 0 {
fmt.Fprintf(sb, "%sCreateUserQuery (children %d)\n", indent, len(n.AuthenticationValues))
for _, val := range n.AuthenticationValues {
// Each AuthenticationData has 1 child (the Literal value)
fmt.Fprintf(sb, "%s AuthenticationData (children 1)\n", indent)
// Escape the value - strings need \' escaping
escaped := escapeStringLiteral(val)
fmt.Fprintf(sb, "%s Literal \\'%s\\'\n", indent, escaped)
}
} else if n.SSHKeyCount > 0 {
// SSH key authentication - each key is a PublicSSHKey child
fmt.Fprintf(sb, "%sCreateUserQuery (children 1)\n", indent)
fmt.Fprintf(sb, "%s AuthenticationData (children %d)\n", indent, n.SSHKeyCount)
for i := 0; i < n.SSHKeyCount; i++ {
fmt.Fprintf(sb, "%s PublicSSHKey\n", indent)
}
} else {
// No values - just output CreateUserQuery with 1 child
fmt.Fprintf(sb, "%sCreateUserQuery (children 1)\n", indent)
fmt.Fprintf(sb, "%s AuthenticationData\n", indent)
}
} else {
fmt.Fprintf(sb, "%sCreateUserQuery\n", indent)
}
explainCreateUser(sb, n, indent)
return
}
if n.CreateDictionary {
Expand Down Expand Up @@ -248,6 +223,12 @@ func explainCreateQuery(sb *strings.Builder, n *ast.CreateQuery, indent string,
if n.HasRefresh {
children++ // Refresh strategy definition
}
if n.SQLSecurity && n.AsSelect != nil {
children++ // View SQL Security
}
if len(n.TimeSeriesTargets) > 0 {
children++ // ViewTargets
}
// For materialized views with TO clause but no storage, count ViewTargets as a child
if n.Materialized && n.To != "" && !hasStorageChild {
children++ // ViewTargets
Expand Down Expand Up @@ -379,6 +360,10 @@ func explainCreateQuery(sb *strings.Builder, n *ast.CreateQuery, indent string,
fmt.Fprintf(sb, "%s Literal \\'%s\\'\n", indent, escapeStringLiteral(n.Comment))
commentDone = true
}
// SQL SECURITY comes right before the SELECT
if n.SQLSecurity && n.AsSelect != nil && n.Materialized {
fmt.Fprintf(sb, "%s View SQL Security\n", indent)
}
// For materialized views, output AsSelect before storage definition
if n.Materialized && n.AsSelect != nil {
// Set context flag to prevent Format from being output at SelectWithUnionQuery level
Expand Down Expand Up @@ -540,6 +525,9 @@ func explainCreateQuery(sb *strings.Builder, n *ast.CreateQuery, indent string,
// output just ViewTargets without children
fmt.Fprintf(sb, "%s ViewTargets\n", indent)
}
if len(n.TimeSeriesTargets) > 0 {
explainTimeSeriesTargets(sb, n.TimeSeriesTargets, indent+" ", depth+1)
}
// For window views, output AsSelect before ViewTargets
if n.WindowView && n.AsSelect != nil {
if hasFormat {
Expand Down Expand Up @@ -598,6 +586,9 @@ func explainCreateQuery(sb *strings.Builder, n *ast.CreateQuery, indent string,
}
// For non-materialized views, output AsSelect after storage
if n.AsSelect != nil && !n.Materialized && !n.WindowView {
if n.SQLSecurity {
fmt.Fprintf(sb, "%s View SQL Security\n", indent)
}
// Set context flag to prevent Format from being output at SelectWithUnionQuery level
// (it will be output at CreateQuery level instead)
if hasFormat {
Expand Down Expand Up @@ -1958,6 +1949,8 @@ func explainAlterCommand(sb *strings.Builder, cmd *ast.AlterCommand, indent stri
explainStatisticsCommand(sb, cmd, indent, depth)
case ast.AlterDropStatistics, ast.AlterClearStatistics, ast.AlterMaterializeStatistics:
explainStatisticsCommand(sb, cmd, indent, depth)
case ast.AlterModifySQLSecurity:
fmt.Fprintf(sb, "%s View SQL Security\n", indent)
case ast.AlterModifyOrderBy:
// When there are multiple expressions, wrap them in a tuple function
if len(cmd.OrderByExpr) > 1 {
Expand Down Expand Up @@ -2271,6 +2264,8 @@ func countAlterCommandChildren(cmd *ast.AlterCommand) int {
if len(cmd.StatisticsColumns) > 0 {
children = 1
}
case ast.AlterModifySQLSecurity:
children = 1
case ast.AlterModifyOrderBy:
// MODIFY ORDER BY: multiple expressions wrapped in tuple (1 child), single expression (1 child)
if len(cmd.OrderByExpr) > 0 {
Expand Down Expand Up @@ -2875,3 +2870,90 @@ func explainCreateWasmFunction(sb *strings.Builder, n *ast.CreateQuery, indent s
fmt.Fprintf(sb, "%s Identifier %s\n", indent, w.Abi)
}
}

// explainTimeSeriesTargets prints the ViewTargets of a TimeSeries table: only
// inner engines (as a Storage definition) and inner columns have children.
func explainTimeSeriesTargets(sb *strings.Builder, targets []*ast.TimeSeriesTarget, indent string, depth int) {
children := 0
for _, t := range targets {
if t.Storage != nil || len(t.Columns) > 0 {
children++
}
}
if children == 0 {
fmt.Fprintf(sb, "%sViewTargets\n", indent)
return
}
fmt.Fprintf(sb, "%sViewTargets (children %d)\n", indent, children)
for _, t := range targets {
if t.Storage != nil {
// Render the inner engine as a table and keep only its Storage definition
var tmp strings.Builder
t.Storage.Table = "x"
Node(&tmp, t.Storage, depth)
lines := strings.Split(strings.TrimRight(tmp.String(), "\n"), "\n")
for _, line := range lines[2:] {
sb.WriteString(line)
sb.WriteString("\n")
}
} else if len(t.Columns) > 0 {
fmt.Fprintf(sb, "%s Columns definition (children 1)\n", indent)
fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", indent, len(t.Columns))
for _, col := range t.Columns {
Column(sb, col, depth+3)
}
}
}
}

func explainCreateUser(sb *strings.Builder, n *ast.CreateQuery, indent string) {
children := 0
if n.HasAuthenticationData {
if len(n.AuthenticationValues) > 0 {
children += len(n.AuthenticationValues)
} else {
children++
}
}
// Without a password value, VALID UNTIL belongs to the authentication data
authValidUntil := n.HasAuthenticationData && len(n.AuthenticationValues) == 0 && n.SSHKeyCount == 0 && n.UserValidUntil != ""
if n.UserValidUntil != "" && !authValidUntil {
children++
}
if children == 0 {
fmt.Fprintf(sb, "%sCreateUserQuery\n", indent)
return
}
fmt.Fprintf(sb, "%sCreateUserQuery (children %d)\n", indent, children)
if n.HasAuthenticationData {
if len(n.AuthenticationValues) > 0 {
// Each authentication value is a separate AuthenticationData child
for i, val := range n.AuthenticationValues {
validUntil, hasValidUntil := n.AuthValidUntil[i]
if hasValidUntil {
fmt.Fprintf(sb, "%s AuthenticationData (children 2)\n", indent)
} else {
fmt.Fprintf(sb, "%s AuthenticationData (children 1)\n", indent)
}
fmt.Fprintf(sb, "%s Literal \\'%s\\'\n", indent, escapeStringLiteral(val))
if hasValidUntil {
fmt.Fprintf(sb, "%s Literal \\'%s\\'\n", indent, escapeStringLiteral(validUntil))
}
}
} else if n.SSHKeyCount > 0 {
// SSH key authentication - each key is a PublicSSHKey child
fmt.Fprintf(sb, "%s AuthenticationData (children %d)\n", indent, n.SSHKeyCount)
for i := 0; i < n.SSHKeyCount; i++ {
fmt.Fprintf(sb, "%s PublicSSHKey\n", indent)
}
} else if authValidUntil {
fmt.Fprintf(sb, "%s AuthenticationData (children 1)\n", indent)
fmt.Fprintf(sb, "%s Literal \\'%s\\'\n", indent, escapeStringLiteral(n.UserValidUntil))
} else {
fmt.Fprintf(sb, "%s AuthenticationData\n", indent)
}
}
if n.UserValidUntil != "" && !authValidUntil {
fmt.Fprintf(sb, "%s Literal \\'%s\\'\n", indent, escapeStringLiteral(n.UserValidUntil))
}
}
6 changes: 5 additions & 1 deletion internal/explain/tables.go
Original file line number Diff line number Diff line change
Expand Up @@ -265,7 +265,11 @@ func abs(x float64) float64 {
func explainViewExplain(sb *strings.Builder, n *ast.ExplainQuery, alias string, indent string, depth int) {
// When EXPLAIN is used as a table source, it becomes wrapped in SELECT * FROM viewExplain(...)
// Structure: Subquery -> SelectWithUnionQuery -> ExpressionList -> SelectQuery -> Asterisk, TablesInSelectQuery -> viewExplain
fmt.Fprintf(sb, "%sSubquery (children %d)\n", indent, 1)
if alias != "" {
fmt.Fprintf(sb, "%sSubquery (alias %s) (children %d)\n", indent, alias, 1)
} else {
fmt.Fprintf(sb, "%sSubquery (children %d)\n", indent, 1)
}
fmt.Fprintf(sb, "%s SelectWithUnionQuery (children %d)\n", indent, 1)
fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", indent, 1)
fmt.Fprintf(sb, "%s SelectQuery (children %d)\n", indent, 2)
Expand Down
11 changes: 6 additions & 5 deletions lexer/lexer.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,11 @@ type Lexer struct {

// Item represents a lexical token with its value and position.
type Item struct {
Token token.Token
Value string
Pos token.Position
Quoted bool // true if this identifier was double-quoted
Token token.Token
Value string
Pos token.Position
Quoted bool // true if this identifier was double-quoted
Backquoted bool // true if this identifier was backtick-quoted
}

// New creates a new Lexer from an io.Reader.
Expand Down Expand Up @@ -763,7 +764,7 @@ func (l *Lexer) readBacktickIdentifier() Item {
sb.WriteRune(l.ch)
l.readChar()
}
return Item{Token: token.IDENT, Value: sb.String(), Pos: pos}
return Item{Token: token.IDENT, Value: sb.String(), Pos: pos, Backquoted: true}
}

// tryReadDollarTag checks if we have a tagged dollar quote like $tag$...$tag$ and returns the tag
Expand Down
Loading
Loading