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
8 changes: 8 additions & 0 deletions ast/ast.go
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,8 @@ type TableExpression struct {
Alias string `json:"alias,omitempty"`
Final bool `json:"final,omitempty"`
Sample *SampleClause `json:"sample,omitempty"`
// ColumnAliases holds the column alias list of "t(a, b, ...)".
ColumnAliases []string `json:"column_aliases,omitempty"`
}

func (t *TableExpression) Pos() token.Position { return t.Position }
Expand Down Expand Up @@ -719,6 +721,7 @@ const (
AlterModifyQuery AlterCommandType = "MODIFY_QUERY"
AlterRemoveSampleBy AlterCommandType = "REMOVE_SAMPLE_BY"
AlterApplyDeletedMask AlterCommandType = "APPLY_DELETED_MASK"
AlterRewriteParts AlterCommandType = "REWRITE_PARTS"
)

// TruncateQuery represents a TRUNCATE statement.
Expand Down Expand Up @@ -1606,6 +1609,10 @@ type WithElement struct {
Name string `json:"name"`
Query Expression `json:"query"` // Subquery or Expression
ScalarWith bool `json:"scalar_with"` // True for "(expr) AS name" syntax, false for "name AS (SELECT ...)"
// Materialized is true for "name AS MATERIALIZED (SELECT ...)".
Materialized bool `json:"materialized,omitempty"`
// ColumnAliases holds the column alias list of "name (a, b, ...) AS (SELECT ...)".
ColumnAliases []string `json:"column_aliases,omitempty"`
}

func (w *WithElement) Pos() token.Position { return w.Position }
Expand Down Expand Up @@ -1776,6 +1783,7 @@ type LikeExpr struct {
Not bool `json:"not,omitempty"`
CaseInsensitive bool `json:"case_insensitive,omitempty"` // true for ILIKE
Pattern Expression `json:"pattern"`
Escape Expression `json:"escape,omitempty"` // ESCAPE 'c'
Alias string `json:"alias,omitempty"`
}

Expand Down
17 changes: 9 additions & 8 deletions internal/explain/explain.go
Original file line number Diff line number Diff line change
Expand Up @@ -433,30 +433,31 @@ func Column(sb *strings.Builder, col *ast.ColumnDeclaration, depth int) {
} else {
fmt.Fprintf(sb, "%sColumnDeclaration %s\n", indent, sanitizeUTF8(col.Name))
}
// Children follow ClickHouse's order: type, default, comment, codec,
// settings, statistics, TTL.
if col.Type != nil {
Node(sb, col.Type, depth+1)
}
// Settings comes right after Type in ClickHouse EXPLAIN output
if len(col.Settings) > 0 {
fmt.Fprintf(sb, "%s Set\n", indent)
}
if col.Default != nil {
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.TTL != nil {
Node(sb, col.TTL, depth+1)
if col.Comment != "" {
fmt.Fprintf(sb, "%s Literal \\'%s\\'\n", indent, col.Comment)
}
if col.Codec != nil {
explainCodecExpr(sb, col.Codec, indent+" ", depth+1)
}
if len(col.Settings) > 0 {
fmt.Fprintf(sb, "%s Set\n", indent)
}
if len(col.Statistics) > 0 {
explainStatisticsExpr(sb, col.Statistics, indent+" ", depth+1)
}
if col.Comment != "" {
fmt.Fprintf(sb, "%s Literal \\'%s\\'\n", indent, col.Comment)
if col.TTL != nil {
Node(sb, col.TTL, depth+1)
}
}

Expand Down
152 changes: 103 additions & 49 deletions internal/explain/functions.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"strings"

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

// escapeFunctionAlias escapes backslashes and single quotes in function alias names.
Expand Down Expand Up @@ -222,6 +223,13 @@ func explainFunctionCallWithAlias(sb *strings.Builder, n *ast.FunctionCall, alia
func handleSpecialFunction(sb *strings.Builder, n *ast.FunctionCall, alias string, indent string, depth int) bool {
fnName := strings.ToUpper(n.Name)

// date_part('unit', expr) is parsed like EXTRACT(unit FROM expr)
if fnName == "DATE_PART" {
if explainDatePart(sb, n, alias, indent, depth) {
return true
}
}

// Handle kql() function - transforms KQL (Kusto Query Language) to SQL
if fnName == "KQL" {
return handleKQLFunction(sb, n, alias, indent, depth)
Expand Down Expand Up @@ -378,31 +386,19 @@ func outputQuantifiedWithAggregate(sb *strings.Builder, left ast.Expression, sub
Node(sb, left, depth+2)

// Output the subquery wrapped with aggregate function
// Structure: Subquery -> SelectWithUnionQuery -> ExpressionList -> SelectQuery with 4 children
// Structure: Subquery -> SelectWithUnionQuery -> ExpressionList -> SelectQuery
fmt.Fprintf(sb, "%s Subquery (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, 4)

// First ExpressionList with aggregate function
fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", indent, 1)
fmt.Fprintf(sb, "%s Function %s (children %d)\n", indent, aggFunc, 1)
fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", indent, 1)
fmt.Fprintf(sb, "%s Asterisk\n", indent)

// First TablesInSelectQuery - wrap the original subquery
fmt.Fprintf(sb, "%s TablesInSelectQuery (children %d)\n", indent, 1)
fmt.Fprintf(sb, "%s TablesInSelectQueryElement (children %d)\n", indent, 1)
fmt.Fprintf(sb, "%s TableExpression (children %d)\n", indent, 1)
Node(sb, subquery, depth+9)
fmt.Fprintf(sb, "%s SelectQuery (children %d)\n", indent, 2)

// Second ExpressionList with aggregate function (repeated)
// ExpressionList with aggregate function
fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", indent, 1)
fmt.Fprintf(sb, "%s Function %s (children %d)\n", indent, aggFunc, 1)
fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", indent, 1)
fmt.Fprintf(sb, "%s Asterisk\n", indent)

// Second TablesInSelectQuery (repeated)
// TablesInSelectQuery wrapping the original subquery
fmt.Fprintf(sb, "%s TablesInSelectQuery (children %d)\n", indent, 1)
fmt.Fprintf(sb, "%s TablesInSelectQueryElement (children %d)\n", indent, 1)
fmt.Fprintf(sb, "%s TableExpression (children %d)\n", indent, 1)
Expand Down Expand Up @@ -1443,9 +1439,22 @@ func explainLikeExpr(sb *strings.Builder, n *ast.LikeExpr, indent string, depth
} else {
fmt.Fprintf(sb, "%sFunction %s (children %d)\n", indent, fnName, 1)
}
fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", indent, 2)
explainLikeArgs(sb, n, indent, depth)
}

// explainLikeArgs prints the argument list of a LIKE function: expr, pattern
// and the optional ESCAPE character.
func explainLikeArgs(sb *strings.Builder, n *ast.LikeExpr, indent string, depth int) {
args := 2
if n.Escape != nil {
args++
}
fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", indent, args)
Node(sb, n.Expr, depth+2)
Node(sb, n.Pattern, depth+2)
if n.Escape != nil {
Node(sb, n.Escape, depth+2)
}
}

func explainLikeExprWithAlias(sb *strings.Builder, n *ast.LikeExpr, alias string, indent string, depth int) {
Expand All @@ -1462,9 +1471,7 @@ func explainLikeExprWithAlias(sb *strings.Builder, n *ast.LikeExpr, alias string
} else {
fmt.Fprintf(sb, "%sFunction %s (children %d)\n", indent, fnName, 1)
}
fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", indent, 2)
Node(sb, n.Expr, depth+2)
Node(sb, n.Pattern, depth+2)
explainLikeArgs(sb, n, indent, depth)
}

func explainBetweenExpr(sb *strings.Builder, n *ast.BetweenExpr, indent string, depth int) {
Expand Down Expand Up @@ -1741,45 +1748,92 @@ func explainExtractExpr(sb *strings.Builder, n *ast.ExtractExpr, indent string,
}

func explainExtractExprWithAlias(sb *strings.Builder, n *ast.ExtractExpr, alias string, indent string, depth int) {
// EXTRACT is represented as Function toYear, toMonth, etc.
// ClickHouse uses specific function names for date/time extraction
fnName := extractFieldToFunction(n.Field)
// Only use the external alias parameter (from explicit AS on EXTRACT itself)
// NOT the alias from the From expression - that stays on the inner expression
if alias != "" {
fmt.Fprintf(sb, "%sFunction %s (alias %s) (children %d)\n", indent, fnName, alias, 1)
} else {
fmt.Fprintf(sb, "%sFunction %s (children %d)\n", indent, fnName, 1)
}
fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", indent, 1)
Node(sb, n.From, depth+2)
// EXTRACT(unit FROM expr) is rewritten into a function such as toYear(expr).
// Only the external alias (an explicit AS on EXTRACT itself) goes on the
// result; the alias of the From expression stays on the inner expression.
fn := extractTimePart(n.Field, n.From)
fn.Alias = alias
explainFunctionCall(sb, fn, indent, depth)
}

// extractFieldToFunction maps EXTRACT field names to ClickHouse function names
func extractFieldToFunction(field string) string {
switch strings.ToUpper(field) {
case "DAY":
return "toDayOfMonth"
case "MONTH":
return "toMonth"
case "YEAR", "YYYY":
return "toYear"
// extractTimePart builds the expression ClickHouse uses for EXTRACT(unit FROM expr).
func extractTimePart(unit string, expr ast.Expression) *ast.FunctionCall {
call := func(name string, args ...ast.Expression) *ast.FunctionCall {
return &ast.FunctionCall{Name: name, Arguments: args}
}
num := func(v int64) *ast.Literal {
return &ast.Literal{Type: ast.LiteralInteger, Value: v}
}
switch strings.ToUpper(unit) {
case "NANOSECOND":
return call("toNanosecond", expr)
case "MICROSECOND":
return call("toMicrosecond", expr)
case "MILLISECOND":
return call("toMillisecond", expr)
case "SECOND":
return "toSecond"
return call("toSecond", expr)
case "MINUTE":
return "toMinute"
return call("toMinute", expr)
case "HOUR":
return "toHour"
case "QUARTER":
return "toQuarter"
return call("toHour", expr)
case "DAY":
return call("toDayOfMonth", expr)
case "WEEK":
return "toWeek"
return call("toISOWeek", expr)
case "MONTH":
return call("toMonth", expr)
case "QUARTER":
return call("toQuarter", expr)
case "YEAR", "YYYY":
return call("toYear", expr)
case "EPOCH":
return call("toUnixTimestamp", expr)
case "DOW":
return call("toDayOfWeek", expr, num(2))
case "DOY":
return call("toDayOfYear", expr)
case "ISODOW":
return call("toDayOfWeek", expr)
case "ISOYEAR":
return call("toISOYear", expr)
case "CENTURY":
return call("plus", call("intDiv", call("minus", call("__toYearCalendarOnly", expr), num(1)), num(100)), num(1))
case "DECADE":
return call("intDiv", call("__toYearCalendarOnly", expr), num(10))
case "MILLENNIUM":
return call("plus", call("intDiv", call("minus", call("__toYearCalendarOnly", expr), num(1)), num(1000)), num(1))
case "TIMEZONE_HOUR":
return call("intDiv", call("timezoneOffset", expr), call("toInt64", num(3600)))
case "TIMEZONE_MINUTE":
return call("intDiv", call("modulo", call("timezoneOffset", expr), call("toInt64", num(3600))), call("toInt64", num(60)))
default:
// Fallback to generic "to" + TitleCase(field)
return "to" + strings.Title(strings.ToLower(field))
// Fallback to generic "to" + TitleCase(unit)
return call("to"+strings.Title(strings.ToLower(unit)), expr)
}
}

// explainDatePart handles date_part('unit', expr), which ClickHouse parses
// like EXTRACT(unit FROM expr). Returns false if the unit is not recognized.
func explainDatePart(sb *strings.Builder, n *ast.FunctionCall, alias string, indent string, depth int) bool {
if len(n.Arguments) != 2 || n.Over != nil || n.Parameters != nil || n.Distinct {
return false
}
lit, ok := n.Arguments[0].(*ast.Literal)
if !ok || lit.Type != ast.LiteralString {
return false
}
s, _ := lit.Value.(string)
unit, ok := extractunit.Canonical(s)
if !ok {
return false
}
fn := extractTimePart(unit, n.Arguments[1])
fn.Alias = alias
explainFunctionCall(sb, fn, indent, depth)
return true
}

func explainWindowSpec(sb *strings.Builder, n *ast.WindowSpec, indent string, depth int) {
// Window spec is represented as WindowDefinition
// For simple cases like OVER (), just output WindowDefinition without children
Expand Down
17 changes: 17 additions & 0 deletions internal/explain/select.go
Original file line number Diff line number Diff line change
Expand Up @@ -376,6 +376,8 @@ func explainSelectQuery(sb *strings.Builder, n *ast.SelectQuery, indent string,
if n.From != nil || n.ArrayJoin != nil {
TablesWithArrayJoin(sb, n.From, n.ArrayJoin, depth+1)
}
// CTE column aliases (WITH t (a, b) AS ...)
explainIdentifierList(sb, cteAliases(n), indent+" ")
// PREWHERE
if n.PreWhere != nil {
Node(sb, n.PreWhere, depth+1)
Expand Down Expand Up @@ -799,6 +801,9 @@ func countSelectQueryChildren(n *ast.SelectQuery) int {
if n.From != nil || n.ArrayJoin != nil {
count++
}
if len(cteAliases(n)) > 0 {
count++
}
if n.PreWhere != nil {
count++
}
Expand Down Expand Up @@ -862,3 +867,15 @@ func explainWindowListElement(sb *strings.Builder, w *ast.WindowDefinition, inde
fmt.Fprintf(sb, "%sWindowListElement (children 1)\n", indent)
explainWindowSpec(sb, w.Spec, indent+" ", depth+1)
}

// cteAliases returns the column alias list of the last WITH element that has
// one. ClickHouse keeps only that list on the SELECT query.
func cteAliases(n *ast.SelectQuery) []string {
var aliases []string
for _, w := range n.With {
if we, ok := w.(*ast.WithElement); ok && len(we.ColumnAliases) > 0 {
aliases = we.ColumnAliases
}
}
return aliases
}
Loading
Loading